From 0bceb055fd5d83d0d6b112933d80c6abb8d1fe1b Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Wed, 7 Feb 2024 15:50:19 -0500 Subject: [PATCH 01/54] Create java-autoformat.yml --- .github/workflows/java-autoformat.yml | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/workflows/java-autoformat.yml diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml new file mode 100644 index 000000000..8bba165c8 --- /dev/null +++ b/.github/workflows/java-autoformat.yml @@ -0,0 +1,35 @@ +name: Java Code Auto Format +on: pull_request + +jobs: + format: + runs-on: ubuntu-latest + if: github.event.pull_request.head.repo.full_name == github.repository + steps: + - name: Checkout code + uses: actions/checkout@v2 + with: + ref: ${{ github.head_ref }} + + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: '21' + + - name: spotless + run: + npm install --save-dev spotless + npx spotlessApply + + - name: Check for modified files + id: git-check + run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_ENV + + - name: Push changes + if: steps.git-check.outputs.modified == 'true' + run: | + git config --global user.name 'Bram van Heuveln' + git config --global user.email 'bram28@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.AUTO_FORMAT_SECRET }}@github.com/${{ github.repository }} + git commit -am "Automated Java code formatting changes" + git push \ No newline at end of file From 782223afedf09400ca34778cd726d6fbde41b2c0 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Wed, 7 Feb 2024 22:29:12 -0500 Subject: [PATCH 02/54] Setup Java --- .github/workflows/java-autoformat.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 8bba165c8..f6acdec73 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -11,10 +11,12 @@ jobs: with: ref: ${{ github.head_ref }} - - name: Set up JDK - uses: actions/setup-java@v2 + - name: Set up JDK 21 + uses: actions/setup-java@v1 with: - java-version: '21' + java-version: 21 + distribution: temurin + - name: spotless run: From ab30e2664ee17a03573456d7aa3c1820e90db836 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Wed, 7 Feb 2024 22:36:36 -0500 Subject: [PATCH 03/54] Run spotless on repository --- .github/workflows/java-autoformat.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index f6acdec73..55ecf6d03 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -18,10 +18,12 @@ jobs: distribution: temurin - - name: spotless - run: - npm install --save-dev spotless - npx spotlessApply + - name: Install spotless + run: | + curl -Ls "https://repo.maven.apache.org/maven2/com/diffplug/spotless/spotless-maven-plugin/5.14.2/spotless-maven-plugin-5.14.2.jar" -o spotless.jar + + - name: Run spotless + run: java -jar spotless.jar apply - name: Check for modified files id: git-check From ee58d4ebde3edae159c393557060097d61de6b15 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Wed, 7 Feb 2024 22:58:34 -0500 Subject: [PATCH 04/54] Adding spotless dependency during build --- .github/workflows/java-autoformat.yml | 7 +------ build.gradle | 7 +++++++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 55ecf6d03..3bd65d4cd 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -17,13 +17,8 @@ jobs: java-version: 21 distribution: temurin - - - name: Install spotless - run: | - curl -Ls "https://repo.maven.apache.org/maven2/com/diffplug/spotless/spotless-maven-plugin/5.14.2/spotless-maven-plugin-5.14.2.jar" -o spotless.jar - - name: Run spotless - run: java -jar spotless.jar apply + run: ./gradlew spotlessApply - name: Check for modified files id: git-check diff --git a/build.gradle b/build.gradle index 062a2cbff..0eeff6506 100644 --- a/build.gradle +++ b/build.gradle @@ -2,6 +2,13 @@ plugins { id 'java' id 'edu.sc.seis.launch4j' version '2.5.3' id 'kr.motd.sphinx' version '2.10.0' + id 'com.diffplug.gradle.spotless' version '5.14.2' +} + +spotless { + java { + target '**/*.java' + } } version '2.0.0' From 283e6c40dd3815013cc0d116a63a35d1a4856a35 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Wed, 7 Feb 2024 23:00:44 -0500 Subject: [PATCH 05/54] Adding spotless dependency during build --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 0eeff6506..1891c4edd 100644 --- a/build.gradle +++ b/build.gradle @@ -2,7 +2,7 @@ plugins { id 'java' id 'edu.sc.seis.launch4j' version '2.5.3' id 'kr.motd.sphinx' version '2.10.0' - id 'com.diffplug.gradle.spotless' version '5.14.2' + id 'com.diffplug.spotless' version '5.14.2' } spotless { From 51070b57f485bebc82deced261435f7070d5679b Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Wed, 7 Feb 2024 23:03:00 -0500 Subject: [PATCH 06/54] Give permissions to run spotless --- .github/workflows/java-autoformat.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 3bd65d4cd..a331451b2 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -16,6 +16,9 @@ jobs: with: java-version: 21 distribution: temurin + + - name: Grant execute permission for gradlew + run: chmod +x gradlew - name: Run spotless run: ./gradlew spotlessApply From 51919f10ccca6a7de30cddf2da6de0dd0dedca23 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Wed, 7 Feb 2024 23:06:07 -0500 Subject: [PATCH 07/54] Syntax --- .github/workflows/java-autoformat.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index a331451b2..f86571271 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -16,12 +16,12 @@ jobs: with: java-version: 21 distribution: temurin - + - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Run spotless - run: ./gradlew spotlessApply + run: ./gradlew :spotlessApply - name: Check for modified files id: git-check From 59c3c8d9fd095d4855391e5eaf92d96507e72569 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 08:13:21 -0500 Subject: [PATCH 08/54] Adding Debug Tag --- .github/workflows/java-autoformat.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index f86571271..6e9ff811f 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -14,14 +14,13 @@ jobs: - name: Set up JDK 21 uses: actions/setup-java@v1 with: - java-version: 21 - distribution: temurin + java-version: 11 - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Run spotless - run: ./gradlew :spotlessApply + run: ./gradlew --debug spotlessApply - name: Check for modified files id: git-check From 06d3d01a9fbb2bb7f5a10a20600c80db46f74222 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 08:16:01 -0500 Subject: [PATCH 09/54] Check for modified files Also removed debug tag --- .github/workflows/java-autoformat.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 6e9ff811f..6ef290cb0 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -20,11 +20,11 @@ jobs: run: chmod +x gradlew - name: Run spotless - run: ./gradlew --debug spotlessApply + run: ./gradlew spotlessApply - name: Check for modified files id: git-check - run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_ENV + run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_OUTPUT - name: Push changes if: steps.git-check.outputs.modified == 'true' From 4cc5893d2bdc5bf7c8cfcbb9d355bddd08cde36e Mon Sep 17 00:00:00 2001 From: Bram van Heuveln Date: Thu, 8 Feb 2024 13:16:45 +0000 Subject: [PATCH 10/54] Automated Java code formatting changes --- gradlew | 0 .../ApplyDefaultDirectRuleCommand.java | 256 ++++++------ .../history/ValidateDirectRuleCommand.java | 304 +++++++------- .../edu/rpi/legup/model/rules/DirectRule.java | 212 +++++----- .../rules/ContinueShipDirectRule.java | 86 ++-- .../rules/FinishWithShipsDirectRule.java | 232 +++++------ .../rules/FinishWithWaterDirectRule.java | 86 ++-- .../rules/SegmentTypeDirectRule.java | 86 ++-- .../rules/SurroundShipDirectRule.java | 86 ++-- .../rules/FinishWithBlackDirectRule.java | 124 +++--- .../rules/FinishWithWhiteDirectRule.java | 124 +++--- .../fillapix/rules/MirrorDirectRule.java | 204 +++++----- .../rules/NonTouchingSharedDirectRule.java | 196 ++++----- .../rules/TouchingCornersDirectRule.java | 214 +++++----- .../rules/TouchingSidesDirectRule.java | 228 +++++------ .../heyawake/rules/BlackPathDirectRule.java | 14 +- .../heyawake/rules/BottleNeckDirectRule.java | 14 +- .../rules/FillRoomBlackDirectRule.java | 86 ++-- .../rules/FillRoomWhiteDirectRule.java | 86 ++-- .../heyawake/rules/OneRowDirectRule.java | 14 +- .../rules/PreventWhiteLineDirectRule.java | 14 +- .../rules/ThreeByThreeDirectRule.java | 14 +- .../heyawake/rules/TwoInCornerDirectRule.java | 14 +- .../rules/WhiteAroundBlackDirectRule.java | 86 ++-- .../heyawake/rules/WhiteEscapeDirectRule.java | 14 +- .../heyawake/rules/ZigZagWhiteDirectRule.java | 14 +- .../rules/EmptyCellinLightDirectRule.java | 128 +++--- .../lightup/rules/EmptyCornersDirectRule.java | 230 +++++------ .../rules/FinishWithBulbsDirectRule.java | 214 +++++----- .../rules/FinishWithEmptyDirectRule.java | 236 +++++------ .../lightup/rules/MustLightDirectRule.java | 298 +++++++------- .../masyu/rules/BlackEdgeDirectRule.java | 84 ++-- .../masyu/rules/BlockedBlackDirectRule.java | 84 ++-- .../masyu/rules/ConnectedCellsDirectRule.java | 84 ++-- .../masyu/rules/FinishPathDirectRule.java | 84 ++-- .../masyu/rules/NearWhiteDirectRule.java | 84 ++-- .../masyu/rules/OnlyOneChoiceDirectRule.java | 84 ++-- .../masyu/rules/WhiteEdgeDirectRule.java | 82 ++-- .../rules/BlackBetweenRegionsDirectRule.java | 224 +++++------ .../rules/BlackBottleNeckDirectRule.java | 130 +++--- .../rules/CannotReachCellDirectRule.java | 122 +++--- .../nurikabe/rules/CornerBlackDirectRule.java | 216 +++++----- .../nurikabe/rules/FillinBlackDirectRule.java | 120 +++--- .../nurikabe/rules/FillinWhiteDirectRule.java | 120 +++--- .../rules/PreventBlackSquareDirectRule.java | 132 +++--- .../rules/SurroundRegionDirectRule.java | 190 ++++----- .../rules/WhiteBottleNeckDirectRule.java | 138 +++---- .../ShortTruthTableOperation.java | 114 +++--- .../elimination/DirectRuleAndElimination.java | 20 +- .../DirectRuleBiconditionalElimination.java | 20 +- .../DirectRuleConditionalElimination.java | 20 +- .../elimination/DirectRuleNotElimination.java | 20 +- .../elimination/DirectRuleOrElimination.java | 20 +- .../DirectRule_GenericElimination.java | 34 +- .../DirectRuleAndIntroduction.java | 20 +- .../DirectRuleBiconditionalIntroduction.java | 20 +- .../DirectRuleConditionalIntroduction.java | 20 +- .../DirectRuleNotIntroduction.java | 20 +- .../DirectRuleOrIntroduction.java | 20 +- .../DirectRule_GenericIntroduction.java | 34 +- .../rules/caserule/CaseRuleAnd.java | 46 +-- .../rules/caserule/CaseRuleConditional.java | 46 +-- .../rules/caserule/CaseRuleOr.java | 46 +-- .../rules/caserule/CaseRule_Generic.java | 142 +++---- .../rules/LastSingularCellDirectRule.java | 228 +++++------ .../rules/LastSingularNumberDirectRule.java | 194 ++++----- .../rules/LastVisibleCellDirectRule.java | 232 +++++------ .../rules/LastVisibleNumberDirectRule.java | 196 ++++----- .../skyscrapers/rules/NEdgeDirectRule.java | 198 ++++----- .../rules/AdvancedDeductionDirectRule.java | 192 ++++----- .../rules/LastCellForNumberDirectRule.java | 186 ++++----- .../rules/LastNumberForCellDirectRule.java | 154 +++---- .../treetent/rules/EmptyFieldDirectRule.java | 174 ++++---- .../rules/FinishWithGrassDirectRule.java | 172 ++++---- .../rules/FinishWithTentsDirectRule.java | 176 ++++---- .../rules/LastCampingSpotDirectRule.java | 204 +++++----- .../SurroundTentWithGrassDirectRule.java | 170 ++++---- .../treetent/rules/TentForTreeDirectRule.java | 248 ++++++------ .../treetent/rules/TreeForTentDirectRule.java | 244 +++++------ .../rulesview/DirectRulePanel.java | 42 +- .../BlackBetweenRegionsDirectRuleTest.java | 380 +++++++++--------- .../rules/CornerBlackDirectRuleTest.java | 168 ++++---- .../rules/FillinWhiteDirectRuleTest.java | 288 ++++++------- .../PreventBlackSquareDirectRuleTest.java | 338 ++++++++-------- .../rules/SurroundRegionDirectRuleTest.java | 248 ++++++------ .../rules/WhiteBottleNeckDirectRuleTest.java | 218 +++++----- 86 files changed, 5602 insertions(+), 5602 deletions(-) mode change 100644 => 100755 gradlew diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 diff --git a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java index bc4c89741..ae53b89f3 100644 --- a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java @@ -1,128 +1,128 @@ -package edu.rpi.legup.history; - -import edu.rpi.legup.app.GameBoardFacade; -import edu.rpi.legup.model.Puzzle; -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.*; -import edu.rpi.legup.ui.proofeditorui.treeview.*; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class ApplyDefaultDirectRuleCommand extends PuzzleCommand { - - private TreeViewSelection selection; - private DirectRule rule; - private Map addMap; - - /** - * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a basic rule - * - * @param selection selection of tree element views - * @param rule basic rule for the command - */ - public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.rule = rule; - this.addMap = new HashMap<>(); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_SELECTED_VIEWS.toString(); - } - else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); - } - else { - if (rule.getDefaultBoard(node) == null) { - return CommandError.DEFAULT_APPLICATION + " - " + "This selection contains a tree element that this rule cannot be applied to."; - } - } - } - else { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } - } - } - return null; - } - - /** - * Executes an command - */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - TreeTransition transition = addMap.get(node); - TreeNode childNode; - if (transition == null) { - transition = (TreeTransition) tree.addTreeElement(node); - childNode = (TreeNode) tree.addTreeElement(transition); - addMap.put(node, transition); - } - else { - tree.addTreeElement(node, transition); - childNode = transition.getChildNode(); - } - - transition.setRule(rule); - Board defaultBoard = rule.getDefaultBoard(node); - transition.setBoard(defaultBoard); - Board copyBoard = defaultBoard.copy(); - copyBoard.setModifiable(false); - childNode.setBoard(copyBoard); - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(childNode)); - } - - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - final TreeTransition transition = addMap.get(node); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - } - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } -} +package edu.rpi.legup.history; + +import edu.rpi.legup.app.GameBoardFacade; +import edu.rpi.legup.model.Puzzle; +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.*; +import edu.rpi.legup.ui.proofeditorui.treeview.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ApplyDefaultDirectRuleCommand extends PuzzleCommand { + + private TreeViewSelection selection; + private DirectRule rule; + private Map addMap; + + /** + * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a basic rule + * + * @param selection selection of tree element views + * @param rule basic rule for the command + */ + public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.rule = rule; + this.addMap = new HashMap<>(); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_SELECTED_VIEWS.toString(); + } + else { + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); + } + else { + if (rule.getDefaultBoard(node) == null) { + return CommandError.DEFAULT_APPLICATION + " - " + "This selection contains a tree element that this rule cannot be applied to."; + } + } + } + else { + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + } + } + return null; + } + + /** + * Executes an command + */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + TreeTransition transition = addMap.get(node); + TreeNode childNode; + if (transition == null) { + transition = (TreeTransition) tree.addTreeElement(node); + childNode = (TreeNode) tree.addTreeElement(transition); + addMap.put(node, transition); + } + else { + tree.addTreeElement(node, transition); + childNode = transition.getChildNode(); + } + + transition.setRule(rule); + Board defaultBoard = rule.getDefaultBoard(node); + transition.setBoard(defaultBoard); + Board copyBoard = defaultBoard.copy(); + copyBoard.setModifiable(false); + childNode.setBoard(copyBoard); + + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(childNode)); + } + + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Undoes an command + */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + final TreeTransition transition = addMap.get(node); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } +} diff --git a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java index 61babe883..970af49a0 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java @@ -1,152 +1,152 @@ -package edu.rpi.legup.history; - -import edu.rpi.legup.app.GameBoardFacade; -import edu.rpi.legup.model.Puzzle; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.Rule; -import edu.rpi.legup.model.tree.*; -import edu.rpi.legup.ui.proofeditorui.treeview.*; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class ValidateDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - - private Map oldRules; - private Map addNode; - private DirectRule newRule; - - /** - * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule - * - * @param selection selection of tree elements - * @param rule basic rule - */ - public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.oldRules = new HashMap<>(); - this.addNode = new HashMap<>(); - } - - /** - * Executes an command - */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } - else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); - - oldRules.put(transition, transition.getRule()); - transition.setRule(newRule); - - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); - } - else { - tree.addTreeElement(transition, childNode); - } - - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - newSelection.addToSelection(treeView.getElementView(childNode)); - } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } - else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); - } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } - - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (nodeView.getChildrenViews().size() != 1) { - return CommandError.ONE_CHILD.toString(); - } - } - else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); - } - } - } - return null; - } - - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } - else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); - transition.setRule(oldRules.get(transition)); - - if (addNode.get(transition) != null) { - final TreeNode childNode = transition.getChildNode(); - tree.removeTreeElement(childNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - } - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } -} +package edu.rpi.legup.history; + +import edu.rpi.legup.app.GameBoardFacade; +import edu.rpi.legup.model.Puzzle; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.Rule; +import edu.rpi.legup.model.tree.*; +import edu.rpi.legup.ui.proofeditorui.treeview.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ValidateDirectRuleCommand extends PuzzleCommand { + private TreeViewSelection selection; + + private Map oldRules; + private Map addNode; + private DirectRule newRule; + + /** + * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule + * + * @param selection selection of tree elements + * @param rule basic rule + */ + public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.oldRules = new HashMap<>(); + this.addNode = new HashMap<>(); + } + + /** + * Executes an command + */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } + else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); + + oldRules.put(transition, transition.getRule()); + transition.setRule(newRule); + + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); + } + else { + tree.addTreeElement(transition, childNode); + } + + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + newSelection.addToSelection(treeView.getElementView(childNode)); + } + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } + else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); + } + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } + + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (nodeView.getChildrenViews().size() != 1) { + return CommandError.ONE_CHILD.toString(); + } + } + else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); + } + } + } + return null; + } + + /** + * Undoes an command + */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } + else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); + transition.setRule(oldRules.get(transition)); + + if (addNode.get(transition) != null) { + final TreeNode childNode = transition.getChildNode(); + tree.removeTreeElement(childNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } +} diff --git a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java index 304a2ca90..be6a0f160 100644 --- a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java @@ -1,106 +1,106 @@ -package edu.rpi.legup.model.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -import static edu.rpi.legup.model.rules.RuleType.BASIC; - -public abstract class DirectRule extends Rule { - /** - * DirectRule Constructor creates a new basic rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public DirectRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = BASIC; - } - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRule(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - // System.out.println(finalBoard.getModifiedData().size()); - if (transition.getParents().size() != 1 || - transition.getParents().get(0).getChildren().size() != 1) { - return "State must have only 1 parent and 1 child"; - } - else if (finalBoard.getModifiedData().isEmpty()) { - // null transition - return null; - } - else { - return checkRuleRaw(transition); - } - } - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRuleRaw(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - String checkStr = null; - - // Go directly to specific direct rule's judgement if no cell's are edited - if (finalBoard.getModifiedData().size() == 0) { - checkStr = checkRuleRawAt(transition, null); - } - for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { - String tempStr = checkRuleAt(transition, puzzleElement); - if (tempStr != null) { - checkStr = tempStr; - } - } - return checkStr; - } - - /** - * Checks whether the child node logically follows from the parent node at the specific {@link PuzzleElement} using - * this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - Board finalBoard = transition.getBoard(); - puzzleElement = finalBoard.getPuzzleElement(puzzleElement); - String checkStr; - if (!puzzleElement.isModified()) { - checkStr = "PuzzleElement must be modified"; - } - else { - if (transition.getParents().size() != 1 || - transition.getParents().get(0).getChildren().size() != 1) { - checkStr = "State must have only 1 parent and 1 child"; - } - else { - checkStr = checkRuleRawAt(transition, puzzleElement); - } - } - puzzleElement.setValid(checkStr == null); - return checkStr; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - public abstract Board getDefaultBoard(TreeNode node); -} +package edu.rpi.legup.model.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +import static edu.rpi.legup.model.rules.RuleType.BASIC; + +public abstract class DirectRule extends Rule { + /** + * DirectRule Constructor creates a new basic rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public DirectRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = BASIC; + } + + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRule(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + // System.out.println(finalBoard.getModifiedData().size()); + if (transition.getParents().size() != 1 || + transition.getParents().get(0).getChildren().size() != 1) { + return "State must have only 1 parent and 1 child"; + } + else if (finalBoard.getModifiedData().isEmpty()) { + // null transition + return null; + } + else { + return checkRuleRaw(transition); + } + } + + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is + * the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRuleRaw(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + String checkStr = null; + + // Go directly to specific direct rule's judgement if no cell's are edited + if (finalBoard.getModifiedData().size() == 0) { + checkStr = checkRuleRawAt(transition, null); + } + for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { + String tempStr = checkRuleAt(transition, puzzleElement); + if (tempStr != null) { + checkStr = tempStr; + } + } + return checkStr; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific {@link PuzzleElement} using + * this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + Board finalBoard = transition.getBoard(); + puzzleElement = finalBoard.getPuzzleElement(puzzleElement); + String checkStr; + if (!puzzleElement.isModified()) { + checkStr = "PuzzleElement must be modified"; + } + else { + if (transition.getParents().size() != 1 || + transition.getParents().get(0).getChildren().size() != 1) { + checkStr = "State must have only 1 parent and 1 child"; + } + else { + checkStr = checkRuleRawAt(transition, puzzleElement); + } + } + puzzleElement.setValid(checkStr == null); + return checkStr; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + public abstract Board getDefaultBoard(TreeNode node); +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java index 18c55d635..8b343f5a7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java @@ -1,43 +1,43 @@ -package edu.rpi.legup.puzzle.battleship.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class ContinueShipDirectRule extends DirectRule { - - public ContinueShipDirectRule() { - super("BTSP-BASC-0001", - "Continue Ship", - "", - "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should be overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.battleship.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class ContinueShipDirectRule extends DirectRule { + + public ContinueShipDirectRule() { + super("BTSP-BASC-0001", + "Continue Ship", + "", + "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should be overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java index 3374d1806..c2fa6f84a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java @@ -1,116 +1,116 @@ -package edu.rpi.legup.puzzle.battleship.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.battleship.BattleshipBoard; -import edu.rpi.legup.puzzle.battleship.BattleshipCell; -import edu.rpi.legup.puzzle.battleship.BattleshipClue; -import edu.rpi.legup.puzzle.battleship.BattleshipType; - -import java.awt.*; -import java.util.List; - -public class FinishWithShipsDirectRule extends DirectRule { - - public FinishWithShipsDirectRule() { - super("BTSP-BASC-0002", - "Finish with Ships", - "The number of undetermined squares is equal to the number " + - "of segments remaining for each clue.", - "edu/rpi/legup/images/battleship/rules/finishShip.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should be overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node - * at the specified puzzleElement, otherwise error message. - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, - PuzzleElement puzzleElement) { - BattleshipBoard initBoard = (BattleshipBoard) transition.getParents() - .get(0).getBoard(); - BattleshipCell initCell = (BattleshipCell) initBoard - .getPuzzleElement(puzzleElement); - BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); - BattleshipCell finalCell = (BattleshipCell) finalBoard - .getPuzzleElement(puzzleElement); - if (!(initCell.getType() == BattleshipType.UNKNOWN - && BattleshipType.isShip(finalCell.getType()))) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; - } - - if (isForced(initBoard, initCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to" + - "be a ship segment."; - } - } - - private boolean isForced(BattleshipBoard board, BattleshipCell cell) { - Point loc = cell.getLocation(); - - // count the number of ship segments and unknowns in the row - List row = board.getRow(loc.y); - int rowCount = 0; - for (BattleshipCell c : row) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN - || BattleshipType.isShip(c.getType())) { - rowCount++; - } - } - - // count the number of ship segments and unknowns in the column - List col = board.getColumn(loc.x); - int colCount = 0; - for (BattleshipCell c : col) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN - || BattleshipType.isShip(c.getType())) { - colCount++; - } - } - - // compare the counts with the clues - BattleshipClue east = board.getEast().get(loc.y); - BattleshipClue south = board.getSouth().get(loc.x); - - return rowCount <= east.getData() && colCount <= south.getData(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the - * {@link TreeNode}. - * - * @param node tree node used to create default transition board. - * @return default board or null if this rule cannot be applied to this tree - * node. - */ - @Override - public Board getDefaultBoard(TreeNode node) { - BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); - for (PuzzleElement element : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) element; - if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { - cell.setData(BattleshipType.SHIP_UNKNOWN); - board.addModifiedData(cell); - } - } - - if (board.getModifiedData().isEmpty()) { - return null; - } - else { - return board; - } - } -} +package edu.rpi.legup.puzzle.battleship.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.battleship.BattleshipBoard; +import edu.rpi.legup.puzzle.battleship.BattleshipCell; +import edu.rpi.legup.puzzle.battleship.BattleshipClue; +import edu.rpi.legup.puzzle.battleship.BattleshipType; + +import java.awt.*; +import java.util.List; + +public class FinishWithShipsDirectRule extends DirectRule { + + public FinishWithShipsDirectRule() { + super("BTSP-BASC-0002", + "Finish with Ships", + "The number of undetermined squares is equal to the number " + + "of segments remaining for each clue.", + "edu/rpi/legup/images/battleship/rules/finishShip.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should be overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node + * at the specified puzzleElement, otherwise error message. + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, + PuzzleElement puzzleElement) { + BattleshipBoard initBoard = (BattleshipBoard) transition.getParents() + .get(0).getBoard(); + BattleshipCell initCell = (BattleshipCell) initBoard + .getPuzzleElement(puzzleElement); + BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); + BattleshipCell finalCell = (BattleshipCell) finalBoard + .getPuzzleElement(puzzleElement); + if (!(initCell.getType() == BattleshipType.UNKNOWN + && BattleshipType.isShip(finalCell.getType()))) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; + } + + if (isForced(initBoard, initCell)) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to" + + "be a ship segment."; + } + } + + private boolean isForced(BattleshipBoard board, BattleshipCell cell) { + Point loc = cell.getLocation(); + + // count the number of ship segments and unknowns in the row + List row = board.getRow(loc.y); + int rowCount = 0; + for (BattleshipCell c : row) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN + || BattleshipType.isShip(c.getType())) { + rowCount++; + } + } + + // count the number of ship segments and unknowns in the column + List col = board.getColumn(loc.x); + int colCount = 0; + for (BattleshipCell c : col) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN + || BattleshipType.isShip(c.getType())) { + colCount++; + } + } + + // compare the counts with the clues + BattleshipClue east = board.getEast().get(loc.y); + BattleshipClue south = board.getSouth().get(loc.x); + + return rowCount <= east.getData() && colCount <= south.getData(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the + * {@link TreeNode}. + * + * @param node tree node used to create default transition board. + * @return default board or null if this rule cannot be applied to this tree + * node. + */ + @Override + public Board getDefaultBoard(TreeNode node) { + BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); + for (PuzzleElement element : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) element; + if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { + cell.setData(BattleshipType.SHIP_UNKNOWN); + board.addModifiedData(cell); + } + } + + if (board.getModifiedData().isEmpty()) { + return null; + } + else { + return board; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java index 157b13d01..803548f34 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java @@ -1,43 +1,43 @@ -package edu.rpi.legup.puzzle.battleship.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class FinishWithWaterDirectRule extends DirectRule { - - public FinishWithWaterDirectRule() { - super("BTSP-BASC-0003", - "Finish with Water", - "", - "edu/rpi/legup/images/battleship/rules/finishWater.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.battleship.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class FinishWithWaterDirectRule extends DirectRule { + + public FinishWithWaterDirectRule() { + super("BTSP-BASC-0003", + "Finish with Water", + "", + "edu/rpi/legup/images/battleship/rules/finishWater.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java index f90dea1bd..42b16bb23 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java @@ -1,43 +1,43 @@ -package edu.rpi.legup.puzzle.battleship.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class SegmentTypeDirectRule extends DirectRule { - - public SegmentTypeDirectRule() { - super("BTSP-BASC-0004", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.battleship.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class SegmentTypeDirectRule extends DirectRule { + + public SegmentTypeDirectRule() { + super("BTSP-BASC-0004", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java index 57ad42121..eb7ae1b9a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java @@ -1,43 +1,43 @@ -package edu.rpi.legup.puzzle.battleship.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class SurroundShipDirectRule extends DirectRule { - - public SurroundShipDirectRule() { - super("BTSP-BASC-0005", - "Surround Ship", - "", - "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.battleship.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class SurroundShipDirectRule extends DirectRule { + + public SurroundShipDirectRule() { + super("BTSP-BASC-0005", + "Surround Ship", + "", + "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java index 06a8045ed..c9f26befd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java @@ -1,63 +1,63 @@ -package edu.rpi.legup.puzzle.fillapix.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.fillapix.FillapixBoard; -import edu.rpi.legup.puzzle.fillapix.FillapixCell; -import edu.rpi.legup.puzzle.fillapix.FillapixCellType; -import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; - -public class FinishWithBlackDirectRule extends DirectRule { - public FinishWithBlackDirectRule() { - super("FPIX-BASC-0001", - "Finish with Black", - "The remaining unknowns around and on a cell must be black to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - - if (!(parentCell.getType() == FillapixCellType.UNKNOWN && cell.getType() == FillapixCellType.BLACK)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be black to be applicable with this rule."; - } - - if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; - } - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.BLACK); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return fillapixBoard; - } - } +package edu.rpi.legup.puzzle.fillapix.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.fillapix.FillapixBoard; +import edu.rpi.legup.puzzle.fillapix.FillapixCell; +import edu.rpi.legup.puzzle.fillapix.FillapixCellType; +import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; + +public class FinishWithBlackDirectRule extends DirectRule { + public FinishWithBlackDirectRule() { + super("FPIX-BASC-0001", + "Finish with Black", + "The remaining unknowns around and on a cell must be black to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + + if (!(parentCell.getType() == FillapixCellType.UNKNOWN && cell.getType() == FillapixCellType.BLACK)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be black to be applicable with this rule."; + } + + if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; + } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.BLACK); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return fillapixBoard; + } + } } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java index 7e213a59c..13f0e4aa0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java @@ -1,63 +1,63 @@ -package edu.rpi.legup.puzzle.fillapix.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.fillapix.FillapixBoard; -import edu.rpi.legup.puzzle.fillapix.FillapixCell; -import edu.rpi.legup.puzzle.fillapix.FillapixCellType; -import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; - -public class FinishWithWhiteDirectRule extends DirectRule { - public FinishWithWhiteDirectRule() { - super("FPIX-BASC-0002", - "Finish with White", - "The remaining unknowns around and on a cell must be white to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - - if (!(parentCell.getType() == FillapixCellType.UNKNOWN && cell.getType() == FillapixCellType.WHITE)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be white to be applicable with this rule"; - } - - if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; - } - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.WHITE); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return fillapixBoard; - } - } +package edu.rpi.legup.puzzle.fillapix.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.fillapix.FillapixBoard; +import edu.rpi.legup.puzzle.fillapix.FillapixCell; +import edu.rpi.legup.puzzle.fillapix.FillapixCellType; +import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; + +public class FinishWithWhiteDirectRule extends DirectRule { + public FinishWithWhiteDirectRule() { + super("FPIX-BASC-0002", + "Finish with White", + "The remaining unknowns around and on a cell must be white to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + + if (!(parentCell.getType() == FillapixCellType.UNKNOWN && cell.getType() == FillapixCellType.WHITE)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be white to be applicable with this rule"; + } + + if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; + } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.WHITE); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return fillapixBoard; + } + } } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java index 656cedb3f..a9e6f85ae 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java @@ -1,103 +1,103 @@ -package edu.rpi.legup.puzzle.fillapix.rules; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.CaseRule; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.fillapix.FillapixBoard; -import edu.rpi.legup.puzzle.fillapix.FillapixCell; -import edu.rpi.legup.puzzle.fillapix.FillapixCellType; -import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; - -public class MirrorDirectRule extends DirectRule { - public MirrorDirectRule() { - super("FPIX-BASC-0003", - "Mirror", - "Two adjacent clues with the same value must have the same number of black squares in their unshared regions", - "edu/rpi/legup/images/fillapix/rules/Mirror.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } - - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } - - // find all cells adjacent to cell that are numbered - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - ArrayList adjNums = new ArrayList(); - for (int i=0; i < adjCells.size(); i++) { - if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { - adjNums.add(adjCells.get(i)); - } - } - // the numbered cells must be next to another numbered cell of the same value - Iterator itr = adjNums.iterator(); - while (itr.hasNext()) { - FillapixCell adjNum = itr.next(); - adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); - boolean found = false; - for (FillapixCell adjCell : adjCells) { - if (adjCell.getNumber() == adjNum.getNumber() && adjCell.getIndex() != adjNum.getIndex()) { - found = true; - } - } - if (!found) { - itr.remove(); - } - } - - // change the color of the parentCell, and check if there exists a valid board - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } - else { - parentCell.setCellType(FillapixCellType.BLACK); - } - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjNum : adjNums) { - caseBoards = completeClue.getCases(parentBoard, adjNum); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } - } - - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } +package edu.rpi.legup.puzzle.fillapix.rules; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.CaseRule; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.fillapix.FillapixBoard; +import edu.rpi.legup.puzzle.fillapix.FillapixCell; +import edu.rpi.legup.puzzle.fillapix.FillapixCellType; +import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; + +public class MirrorDirectRule extends DirectRule { + public MirrorDirectRule() { + super("FPIX-BASC-0003", + "Mirror", + "Two adjacent clues with the same value must have the same number of black squares in their unshared regions", + "edu/rpi/legup/images/fillapix/rules/Mirror.png"); + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } + + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } + + // find all cells adjacent to cell that are numbered + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + ArrayList adjNums = new ArrayList(); + for (int i=0; i < adjCells.size(); i++) { + if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { + adjNums.add(adjCells.get(i)); + } + } + // the numbered cells must be next to another numbered cell of the same value + Iterator itr = adjNums.iterator(); + while (itr.hasNext()) { + FillapixCell adjNum = itr.next(); + adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); + boolean found = false; + for (FillapixCell adjCell : adjCells) { + if (adjCell.getNumber() == adjNum.getNumber() && adjCell.getIndex() != adjNum.getIndex()) { + found = true; + } + } + if (!found) { + itr.remove(); + } + } + + // change the color of the parentCell, and check if there exists a valid board + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } + else { + parentCell.setCellType(FillapixCellType.BLACK); + } + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjNum : adjNums) { + caseBoards = completeClue.getCases(parentBoard, adjNum); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } + } + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java index fe94dbcb4..df6b5b76d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java @@ -1,99 +1,99 @@ -package edu.rpi.legup.puzzle.fillapix.rules; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.CaseRule; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.fillapix.FillapixBoard; -import edu.rpi.legup.puzzle.fillapix.FillapixCell; -import edu.rpi.legup.puzzle.fillapix.FillapixCellType; -import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; - -public class NonTouchingSharedDirectRule extends DirectRule { - public NonTouchingSharedDirectRule() { - super("FPIX-BASC-0005", - "NonTouching Shared", - "Clues with shared cells have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } - - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } - - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell not - * touching, but sharing cells */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - ArrayList sharingCells = FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); - boolean found = false; - for (FillapixCell sharingCell : sharingCells) { - if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { - found = true; - } - } - if (!found) { - itr.remove(); - } - } - - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } - else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } - } - - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } +package edu.rpi.legup.puzzle.fillapix.rules; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.CaseRule; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.fillapix.FillapixBoard; +import edu.rpi.legup.puzzle.fillapix.FillapixCell; +import edu.rpi.legup.puzzle.fillapix.FillapixCellType; +import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; + +public class NonTouchingSharedDirectRule extends DirectRule { + public NonTouchingSharedDirectRule() { + super("FPIX-BASC-0005", + "NonTouching Shared", + "Clues with shared cells have the same difference in black cells in their unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } + + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } + + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell not + * touching, but sharing cells */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + ArrayList sharingCells = FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); + boolean found = false; + for (FillapixCell sharingCell : sharingCells) { + if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { + found = true; + } + } + if (!found) { + itr.remove(); + } + } + + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } + else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } + } + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java index 6f4be7842..f0c8bb00d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java @@ -1,108 +1,108 @@ -package edu.rpi.legup.puzzle.fillapix.rules; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.CaseRule; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.fillapix.FillapixBoard; -import edu.rpi.legup.puzzle.fillapix.FillapixCell; -import edu.rpi.legup.puzzle.fillapix.FillapixCellType; -import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; - -public class TouchingCornersDirectRule extends DirectRule { - public TouchingCornersDirectRule() { - super("FPIX-BASC-0005", - "Touching Corners", - "Clues with touching corners have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } - - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } - - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell diagonally - * adjacent to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - FillapixCell adjCell = itr.next(); - - boolean found = false; - ArrayList adjAdjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjCell); - for (FillapixCell adjAdjCell : adjAdjCells) { - if (adjAdjCell.getLocation().x != adjCell.getLocation().x && - adjAdjCell.getLocation().y != adjCell.getLocation().y && - adjAdjCell.getNumber() >= 0 && adjAdjCell.getNumber() < 10 && - adjAdjCell.getIndex() != parentCell.getIndex()) { - // adjAdjCell is diagonally adjacent to adjCell && it has a - // number && it is not parentCell - found = true; - } - } - - // does not qualify for this rule - if (!found) { - itr.remove(); - } - } - - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } - else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } - } - - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } +package edu.rpi.legup.puzzle.fillapix.rules; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.CaseRule; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.fillapix.FillapixBoard; +import edu.rpi.legup.puzzle.fillapix.FillapixCell; +import edu.rpi.legup.puzzle.fillapix.FillapixCellType; +import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; + +public class TouchingCornersDirectRule extends DirectRule { + public TouchingCornersDirectRule() { + super("FPIX-BASC-0005", + "Touching Corners", + "Clues with touching corners have the same difference in black cells in their unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } + + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } + + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell diagonally + * adjacent to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + FillapixCell adjCell = itr.next(); + + boolean found = false; + ArrayList adjAdjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjCell); + for (FillapixCell adjAdjCell : adjAdjCells) { + if (adjAdjCell.getLocation().x != adjCell.getLocation().x && + adjAdjCell.getLocation().y != adjCell.getLocation().y && + adjAdjCell.getNumber() >= 0 && adjAdjCell.getNumber() < 10 && + adjAdjCell.getIndex() != parentCell.getIndex()) { + // adjAdjCell is diagonally adjacent to adjCell && it has a + // number && it is not parentCell + found = true; + } + } + + // does not qualify for this rule + if (!found) { + itr.remove(); + } + } + + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } + else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } + } + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java index bd6dd0169..5e60ab174 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java @@ -1,115 +1,115 @@ -package edu.rpi.legup.puzzle.fillapix.rules; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.CaseRule; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.fillapix.FillapixBoard; -import edu.rpi.legup.puzzle.fillapix.FillapixCell; -import edu.rpi.legup.puzzle.fillapix.FillapixCellType; -import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; - -public class TouchingSidesDirectRule extends DirectRule { - public TouchingSidesDirectRule() { - super("FPIX-BASC-0004", - "Touching Sides", - "Clues with touching sides have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } - - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } - - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell adjacent - * to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - // calculate x and y offset of adjCell from cell - FillapixCell adjCell = itr.next(); - int xOffset = adjCell.getLocation().x - cell.getLocation().x; - int yOffset = adjCell.getLocation().y - cell.getLocation().y; - - boolean found = false; - // check vertically for numbered cell in opposite direction of cell - if (adjCell.getLocation().x + xOffset >= 0 && adjCell.getLocation().x < parentBoard.getWidth()) { - int adjNum = parentBoard.getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y).getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; - } - } - // check horizontally for numbered cell in opposite direction of cell - if (adjCell.getLocation().y + yOffset >= 0 && adjCell.getLocation().y < parentBoard.getHeight()) { - int adjNum = parentBoard.getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset).getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; - } - } - - // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, - // then adjCell is not valid, so should be removed - if (!found) { - itr.remove(); - } - } - - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } - else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } - } - - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } +package edu.rpi.legup.puzzle.fillapix.rules; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.CaseRule; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.fillapix.FillapixBoard; +import edu.rpi.legup.puzzle.fillapix.FillapixCell; +import edu.rpi.legup.puzzle.fillapix.FillapixCellType; +import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; + +public class TouchingSidesDirectRule extends DirectRule { + public TouchingSidesDirectRule() { + super("FPIX-BASC-0004", + "Touching Sides", + "Clues with touching sides have the same difference in black cells in their unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } + + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } + + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell adjacent + * to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + // calculate x and y offset of adjCell from cell + FillapixCell adjCell = itr.next(); + int xOffset = adjCell.getLocation().x - cell.getLocation().x; + int yOffset = adjCell.getLocation().y - cell.getLocation().y; + + boolean found = false; + // check vertically for numbered cell in opposite direction of cell + if (adjCell.getLocation().x + xOffset >= 0 && adjCell.getLocation().x < parentBoard.getWidth()) { + int adjNum = parentBoard.getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y).getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; + } + } + // check horizontally for numbered cell in opposite direction of cell + if (adjCell.getLocation().y + yOffset >= 0 && adjCell.getLocation().y < parentBoard.getHeight()) { + int adjNum = parentBoard.getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset).getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; + } + } + + // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, + // then adjCell is not valid, so should be removed + if (!found) { + itr.remove(); + } + } + + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } + else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } + } + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java index 474bdccdd..1fc3d0776 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java @@ -1,7 +1,7 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -public class BlackPathDirectRule { - public BlackPathDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +public class BlackPathDirectRule { + public BlackPathDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java index f2e7fef5c..41d950378 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java @@ -1,7 +1,7 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -public class BottleNeckDirectRule { - public BottleNeckDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +public class BottleNeckDirectRule { + public BottleNeckDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java index 828739160..255678e02 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java @@ -1,43 +1,43 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class FillRoomBlackDirectRule extends DirectRule { - - public FillRoomBlackDirectRule() { - super("HEYA-BASC-0003", - "Fill Room Black", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class FillRoomBlackDirectRule extends DirectRule { + + public FillRoomBlackDirectRule() { + super("HEYA-BASC-0003", + "Fill Room Black", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java index 6b1a11c29..1dee36ecc 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java @@ -1,43 +1,43 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class FillRoomWhiteDirectRule extends DirectRule { - - public FillRoomWhiteDirectRule() { - super("HEYA-BASC-0004", - "Fill Room White", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class FillRoomWhiteDirectRule extends DirectRule { + + public FillRoomWhiteDirectRule() { + super("HEYA-BASC-0004", + "Fill Room White", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java index 3e8c07a4d..8b6f21564 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java @@ -1,7 +1,7 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -public class OneRowDirectRule { - public OneRowDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +public class OneRowDirectRule { + public OneRowDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java index 0efd90694..f5d4e78b7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java @@ -1,7 +1,7 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -public class PreventWhiteLineDirectRule { - public PreventWhiteLineDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +public class PreventWhiteLineDirectRule { + public PreventWhiteLineDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java index 6dee3fc83..cf2c241e3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java @@ -1,7 +1,7 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -public class ThreeByThreeDirectRule { - public ThreeByThreeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +public class ThreeByThreeDirectRule { + public ThreeByThreeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java index 8e2776fc7..83f1ca72f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java @@ -1,7 +1,7 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -public class TwoInCornerDirectRule { - public TwoInCornerDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +public class TwoInCornerDirectRule { + public TwoInCornerDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java index 21a698d41..e0f17a0ed 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java @@ -1,43 +1,43 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class WhiteAroundBlackDirectRule extends DirectRule { - - public WhiteAroundBlackDirectRule() { - super("HEYA-BASC-0009", - "White Around Black", - "", - "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class WhiteAroundBlackDirectRule extends DirectRule { + + public WhiteAroundBlackDirectRule() { + super("HEYA-BASC-0009", + "White Around Black", + "", + "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java index 231d353e6..f151ec12a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java @@ -1,7 +1,7 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -public class WhiteEscapeDirectRule { - public WhiteEscapeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +public class WhiteEscapeDirectRule { + public WhiteEscapeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java index 22a76b9a9..9df735b0b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java @@ -1,7 +1,7 @@ -package edu.rpi.legup.puzzle.heyawake.rules; - -public class ZigZagWhiteDirectRule { - public ZigZagWhiteDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } -} +package edu.rpi.legup.puzzle.heyawake.rules; + +public class ZigZagWhiteDirectRule { + public ZigZagWhiteDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java index a40ede284..290671cb8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java @@ -1,64 +1,64 @@ -package edu.rpi.legup.puzzle.lightup.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import edu.rpi.legup.puzzle.lightup.LightUpCell; -import edu.rpi.legup.puzzle.lightup.LightUpCellType; - -public class EmptyCellinLightDirectRule extends DirectRule { - - public EmptyCellinLightDirectRule() { - super("LTUP-BASC-0002", "Empty Cells in Light", - "Cells in light must be empty.", - "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - initialBoard.fillWithLight(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); - if (finalCell.getType() == LightUpCellType.EMPTY && initCell.getType() == LightUpCellType.UNKNOWN && initCell.isLite()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.lightup.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; +import edu.rpi.legup.puzzle.lightup.LightUpCell; +import edu.rpi.legup.puzzle.lightup.LightUpCellType; + +public class EmptyCellinLightDirectRule extends DirectRule { + + public EmptyCellinLightDirectRule() { + super("LTUP-BASC-0002", "Empty Cells in Light", + "Cells in light must be empty.", + "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + initialBoard.fillWithLight(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); + if (finalCell.getType() == LightUpCellType.EMPTY && initCell.getType() == LightUpCellType.UNKNOWN && initCell.isLite()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java index 04c493f08..173c15fd2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java @@ -1,115 +1,115 @@ -package edu.rpi.legup.puzzle.lightup.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import edu.rpi.legup.puzzle.lightup.LightUpCell; -import edu.rpi.legup.puzzle.lightup.LightUpCellType; - -import java.awt.*; -import java.util.ArrayList; -import java.util.List; - -public class EmptyCornersDirectRule extends DirectRule { - - public EmptyCornersDirectRule() { - super("LTUP-BASC-0003", "Empty Corners", - "Cells on the corners of a number must be empty if placing bulbs would prevent the number from being satisfied.", - "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - - if (!(cell.getType() == LightUpCellType.UNKNOWN && finalCell.getType() == LightUpCellType.EMPTY)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; - } - - Point loc = finalCell.getLocation(); - List numberedCells = new ArrayList<>(); - LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); - if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperRight); - } - LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); - if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperLeft); - } - LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); - if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerRight); - } - LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); - if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerLeft); - } - if (numberedCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() + ": This cell must diagonal to a numbered cell"; - } - - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - LightUpBoard bulbCaseBoard = finalBoard.copy(); - LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); - bulbCaseCell.setData(LightUpCellType.BULB.value); - bulbCaseBoard.fillWithLight(); - - boolean createsContra = false; - for (LightUpCell c : numberedCells) { - createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; - } - if (createsContra) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; - } - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); - TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); - for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - int temp = cell.getData(); - cell.setData(LightUpCellType.EMPTY.value); - if (checkRuleRawAt(transition, cell) == null) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(modCell); - } - else { - cell.setData(temp); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.lightup.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; +import edu.rpi.legup.puzzle.lightup.LightUpCell; +import edu.rpi.legup.puzzle.lightup.LightUpCellType; + +import java.awt.*; +import java.util.ArrayList; +import java.util.List; + +public class EmptyCornersDirectRule extends DirectRule { + + public EmptyCornersDirectRule() { + super("LTUP-BASC-0003", "Empty Corners", + "Cells on the corners of a number must be empty if placing bulbs would prevent the number from being satisfied.", + "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + + if (!(cell.getType() == LightUpCellType.UNKNOWN && finalCell.getType() == LightUpCellType.EMPTY)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; + } + + Point loc = finalCell.getLocation(); + List numberedCells = new ArrayList<>(); + LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); + if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperRight); + } + LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); + if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperLeft); + } + LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); + if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerRight); + } + LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); + if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerLeft); + } + if (numberedCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + ": This cell must diagonal to a numbered cell"; + } + + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + LightUpBoard bulbCaseBoard = finalBoard.copy(); + LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); + bulbCaseCell.setData(LightUpCellType.BULB.value); + bulbCaseBoard.fillWithLight(); + + boolean createsContra = false; + for (LightUpCell c : numberedCells) { + createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; + } + if (createsContra) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; + } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); + TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); + for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + int temp = cell.getData(); + cell.setData(LightUpCellType.EMPTY.value); + if (checkRuleRawAt(transition, cell) == null) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(modCell); + } + else { + cell.setData(temp); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java index cdea7880f..632a3e4dd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java @@ -1,107 +1,107 @@ -package edu.rpi.legup.puzzle.lightup.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import edu.rpi.legup.puzzle.lightup.LightUpCell; -import edu.rpi.legup.puzzle.lightup.LightUpCellType; - -import java.util.Set; - -public class FinishWithBulbsDirectRule extends DirectRule { - - public FinishWithBulbsDirectRule() { - super("LTUP-BASC-0004", "Finish with Bulbs", - "The remaining unknowns around a block must be bulbs to satisfy the number.", - "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == LightUpCellType.UNKNOWN && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; - } - - Set adjCells = finalBoard.getAdj(finalCell); - adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() + ": This cell is not adjacent to a numbered cell"; - } - - LightUpBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return null; - } - } - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; - } - - /** - * Determines whether the specified cell is forced to be a bulb or not - * - * @param board the entire board - * @param cell specified cell - * @return whether cell is forced to be a bulb or not - */ - private boolean isForced(LightUpBoard board, LightUpCell cell) { - Set adjCells = board.getAdj(cell); - adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return false; - } - - LightUpBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return true; - } - } - return false; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { - cell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.lightup.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; +import edu.rpi.legup.puzzle.lightup.LightUpCell; +import edu.rpi.legup.puzzle.lightup.LightUpCellType; + +import java.util.Set; + +public class FinishWithBulbsDirectRule extends DirectRule { + + public FinishWithBulbsDirectRule() { + super("LTUP-BASC-0004", "Finish with Bulbs", + "The remaining unknowns around a block must be bulbs to satisfy the number.", + "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == LightUpCellType.UNKNOWN && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } + + Set adjCells = finalBoard.getAdj(finalCell); + adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + ": This cell is not adjacent to a numbered cell"; + } + + LightUpBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return null; + } + } + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; + } + + /** + * Determines whether the specified cell is forced to be a bulb or not + * + * @param board the entire board + * @param cell specified cell + * @return whether cell is forced to be a bulb or not + */ + private boolean isForced(LightUpBoard board, LightUpCell cell) { + Set adjCells = board.getAdj(cell); + adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return false; + } + + LightUpBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return true; + } + } + return false; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { + cell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java index f7433150c..ca90d4e0a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java @@ -1,118 +1,118 @@ -package edu.rpi.legup.puzzle.lightup.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import edu.rpi.legup.puzzle.lightup.LightUpCell; -import edu.rpi.legup.puzzle.lightup.LightUpCellType; - -import java.awt.*; - -public class FinishWithEmptyDirectRule extends DirectRule { - - public FinishWithEmptyDirectRule() { - super("LTUP-BASC-0005", "Finish with Empty", - "The remaining unknowns around a block must be empty if the number is satisfied.", - "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.EMPTY) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; - } - - if (isForced(initialBoard, cell.getLocation())) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; - } - - /** - * Checks whether a certain cell is forced to not be a bulb - * - * @param board specified board - * @param location location of cell to check - * @return boolean value based on whether a certain cell has an adjacent cell that has the required amount of adjacent bulbs - */ - private boolean isForced(LightUpBoard board, Point location) { - return isForcedEmpty(board, new Point(location.x + 1, location.y)) || - isForcedEmpty(board, new Point(location.x, location.y + 1)) || - isForcedEmpty(board, new Point(location.x - 1, location.y)) || - isForcedEmpty(board, new Point(location.x, location.y - 1)); - } - - /** - * Checks whether a certain cell has the required amount of adjacent bulbs - * - * @param board specified board - * @param loc location of cell to check - * @return boolean value based on whether a certain cell has the required amount of adjacent bulbs - */ - private boolean isForcedEmpty(LightUpBoard board, Point loc) { - LightUpCell cell = board.getCell(loc.x, loc.y); - if (cell == null || cell.getType() != LightUpCellType.NUMBER) { - return false; - } - - int bulbs = 0; - int bulbsNeeded = cell.getData(); - cell = board.getCell(loc.x + 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y + 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x - 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y - 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - return bulbs == bulbsNeeded; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell.getLocation())) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.lightup.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; +import edu.rpi.legup.puzzle.lightup.LightUpCell; +import edu.rpi.legup.puzzle.lightup.LightUpCellType; + +import java.awt.*; + +public class FinishWithEmptyDirectRule extends DirectRule { + + public FinishWithEmptyDirectRule() { + super("LTUP-BASC-0005", "Finish with Empty", + "The remaining unknowns around a block must be empty if the number is satisfied.", + "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.EMPTY) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; + } + + if (isForced(initialBoard, cell.getLocation())) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; + } + + /** + * Checks whether a certain cell is forced to not be a bulb + * + * @param board specified board + * @param location location of cell to check + * @return boolean value based on whether a certain cell has an adjacent cell that has the required amount of adjacent bulbs + */ + private boolean isForced(LightUpBoard board, Point location) { + return isForcedEmpty(board, new Point(location.x + 1, location.y)) || + isForcedEmpty(board, new Point(location.x, location.y + 1)) || + isForcedEmpty(board, new Point(location.x - 1, location.y)) || + isForcedEmpty(board, new Point(location.x, location.y - 1)); + } + + /** + * Checks whether a certain cell has the required amount of adjacent bulbs + * + * @param board specified board + * @param loc location of cell to check + * @return boolean value based on whether a certain cell has the required amount of adjacent bulbs + */ + private boolean isForcedEmpty(LightUpBoard board, Point loc) { + LightUpCell cell = board.getCell(loc.x, loc.y); + if (cell == null || cell.getType() != LightUpCellType.NUMBER) { + return false; + } + + int bulbs = 0; + int bulbsNeeded = cell.getData(); + cell = board.getCell(loc.x + 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y + 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x - 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y - 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + return bulbs == bulbsNeeded; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell.getLocation())) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java index f0f943401..6b44fc0b7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java @@ -1,149 +1,149 @@ -package edu.rpi.legup.puzzle.lightup.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import edu.rpi.legup.puzzle.lightup.LightUpCell; -import edu.rpi.legup.puzzle.lightup.LightUpCellType; - -import java.awt.*; - -public class MustLightDirectRule extends DirectRule { - - public MustLightDirectRule() { - super("LTUP-BASC-0006", "Must Light", - "A cell must be a bulb if it is the only cell to be able to light another.", - "edu/rpi/legup/images/lightup/rules/MustLight.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == LightUpCellType.UNKNOWN && !parentCell.isLite() && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; - } - - finalBoard.fillWithLight(); - boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); - finalCell.setData(LightUpCellType.BULB.value); - finalBoard.fillWithLight(); - - if (isForced) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; - } - } - - private boolean isForcedBulb(LightUpBoard board, Point loc) { - CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); - LightUpBoard modifiedBoard = board.copy(); - LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); - modifiedCell.setData(LightUpCellType.EMPTY.value); - //Check if this cell itself (the one with the bulb) has no other lighting option - if ((modifiedCell.getType() == LightUpCellType.EMPTY || modifiedCell.getType() == LightUpCellType.UNKNOWN) && - !modifiedCell.isLite() && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { - return true; - } - //Look right - for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.EMPTY && - !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } - } - //Look left - for (int i = loc.x - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.EMPTY && - !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } - } - //Look down - for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.EMPTY && - !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } - } - //Look up - for (int i = loc.y - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.EMPTY && - !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } - } - return false; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : tempBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - if (isForcedBulb(initialBoard, cell.getLocation())) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(modCell); - } - cell.setData(LightUpCellType.UNKNOWN.value); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.lightup.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; +import edu.rpi.legup.puzzle.lightup.LightUpCell; +import edu.rpi.legup.puzzle.lightup.LightUpCellType; + +import java.awt.*; + +public class MustLightDirectRule extends DirectRule { + + public MustLightDirectRule() { + super("LTUP-BASC-0006", "Must Light", + "A cell must be a bulb if it is the only cell to be able to light another.", + "edu/rpi/legup/images/lightup/rules/MustLight.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(parentCell.getType() == LightUpCellType.UNKNOWN && !parentCell.isLite() && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } + + finalBoard.fillWithLight(); + boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); + finalCell.setData(LightUpCellType.BULB.value); + finalBoard.fillWithLight(); + + if (isForced) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; + } + } + + private boolean isForcedBulb(LightUpBoard board, Point loc) { + CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); + LightUpBoard modifiedBoard = board.copy(); + LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); + modifiedCell.setData(LightUpCellType.EMPTY.value); + //Check if this cell itself (the one with the bulb) has no other lighting option + if ((modifiedCell.getType() == LightUpCellType.EMPTY || modifiedCell.getType() == LightUpCellType.UNKNOWN) && + !modifiedCell.isLite() && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { + return true; + } + //Look right + for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } + else { + if (c.getType() == LightUpCellType.EMPTY && + !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } + } + //Look left + for (int i = loc.x - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } + else { + if (c.getType() == LightUpCellType.EMPTY && + !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } + } + //Look down + for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } + else { + if (c.getType() == LightUpCellType.EMPTY && + !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } + } + //Look up + for (int i = loc.y - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } + else { + if (c.getType() == LightUpCellType.EMPTY && + !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } + } + return false; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : tempBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + if (isForcedBulb(initialBoard, cell.getLocation())) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(modCell); + } + cell.setData(LightUpCellType.UNKNOWN.value); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java index b35dceaa7..f9f29be75 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java @@ -1,42 +1,42 @@ -package edu.rpi.legup.puzzle.masyu.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class BlackEdgeDirectRule extends DirectRule { - - public BlackEdgeDirectRule() { - super("MASY-BASC-0001", "Black Edge", - "", - "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.masyu.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class BlackEdgeDirectRule extends DirectRule { + + public BlackEdgeDirectRule() { + super("MASY-BASC-0001", "Black Edge", + "", + "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java index 4364d016c..6b191fee7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java @@ -1,42 +1,42 @@ -package edu.rpi.legup.puzzle.masyu.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class BlockedBlackDirectRule extends DirectRule { - - public BlockedBlackDirectRule() { - super("MASY-BASC-0002", "Blocked Black", - "", - "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.masyu.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class BlockedBlackDirectRule extends DirectRule { + + public BlockedBlackDirectRule() { + super("MASY-BASC-0002", "Blocked Black", + "", + "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java index 49949ecec..ad1e6a264 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java @@ -1,42 +1,42 @@ -package edu.rpi.legup.puzzle.masyu.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class ConnectedCellsDirectRule extends DirectRule { - - public ConnectedCellsDirectRule() { - super("MASY-BASC-0003", "Connected Cells", - "", - "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.masyu.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class ConnectedCellsDirectRule extends DirectRule { + + public ConnectedCellsDirectRule() { + super("MASY-BASC-0003", "Connected Cells", + "", + "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java index e04301ce2..9fe7f3fa7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java @@ -1,42 +1,42 @@ -package edu.rpi.legup.puzzle.masyu.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class FinishPathDirectRule extends DirectRule { - - public FinishPathDirectRule() { - super("MASY-BASC-0004", "Finished Path", - "", - "edu/rpi/legup/images/masyu/RuleFinishPath.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.masyu.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class FinishPathDirectRule extends DirectRule { + + public FinishPathDirectRule() { + super("MASY-BASC-0004", "Finished Path", + "", + "edu/rpi/legup/images/masyu/RuleFinishPath.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java index 7cf707d0d..e6ecd872b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java @@ -1,42 +1,42 @@ -package edu.rpi.legup.puzzle.masyu.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class NearWhiteDirectRule extends DirectRule { - - public NearWhiteDirectRule() { - super("MASY-BASC-0005", "Near White", - "", - "edu/rpi/legup/images/masyu/RuleNearWhite.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.masyu.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class NearWhiteDirectRule extends DirectRule { + + public NearWhiteDirectRule() { + super("MASY-BASC-0005", "Near White", + "", + "edu/rpi/legup/images/masyu/RuleNearWhite.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java index b0311e741..017768867 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java @@ -1,42 +1,42 @@ -package edu.rpi.legup.puzzle.masyu.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class OnlyOneChoiceDirectRule extends DirectRule { - - public OnlyOneChoiceDirectRule() { - super("MASY-BASC-0006", "Only One Choice", - "", - "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.masyu.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class OnlyOneChoiceDirectRule extends DirectRule { + + public OnlyOneChoiceDirectRule() { + super("MASY-BASC-0006", "Only One Choice", + "", + "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java index bd894e1d4..67488775e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java @@ -1,41 +1,41 @@ -package edu.rpi.legup.puzzle.masyu.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; - -public class WhiteEdgeDirectRule extends DirectRule { - public WhiteEdgeDirectRule() { - super("MASY-BASC-0007", "White Edge", - "", - "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.masyu.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; + +public class WhiteEdgeDirectRule extends DirectRule { + public WhiteEdgeDirectRule() { + super("MASY-BASC-0007", "White Edge", + "", + "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * This method is the one that should overridden in child classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java index bb527e4e2..62d305048 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java @@ -1,112 +1,112 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; -import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; -import edu.rpi.legup.utility.DisjointSets; - -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; - -public class BlackBetweenRegionsDirectRule extends DirectRule { - - public BlackBetweenRegionsDirectRule() { - super("NURI-BASC-0001", - "Black Between Regions", - "Any unknowns between two regions must be black.", - "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new MultipleNumbersContradictionRule()); - contras.add(new TooManySpacesContradictionRule()); - - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } - - int x = cell.getLocation().x; - int y = cell.getLocation().y; - - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adjacentWhiteRegions = new HashSet<>(); - NurikabeCell upCell = destBoardState.getCell(x, y - 1); - NurikabeCell rightCell = destBoardState.getCell(x + 1, y); - NurikabeCell downCell = destBoardState.getCell(x, y + 1); - NurikabeCell leftCell = destBoardState.getCell(x - 1, y); - - if (upCell != null && (upCell.getType() == NurikabeType.WHITE || upCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(upCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (rightCell != null && (rightCell.getType() == NurikabeType.WHITE || rightCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(rightCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (downCell != null && (downCell.getType() == NurikabeType.WHITE || downCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(downCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (leftCell != null && (leftCell.getType() == NurikabeType.WHITE || leftCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(leftCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - - if (adjacentWhiteRegions.size() < 2) { - return "The new black cell must separate two white regions for this rule!"; - } - - NurikabeBoard modified = origBoardState.copy(); - modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); - - for (ContradictionRule c : contras) { - if (c.checkContradiction(modified) == null) { - return null; - } - } - return "Does not follow from the rule"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; +import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; +import edu.rpi.legup.utility.DisjointSets; + +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; + +public class BlackBetweenRegionsDirectRule extends DirectRule { + + public BlackBetweenRegionsDirectRule() { + super("NURI-BASC-0001", + "Black Between Regions", + "Any unknowns between two regions must be black.", + "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new MultipleNumbersContradictionRule()); + contras.add(new TooManySpacesContradictionRule()); + + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; + } + + int x = cell.getLocation().x; + int y = cell.getLocation().y; + + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adjacentWhiteRegions = new HashSet<>(); + NurikabeCell upCell = destBoardState.getCell(x, y - 1); + NurikabeCell rightCell = destBoardState.getCell(x + 1, y); + NurikabeCell downCell = destBoardState.getCell(x, y + 1); + NurikabeCell leftCell = destBoardState.getCell(x - 1, y); + + if (upCell != null && (upCell.getType() == NurikabeType.WHITE || upCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(upCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (rightCell != null && (rightCell.getType() == NurikabeType.WHITE || rightCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(rightCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (downCell != null && (downCell.getType() == NurikabeType.WHITE || downCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(downCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (leftCell != null && (leftCell.getType() == NurikabeType.WHITE || leftCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(leftCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + + if (adjacentWhiteRegions.size() < 2) { + return "The new black cell must separate two white regions for this rule!"; + } + + NurikabeBoard modified = origBoardState.copy(); + modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); + + for (ContradictionRule c : contras) { + if (c.checkContradiction(modified) == null) { + return null; + } + } + return "Does not follow from the rule"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java index c4cf0d3fd..6eca91dbf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java @@ -1,65 +1,65 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; - -public class BlackBottleNeckDirectRule extends DirectRule { - - public BlackBottleNeckDirectRule() { - super("NURI-BASC-0002", - "Black Bottle Neck", - "If there is only one path for a black to escape, then those unknowns must be black.", - "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new IsolateBlackContradictionRule(); - - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); - - if (contraRule.checkContradiction(modified) == null) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This is not the only way for black to escape!"; - } - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; + +public class BlackBottleNeckDirectRule extends DirectRule { + + public BlackBottleNeckDirectRule() { + super("NURI-BASC-0002", + "Black Bottle Neck", + "If there is only one path for a black to escape, then those unknowns must be black.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new IsolateBlackContradictionRule(); + + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); + + if (contraRule.checkContradiction(modified) == null) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This is not the only way for black to escape!"; + } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java index e86724ed9..4c8f37e05 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java @@ -1,61 +1,61 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; - -public class CannotReachCellDirectRule extends DirectRule { - public CannotReachCellDirectRule() { - super("NURI-BASC-0008", - "Can't Reach Cell", - "A cell must be black if it cannot be reached by any white region", - "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); - - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } - - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeBoard modified = origBoardState.copy(); - - NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modifiedCell.setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; + +public class CannotReachCellDirectRule extends DirectRule { + public CannotReachCellDirectRule() { + super("NURI-BASC-0008", + "Can't Reach Cell", + "A cell must be black if it cannot be reached by any white region", + "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); + + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; + } + + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard modified = origBoardState.copy(); + + NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modifiedCell.setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java index 55316fcbb..fe79d8919 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java @@ -1,108 +1,108 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; -import edu.rpi.legup.utility.ConnectedRegions; - -import java.awt.*; -import java.util.Set; - -public class CornerBlackDirectRule extends DirectRule { - - public CornerBlackDirectRule() { - super("NURI-BASC-0003", - "Corners Black", - "If there is only one white square connected to unknowns and one more white is needed then the angles of that white square are black", - "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } - - ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); - Point cellLocation = cell.getLocation(); - // 1. Find the coordinates of the white space (should be a corner of cell) - for (int i = -1; i < 2; i += 2) { - for (int j = -1; j < 2; j += 2) { - // If the corner does not exist, skip the corner - if (!(cellLocation.x + i >= 0 && cellLocation.x + i < board.getWidth() && cellLocation.y + j >= 0 && cellLocation.y + j < board.getHeight())) { - continue; - } - - NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); - NurikabeType cornerType = corner.getType(); - if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { - Point cornerLocation = corner.getLocation(); - // 2. Check if the intersecting adjacent spaces of the white space and the black corner are empty - if (board.getCell(cornerLocation.x, cellLocation.y).getType() == NurikabeType.UNKNOWN && board.getCell(cellLocation.x, cornerLocation.y).getType() == NurikabeType.UNKNOWN) { - // System.out.println("Went inside if statement"); - NurikabeBoard modified = board.copy(); - modified.getCell(cornerLocation.x, cellLocation.y).setData(NurikabeType.BLACK.toValue()); - modified.getCell(cellLocation.x, cornerLocation.y).setData(NurikabeType.BLACK.toValue()); - boolean containsContradiction = tooFewContra.checkContradiction(modified) == null; - if (containsContradiction) { - // 3. Check if the connected region is 1 under what is needed - Set region = ConnectedRegions.getRegionAroundPoint(cornerLocation, NurikabeType.BLACK.toValue(), modified.getIntArray(), modified.getWidth(), modified.getHeight()); - int regionNumber = 0; - // System.out.println("Region set size: " + region.size()); - for (Point p : region) { - NurikabeCell pCell = modified.getCell(p.x, p.y); - if (pCell.getType() == NurikabeType.NUMBER) { - if (regionNumber == 0) { - regionNumber = pCell.getData(); - } - else { - return "There is a MultipleNumbers Contradiction on the board."; - } - } - } - // If the region size is 0, there is a possibility that there was only 1 cell in the white - // region, and that white cell was a NurikabeType.NUMBER cell - if (regionNumber == 0 && corner.getType() == NurikabeType.NUMBER && corner.getData() == 2) { - return null; - } - // If the region size is not 0, make sure the regionNumber and the region size match (need - // to add 1 to account for the cell that was surrounded - if (regionNumber != 0 && region.size() + 1 == regionNumber) { - return null; - } - } - } - } - } - } - return "This is not a valid use of the corner black rule!"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; +import edu.rpi.legup.utility.ConnectedRegions; + +import java.awt.*; +import java.util.Set; + +public class CornerBlackDirectRule extends DirectRule { + + public CornerBlackDirectRule() { + super("NURI-BASC-0003", + "Corners Black", + "If there is only one white square connected to unknowns and one more white is needed then the angles of that white square are black", + "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } + + ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); + Point cellLocation = cell.getLocation(); + // 1. Find the coordinates of the white space (should be a corner of cell) + for (int i = -1; i < 2; i += 2) { + for (int j = -1; j < 2; j += 2) { + // If the corner does not exist, skip the corner + if (!(cellLocation.x + i >= 0 && cellLocation.x + i < board.getWidth() && cellLocation.y + j >= 0 && cellLocation.y + j < board.getHeight())) { + continue; + } + + NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); + NurikabeType cornerType = corner.getType(); + if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { + Point cornerLocation = corner.getLocation(); + // 2. Check if the intersecting adjacent spaces of the white space and the black corner are empty + if (board.getCell(cornerLocation.x, cellLocation.y).getType() == NurikabeType.UNKNOWN && board.getCell(cellLocation.x, cornerLocation.y).getType() == NurikabeType.UNKNOWN) { + // System.out.println("Went inside if statement"); + NurikabeBoard modified = board.copy(); + modified.getCell(cornerLocation.x, cellLocation.y).setData(NurikabeType.BLACK.toValue()); + modified.getCell(cellLocation.x, cornerLocation.y).setData(NurikabeType.BLACK.toValue()); + boolean containsContradiction = tooFewContra.checkContradiction(modified) == null; + if (containsContradiction) { + // 3. Check if the connected region is 1 under what is needed + Set region = ConnectedRegions.getRegionAroundPoint(cornerLocation, NurikabeType.BLACK.toValue(), modified.getIntArray(), modified.getWidth(), modified.getHeight()); + int regionNumber = 0; + // System.out.println("Region set size: " + region.size()); + for (Point p : region) { + NurikabeCell pCell = modified.getCell(p.x, p.y); + if (pCell.getType() == NurikabeType.NUMBER) { + if (regionNumber == 0) { + regionNumber = pCell.getData(); + } + else { + return "There is a MultipleNumbers Contradiction on the board."; + } + } + } + // If the region size is 0, there is a possibility that there was only 1 cell in the white + // region, and that white cell was a NurikabeType.NUMBER cell + if (regionNumber == 0 && corner.getType() == NurikabeType.NUMBER && corner.getData() == 2) { + return null; + } + // If the region size is not 0, make sure the regionNumber and the region size match (need + // to add 1 to account for the cell that was surrounded + if (regionNumber != 0 && region.size() + 1 == regionNumber) { + return null; + } + } + } + } + } + } + return "This is not a valid use of the corner black rule!"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java index aab389e4a..7e2568b58 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java @@ -1,60 +1,60 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; - -public class FillinBlackDirectRule extends DirectRule { - - public FillinBlackDirectRule() { - super("NURI-BASC-0004", - "Fill In Black", - "If there an unknown region surrounded by black, it must be black.", - "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new NoNumberContradictionRule(); - - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "Black cells must be placed in a region of black cells!"; - } - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; + +public class FillinBlackDirectRule extends DirectRule { + + public FillinBlackDirectRule() { + super("NURI-BASC-0004", + "Fill In Black", + "If there an unknown region surrounded by black, it must be black.", + "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new NoNumberContradictionRule(); + + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "Black cells must be placed in a region of black cells!"; + } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java index 4f57602d5..e5a901158 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java @@ -1,60 +1,60 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; - -public class FillinWhiteDirectRule extends DirectRule { - - public FillinWhiteDirectRule() { - super("NURI-BASC-0005", - "Fill In White", - "If there an unknown region surrounded by white, it must be white.", - "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new IsolateBlackContradictionRule(); - - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "white cells must be placed in a region of white cells!"; - } - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; + +public class FillinWhiteDirectRule extends DirectRule { + + public FillinWhiteDirectRule() { + super("NURI-BASC-0005", + "Fill In White", + "If there an unknown region surrounded by white, it must be white.", + "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new IsolateBlackContradictionRule(); + + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "white cells must be placed in a region of white cells!"; + } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java index 2502ee62f..eff0c8e1f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java @@ -1,66 +1,66 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; - -public class PreventBlackSquareDirectRule extends DirectRule { - - public PreventBlackSquareDirectRule() { - super("NURI-BASC-0006", - "Prevent Black Square", - "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", - "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new BlackSquareContradictionRule(); - - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); - - if (contraRule.checkContradiction(modified) == null) { - return null; - } - else { - return "Does not contain a contradiction at this index"; - } - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; + +public class PreventBlackSquareDirectRule extends DirectRule { + + public PreventBlackSquareDirectRule() { + super("NURI-BASC-0006", + "Prevent Black Square", + "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", + "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new BlackSquareContradictionRule(); + + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } + + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); + + if (contraRule.checkContradiction(modified) == null) { + return null; + } + else { + return "Does not contain a contradiction at this index"; + } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java index d992fd22c..9ee0ee245 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java @@ -1,95 +1,95 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; -import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; -import edu.rpi.legup.utility.DisjointSets; - -import java.util.Arrays; -import java.util.ArrayList; -import java.util.List; -import java.util.HashSet; -import java.util.Set; -import java.awt.*; - -public class SurroundRegionDirectRule extends DirectRule { - - public SurroundRegionDirectRule() { - super("NURI-BASC-0007", "Surround Region", - "Surround Region", - "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } - - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); - - if(cell.getType() == NurikabeType.BLACK) { - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adj = new HashSet<>(); //set to hold adjacent cells - Point loc = cell.getLocation(); //position of placed cell - List directions = Arrays.asList(new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); - for(Point direction : directions) { - NurikabeCell curr = destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); - if(curr != null) { - if(curr.getType() == NurikabeType.WHITE || curr.getType() == NurikabeType.NUMBER) { - adj.add(curr); //adds cells to adj only if they are white or number blocks - } - } - } - List numberedCells = new ArrayList<>(); //number value of number cells - for (NurikabeCell c : adj) { //loops through adjacent cells - Set disRow = regions.getSet(c); //set of white spaces - for (NurikabeCell d : disRow) { //loops through white spaces - if (d.getType() == NurikabeType.NUMBER) { //if the white space is a number - numberedCells.add(d); //add that number to numberedCells - } - } - } - for (NurikabeCell number : numberedCells) { //loops through numberedCells - if (regions.getSet(number).size() == number.getData()) { //if that cells white area is the exact - return null; //size of the number of one of the number cells within that set - } - } - } - return "Does not follow from this rule at this index"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; +import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; +import edu.rpi.legup.utility.DisjointSets; + +import java.util.Arrays; +import java.util.ArrayList; +import java.util.List; +import java.util.HashSet; +import java.util.Set; +import java.awt.*; + +public class SurroundRegionDirectRule extends DirectRule { + + public SurroundRegionDirectRule() { + super("NURI-BASC-0007", "Surround Region", + "Surround Region", + "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } + + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); + + if(cell.getType() == NurikabeType.BLACK) { + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adj = new HashSet<>(); //set to hold adjacent cells + Point loc = cell.getLocation(); //position of placed cell + List directions = Arrays.asList(new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); + for(Point direction : directions) { + NurikabeCell curr = destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); + if(curr != null) { + if(curr.getType() == NurikabeType.WHITE || curr.getType() == NurikabeType.NUMBER) { + adj.add(curr); //adds cells to adj only if they are white or number blocks + } + } + } + List numberedCells = new ArrayList<>(); //number value of number cells + for (NurikabeCell c : adj) { //loops through adjacent cells + Set disRow = regions.getSet(c); //set of white spaces + for (NurikabeCell d : disRow) { //loops through white spaces + if (d.getType() == NurikabeType.NUMBER) { //if the white space is a number + numberedCells.add(d); //add that number to numberedCells + } + } + } + for (NurikabeCell number : numberedCells) { //loops through numberedCells + if (regions.getSet(number).size() == number.getData()) { //if that cells white area is the exact + return null; //size of the number of one of the number cells within that set + } + } + } + return "Does not follow from this rule at this index"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java index dd337858c..7d10c36d0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java @@ -1,69 +1,69 @@ -package edu.rpi.legup.puzzle.nurikabe.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; - -import java.util.LinkedHashSet; -import java.util.Set; - -public class WhiteBottleNeckDirectRule extends DirectRule { - - public WhiteBottleNeckDirectRule() { - super("NURI-BASC-0009", - "White Bottle Neck", - "If a region needs more whites and there is only one path for the region to expand, then those unknowns must be white.", "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new NoNumberContradictionRule()); - contras.add(new TooFewSpacesContradictionRule()); - - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); - - for (ContradictionRule contraRule : contras) { - if (contraRule.checkContradiction(modified) == null) { - return null; - } - } - return "This is not the only way for white to escape!"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.nurikabe.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; + +import java.util.LinkedHashSet; +import java.util.Set; + +public class WhiteBottleNeckDirectRule extends DirectRule { + + public WhiteBottleNeckDirectRule() { + super("NURI-BASC-0009", + "White Bottle Neck", + "If a region needs more whites and there is only one path for the region to expand, then those unknowns must be white.", "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new NoNumberContradictionRule()); + contras.add(new TooFewSpacesContradictionRule()); + + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); + + for (ContradictionRule contraRule : contras) { + if (contraRule.checkContradiction(modified) == null) { + return null; + } + } + return "This is not the only way for white to escape!"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java index bc713d407..70011d5dd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java @@ -1,57 +1,57 @@ -package edu.rpi.legup.puzzle.shorttruthtable; - -import java.util.Collections; -import java.util.Map; -import java.util.TreeMap; - -public class ShortTruthTableOperation { - - public static final char AND = '^'; - public static final char OR = '|'; - public static final char NOT = '~'; - public static final char CONDITIONAL = '>'; - public static final char BICONDITIONAL = '-'; - - private ShortTruthTableOperation() { - } - - public static String getLogicSymbol(char c) { - switch (c) { - case AND: - return "\u2227"; - case OR: - return "\u2228"; - case NOT: - return "\u00AC"; - case CONDITIONAL: - return "\u2192"; - case BICONDITIONAL: - return "\u2194"; - } - return "" + c; - } - - public static String getRuleName(char operation) { - switch (operation) { - case AND: - return "And"; - case OR: - return "Or"; - case NOT: - return "Not"; - case CONDITIONAL: - return "Conditional"; - case BICONDITIONAL: - return "Biconditional"; - } - return null; - } - - public static boolean isOperation(char c) { - return c == AND || - c == OR || - c == NOT || - c == CONDITIONAL || - c == BICONDITIONAL; - } -} +package edu.rpi.legup.puzzle.shorttruthtable; + +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; + +public class ShortTruthTableOperation { + + public static final char AND = '^'; + public static final char OR = '|'; + public static final char NOT = '~'; + public static final char CONDITIONAL = '>'; + public static final char BICONDITIONAL = '-'; + + private ShortTruthTableOperation() { + } + + public static String getLogicSymbol(char c) { + switch (c) { + case AND: + return "\u2227"; + case OR: + return "\u2228"; + case NOT: + return "\u00AC"; + case CONDITIONAL: + return "\u2192"; + case BICONDITIONAL: + return "\u2194"; + } + return "" + c; + } + + public static String getRuleName(char operation) { + switch (operation) { + case AND: + return "And"; + case OR: + return "Or"; + case NOT: + return "Not"; + case CONDITIONAL: + return "Conditional"; + case BICONDITIONAL: + return "Biconditional"; + } + return null; + } + + public static boolean isOperation(char c) { + return c == AND || + c == OR || + c == NOT || + c == CONDITIONAL || + c == BICONDITIONAL; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java index 63e3c8dd9..3456d3aa0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleAnd; - -public class DirectRuleAndElimination extends DirectRule_GenericElimination { - - public DirectRuleAndElimination() { - super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleAnd; + +public class DirectRuleAndElimination extends DirectRule_GenericElimination { + + public DirectRuleAndElimination() { + super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java index 7f7336a4c..4d53d05cf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleBiconditional; - -public class DirectRuleBiconditionalElimination extends DirectRule_GenericElimination { - - public DirectRuleBiconditionalElimination() { - super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleBiconditional; + +public class DirectRuleBiconditionalElimination extends DirectRule_GenericElimination { + + public DirectRuleBiconditionalElimination() { + super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java index 8f15be021..c1c1720af 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleConditional; - -public class DirectRuleConditionalElimination extends DirectRule_GenericElimination { - - public DirectRuleConditionalElimination() { - super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleConditional; + +public class DirectRuleConditionalElimination extends DirectRule_GenericElimination { + + public DirectRuleConditionalElimination() { + super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java index a2f08635c..576cef6ec 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleNot; - -public class DirectRuleNotElimination extends DirectRule_GenericElimination { - - public DirectRuleNotElimination() { - super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleNot; + +public class DirectRuleNotElimination extends DirectRule_GenericElimination { + + public DirectRuleNotElimination() { + super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java index eca1848bd..c57266d0d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleOr; - -public class DirectRuleOrElimination extends DirectRule_GenericElimination { - - public DirectRuleOrElimination() { - super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleOr; + +public class DirectRuleOrElimination extends DirectRule_GenericElimination { + + public DirectRuleOrElimination() { + super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java index 49dc43510..e47c9d11c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java @@ -1,18 +1,18 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.basic.DirectRule_Generic; -import edu.rpi.legup.model.rules.ContradictionRule; - -public abstract class DirectRule_GenericElimination extends DirectRule_Generic { - - public DirectRule_GenericElimination(String ruleID, String ruleName, ContradictionRule contradictionRule) { - - super(ruleID, ruleName + " Elimination", - ruleName + " statements must have a valid pattern", - "elimination/" + ruleName, - contradictionRule, - true - ); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.basic.DirectRule_Generic; +import edu.rpi.legup.model.rules.ContradictionRule; + +public abstract class DirectRule_GenericElimination extends DirectRule_Generic { + + public DirectRule_GenericElimination(String ruleID, String ruleName, ContradictionRule contradictionRule) { + + super(ruleID, ruleName + " Elimination", + ruleName + " statements must have a valid pattern", + "elimination/" + ruleName, + contradictionRule, + true + ); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java index 0ca2a7dcf..03db396ad 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleAnd; - -public class DirectRuleAndIntroduction extends DirectRule_GenericIntroduction { - - public DirectRuleAndIntroduction() { - super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleAnd; + +public class DirectRuleAndIntroduction extends DirectRule_GenericIntroduction { + + public DirectRuleAndIntroduction() { + super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java index b72d5299c..74024c95d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleBiconditional; - -public class DirectRuleBiconditionalIntroduction extends DirectRule_GenericIntroduction { - - public DirectRuleBiconditionalIntroduction() { - super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleBiconditional; + +public class DirectRuleBiconditionalIntroduction extends DirectRule_GenericIntroduction { + + public DirectRuleBiconditionalIntroduction() { + super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java index 0e27d267c..2782098f3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleConditional; - -public class DirectRuleConditionalIntroduction extends DirectRule_GenericIntroduction { - - public DirectRuleConditionalIntroduction() { - super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleConditional; + +public class DirectRuleConditionalIntroduction extends DirectRule_GenericIntroduction { + + public DirectRuleConditionalIntroduction() { + super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java index 980a132fe..ca98cdc21 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleNot; - -public class DirectRuleNotIntroduction extends DirectRule_GenericIntroduction { - - public DirectRuleNotIntroduction() { - super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleNot; + +public class DirectRuleNotIntroduction extends DirectRule_GenericIntroduction { + + public DirectRuleNotIntroduction() { + super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java index 0fd7108bd..3c82faaf9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java @@ -1,11 +1,11 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleOr; - -public class DirectRuleOrIntroduction extends DirectRule_GenericIntroduction { - - public DirectRuleOrIntroduction() { - super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction.ContradictionRuleOr; + +public class DirectRuleOrIntroduction extends DirectRule_GenericIntroduction { + + public DirectRuleOrIntroduction() { + super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java index 123165d7a..9d6c3f7d4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java @@ -1,18 +1,18 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; - -import edu.rpi.legup.puzzle.shorttruthtable.rules.basic.DirectRule_Generic; -import edu.rpi.legup.model.rules.ContradictionRule; - -public abstract class DirectRule_GenericIntroduction extends DirectRule_Generic { - - protected DirectRule_GenericIntroduction(String ruleID, String ruleName, ContradictionRule contradictionRule) { - - super(ruleID, ruleName + " Introduction", - ruleName + " statements must have a valid pattern", - "introduction/" + ruleName, - contradictionRule, - false - ); - } - +package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; + +import edu.rpi.legup.puzzle.shorttruthtable.rules.basic.DirectRule_Generic; +import edu.rpi.legup.model.rules.ContradictionRule; + +public abstract class DirectRule_GenericIntroduction extends DirectRule_Generic { + + protected DirectRule_GenericIntroduction(String ruleID, String ruleName, ContradictionRule contradictionRule) { + + super(ruleID, ruleName + " Introduction", + ruleName + " statements must have a valid pattern", + "introduction/" + ruleName, + contradictionRule, + false + ); + } + } \ No newline at end of file diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java index 12fac9c4c..2b8d39b22 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java @@ -1,23 +1,23 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; - -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; - -public class CaseRuleAnd extends CaseRule_GenericStatement { - - public CaseRuleAnd() { - super("STTT-CASE-0001", ShortTruthTableOperation.AND, - "And", - trueCases, - falseCases); - } - - private static final ShortTruthTableCellType[][] trueCases = { - {T, T} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {F, U}, - {U, F} - }; - -} +package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; + +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; + +public class CaseRuleAnd extends CaseRule_GenericStatement { + + public CaseRuleAnd() { + super("STTT-CASE-0001", ShortTruthTableOperation.AND, + "And", + trueCases, + falseCases); + } + + private static final ShortTruthTableCellType[][] trueCases = { + {T, T} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {F, U}, + {U, F} + }; + +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java index a9fee2b4e..cb34bb6e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java @@ -1,23 +1,23 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; - -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; - -public class CaseRuleConditional extends CaseRule_GenericStatement { - - public CaseRuleConditional() { - super("STTT-CASE-0004", ShortTruthTableOperation.CONDITIONAL, - "Conditional", - trueCases, - falseCases); - } - - private static final ShortTruthTableCellType[][] trueCases = { - {U, T}, - {F, U} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - }; - -} +package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; + +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; + +public class CaseRuleConditional extends CaseRule_GenericStatement { + + public CaseRuleConditional() { + super("STTT-CASE-0004", ShortTruthTableOperation.CONDITIONAL, + "Conditional", + trueCases, + falseCases); + } + + private static final ShortTruthTableCellType[][] trueCases = { + {U, T}, + {F, U} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + }; + +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java index 82f814cc8..2a155a41a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java @@ -1,23 +1,23 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; - -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; - -public class CaseRuleOr extends CaseRule_GenericStatement { - - public CaseRuleOr() { - super("STTT-CASE-0005", ShortTruthTableOperation.OR, - "Or", - trueCases, - falseCases); - } - - private static final ShortTruthTableCellType[][] trueCases = { - {T, U}, - {U, T} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {F, F}, - }; - -} +package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; + +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; + +public class CaseRuleOr extends CaseRule_GenericStatement { + + public CaseRuleOr() { + super("STTT-CASE-0005", ShortTruthTableOperation.OR, + "Or", + trueCases, + falseCases); + } + + private static final ShortTruthTableCellType[][] trueCases = { + {T, U}, + {U, T} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {F, F}, + }; + +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java index 46163c2a3..1d8f54d62 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java @@ -1,71 +1,71 @@ -package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.CaseBoard; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.CaseRule; -import edu.rpi.legup.model.tree.TreeTransition; - -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; - - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.swing.JOptionPane; - -import com.google.firebase.database.core.utilities.Tree; - -public abstract class CaseRule_Generic extends CaseRule { - - public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { - super(ruleID, title, description, "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); - } - - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - // Validate that two children are generated - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "ERROR: This case rule must spawn at least 1 child."; - } - - // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE - // List cases = Arrays.asList(childTransitions.get(0), childTransitions.get(1)); - // for (TreeTransition c : cases) { - // ShortTruthTableCell mod1 = (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // ShortTruthTableCell mod2 = (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && - // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { - // return "ERROR: This case rule must be an unknown, true, or false cell."; - // } - // } - return null; - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } -} +package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.CaseBoard; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.CaseRule; +import edu.rpi.legup.model.tree.TreeTransition; + +import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; +import edu.rpi.legup.puzzle.nurikabe.NurikabeType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; + + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.swing.JOptionPane; + +import com.google.firebase.database.core.utilities.Tree; + +public abstract class CaseRule_Generic extends CaseRule { + + public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { + super(ruleID, title, description, "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); + } + + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + // Validate that two children are generated + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "ERROR: This case rule must spawn at least 1 child."; + } + + // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE + // List cases = Arrays.asList(childTransitions.get(0), childTransitions.get(1)); + // for (TreeTransition c : cases) { + // ShortTruthTableCell mod1 = (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // ShortTruthTableCell mod2 = (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && + // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { + // return "ERROR: This case rule must be an unknown, true, or false cell."; + // } + // } + return null; + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java index 2cede4117..6aed653f6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java @@ -1,114 +1,114 @@ -package edu.rpi.legup.puzzle.skyscrapers.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - -import java.util.ArrayList; - -public class LastSingularCellDirectRule extends DirectRule { - - public LastSingularCellDirectRule() { - super("SKYS-BASC-0002", "Last Cell for Number", - "There is only one cell on this row/col for this number that does not create a duplicate contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; - } - - //set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getWestClues().get(finalCell.getLocation().y), (Integer) finalCell.getData()); - ArrayList YCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getNorthClues().get(finalCell.getLocation().x), (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); - - //System.out.println(XCandidates.size()); - //System.out.println(YCandidates.size()); - - //return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; - } - - //helper to check if candidate list is valid - private String candidateCheck(ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; - } - return ": This cell is not forced."; - } - - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.skyscrapers.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; + +import java.util.ArrayList; + +public class LastSingularCellDirectRule extends DirectRule { + + public LastSingularCellDirectRule() { + super("SKYS-BASC-0002", "Last Cell for Number", + "There is only one cell on this row/col for this number that does not create a duplicate contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } + + //set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getWestClues().get(finalCell.getLocation().y), (Integer) finalCell.getData()); + ArrayList YCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getNorthClues().get(finalCell.getLocation().x), (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); + + //System.out.println(XCandidates.size()); + //System.out.println(YCandidates.size()); + + //return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; + } + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + } + + //helper to check if candidate list is valid + private String candidateCheck(ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; + } + return ": Wrong number in the cell."; + } + return ": No case for this cell."; + } + return ": This cell is not forced."; + } + + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + //System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + //cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java index 280325190..e9bacd7a6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java @@ -1,97 +1,97 @@ -package edu.rpi.legup.puzzle.skyscrapers.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - -import java.util.ArrayList; - -public class LastSingularNumberDirectRule extends DirectRule { - - public LastSingularNumberDirectRule() { - super("SKYS-BASC-0003", "Last Number for Cell", - "There is only one number for this cell that does not create a duplicate contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; - } - - //set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); - - //check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; - } - - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.skyscrapers.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; + +import java.util.ArrayList; + +public class LastSingularNumberDirectRule extends DirectRule { + + public LastSingularNumberDirectRule() { + super("SKYS-BASC-0003", "Last Number for Cell", + "There is only one number for this cell that does not create a duplicate contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; + } + + //set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); + + //check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; + } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + } + + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + //System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + //cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java index 3aa28bab8..62b22041e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java @@ -1,116 +1,116 @@ -package edu.rpi.legup.puzzle.skyscrapers.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - -import java.util.ArrayList; - -public class LastVisibleCellDirectRule extends DirectRule { - - public LastVisibleCellDirectRule() { - super("SKYS-BASC-0001", "Last Visible Cell", - "There is only one cell on this row/col for this number that does not create a visibility contradiction", - "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - //last cell for number based on preemptive visibility rules - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; - } - - //set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getWestClues().get(finalCell.getLocation().y), (Integer) finalCell.getData()); - ArrayList YCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getNorthClues().get(finalCell.getLocation().x), (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); - - //System.out.println(XCandidates.size()); - //System.out.println(YCandidates.size()); - - //return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; - } - - //helper to check if candidate list is valid - private String candidateCheck(ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; - } - return ": This cell is not forced."; - } - - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(modBoard.getPuzzleElements().size()); - for (PuzzleElement element : modBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - modBoard.addModifiedData(cell); - } - } - //System.out.println(modBoard.getModifiedData().isEmpty()); - if (modBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return modBoard; - } - } -} +package edu.rpi.legup.puzzle.skyscrapers.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; + +import java.util.ArrayList; + +public class LastVisibleCellDirectRule extends DirectRule { + + public LastVisibleCellDirectRule() { + super("SKYS-BASC-0001", "Last Visible Cell", + "There is only one cell on this row/col for this number that does not create a visibility contradiction", + "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + //last cell for number based on preemptive visibility rules + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; + } + + //set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getWestClues().get(finalCell.getLocation().y), (Integer) finalCell.getData()); + ArrayList YCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getNorthClues().get(finalCell.getLocation().x), (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); + + //System.out.println(XCandidates.size()); + //System.out.println(YCandidates.size()); + + //return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; + } + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + } + + //helper to check if candidate list is valid + private String candidateCheck(ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; + } + return ": Wrong number in the cell."; + } + return ": No case for this cell."; + } + return ": This cell is not forced."; + } + + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); + //System.out.println(modBoard.getPuzzleElements().size()); + for (PuzzleElement element : modBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + //cell.setData(SkyscrapersType.BULB.value); + modBoard.addModifiedData(cell); + } + } + //System.out.println(modBoard.getModifiedData().isEmpty()); + if (modBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return modBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java index e5524418d..255d1eab6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java @@ -1,98 +1,98 @@ -package edu.rpi.legup.puzzle.skyscrapers.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - -import java.util.ArrayList; - -public class LastVisibleNumberDirectRule extends DirectRule { - - public LastVisibleNumberDirectRule() { - super("SKYS-BASC-0005", "Last Visible Number", - "There is only one number for this cell that does not create a visibility contradiction", - "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - //last number for cell based upon preemptive visibility rules - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; - } - - //set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); - - //check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; - } - - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.skyscrapers.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; + +import java.util.ArrayList; + +public class LastVisibleNumberDirectRule extends DirectRule { + + public LastVisibleNumberDirectRule() { + super("SKYS-BASC-0005", "Last Visible Number", + "There is only one number for this cell that does not create a visibility contradiction", + "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + //last number for cell based upon preemptive visibility rules + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; + } + + //set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); + + //check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; + } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + } + + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + //System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + //cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java index 78533a819..db5d60440 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java @@ -1,99 +1,99 @@ -package edu.rpi.legup.puzzle.skyscrapers.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - -import java.awt.Point; - -public class NEdgeDirectRule extends DirectRule { - - public NEdgeDirectRule() { - super("SKYS-BASC-0004", "N Edge", - "If the maximum number appears on an edge, the row or column's numbers appear in ascending order, starting at that edge.", - "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; - } - - SkyscrapersBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); - Point loc = finalCell.getLocation(); - int max = initialBoard.getHeight(); - - if (initialBoard.getWestClues().get(loc.y).getData() == max && finalCell.getData() == loc.x + 1) { - return null; - } - if (initialBoard.getEastClues().get(loc.y).getData() == max && finalCell.getData() == max - loc.x) { - return null; - } - if (initialBoard.getNorthClues().get(loc.x).getData() == max && finalCell.getData() == loc.y + 1) { - return null; - } - if (initialBoard.getSouthClues().get(loc.x).getData() == max && finalCell.getData() == max - loc.y) { - return null; - } - - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; - - } - - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } - } -} +package edu.rpi.legup.puzzle.skyscrapers.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; +import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; + +import java.awt.Point; + +public class NEdgeDirectRule extends DirectRule { + + public NEdgeDirectRule() { + super("SKYS-BASC-0004", "N Edge", + "If the maximum number appears on an edge, the row or column's numbers appear in ascending order, starting at that edge.", + "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } + + SkyscrapersBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); + Point loc = finalCell.getLocation(); + int max = initialBoard.getHeight(); + + if (initialBoard.getWestClues().get(loc.y).getData() == max && finalCell.getData() == loc.x + 1) { + return null; + } + if (initialBoard.getEastClues().get(loc.y).getData() == max && finalCell.getData() == max - loc.x) { + return null; + } + if (initialBoard.getNorthClues().get(loc.x).getData() == max && finalCell.getData() == loc.y + 1) { + return null; + } + if (initialBoard.getSouthClues().get(loc.x).getData() == max && finalCell.getData() == max - loc.y) { + return null; + } + + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; + + } + + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + //System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + //cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return lightUpBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java index 0be30fa36..d3bca5d12 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java @@ -1,96 +1,96 @@ -package edu.rpi.legup.puzzle.sudoku.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.sudoku.SudokuBoard; -import edu.rpi.legup.puzzle.sudoku.SudokuCell; - -public class AdvancedDeductionDirectRule extends DirectRule { - - public AdvancedDeductionDirectRule() { - super("SUDO-BASC-0001", "Advanced Deduction", - "Use of group logic deduces more answers by means of forced by Location and forced by Deduction", - "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - int index = cell.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int relX = rowIndex / groupDim; - int relY = colIndex % groupDim; - int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; - boolean[][] possible = new boolean[groupDim][groupDim]; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - SudokuCell c = initialBoard.getCell(groupNum, x, y); - if (c.getData() == cell.getData() && x != relX && y != relY) { - return super.getRuleName() + ": Duplicate value in sub-region"; - } - possible[y][x] = c.getData() == 0; - } - } - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupSize; x++) { - SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); - SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); - if (r.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[y][i] = false; - } - } - if (c.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[i][y] = false; - } - } - } - } - boolean isForced = false; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - if (possible[y][x] && !isForced) { - isForced = true; - } - else { - if (possible[y][x]) { - return super.getInvalidUseOfRuleMessage() + ": Not forced"; - } - } - } - } - if (!isForced) { - return super.getInvalidUseOfRuleMessage() + ": Not forced"; - } - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.sudoku.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.sudoku.SudokuBoard; +import edu.rpi.legup.puzzle.sudoku.SudokuCell; + +public class AdvancedDeductionDirectRule extends DirectRule { + + public AdvancedDeductionDirectRule() { + super("SUDO-BASC-0001", "Advanced Deduction", + "Use of group logic deduces more answers by means of forced by Location and forced by Deduction", + "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + int index = cell.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int relX = rowIndex / groupDim; + int relY = colIndex % groupDim; + int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; + boolean[][] possible = new boolean[groupDim][groupDim]; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + SudokuCell c = initialBoard.getCell(groupNum, x, y); + if (c.getData() == cell.getData() && x != relX && y != relY) { + return super.getRuleName() + ": Duplicate value in sub-region"; + } + possible[y][x] = c.getData() == 0; + } + } + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupSize; x++) { + SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); + SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); + if (r.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[y][i] = false; + } + } + if (c.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[i][y] = false; + } + } + } + } + boolean isForced = false; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + if (possible[y][x] && !isForced) { + isForced = true; + } + else { + if (possible[y][x]) { + return super.getInvalidUseOfRuleMessage() + ": Not forced"; + } + } + } + } + if (!isForced) { + return super.getInvalidUseOfRuleMessage() + ": Not forced"; + } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java index 51d963247..501bfa86b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java @@ -1,93 +1,93 @@ -package edu.rpi.legup.puzzle.sudoku.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.sudoku.SudokuBoard; -import edu.rpi.legup.puzzle.sudoku.SudokuCell; - -import java.util.Set; - -public class LastCellForNumberDirectRule extends DirectRule { - public LastCellForNumberDirectRule() { - super("SUDO-BASC-0002", "Last Cell for Number", - "This is the only cell open in its group for some number.", - "edu/rpi/legup/images/sudoku/forcedByElimination.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; - } - - int size = initialBoard.getSize(); - - Set region = initialBoard.getRegion(cell.getGroupIndex()); - Set row = initialBoard.getRow(cell.getLocation().y); - Set col = initialBoard.getCol(cell.getLocation().x); - - boolean contains = false; - if (region.size() == size - 1) { - for (SudokuCell c : region) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } - } - if (row.size() == size - 1) { - contains = false; - for (SudokuCell c : row) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } - } - if (col.size() == size - 1) { - contains = false; - for (SudokuCell c : col) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } - } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.sudoku.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.sudoku.SudokuBoard; +import edu.rpi.legup.puzzle.sudoku.SudokuCell; + +import java.util.Set; + +public class LastCellForNumberDirectRule extends DirectRule { + public LastCellForNumberDirectRule() { + super("SUDO-BASC-0002", "Last Cell for Number", + "This is the only cell open in its group for some number.", + "edu/rpi/legup/images/sudoku/forcedByElimination.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } + + int size = initialBoard.getSize(); + + Set region = initialBoard.getRegion(cell.getGroupIndex()); + Set row = initialBoard.getRow(cell.getLocation().y); + Set col = initialBoard.getCol(cell.getLocation().x); + + boolean contains = false; + if (region.size() == size - 1) { + for (SudokuCell c : region) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } + } + if (row.size() == size - 1) { + contains = false; + for (SudokuCell c : row) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } + } + if (col.size() == size - 1) { + contains = false; + for (SudokuCell c : col) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } + } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java index 28e64ce7b..9a6834182 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java @@ -1,77 +1,77 @@ -package edu.rpi.legup.puzzle.sudoku.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.sudoku.SudokuBoard; -import edu.rpi.legup.puzzle.sudoku.SudokuCell; - -import java.util.HashSet; - -public class LastNumberForCellDirectRule extends DirectRule { - - public LastNumberForCellDirectRule() { - super("SUDO-BASC-0003", "Last Number for Cell", - "This is the only number left that can fit in the cell of a group.", - "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - - int index = puzzleElement.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; - HashSet numbers = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - numbers.add(i); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); - numbers.remove(cell.getData()); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(i, colIndex); - numbers.remove(cell.getData()); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(rowIndex, i); - numbers.remove(cell.getData()); - } - if (numbers.size() > 1) { - return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; - } - else { - if (numbers.size() == 1 && numbers.iterator().next() != finalBoard.getPuzzleElement(puzzleElement).getData()) { - return super.getInvalidUseOfRuleMessage() + ": The number at the index is forced but not correct"; - } - } - return null; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.sudoku.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.sudoku.SudokuBoard; +import edu.rpi.legup.puzzle.sudoku.SudokuCell; + +import java.util.HashSet; + +public class LastNumberForCellDirectRule extends DirectRule { + + public LastNumberForCellDirectRule() { + super("SUDO-BASC-0003", "Last Number for Cell", + "This is the only number left that can fit in the cell of a group.", + "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + + int index = puzzleElement.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; + HashSet numbers = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + numbers.add(i); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); + numbers.remove(cell.getData()); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(i, colIndex); + numbers.remove(cell.getData()); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(rowIndex, i); + numbers.remove(cell.getData()); + } + if (numbers.size() > 1) { + return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; + } + else { + if (numbers.size() == 1 && numbers.iterator().next() != finalBoard.getPuzzleElement(puzzleElement).getData()) { + return super.getInvalidUseOfRuleMessage() + ": The number at the index is forced but not correct"; + } + } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java index adfad52f6..6fec1ee0d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java @@ -1,87 +1,87 @@ -package edu.rpi.legup.puzzle.treetent.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentLine; -import edu.rpi.legup.puzzle.treetent.TreeTentType; - -import java.util.List; - -public class EmptyFieldDirectRule extends DirectRule { - public EmptyFieldDirectRule() { - super("TREE-BASC-0001", "Empty Field", - "Blank cells not adjacent to an unlinked tree are grass.", - "edu/rpi/legup/images/treetent/noTreesAround.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; - } - - if (isForced(finalBoard, finalCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; - } - } - - /** - * Returns a boolean value based on whether the specified cell has adjacent cells (true - no adjacent, false - has adjacent) - * - * @param board the TreeTent board - * @param cell the specified TreeTent cell - * @return true - no adjacent, false - has adjacent - */ - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjCells = board.getAdjacent(cell, TreeTentType.TREE); - return adjCells.isEmpty(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } - } -} +package edu.rpi.legup.puzzle.treetent.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.treetent.TreeTentBoard; +import edu.rpi.legup.puzzle.treetent.TreeTentCell; +import edu.rpi.legup.puzzle.treetent.TreeTentLine; +import edu.rpi.legup.puzzle.treetent.TreeTentType; + +import java.util.List; + +public class EmptyFieldDirectRule extends DirectRule { + public EmptyFieldDirectRule() { + super("TREE-BASC-0001", "Empty Field", + "Blank cells not adjacent to an unlinked tree are grass.", + "edu/rpi/legup/images/treetent/noTreesAround.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; + } + + if (isForced(finalBoard, finalCell)) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; + } + } + + /** + * Returns a boolean value based on whether the specified cell has adjacent cells (true - no adjacent, false - has adjacent) + * + * @param board the TreeTent board + * @param cell the specified TreeTent cell + * @return true - no adjacent, false - has adjacent + */ + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjCells = board.getAdjacent(cell, TreeTentType.TREE); + return adjCells.isEmpty(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return treeTentBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java index 40ee11e99..69b5d8ca2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java @@ -1,86 +1,86 @@ -package edu.rpi.legup.puzzle.treetent.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentLine; -import edu.rpi.legup.puzzle.treetent.TreeTentType; - -import java.awt.*; -import java.util.List; - -public class FinishWithGrassDirectRule extends DirectRule { - - public FinishWithGrassDirectRule() { - super("TREE-BASC-0002", "Finish with Grass", - "Grass can be added to finish a row or column that has reached its tent limit.", - "edu/rpi/legup/images/treetent/finishGrass.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; - } - - if (isForced(initialBoard, initCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; - } - } - - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - - return tentsRow.size() >= board.getRowClues().get(loc.y).getData() || - tentsCol.size() >= board.getColClues().get(loc.x).getData(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } - } -} +package edu.rpi.legup.puzzle.treetent.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.treetent.TreeTentBoard; +import edu.rpi.legup.puzzle.treetent.TreeTentCell; +import edu.rpi.legup.puzzle.treetent.TreeTentLine; +import edu.rpi.legup.puzzle.treetent.TreeTentType; + +import java.awt.*; +import java.util.List; + +public class FinishWithGrassDirectRule extends DirectRule { + + public FinishWithGrassDirectRule() { + super("TREE-BASC-0002", "Finish with Grass", + "Grass can be added to finish a row or column that has reached its tent limit.", + "edu/rpi/legup/images/treetent/finishGrass.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; + } + + if (isForced(initialBoard, initCell)) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; + } + } + + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + + return tentsRow.size() >= board.getRowClues().get(loc.y).getData() || + tentsCol.size() >= board.getColClues().get(loc.x).getData(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return treeTentBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java index 145a9760a..3a782e191 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java @@ -1,88 +1,88 @@ -package edu.rpi.legup.puzzle.treetent.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentLine; -import edu.rpi.legup.puzzle.treetent.TreeTentType; - -import java.awt.*; -import java.util.List; - -public class FinishWithTentsDirectRule extends DirectRule { - - public FinishWithTentsDirectRule() { - super("TREE-BASC-0003", "Finish with Tents", - "Tents can be added to finish a row or column that has one open spot per required tent.", - "edu/rpi/legup/images/treetent/finishTent.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } - - if (isForced(initialBoard, initCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } - - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); - - return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() || - unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } - } -} +package edu.rpi.legup.puzzle.treetent.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.treetent.TreeTentBoard; +import edu.rpi.legup.puzzle.treetent.TreeTentCell; +import edu.rpi.legup.puzzle.treetent.TreeTentLine; +import edu.rpi.legup.puzzle.treetent.TreeTentType; + +import java.awt.*; +import java.util.List; + +public class FinishWithTentsDirectRule extends DirectRule { + + public FinishWithTentsDirectRule() { + super("TREE-BASC-0003", "Finish with Tents", + "Tents can be added to finish a row or column that has one open spot per required tent.", + "edu/rpi/legup/images/treetent/finishTent.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } + + if (isForced(initialBoard, initCell)) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; + } + } + + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); + + return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() || + unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return treeTentBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java index ffb33e4c0..3be401fd0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java @@ -1,102 +1,102 @@ -package edu.rpi.legup.puzzle.treetent.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentLine; -import edu.rpi.legup.puzzle.treetent.TreeTentType; - -import java.util.List; - -public class LastCampingSpotDirectRule extends DirectRule { - - public LastCampingSpotDirectRule() { - super("TREE-BASC-0004", "Last Camping Spot", - "If an unlinked tree is adjacent to only one blank cell and not adjacent to any unlinked tents, the blank cell must be a tent.", - "edu/rpi/legup/images/treetent/oneTentPosition.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } - - if (isForced(finalBoard, finalCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } - - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); - for (TreeTentCell c : adjTrees) { - List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); - List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); - if (unkAroundTree.size() == 0) { - if (tntAroundTree.size() == 1) { - return true; - } - else { - for (TreeTentCell t : tntAroundTree) { - if (t == cell) { - continue; - } - List treesAroundTents = board.getAdjacent(t, TreeTentType.TREE); - if (treesAroundTents.size() == 1) { - return false; - } - } - return true; - } - } - } - return false; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } - } -} +package edu.rpi.legup.puzzle.treetent.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.treetent.TreeTentBoard; +import edu.rpi.legup.puzzle.treetent.TreeTentCell; +import edu.rpi.legup.puzzle.treetent.TreeTentLine; +import edu.rpi.legup.puzzle.treetent.TreeTentType; + +import java.util.List; + +public class LastCampingSpotDirectRule extends DirectRule { + + public LastCampingSpotDirectRule() { + super("TREE-BASC-0004", "Last Camping Spot", + "If an unlinked tree is adjacent to only one blank cell and not adjacent to any unlinked tents, the blank cell must be a tent.", + "edu/rpi/legup/images/treetent/oneTentPosition.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } + + if (isForced(finalBoard, finalCell)) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; + } + } + + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); + for (TreeTentCell c : adjTrees) { + List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); + List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); + if (unkAroundTree.size() == 0) { + if (tntAroundTree.size() == 1) { + return true; + } + else { + for (TreeTentCell t : tntAroundTree) { + if (t == cell) { + continue; + } + List treesAroundTents = board.getAdjacent(t, TreeTentType.TREE); + if (treesAroundTents.size() == 1) { + return false; + } + } + return true; + } + } + } + return false; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return treeTentBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java index 44e9dfcc4..01f9e7058 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java @@ -1,85 +1,85 @@ -package edu.rpi.legup.puzzle.treetent.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentLine; -import edu.rpi.legup.puzzle.treetent.TreeTentType; - -import java.util.List; - -public class SurroundTentWithGrassDirectRule extends DirectRule { - - public SurroundTentWithGrassDirectRule() { - super("TREE-BASC-0005", "Surround Tent with Grass", - "Blank cells adjacent or diagonal to a tent are grass.", - "edu/rpi/legup/images/treetent/aroundTent.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement == null) { - return null; - } - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.GRASS)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } - - if (isForced(initialBoard, initCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } - - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List tents = board.getAdjacent(cell, TreeTentType.TENT); - tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); - return !tents.isEmpty(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } - } -} +package edu.rpi.legup.puzzle.treetent.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.treetent.TreeTentBoard; +import edu.rpi.legup.puzzle.treetent.TreeTentCell; +import edu.rpi.legup.puzzle.treetent.TreeTentLine; +import edu.rpi.legup.puzzle.treetent.TreeTentType; + +import java.util.List; + +public class SurroundTentWithGrassDirectRule extends DirectRule { + + public SurroundTentWithGrassDirectRule() { + super("TREE-BASC-0005", "Surround Tent with Grass", + "Blank cells adjacent or diagonal to a tent are grass.", + "edu/rpi/legup/images/treetent/aroundTent.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement == null) { + return null; + } + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.GRASS)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } + + if (isForced(initialBoard, initCell)) { + return null; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; + } + } + + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List tents = board.getAdjacent(cell, TreeTentType.TENT); + tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); + return !tents.isEmpty(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } + else { + return treeTentBoard; + } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java index 03a83e516..fd10c5d73 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java @@ -1,124 +1,124 @@ -package edu.rpi.legup.puzzle.treetent.rules; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentLine; -import edu.rpi.legup.puzzle.treetent.TreeTentType; - -import java.util.ArrayList; - -import java.util.List; - -public class TentForTreeDirectRule extends DirectRule { - - public TentForTreeDirectRule() { - super("TREE-BASC-0006", "Tent for Tree", - "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the unlinked tree must link to the unlinked tent.", - "edu/rpi/legup/images/treetent/NewTreeLink.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } - else { - if (line.getC2().getType() == TreeTentType.TREE && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } - else { - return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; - } - } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; - } - else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; - } - else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This tree and tent don't need to be linked."; - } - } - } - } - - private Integer isForced(TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTents = board.getAdjacent(tree, TreeTentType.TENT); - adjTents.remove(tent); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTents) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tree.getLocation())) { - return -1; - } - toRemove.add(c); - - } - else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tree.getLocation())) { - return -1; - } - toRemove.add(c); - } - } - } - for (TreeTentCell c : toRemove) { - adjTents.remove(c); - } - toRemove.clear(); - } - if (adjTents.size() == 0) { - return 1; - } - else { - return 0; - } - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.treetent.rules; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.treetent.TreeTentBoard; +import edu.rpi.legup.puzzle.treetent.TreeTentCell; +import edu.rpi.legup.puzzle.treetent.TreeTentLine; +import edu.rpi.legup.puzzle.treetent.TreeTentType; + +import java.util.ArrayList; + +import java.util.List; + +public class TentForTreeDirectRule extends DirectRule { + + public TentForTreeDirectRule() { + super("TREE-BASC-0006", "Tent for Tree", + "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the unlinked tree must link to the unlinked tent.", + "edu/rpi/legup/images/treetent/NewTreeLink.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); + } + else { + if (line.getC2().getType() == TreeTentType.TREE && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } + else { + return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } + else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } + else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This tree and tent don't need to be linked."; + } + } + } + } + + private Integer isForced(TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTents = board.getAdjacent(tree, TreeTentType.TENT); + adjTents.remove(tent); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTents) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); + + } + else { + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); + } + } + } + for (TreeTentCell c : toRemove) { + adjTents.remove(c); + } + toRemove.clear(); + } + if (adjTents.size() == 0) { + return 1; + } + else { + return 0; + } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java index 63d43e9a4..62e1af51c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java @@ -1,122 +1,122 @@ -package edu.rpi.legup.puzzle.treetent.rules; - -import java.util.List; -import java.util.ArrayList; - -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.treetent.TreeTentLine; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentType; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; - -public class TreeForTentDirectRule extends DirectRule { - public TreeForTentDirectRule() { - super("TREE-BASC-0007", "Tree for Tent", - "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must link to the unlinked tree.", - "edu/rpi/legup/images/treetent/NewTentLink.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } - else { - if (line.getC2().getType() == TreeTentType.TREE && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } - else { - return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; - } - } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; - } - else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; - } - else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This tree and tent don't need to be linked."; - } - } - } - } - - private Integer isForced(TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); - adjTrees.remove(tree); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTrees) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tent.getLocation())) { - return -1; - } - toRemove.add(c); - - } - else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tent.getLocation())) { - return -1; - } - toRemove.add(c); - } - } - } - for (TreeTentCell c : toRemove) { - adjTrees.remove(c); - } - toRemove.clear(); - } - if (adjTrees.size() == 0) { - return 1; - } - else { - return 0; - } - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} +package edu.rpi.legup.puzzle.treetent.rules; + +import java.util.List; +import java.util.ArrayList; + +import edu.rpi.legup.model.gameboard.Board; +import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.treetent.TreeTentLine; +import edu.rpi.legup.puzzle.treetent.TreeTentBoard; +import edu.rpi.legup.puzzle.treetent.TreeTentType; +import edu.rpi.legup.puzzle.treetent.TreeTentCell; + +public class TreeForTentDirectRule extends DirectRule { + public TreeForTentDirectRule() { + super("TREE-BASC-0007", "Tree for Tent", + "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must link to the unlinked tree.", + "edu/rpi/legup/images/treetent/NewTentLink.png"); + } + + /** + * Checks whether the child node logically follows from the parent node + * at the specific puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); + } + else { + if (line.getC2().getType() == TreeTentType.TREE && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } + else { + return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } + else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } + else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } + else { + return super.getInvalidUseOfRuleMessage() + ": This tree and tent don't need to be linked."; + } + } + } + } + + private Integer isForced(TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); + adjTrees.remove(tree); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTrees) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); + + } + else { + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); + } + } + } + for (TreeTentCell c : toRemove) { + adjTrees.remove(c); + } + toRemove.clear(); + } + if (adjTrees.size() == 0) { + return 1; + } + else { + return 0; + } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java index 3d0672525..2f165b55d 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java @@ -1,22 +1,22 @@ -package edu.rpi.legup.ui.proofeditorui.rulesview; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.ImageIcon; - -public class DirectRulePanel extends RulePanel { - private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); - - /** - * DirectRulePanel Constructor creates a basic rule panel - * - * @param ruleFrame rule frame that this basic rule panel is contained in - */ - DirectRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = new ImageIcon(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Direct Rules"; - this.toolTip = "Direct Rules"; - } +package edu.rpi.legup.ui.proofeditorui.rulesview; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.swing.ImageIcon; + +public class DirectRulePanel extends RulePanel { + private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); + + /** + * DirectRulePanel Constructor creates a basic rule panel + * + * @param ruleFrame rule frame that this basic rule panel is contained in + */ + DirectRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = new ImageIcon(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Direct Rules"; + this.toolTip = "Direct Rules"; + } } \ No newline at end of file diff --git a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java index 7e8b5eb83..18ee3d42b 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java @@ -1,190 +1,190 @@ -package puzzles.nurikabe.rules; - -//import javafx.scene.layout.Pane; - -import legup.MockGameBoardFacade; -import legup.TestUtilities; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import edu.rpi.legup.puzzle.nurikabe.Nurikabe; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; -import edu.rpi.legup.puzzle.nurikabe.rules.BlackBetweenRegionsDirectRule; -import edu.rpi.legup.save.InvalidFileFormatException; - -import java.awt.*; - -public class BlackBetweenRegionsDirectRuleTest { - - private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other (diagonal going from top left to bottom right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(2, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(1, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other (diagonal going from bottom left to top right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(1, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(2, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - } - - /** - * Tests the Black Between Regions direct rule for regions that are horizontally opposite each other - */ - @Test - public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - } - - /** - * Tests the Black Between Regions direct rule for regions that are vertically opposite each other - */ - @Test - public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - } - - /** - * Tests the Black Between Regions direct rule for a false application of the rule, where a black tile is enclosed by one region - */ - @Test - public void BlackBetweenRegionsDirectRule_FalseBlackBetweenRegionsTest() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/FalseBlackBetweenRegions",nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1,1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for(int i=0; i Date: Thu, 8 Feb 2024 08:26:55 -0500 Subject: [PATCH 11/54] Test command syntax --- .github/workflows/java-autoformat.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 6ef290cb0..a5ed51a37 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -20,7 +20,7 @@ jobs: run: chmod +x gradlew - name: Run spotless - run: ./gradlew spotlessApply + run: ./gradlew :spotlessApply - name: Check for modified files id: git-check From 4d556fe6ac319559fc575050fd74b18607fd5de6 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 08:31:57 -0500 Subject: [PATCH 12/54] Correctly Identify modified files --- .github/workflows/java-autoformat.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index a5ed51a37..4a2ff2b0d 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -24,7 +24,7 @@ jobs: - name: Check for modified files id: git-check - run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_OUTPUT + run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_ENV - name: Push changes if: steps.git-check.outputs.modified == 'true' From bbe699b014da91b954056609feaf7d1564509557 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 08:34:03 -0500 Subject: [PATCH 13/54] Test autoformatter --- .../edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java index 65f5eb561..a727c8627 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java @@ -97,9 +97,8 @@ public int getSize() { @Override public PuzzleElement getPuzzleElement(PuzzleElement element) { // If the element index is -2, it is a clue and should be returned separately - if (element.getIndex() == -2) { + if (element.getIndex() == -2) return element; - } return super.getPuzzleElement(element); } From e7eca252e0a740e47d38a4c26ca8871b2325a3de Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 08:41:16 -0500 Subject: [PATCH 14/54] Test autoformatter --- .github/workflows/java-autoformat.yml | 7 ++++++- .../edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 4a2ff2b0d..8d1464e0f 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -24,7 +24,12 @@ jobs: - name: Check for modified files id: git-check - run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_ENV + run: | + if git diff-index --quiet HEAD --; then + echo "false" >> $GITHUB_OUTPUT + else + echo "true" >> $GITHUB_OUTPUT + fi - name: Push changes if: steps.git-check.outputs.modified == 'true' diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java index a727c8627..65f5eb561 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java @@ -97,8 +97,9 @@ public int getSize() { @Override public PuzzleElement getPuzzleElement(PuzzleElement element) { // If the element index is -2, it is a clue and should be returned separately - if (element.getIndex() == -2) + if (element.getIndex() == -2) { return element; + } return super.getPuzzleElement(element); } From 5850b268e531a3bbf9e12ffb9a79515f7d05aee9 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 08:43:43 -0500 Subject: [PATCH 15/54] Test autoformatter --- .github/workflows/java-autoformat.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 8d1464e0f..d98df1af8 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -26,9 +26,9 @@ jobs: id: git-check run: | if git diff-index --quiet HEAD --; then - echo "false" >> $GITHUB_OUTPUT + echo "modified=false" >> $GITHUB_OUTPUT else - echo "true" >> $GITHUB_OUTPUT + echo "modified=true" >> $GITHUB_OUTPUT fi - name: Push changes From e5e3221b0a8e41edd8793279d927a6ed1951cb77 Mon Sep 17 00:00:00 2001 From: jadeandtea <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 13:00:43 -0500 Subject: [PATCH 16/54] Debugging --- .github/workflows/java-autoformat.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index d98df1af8..e97b4dff6 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -11,7 +11,7 @@ jobs: with: ref: ${{ github.head_ref }} - - name: Set up JDK 21 + - name: Set up JDK 11 uses: actions/setup-java@v1 with: java-version: 11 @@ -25,6 +25,7 @@ jobs: - name: Check for modified files id: git-check run: | + git diff-index HEAD if git diff-index --quiet HEAD --; then echo "modified=false" >> $GITHUB_OUTPUT else From bb9c82e2d1a27c0b53e6bb31745dc04e151bbb65 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 13:12:01 -0500 Subject: [PATCH 17/54] Debugging --- .github/workflows/java-autoformat.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index e97b4dff6..22c052abe 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -4,10 +4,11 @@ on: pull_request jobs: format: runs-on: ubuntu-latest + # Check if the PR is not from a fork if: github.event.pull_request.head.repo.full_name == github.repository steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v1 with: ref: ${{ github.head_ref }} @@ -25,7 +26,6 @@ jobs: - name: Check for modified files id: git-check run: | - git diff-index HEAD if git diff-index --quiet HEAD --; then echo "modified=false" >> $GITHUB_OUTPUT else From 3330a5a737ca38593fead7eabf3dbed5a682e47b Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 13:15:06 -0500 Subject: [PATCH 18/54] Change method for detecting changed files --- .github/workflows/java-autoformat.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 22c052abe..f14462313 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -26,14 +26,16 @@ jobs: - name: Check for modified files id: git-check run: | - if git diff-index --quiet HEAD --; then - echo "modified=false" >> $GITHUB_OUTPUT + LOCAL=$(git rev-parse HEAD) + REMOTE=$(git rev-parse origin/main) + if [ "$LOCAL" == "$REMOTE" ]; then + echo "::set-output name=up-to-date::true" else - echo "modified=true" >> $GITHUB_OUTPUT + echo "::set-output name=up-to-date::false" fi - name: Push changes - if: steps.git-check.outputs.modified == 'true' + if: steps.git-check.outputs.up-to-date == 'false' run: | git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' From b33ba207553e0bcfa064c0107ff2edb07fa990ad Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Thu, 8 Feb 2024 15:49:16 -0500 Subject: [PATCH 19/54] Try building before calling spotless --- .github/workflows/java-autoformat.yml | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index f14462313..9a1b1c933 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -20,22 +20,18 @@ jobs: - name: Grant execute permission for gradlew run: chmod +x gradlew + - name: Build with Gradle + run: ./gradlew build -x test + - name: Run spotless run: ./gradlew :spotlessApply - name: Check for modified files id: git-check - run: | - LOCAL=$(git rev-parse HEAD) - REMOTE=$(git rev-parse origin/main) - if [ "$LOCAL" == "$REMOTE" ]; then - echo "::set-output name=up-to-date::true" - else - echo "::set-output name=up-to-date::false" - fi + run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_OUTPUT - name: Push changes - if: steps.git-check.outputs.up-to-date == 'false' + if: steps.git-check.outputs.modified == 'true' run: | git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' From 6fb587ffaa54bbed929f8a121f5831ccad59f1a3 Mon Sep 17 00:00:00 2001 From: Charles Tian <46334090+charlestian23@users.noreply.github.com> Date: Tue, 13 Feb 2024 14:44:33 -0500 Subject: [PATCH 20/54] Update java-autoformat.yml --- .github/workflows/java-autoformat.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 9a1b1c933..e75b63525 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -36,5 +36,4 @@ jobs: git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' git remote set-url origin https://x-access-token:${{ secrets.AUTO_FORMAT_SECRET }}@github.com/${{ github.repository }} - git commit -am "Automated Java code formatting changes" - git push \ No newline at end of file + git diff --cached --exit-code || git commit -m "Automated Java code formatting changes" && git push From 932daebf1c179b25c72c3f7c040b296272d3c6ec Mon Sep 17 00:00:00 2001 From: Charles Tian <46334090+charlestian23@users.noreply.github.com> Date: Tue, 13 Feb 2024 14:58:49 -0500 Subject: [PATCH 21/54] Update java-autoformat.yml --- .github/workflows/java-autoformat.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index e75b63525..5b282d386 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -36,4 +36,4 @@ jobs: git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' git remote set-url origin https://x-access-token:${{ secrets.AUTO_FORMAT_SECRET }}@github.com/${{ github.repository }} - git diff --cached --exit-code || git commit -m "Automated Java code formatting changes" && git push + git diff --cached --exit-code || git commit -am "Automated Java code formatting changes" && git push From ecfc69e4789092621f6b5b3806e3ffe60c7fa564 Mon Sep 17 00:00:00 2001 From: Charles Tian <46334090+charlestian23@users.noreply.github.com> Date: Tue, 13 Feb 2024 15:10:01 -0500 Subject: [PATCH 22/54] Update java-autoformat.yml --- .github/workflows/java-autoformat.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 5b282d386..ee16d7dd0 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -35,5 +35,5 @@ jobs: run: | git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.AUTO_FORMAT_SECRET }}@github.com/${{ github.repository }} + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} git diff --cached --exit-code || git commit -am "Automated Java code formatting changes" && git push From 05bed9f6871db8965195050d763481c59e5ee6a1 Mon Sep 17 00:00:00 2001 From: Charles Tian <46334090+charlestian23@users.noreply.github.com> Date: Tue, 13 Feb 2024 15:14:11 -0500 Subject: [PATCH 23/54] Purposely bad formatting Purposely adding some bad formatting to see if the auto-formatter triggers --- .../rpi/legup/history/ApplyDefaultDirectRuleCommand.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java index ae53b89f3..8089b202d 100644 --- a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java @@ -46,8 +46,10 @@ public String getErrorString() { TreeElement element = view.getTreeElement(); if (element.getType() == TreeElementType.NODE) { TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); + if (!node.getChildren().isEmpty()) + { + + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); } else { if (rule.getDefaultBoard(node) == null) { From 92ed81167b0ae6b0f049f7c62fc625705b49ba2d Mon Sep 17 00:00:00 2001 From: Charles Tian <46334090+charlestian23@users.noreply.github.com> Date: Tue, 13 Feb 2024 15:18:21 -0500 Subject: [PATCH 24/54] Update build.gradle Disabling Checkstyle in build so the auto-formatter can trigger --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 1891c4edd..5c0df4b28 100644 --- a/build.gradle +++ b/build.gradle @@ -15,7 +15,7 @@ version '2.0.0' apply plugin: 'java' apply plugin: 'application' -apply plugin: 'checkstyle' +// apply plugin: 'checkstyle' mainClassName = 'edu.rpi.legup.Legup' sourceCompatibility = 11 From 25b884e6dbab502b9d168b6d453805665be68896 Mon Sep 17 00:00:00 2001 From: Charles Tian <46334090+charlestian23@users.noreply.github.com> Date: Tue, 13 Feb 2024 15:22:04 -0500 Subject: [PATCH 25/54] Update java-autoformat.yml Have auto-formatter trigger when more commits are added to a pull request --- .github/workflows/java-autoformat.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index ee16d7dd0..a77f2efbd 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -1,5 +1,7 @@ name: Java Code Auto Format -on: pull_request +on: + pull_request_target: + types: [opened, synchronize] jobs: format: From 26b53f11004f51b10f918a40b33c7a4a1362315c Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 15:28:43 -0500 Subject: [PATCH 26/54] Debugging --- .github/workflows/java-autoformat.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index a77f2efbd..33dd56e41 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -6,18 +6,16 @@ on: jobs: format: runs-on: ubuntu-latest - # Check if the PR is not from a fork - if: github.event.pull_request.head.repo.full_name == github.repository steps: - name: Checkout code - uses: actions/checkout@v1 + uses: actions/checkout@v2 with: - ref: ${{ github.head_ref }} + ref: ${{ github.event.pull_request.head.sha }} - name: Set up JDK 11 uses: actions/setup-java@v1 with: - java-version: 11 + java-version: 11 - name: Grant execute permission for gradlew run: chmod +x gradlew From bbd679ae98c54628a154a1996b46ca189849f2b0 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 15:30:07 -0500 Subject: [PATCH 27/54] Adding more awful formatting --- .../edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java index 8089b202d..77e229dfb 100644 --- a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java @@ -49,7 +49,7 @@ public String getErrorString() { if (!node.getChildren().isEmpty()) { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); } else { if (rule.getDefaultBoard(node) == null) { From ba776d085884e45ff5a5679d5c21226796ff9ad7 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 15:31:04 -0500 Subject: [PATCH 28/54] Update java-autoformat.yml --- .github/workflows/java-autoformat.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 33dd56e41..2b01be26d 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -1,7 +1,5 @@ name: Java Code Auto Format -on: - pull_request_target: - types: [opened, synchronize] +on: pull_request jobs: format: From 1a8af741cf5312afd6201b2b3892d8845a0ade6b Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 15:34:08 -0500 Subject: [PATCH 29/54] Changing repo URL --- .github/workflows/java-autoformat.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 2b01be26d..a907877d4 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -33,5 +33,5 @@ jobs: run: | git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} + git remote set-url origin https://${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} git diff --cached --exit-code || git commit -am "Automated Java code formatting changes" && git push From b43f50ff8cff253b85cd7f1d8e43547acad84294 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 15:36:47 -0500 Subject: [PATCH 30/54] Going back to checkout v1 --- .github/workflows/java-autoformat.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index a907877d4..321b7c6e7 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -6,9 +6,9 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v1 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.head_ref }} - name: Set up JDK 11 uses: actions/setup-java@v1 From 112937e6d493ab77b0914c3bcd75098fedc0399e Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 15:39:51 -0500 Subject: [PATCH 31/54] Trying URL change --- .github/workflows/java-autoformat.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 321b7c6e7..eb2b30c8f 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -33,5 +33,5 @@ jobs: run: | git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' - git remote set-url origin https://${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} git diff --cached --exit-code || git commit -am "Automated Java code formatting changes" && git push From ac6ee768112abde9d726e23be89557e86edab0b9 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 15:44:15 -0500 Subject: [PATCH 32/54] Trying out using env --- .github/workflows/java-autoformat.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index eb2b30c8f..9189cdf9b 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -33,5 +33,7 @@ jobs: run: | git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} +# git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} git diff --cached --exit-code || git commit -am "Automated Java code formatting changes" && git push + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file From 872a268531bb89c16023981b3641cbff139c68f3 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 15:59:07 -0500 Subject: [PATCH 33/54] Trying this now...? --- .github/workflows/java-autoformat.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/java-autoformat.yml b/.github/workflows/java-autoformat.yml index 9189cdf9b..5afb1f7a1 100644 --- a/.github/workflows/java-autoformat.yml +++ b/.github/workflows/java-autoformat.yml @@ -33,7 +33,6 @@ jobs: run: | git config --global user.name 'Bram van Heuveln' git config --global user.email 'bram28@users.noreply.github.com' -# git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} - git diff --cached --exit-code || git commit -am "Automated Java code formatting changes" && git push - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} + git add . + git diff --cached --exit-code || git commit -am "Automated Java code formatting changes" && git push \ No newline at end of file From c707f57cbdeeb6ca98e9fa4d85457ca46b22b31f Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Tue, 13 Feb 2024 16:01:13 -0500 Subject: [PATCH 34/54] Introducing more horrible changes --- .../edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java index 77e229dfb..f3bca611e 100644 --- a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java @@ -48,7 +48,9 @@ public String getErrorString() { TreeNode node = (TreeNode) element; if (!node.getChildren().isEmpty()) { - + + + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); } else { From 9936767843c6a4331191eae4129c919b781c0da0 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 18:14:20 -0500 Subject: [PATCH 35/54] Spotless formatting using google format v1.19.2 --- build.gradle | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 5c0df4b28..f7bde7b55 100644 --- a/build.gradle +++ b/build.gradle @@ -2,20 +2,42 @@ plugins { id 'java' id 'edu.sc.seis.launch4j' version '2.5.3' id 'kr.motd.sphinx' version '2.10.0' - id 'com.diffplug.spotless' version '5.14.2' + id 'com.diffplug.spotless' version '6.25.0' } -spotless { - java { - target '**/*.java' - } -} version '2.0.0' apply plugin: 'java' apply plugin: 'application' // apply plugin: 'checkstyle' + +spotless{ + enforceCheck false + + format 'misc', { + // define the files to apply `misc` to + target '*.gradle', '*.md', '.gitignore' + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithSpaces() // or spaces. Takes an integer argument if you don't like 4 + endWithNewline() + } + + java{ + importOrder() + + removeUnusedImports() + + cleanthat() + + formatAnnotations() + + googleJavaFormat('1.19.2') + } +} + mainClassName = 'edu.rpi.legup.Legup' sourceCompatibility = 11 From f6c5453e4842985549e7e329c3b427c6538a46ee Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 18:15:19 -0500 Subject: [PATCH 36/54] Manual formatting fix --- .../edu/rpi/legup/puzzle/sudoku/SudokuCellController.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java index 18b6cd0a8..b25ddfe08 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java @@ -1,12 +1,5 @@ package edu.rpi.legup.puzzle.sudoku; -/*import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; - - -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.treetent.TreeTentCell;*/ - import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.gameboard.PuzzleElement; From 3eddb778f97545bbb2a1d450b5d6cbe578d05c51 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln Date: Tue, 13 Feb 2024 23:17:01 +0000 Subject: [PATCH 37/54] Automated Java code formatting changes --- src/main/java/edu/rpi/legup/Legup.java | 22 +- src/main/java/edu/rpi/legup/ai/Solver.java | 3 +- src/main/java/edu/rpi/legup/app/Config.java | 257 ++- .../edu/rpi/legup/app/GameBoardFacade.java | 913 ++++---- .../rpi/legup/app/InvalidConfigException.java | 6 +- .../edu/rpi/legup/app/LegupPreferences.java | 217 +- .../rpi/legup/app/PuzzleKeyAccelerator.java | 178 +- .../rpi/legup/controller/BoardController.java | 181 +- .../edu/rpi/legup/controller/Controller.java | 231 +- .../legup/controller/CursorController.java | 73 +- .../controller/EditorElementController.java | 87 +- .../legup/controller/ElementController.java | 606 +++--- .../rpi/legup/controller/RuleController.java | 188 +- .../legup/controller/ToolbarController.java | 40 +- .../rpi/legup/controller/TreeController.java | 290 +-- .../legup/history/AddTreeElementCommand.java | 179 +- .../ApplyDefaultDirectRuleCommand.java | 209 +- .../legup/history/AutoCaseRuleCommand.java | 237 +-- .../edu/rpi/legup/history/CommandError.java | 45 +- .../edu/rpi/legup/history/CommandState.java | 21 +- .../history/DeleteTreeElementCommand.java | 170 +- .../rpi/legup/history/EditDataCommand.java | 285 ++- .../java/edu/rpi/legup/history/History.java | 159 +- .../java/edu/rpi/legup/history/ICommand.java | 45 +- .../rpi/legup/history/IHistoryListener.java | 46 +- .../rpi/legup/history/IHistorySubject.java | 36 +- .../InvalidCommandStateTransition.java | 13 +- .../edu/rpi/legup/history/MergeCommand.java | 230 +- .../edu/rpi/legup/history/PuzzleCommand.java | 169 +- .../history/ValidateCaseRuleCommand.java | 226 +- .../ValidateContradictionRuleCommand.java | 275 ++- .../history/ValidateDirectRuleCommand.java | 250 ++- src/main/java/edu/rpi/legup/model/Puzzle.java | 1235 ++++++----- .../edu/rpi/legup/model/PuzzleExporter.java | 248 ++- .../edu/rpi/legup/model/PuzzleImporter.java | 704 +++--- .../edu/rpi/legup/model/RegisterPuzzle.java | 4 +- .../edu/rpi/legup/model/elements/Element.java | 112 +- .../rpi/legup/model/elements/ElementType.java | 3 +- .../model/elements/NonPlaceableElement.java | 9 +- .../model/elements/PlaceableElement.java | 9 +- .../legup/model/elements/RegisterElement.java | 4 +- .../edu/rpi/legup/model/gameboard/Board.java | 414 ++-- .../rpi/legup/model/gameboard/CaseBoard.java | 91 +- .../legup/model/gameboard/ElementFactory.java | 40 +- .../rpi/legup/model/gameboard/GridBoard.java | 279 +-- .../rpi/legup/model/gameboard/GridCell.java | 111 +- .../legup/model/gameboard/PuzzleElement.java | 357 ++-- .../legup/model/observer/IBoardListener.java | 36 +- .../legup/model/observer/IBoardSubject.java | 36 +- .../legup/model/observer/ITreeListener.java | 42 +- .../legup/model/observer/ITreeSubject.java | 36 +- .../edu/rpi/legup/model/rules/CaseRule.java | 248 +-- .../legup/model/rules/ContradictionRule.java | 181 +- .../edu/rpi/legup/model/rules/DirectRule.java | 175 +- .../edu/rpi/legup/model/rules/MergeRule.java | 160 +- .../rpi/legup/model/rules/RegisterRule.java | 4 +- .../java/edu/rpi/legup/model/rules/Rule.java | 314 ++- .../edu/rpi/legup/model/rules/RuleType.java | 5 +- .../java/edu/rpi/legup/model/tree/Tree.java | 353 ++- .../edu/rpi/legup/model/tree/TreeElement.java | 113 +- .../rpi/legup/model/tree/TreeElementType.java | 3 +- .../edu/rpi/legup/model/tree/TreeNode.java | 610 +++--- .../rpi/legup/model/tree/TreeTransition.java | 794 ++++--- .../rpi/legup/puzzle/PuzzleElementTypes.java | 3 +- .../legup/puzzle/battleship/Battleship.java | 286 +-- .../puzzle/battleship/BattleshipBoard.java | 275 ++- .../puzzle/battleship/BattleshipCell.java | 59 +- .../battleship/BattleshipCellController.java | 64 +- .../battleship/BattleshipCellFactory.java | 111 +- .../puzzle/battleship/BattleshipClue.java | 124 +- .../puzzle/battleship/BattleshipClueView.java | 98 +- .../battleship/BattleshipElementView.java | 158 +- .../puzzle/battleship/BattleshipExporter.java | 101 +- .../puzzle/battleship/BattleshipImporter.java | 348 ++- .../puzzle/battleship/BattleshipType.java | 71 +- .../puzzle/battleship/BattleshipView.java | 33 +- .../rules/AdjacentShipsContradictionRule.java | 132 +- .../rules/ContinueShipDirectRule.java | 61 +- .../rules/FinishWithShipsDirectRule.java | 167 +- .../rules/FinishWithWaterDirectRule.java | 61 +- .../IncompleteShipContradictionRule.java | 38 +- .../battleship/rules/SegmentTypeCaseRule.java | 107 +- .../rules/SegmentTypeDirectRule.java | 61 +- .../rules/ShipLocationCaseRule.java | 107 +- .../battleship/rules/ShipOrWaterCaseRule.java | 107 +- .../rules/SurroundShipDirectRule.java | 61 +- .../rules/TooFewInFleetContradictionRule.java | 38 +- .../rules/TooFewRowColContradictionRule.java | 38 +- .../TooManyInFleetContradictionRule.java | 38 +- .../rules/TooManyRowColContradiction.java | 38 +- .../rpi/legup/puzzle/fillapix/Fillapix.java | 102 +- .../legup/puzzle/fillapix/FillapixBoard.java | 99 +- .../legup/puzzle/fillapix/FillapixCell.java | 162 +- .../fillapix/FillapixCellController.java | 74 +- .../puzzle/fillapix/FillapixCellFactory.java | 109 +- .../puzzle/fillapix/FillapixCellType.java | 18 +- .../puzzle/fillapix/FillapixElementView.java | 99 +- .../puzzle/fillapix/FillapixExporter.java | 53 +- .../puzzle/fillapix/FillapixImporter.java | 186 +- .../puzzle/fillapix/FillapixUtilities.java | 382 ++-- .../legup/puzzle/fillapix/FillapixView.java | 25 +- .../puzzle/fillapix/elements/BlackTile.java | 10 +- .../puzzle/fillapix/elements/NumberTile.java | 39 +- .../puzzle/fillapix/elements/UnknownTile.java | 10 +- .../puzzle/fillapix/elements/WhiteTile.java | 10 +- .../fillapix/rules/BlackOrWhiteCaseRule.java | 128 +- .../rules/FinishWithBlackDirectRule.java | 90 +- .../rules/FinishWithWhiteDirectRule.java | 90 +- .../fillapix/rules/MirrorDirectRule.java | 159 +- .../rules/NonTouchingSharedDirectRule.java | 152 +- .../fillapix/rules/SatisfyClueCaseRule.java | 390 ++-- .../TooFewBlackCellsContradictionRule.java | 77 +- .../TooManyBlackCellsContradictionRule.java | 71 +- .../rules/TouchingCornersDirectRule.java | 169 +- .../rules/TouchingSidesDirectRule.java | 187 +- .../rpi/legup/puzzle/heyawake/Heyawake.java | 106 +- .../legup/puzzle/heyawake/HeyawakeBoard.java | 81 +- .../legup/puzzle/heyawake/HeyawakeCell.java | 33 +- .../puzzle/heyawake/HeyawakeController.java | 3 +- .../puzzle/heyawake/HeyawakeElementView.java | 73 +- .../puzzle/heyawake/HeyawakeExporter.java | 53 +- .../puzzle/heyawake/HeyawakeFactory.java | 115 +- .../puzzle/heyawake/HeyawakeImporter.java | 170 +- .../legup/puzzle/heyawake/HeyawakeView.java | 70 +- .../AdjacentBlacksContradictionRule.java | 37 +- .../heyawake/rules/BlackOrWhiteCaseRule.java | 107 +- .../heyawake/rules/BlackPathDirectRule.java | 6 +- .../heyawake/rules/BottleNeckDirectRule.java | 6 +- .../rules/FillRoomBlackDirectRule.java | 61 +- .../rules/FillRoomWhiteDirectRule.java | 61 +- .../heyawake/rules/OneRowDirectRule.java | 6 +- .../rules/PreventWhiteLineDirectRule.java | 6 +- .../rules/RoomTooEmptyContradictionRule.java | 38 +- .../rules/RoomTooFullContradictionRule.java | 38 +- .../rules/ThreeByThreeDirectRule.java | 6 +- .../heyawake/rules/TwoInCornerDirectRule.java | 6 +- .../rules/WhiteAreaContradictionRule.java | 38 +- .../rules/WhiteAroundBlackDirectRule.java | 61 +- .../heyawake/rules/WhiteEscapeDirectRule.java | 6 +- .../rules/WhiteLineContradictionRule.java | 39 +- .../puzzle/heyawake/rules/ZigZagCaseRule.java | 6 +- .../heyawake/rules/ZigZagWhiteDirectRule.java | 6 +- .../edu/rpi/legup/puzzle/lightup/LightUp.java | 135 +- .../legup/puzzle/lightup/LightUpBoard.java | 288 +-- .../rpi/legup/puzzle/lightup/LightUpCell.java | 131 +- .../puzzle/lightup/LightUpCellController.java | 68 +- .../puzzle/lightup/LightUpCellFactory.java | 108 +- .../legup/puzzle/lightup/LightUpCellType.java | 14 +- .../puzzle/lightup/LightUpElementView.java | 138 +- .../legup/puzzle/lightup/LightUpExporter.java | 53 +- .../legup/puzzle/lightup/LightUpImporter.java | 190 +- .../rpi/legup/puzzle/lightup/LightUpView.java | 143 +- .../puzzle/lightup/elements/BlackTile.java | 7 +- .../puzzle/lightup/elements/BulbTile.java | 6 +- .../puzzle/lightup/elements/NumberTile.java | 24 +- .../puzzle/lightup/elements/UnknownTile.java | 10 +- .../rules/BulbsInPathContradictionRule.java | 124 +- .../CannotLightACellContradictionRule.java | 144 +- .../rules/EmptyCellinLightDirectRule.java | 95 +- .../lightup/rules/EmptyCornersDirectRule.java | 179 +- .../rules/FinishWithBulbsDirectRule.java | 167 +- .../rules/FinishWithEmptyDirectRule.java | 189 +- .../lightup/rules/LightOrEmptyCaseRule.java | 166 +- .../lightup/rules/MustLightDirectRule.java | 245 +-- .../lightup/rules/SatisfyNumberCaseRule.java | 594 +++--- .../rules/TooFewBulbsContradictionRule.java | 56 +- .../rules/TooManyBulbsContradictionRule.java | 94 +- .../legup/puzzle/masyu/EditLineCommand.java | 276 ++- .../edu/rpi/legup/puzzle/masyu/Masyu.java | 107 +- .../rpi/legup/puzzle/masyu/MasyuBoard.java | 84 +- .../edu/rpi/legup/puzzle/masyu/MasyuCell.java | 29 +- .../legup/puzzle/masyu/MasyuCellFactory.java | 107 +- .../legup/puzzle/masyu/MasyuController.java | 154 +- .../legup/puzzle/masyu/MasyuElementView.java | 83 +- .../rpi/legup/puzzle/masyu/MasyuExporter.java | 48 +- .../rpi/legup/puzzle/masyu/MasyuImporter.java | 169 +- .../edu/rpi/legup/puzzle/masyu/MasyuLine.java | 70 +- .../rpi/legup/puzzle/masyu/MasyuLineView.java | 37 +- .../edu/rpi/legup/puzzle/masyu/MasyuType.java | 30 +- .../edu/rpi/legup/puzzle/masyu/MasyuView.java | 75 +- .../rules/BadLoopingContradictionRule.java | 37 +- .../masyu/rules/BlackContradictionRule.java | 33 +- .../masyu/rules/BlackEdgeDirectRule.java | 56 +- .../masyu/rules/BlackSplitCaseRule.java | 102 +- .../masyu/rules/BlockedBlackDirectRule.java | 56 +- .../masyu/rules/ConnectedCellsDirectRule.java | 60 +- .../masyu/rules/FinishPathDirectRule.java | 56 +- .../masyu/rules/NearWhiteDirectRule.java | 56 +- .../rules/NoOptionsContradictionRule.java | 37 +- .../masyu/rules/NormalSplitCaseRule.java | 102 +- .../masyu/rules/OnlyOneChoiceDirectRule.java | 60 +- .../masyu/rules/OnlyTwoContradictionRule.java | 33 +- .../masyu/rules/WhiteContradictionRule.java | 33 +- .../masyu/rules/WhiteEdgeDirectRule.java | 56 +- .../masyu/rules/WhiteSplitCaseRule.java | 102 +- .../rpi/legup/puzzle/nurikabe/Nurikabe.java | 130 +- .../legup/puzzle/nurikabe/NurikabeBoard.java | 82 +- .../legup/puzzle/nurikabe/NurikabeCell.java | 157 +- .../puzzle/nurikabe/NurikabeCellFactory.java | 109 +- .../puzzle/nurikabe/NurikabeController.java | 68 +- .../puzzle/nurikabe/NurikabeElementView.java | 106 +- .../puzzle/nurikabe/NurikabeExporter.java | 52 +- .../puzzle/nurikabe/NurikabeImporter.java | 188 +- .../legup/puzzle/nurikabe/NurikabeType.java | 11 +- .../puzzle/nurikabe/NurikabeUtilities.java | 559 ++--- .../legup/puzzle/nurikabe/NurikabeView.java | 23 +- .../puzzle/nurikabe/elements/BlackTile.java | 10 +- .../puzzle/nurikabe/elements/NumberTile.java | 39 +- .../puzzle/nurikabe/elements/UnknownTile.java | 10 +- .../puzzle/nurikabe/elements/WhiteTile.java | 10 +- .../rules/BlackBetweenRegionsDirectRule.java | 169 +- .../rules/BlackBottleNeckDirectRule.java | 88 +- .../nurikabe/rules/BlackOrWhiteCaseRule.java | 169 +- .../rules/BlackSquareContradictionRule.java | 83 +- .../rules/CannotReachCellDirectRule.java | 85 +- .../nurikabe/rules/CornerBlackDirectRule.java | 183 +- .../nurikabe/rules/FillinBlackDirectRule.java | 83 +- .../nurikabe/rules/FillinWhiteDirectRule.java | 83 +- .../rules/IsolateBlackContradictionRule.java | 82 +- .../MultipleNumbersContradictionRule.java | 65 +- .../rules/NoNumberContradictionRule.java | 101 +- .../rules/PreventBlackSquareDirectRule.java | 88 +- .../rules/SurroundRegionDirectRule.java | 137 +- .../rules/TooFewSpacesContradictionRule.java | 82 +- .../rules/TooManySpacesContradictionRule.java | 81 +- ...UnreachableWhiteCellContradictionRule.java | 155 +- .../rules/WhiteBottleNeckDirectRule.java | 91 +- .../shorttruthtable/ShortTruthTable.java | 193 +- .../shorttruthtable/ShortTruthTableBoard.java | 207 +- .../shorttruthtable/ShortTruthTableCell.java | 408 ++-- .../ShortTruthTableCellFactory.java | 96 +- .../ShortTruthTableCellType.java | 104 +- .../ShortTruthTableController.java | 40 +- .../ShortTruthTableElementView.java | 140 +- .../ShortTruthTableExporter.java | 61 +- .../ShortTruthTableImporter.java | 625 +++--- .../ShortTruthTableOperation.java | 83 +- .../ShortTruthTableStatement.java | 507 +++-- .../shorttruthtable/ShortTruthTableView.java | 25 +- .../elements/ArgumentElement.java | 10 +- .../elements/GreenElement.java | 10 +- .../elements/LogicSymbolElement.java | 10 +- .../shorttruthtable/elements/RedElement.java | 10 +- .../elements/UnknownElement.java | 10 +- .../rules/basic/DirectRuleAtomic.java | 20 +- .../rules/basic/DirectRule_Generic.java | 117 +- .../elimination/DirectRuleAndElimination.java | 9 +- .../DirectRuleBiconditionalElimination.java | 9 +- .../DirectRuleConditionalElimination.java | 9 +- .../elimination/DirectRuleNotElimination.java | 9 +- .../elimination/DirectRuleOrElimination.java | 9 +- .../DirectRule_GenericElimination.java | 23 +- .../DirectRuleAndIntroduction.java | 9 +- .../DirectRuleBiconditionalIntroduction.java | 9 +- .../DirectRuleConditionalIntroduction.java | 9 +- .../DirectRuleNotIntroduction.java | 9 +- .../DirectRuleOrIntroduction.java | 9 +- .../DirectRule_GenericIntroduction.java | 23 +- .../rules/caserule/CaseRuleAnd.java | 24 +- .../rules/caserule/CaseRuleAtomic.java | 95 +- .../rules/caserule/CaseRuleBiconditional.java | 33 +- .../rules/caserule/CaseRuleConditional.java | 31 +- .../rules/caserule/CaseRuleOr.java | 26 +- .../rules/caserule/CaseRule_Generic.java | 109 +- .../caserule/CaseRule_GenericStatement.java | 240 ++- .../contradiction/ContradictionRuleAnd.java | 32 +- .../ContradictionRuleAtomic.java | 83 +- .../ContradictionRuleBiconditional.java | 32 +- .../ContradictionRuleConditional.java | 30 +- .../contradiction/ContradictionRuleNot.java | 28 +- .../contradiction/ContradictionRuleOr.java | 30 +- .../ContradictionRule_GenericStatement.java | 115 +- .../legup/puzzle/skyscrapers/Skyscrapers.java | 132 +- .../puzzle/skyscrapers/SkyscrapersBoard.java | 500 +++-- .../puzzle/skyscrapers/SkyscrapersCell.java | 102 +- .../skyscrapers/SkyscrapersCellFactory.java | 107 +- .../puzzle/skyscrapers/SkyscrapersClue.java | 94 +- .../skyscrapers/SkyscrapersClueView.java | 97 +- .../skyscrapers/SkyscrapersController.java | 48 +- .../skyscrapers/SkyscrapersElementView.java | 51 +- .../skyscrapers/SkyscrapersExporter.java | 102 +- .../skyscrapers/SkyscrapersImporter.java | 348 +-- .../puzzle/skyscrapers/SkyscrapersType.java | 58 +- .../puzzle/skyscrapers/SkyscrapersView.java | 328 +-- .../puzzle/skyscrapers/elements/ClueTile.java | 10 +- .../skyscrapers/elements/NumberTile.java | 10 +- .../skyscrapers/elements/UnknownTile.java | 10 +- .../rules/CellForNumberCaseRule.java | 319 +-- .../DuplicateNumberContradictionRule.java | 92 +- .../ExceedingVisibilityContradictionRule.java | 221 +- ...sufficientVisibilityContradictionRule.java | 221 +- .../rules/LastSingularCellDirectRule.java | 185 +- .../rules/LastSingularNumberDirectRule.java | 150 +- .../rules/LastVisibleCellDirectRule.java | 190 +- .../rules/LastVisibleNumberDirectRule.java | 152 +- .../skyscrapers/rules/NEdgeDirectRule.java | 154 +- .../rules/NumberForCellCaseRule.java | 285 +-- ...PreemptiveVisibilityContradictionRule.java | 336 +-- .../UnresolvedCellContradictionRule.java | 57 +- .../UnresolvedNumberContradictionRule.java | 155 +- .../rpi/legup/puzzle/sudoku/GroupType.java | 4 +- .../sudoku/PossibleNumberCaseBoard.java | 117 +- .../edu/rpi/legup/puzzle/sudoku/Sudoku.java | 183 +- .../rpi/legup/puzzle/sudoku/SudokuBoard.java | 308 ++- .../rpi/legup/puzzle/sudoku/SudokuCell.java | 107 +- .../puzzle/sudoku/SudokuCellController.java | 56 +- .../puzzle/sudoku/SudokuCellFactory.java | 109 +- .../puzzle/sudoku/SudokuElementView.java | 109 +- .../legup/puzzle/sudoku/SudokuExporter.java | 51 +- .../legup/puzzle/sudoku/SudokuImporter.java | 210 +- .../rpi/legup/puzzle/sudoku/SudokuView.java | 282 +-- .../puzzle/sudoku/elements/NumberTile.java | 36 +- .../rules/AdvancedDeductionDirectRule.java | 149 +- .../rules/LastCellForNumberDirectRule.java | 141 +- .../rules/LastNumberForCellDirectRule.java | 120 +- .../rules/NoSolutionContradictionRule.java | 94 +- .../sudoku/rules/PossibleCellCaseRule.java | 165 +- .../sudoku/rules/PossibleNumberCaseRule.java | 200 +- .../RepeatedNumberContradictionRule.java | 96 +- .../legup/puzzle/treetent/ClueCommand.java | 324 ++- .../puzzle/treetent/EditLineCommand.java | 393 ++-- .../rpi/legup/puzzle/treetent/TreeTent.java | 142 +- .../legup/puzzle/treetent/TreeTentBoard.java | 430 ++-- .../legup/puzzle/treetent/TreeTentCell.java | 89 +- .../puzzle/treetent/TreeTentCellFactory.java | 156 +- .../legup/puzzle/treetent/TreeTentClue.java | 98 +- .../puzzle/treetent/TreeTentClueView.java | 89 +- .../puzzle/treetent/TreeTentController.java | 209 +- .../puzzle/treetent/TreeTentElementView.java | 83 +- .../puzzle/treetent/TreeTentExporter.java | 114 +- .../puzzle/treetent/TreeTentImporter.java | 351 +-- .../legup/puzzle/treetent/TreeTentLine.java | 70 +- .../puzzle/treetent/TreeTentLineView.java | 49 +- .../legup/puzzle/treetent/TreeTentType.java | 36 +- .../legup/puzzle/treetent/TreeTentView.java | 391 ++-- .../puzzle/treetent/elements/GrassTile.java | 13 +- .../puzzle/treetent/elements/TentTile.java | 9 +- .../puzzle/treetent/elements/TreeTile.java | 8 +- .../puzzle/treetent/elements/UnknownTile.java | 12 +- .../treetent/rules/EmptyFieldDirectRule.java | 133 +- .../treetent/rules/FillinRowCaseRule.java | 338 +-- .../rules/FinishWithGrassDirectRule.java | 124 +- .../rules/FinishWithTentsDirectRule.java | 127 +- .../rules/LastCampingSpotDirectRule.java | 152 +- .../treetent/rules/LinkTentCaseRule.java | 282 +-- .../treetent/rules/LinkTreeCaseRule.java | 311 +-- .../rules/NoTentForTreeContradictionRule.java | 99 +- .../rules/NoTreeForTentContradictionRule.java | 85 +- .../SurroundTentWithGrassDirectRule.java | 126 +- .../treetent/rules/TentForTreeDirectRule.java | 194 +- .../treetent/rules/TentOrGrassCaseRule.java | 168 +- .../rules/TooFewTentsContradictionRule.java | 61 +- .../rules/TooManyTentsContradictionRule.java | 57 +- .../rules/TouchingTentsContradictionRule.java | 60 +- .../treetent/rules/TreeForTentDirectRule.java | 201 +- .../rpi/legup/save/ExportFileException.java | 7 +- .../save/InvalidFileFormatException.java | 7 +- .../java/edu/rpi/legup/save/SavableBoard.java | 21 +- .../java/edu/rpi/legup/save/SavableProof.java | 4 +- .../edu/rpi/legup/ui/CreatePuzzleDialog.java | 306 +-- .../java/edu/rpi/legup/ui/DynamicView.java | 396 ++-- .../edu/rpi/legup/ui/DynamicViewType.java | 4 +- src/main/java/edu/rpi/legup/ui/HomePanel.java | 1202 ++++++----- .../java/edu/rpi/legup/ui/LegupPanel.java | 9 +- src/main/java/edu/rpi/legup/ui/LegupUI.java | 385 ++-- .../legup/ui/ManualPuzzleCreatorDialog.java | 8 +- .../java/edu/rpi/legup/ui/PickGameDialog.java | 269 ++- .../edu/rpi/legup/ui/PreferencesDialog.java | 711 ++++--- .../edu/rpi/legup/ui/ProofEditorPanel.java | 1883 +++++++++-------- .../edu/rpi/legup/ui/PuzzleEditorPanel.java | 959 ++++----- .../java/edu/rpi/legup/ui/ScrollView.java | 567 +++-- .../java/edu/rpi/legup/ui/ToolbarName.java | 44 +- .../java/edu/rpi/legup/ui/WrapLayout.java | 306 ++- .../java/edu/rpi/legup/ui/ZoomWidget.java | 81 +- .../java/edu/rpi/legup/ui/ZoomablePane.java | 60 +- .../edu/rpi/legup/ui/boardview/BoardView.java | 384 ++-- .../legup/ui/boardview/DataSelectionView.java | 11 +- .../legup/ui/boardview/ElementSelection.java | 105 +- .../rpi/legup/ui/boardview/ElementView.java | 645 +++--- .../rpi/legup/ui/boardview/GridBoardView.java | 135 +- .../legup/ui/boardview/GridElementView.java | 6 +- .../legup/ui/boardview/SelectionItemView.java | 49 +- .../ui/lookandfeel/LegupLookAndFeel.java | 666 +++--- .../animation/MaterialUIMovement.java | 17 +- .../animation/MaterialUITimer.java | 195 +- .../components/MaterialButtonUI.java | 63 +- .../MaterialCheckBoxMenuItemUI.java | 71 +- .../components/MaterialCheckBoxUI.java | 39 +- .../components/MaterialComboBoxRenderer.java | 26 +- .../components/MaterialComboBoxUI.java | 78 +- .../components/MaterialEditorPaneUI.java | 15 +- .../components/MaterialFileChooserUI.java | 91 +- .../components/MaterialLabelUI.java | 37 +- .../components/MaterialMenuBarUI.java | 35 +- .../components/MaterialMenuItemUI.java | 39 +- .../components/MaterialMenuUI.java | 37 +- .../components/MaterialPanelUI.java | 35 +- .../components/MaterialPasswordFieldUI.java | 326 +-- .../components/MaterialPopupMenuUI.java | 33 +- .../components/MaterialProgressBarUI.java | 35 +- .../MaterialRadioButtonMenuItemUI.java | 71 +- .../components/MaterialRadioButtonUI.java | 41 +- .../components/MaterialScrollBarUI.java | 77 +- .../components/MaterialSeparatorUI.java | 25 +- .../components/MaterialSliderUI.java | 227 +- .../components/MaterialSpinnerUI.java | 115 +- .../components/MaterialSplitPaneDivider.java | 32 +- .../components/MaterialSplitPaneUI.java | 36 +- .../components/MaterialTabbedPaneUI.java | 120 +- .../components/MaterialTableCellEditor.java | 33 +- .../components/MaterialTableCellRenderer.java | 23 +- .../MaterialTableHeaderCellRenderer.java | 25 +- .../components/MaterialTableHeaderUI.java | 29 +- .../components/MaterialTableUI.java | 64 +- .../components/MaterialTextFieldUI.java | 328 +-- .../components/MaterialTextPaneUI.java | 15 +- .../components/MaterialToggleButtonUI.java | 41 +- .../components/MaterialToolBarUI.java | 51 +- .../components/MaterialToolTipUI.java | 25 +- .../components/MaterialTreeCellEditor.java | 77 +- .../components/MaterialTreeCellRenderer.java | 59 +- .../components/MaterialTreeUI.java | 51 +- .../materialdesign/DropShadowBorder.java | 671 +++--- .../materialdesign/MaterialBorders.java | 19 +- .../materialdesign/MaterialColors.java | 529 +++-- .../materialdesign/MaterialDrawingUtils.java | 38 +- .../materialdesign/MaterialFonts.java | 85 +- .../materialdesign/MaterialImages.java | 66 +- .../rulesview/CaseRulePanel.java | 27 +- .../rulesview/CaseRuleSelectionView.java | 23 +- .../rulesview/ContradictionRulePanel.java | 25 +- .../rulesview/DirectRulePanel.java | 32 +- .../proofeditorui/rulesview/RuleButton.java | 57 +- .../ui/proofeditorui/rulesview/RuleFrame.java | 311 ++- .../ui/proofeditorui/rulesview/RulePanel.java | 623 +++--- .../rulesview/SearchBarPanel.java | 28 +- .../treeview/TreeElementView.java | 331 ++- .../proofeditorui/treeview/TreeNodeView.java | 561 +++-- .../ui/proofeditorui/treeview/TreePanel.java | 197 +- .../treeview/TreeToolBarButton.java | 26 +- .../treeview/TreeToolBarName.java | 5 +- .../treeview/TreeToolbarPanel.java | 84 +- .../treeview/TreeTransitionView.java | 662 +++--- .../ui/proofeditorui/treeview/TreeView.java | 1595 +++++++------- .../treeview/TreeViewSelection.java | 312 ++- .../elementsview/ElementButton.java | 58 +- .../elementsview/ElementFrame.java | 165 +- .../elementsview/ElementPanel.java | 130 +- .../NonPlaceableElementPanel.java | 15 +- .../elementsview/PlaceableElementPanel.java | 15 +- .../resizeview/ResizePanel.java | 3 +- .../java/edu/rpi/legup/user/Submission.java | 8 +- .../edu/rpi/legup/user/UsageStatistics.java | 78 +- src/main/java/edu/rpi/legup/user/User.java | 4 +- .../rpi/legup/utility/ConnectedRegions.java | 103 +- .../edu/rpi/legup/utility/DisjointSets.java | 286 +-- .../java/edu/rpi/legup/utility/Entry.java | 88 +- .../edu/rpi/legup/utility/LegupUtils.java | 137 +- .../java/edu/rpi/legup/utility/Logger.java | 55 +- src/test/java/legup/MockGameBoardFacade.java | 61 +- src/test/java/legup/TestRunner.java | 179 +- src/test/java/legup/TestUtilities.java | 17 +- .../AdjacentShipsContradictionRuleTest.java | 99 +- .../rules/FinishWithShipsDirectRuleTests.java | 102 +- .../BulbsInPathContradictionRuleTest.java | 151 +- ...CannotLightACellContradictionRuleTest.java | 137 +- .../rules/EmptyCellinLightDirectRuleTest.java | 174 +- .../rules/EmptyCornersDirectRuleTest.java | 111 +- .../rules/FinishWithBulbsDirectRuleTest.java | 155 +- .../rules/LightOrEmptyCaseRuleTest.java | 104 +- .../rules/MustLightDirectRuleTest.java | 87 +- .../rules/SatisfyNumberCaseRuleTest.java | 295 +-- .../TooFewBulbsContradictionRuleTest.java | 96 +- .../TooManyBulbsContradictionRuleTest.java | 97 +- .../BlackBetweenRegionsDirectRuleTest.java | 342 +-- .../rules/BlackBottleNeckDirectRuleTest.java | 184 +- .../rules/BlackOrWhiteCaseRuleTest.java | 113 +- .../BlackSquareContradictionRuleTest.java | 162 +- .../rules/CannotReachCellDirectRuleTest.java | 129 +- .../rules/CornerBlackDirectRuleTest.java | 119 +- .../rules/FillinBlackDirectRuleTest.java | 240 ++- .../rules/FillinWhiteDirectRuleTest.java | 250 ++- .../IsolateBlackContradictionRuleTest.java | 180 +- .../MultipleNumbersContradictionRuleTest.java | 162 +- .../rules/NoNumbersContradictionRuleTest.java | 129 +- .../PreventBlackSquareDirectRuleTest.java | 294 +-- .../rules/SurroundRegionDirectRuleTest.java | 203 +- .../TooFewSpacesContradictionRuleTest.java | 170 +- .../TooManySpacesContradictionRuleTest.java | 173 +- ...achableWhiteCellContradictionRuleTest.java | 111 +- .../rules/WhiteBottleNeckDirectRuleTest.java | 174 +- .../ShortTruthTableImporterTest.java | 9 +- .../ShortTruthTableStatementTest.java | 9 +- .../rules/AndCaseRuleTest.java | 277 ++- .../rules/AndEliminationDirectRuleTest.java | 348 +-- .../rules/AndIntroductionDirectRuleTest.java | 150 +- .../rules/AtomicDirectRuleTest.java | 324 ++- .../rules/BiconditionalEliminationTest.java | 695 +++--- .../rules/BiconditionalIntroductionTest.java | 167 +- .../rules/ConditionalEliminationTest.java | 406 ++-- .../rules/ConditionalIntroductionTest.java | 153 +- .../rules/NotEliminationTest.java | 196 +- .../rules/NotIntroductionTest.java | 211 +- .../shorttruthtable/rules/OrCaseRuleTest.java | 278 ++- .../rules/OrEliminationTest.java | 251 +-- .../rules/OrIntroductionTest.java | 150 +- .../rules/TrueOrFalseCaseRuleTest.java | 99 +- .../rules/CellForNumberCaseRuleTest.java | 338 +-- .../DuplicateNumberContradictionTest.java | 244 +-- .../ExceedingVisibilityContradictionTest.java | 206 +- ...sufficientVisibilityContradictionTest.java | 206 +- .../rules/LastSingularCellDirectTest.java | 398 ++-- .../rules/LastSingularNumberDirectTest.java | 236 +-- .../rules/LastVisibleCellDirectTest.java | 442 ++-- .../rules/LastVisibleNumberDirectTest.java | 443 ++-- .../skyscrapers/rules/NEdgeDirectTest.java | 223 +- .../rules/NumberForCellCaseRuleTest.java | 302 +-- ...PreemptiveVisibilityContradictionTest.java | 235 +- .../UnresolvedCellContradictionTest.java | 247 +-- .../UnresolvedNumberContradictionTest.java | 268 +-- .../rules/EmptyFieldDirectRuleTest.java | 491 ++--- .../rules/FinishWithGrassDirectRuleTest.java | 666 +++--- .../rules/FinishWithTentsDirectRuleTest.java | 625 +++--- .../rules/LastCampingSpotDirectRuleTest.java | 278 ++- .../NoTentForTreeContradictionRuleTest.java | 195 +- .../NoTreeForTentContradictionRuleTest.java | 397 ++-- .../SurroundTentWithGrassDirectRuleTest.java | 258 +-- .../rules/TentForTreeDirectRuleTest.java | 19 +- .../rules/TentOrGrassCaseRuleTest.java | 104 +- .../TooFewTentsContradictionRuleTest.java | 447 ++-- .../TooManyTentsContradictionRuleTest.java | 480 ++--- .../TouchingTentsContradictionRuleTest.java | 477 ++--- .../rules/TreeForTentDirectRuleTest.java | 19 +- 533 files changed, 40716 insertions(+), 40451 deletions(-) diff --git a/src/main/java/edu/rpi/legup/Legup.java b/src/main/java/edu/rpi/legup/Legup.java index 49887de4f..0ea5b638a 100644 --- a/src/main/java/edu/rpi/legup/Legup.java +++ b/src/main/java/edu/rpi/legup/Legup.java @@ -5,14 +5,14 @@ public class Legup { - /** - * Starts the Legup Program - * - * @param args arguments to Legup - */ - public static void main(String[] args) { - Logger.initLogger(); - GameBoardFacade.getInstance(); - GameBoardFacade.setupConfig(); - } -} \ No newline at end of file + /** + * Starts the Legup Program + * + * @param args arguments to Legup + */ + public static void main(String[] args) { + Logger.initLogger(); + GameBoardFacade.getInstance(); + GameBoardFacade.setupConfig(); + } +} diff --git a/src/main/java/edu/rpi/legup/ai/Solver.java b/src/main/java/edu/rpi/legup/ai/Solver.java index 68b934bfb..5b39c2008 100644 --- a/src/main/java/edu/rpi/legup/ai/Solver.java +++ b/src/main/java/edu/rpi/legup/ai/Solver.java @@ -1,4 +1,3 @@ package edu.rpi.legup.ai; -public class Solver { -} +public class Solver {} diff --git a/src/main/java/edu/rpi/legup/app/Config.java b/src/main/java/edu/rpi/legup/app/Config.java index 1847e14e4..baaeb1dbd 100644 --- a/src/main/java/edu/rpi/legup/app/Config.java +++ b/src/main/java/edu/rpi/legup/app/Config.java @@ -2,153 +2,150 @@ import java.io.*; import java.util.*; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; - import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class Config { - private final static Logger Logger = LogManager.getLogger(Config.class.getName()); - - private Map puzzles; - private Map fileCreationDisabledStatuses; - private static final String CONFIG_LOCATION = "edu/rpi/legup/legup/config"; - - /** - * Config Constructor for logic puzzles - * - * @throws InvalidConfigException if configuration is invalid - */ - public Config() throws InvalidConfigException { - this.puzzles = new Hashtable<>(); - this.fileCreationDisabledStatuses = new Hashtable<>(); - loadConfig(this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION)); + private static final Logger Logger = LogManager.getLogger(Config.class.getName()); + + private Map puzzles; + private Map fileCreationDisabledStatuses; + private static final String CONFIG_LOCATION = "edu/rpi/legup/legup/config"; + + /** + * Config Constructor for logic puzzles + * + * @throws InvalidConfigException if configuration is invalid + */ + public Config() throws InvalidConfigException { + this.puzzles = new Hashtable<>(); + this.fileCreationDisabledStatuses = new Hashtable<>(); + loadConfig(this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION)); + } + + /** + * Gets a list of all available Puzzle names + * + * @return Vector of Puzzle names which are Strings + */ + public List getPuzzleClassNames() { + return new LinkedList<>(puzzles.keySet()); + } + + /** + * Returns a list of the names of the puzzles which can have puzzles created and edited within the + * proof editor. + * + * @return the aforementioned list of Strings + */ + public List getFileCreationEnabledPuzzles() { + LinkedList puzzles = new LinkedList(); + for (String puzzle : this.getPuzzleClassNames()) { + if (!this.fileCreationDisabledStatuses.get(puzzle)) { + puzzles.add(puzzle); + } } - - /** - * Gets a list of all available Puzzle names - * - * @return Vector of Puzzle names which are Strings - */ - public List getPuzzleClassNames() { - return new LinkedList<>(puzzles.keySet()); + return puzzles; + } + + /** + * Converts the class name of the puzzles to their display names. Some examples of the conversion: + * convertClassNameToDisplayName("TreeTent") will return "Tree Tent" + * convertClassNameToDisplayName("Nurikabe") will return "Nurikabe" + * + * @param className the name of the class + * @return displayName the name of the puzzle + */ + public static String convertClassNameToDisplayName(String className) { + String displayName = ""; + for (int i = 0; i < className.length(); i++) { + if (Character.isUpperCase(className.charAt(i)) && i != 0) { + displayName += " "; + } + displayName += className.charAt(i); } - - /** - * Returns a list of the names of the puzzles which can have puzzles created and edited - * within the proof editor. - * - * @return the aforementioned list of Strings - */ - public List getFileCreationEnabledPuzzles() { - LinkedList puzzles = new LinkedList(); - for (String puzzle : this.getPuzzleClassNames()) { - if (!this.fileCreationDisabledStatuses.get(puzzle)) { - puzzles.add(puzzle); - } - } - return puzzles; + return displayName; + } + + public static String convertDisplayNameToClassName(String displayName) { + String className = ""; + for (int i = 0; i < displayName.length(); i++) { + if (displayName.charAt(i) != ' ') { + className += displayName.charAt(i); + } } + return className; + } - /** - * Converts the class name of the puzzles to their display names. Some examples of the conversion: - * convertClassNameToDisplayName("TreeTent") will return "Tree Tent" - * convertClassNameToDisplayName("Nurikabe") will return "Nurikabe" - * - * @param className the name of the class - * @return displayName the name of the puzzle - */ - public static String convertClassNameToDisplayName(String className) { - String displayName = ""; - for (int i = 0; i < className.length(); i++) { - if (Character.isUpperCase(className.charAt(i)) && i != 0) { - displayName += " "; - } - displayName += className.charAt(i); - } - return displayName; + public List getPuzzleNames() { + List names = new LinkedList(); + for (String puzzle : this.getPuzzleClassNames()) { + names.add(Config.convertClassNameToDisplayName(puzzle)); } + return names; + } - public static String convertDisplayNameToClassName(String displayName) { - String className = ""; - for (int i = 0; i < displayName.length(); i++) { - if (displayName.charAt(i) != ' ') { - className += displayName.charAt(i); - } - } - return className; + public List getFileCreationEnabledPuzzleNames() { + List names = new LinkedList(); + for (String puzzle : this.getFileCreationEnabledPuzzles()) { + names.add(Config.convertClassNameToDisplayName(puzzle)); } - - public List getPuzzleNames() { - List names = new LinkedList(); - for (String puzzle : this.getPuzzleClassNames()) { - names.add(Config.convertClassNameToDisplayName(puzzle)); - } - return names; + return names; + } + + /** + * Gets a {@link edu.rpi.legup.model.Puzzle} class for a puzzle name + * + * @param puzzleName puzzle name of the class + * @return class name for the puzzle name + */ + public String getPuzzleClassForName(String puzzleName) { + if (puzzles.containsKey(puzzleName)) { + return puzzles.get(puzzleName); } - - public List getFileCreationEnabledPuzzleNames() { - List names = new LinkedList(); - for (String puzzle : this.getFileCreationEnabledPuzzles()) { - names.add(Config.convertClassNameToDisplayName(puzzle)); - } - return names; - } - - /** - * Gets a {@link edu.rpi.legup.model.Puzzle} class for a puzzle name - * - * @param puzzleName puzzle name of the class - * @return class name for the puzzle name - */ - public String getPuzzleClassForName(String puzzleName) { - if (puzzles.containsKey(puzzleName)) { - return puzzles.get(puzzleName); - } - return null; - } - - /** - * Loads the config object from the config xml file - * - * @param stream file stream for the config xml file - */ - private void loadConfig(InputStream stream) throws InvalidConfigException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.parse(stream); - Element configNode = document.getDocumentElement(); - - if (!configNode.getNodeName().equalsIgnoreCase("Legup")) { - throw new InvalidConfigException("Config is not formatted correctly"); - } - - Element puzzleList = (Element) configNode.getElementsByTagName("puzzles").item(0); - Logger.debug(puzzleList); - NodeList puzzleNodes = puzzleList.getElementsByTagName("puzzle"); - - for (int i = 0; i < puzzleNodes.getLength(); i++) { - Element puzzle = (Element) puzzleNodes.item(i); - String name = puzzle.getAttribute("name"); - String className = puzzle.getAttribute("qualifiedClassName"); - boolean status = Boolean.parseBoolean(puzzle.getAttribute("fileCreationDisabled").toLowerCase()); - Logger.debug("Class Name: " + className); - this.puzzles.put(name, className); - this.fileCreationDisabledStatuses.put(name, Boolean.valueOf(status)); - } - - } - catch (ParserConfigurationException | SAXException | IOException e) { - throw new InvalidConfigException(e.getMessage()); - } + return null; + } + + /** + * Loads the config object from the config xml file + * + * @param stream file stream for the config xml file + */ + private void loadConfig(InputStream stream) throws InvalidConfigException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(stream); + Element configNode = document.getDocumentElement(); + + if (!configNode.getNodeName().equalsIgnoreCase("Legup")) { + throw new InvalidConfigException("Config is not formatted correctly"); + } + + Element puzzleList = (Element) configNode.getElementsByTagName("puzzles").item(0); + Logger.debug(puzzleList); + NodeList puzzleNodes = puzzleList.getElementsByTagName("puzzle"); + + for (int i = 0; i < puzzleNodes.getLength(); i++) { + Element puzzle = (Element) puzzleNodes.item(i); + String name = puzzle.getAttribute("name"); + String className = puzzle.getAttribute("qualifiedClassName"); + boolean status = + Boolean.parseBoolean(puzzle.getAttribute("fileCreationDisabled").toLowerCase()); + Logger.debug("Class Name: " + className); + this.puzzles.put(name, className); + this.fileCreationDisabledStatuses.put(name, Boolean.valueOf(status)); + } + + } catch (ParserConfigurationException | SAXException | IOException e) { + throw new InvalidConfigException(e.getMessage()); } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/app/GameBoardFacade.java b/src/main/java/edu/rpi/legup/app/GameBoardFacade.java index 55273ab4f..0dccc739e 100644 --- a/src/main/java/edu/rpi/legup/app/GameBoardFacade.java +++ b/src/main/java/edu/rpi/legup/app/GameBoardFacade.java @@ -11,16 +11,6 @@ import edu.rpi.legup.ui.LegupUI; import edu.rpi.legup.ui.ProofEditorPanel; import edu.rpi.legup.ui.PuzzleEditorPanel; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.io.File; import java.io.FileInputStream; @@ -31,487 +21,500 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; public class GameBoardFacade implements IHistorySubject { - private final static Logger LOGGER = LogManager.getLogger(GameBoardFacade.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(GameBoardFacade.class.getName()); - protected volatile static GameBoardFacade instance; + protected static volatile GameBoardFacade instance; - private Config config; + private Config config; - protected Puzzle puzzle; + protected Puzzle puzzle; - private LegupUI legupUI; + private LegupUI legupUI; - private ProofEditorPanel puzzleSolver; + private ProofEditorPanel puzzleSolver; - private PuzzleEditorPanel puzzleEditor; + private PuzzleEditorPanel puzzleEditor; - private String curFileName; + private String curFileName; - private History history; - private List historyListeners; + private History history; + private List historyListeners; - /** - * Private GameBoardFacade Constructor creates a game board facade - */ - protected GameBoardFacade() { - history = new History(); - historyListeners = new ArrayList<>(); - curFileName = null; - LegupPreferences.getInstance(); - initializeUI(); - } + /** Private GameBoardFacade Constructor creates a game board facade */ + protected GameBoardFacade() { + history = new History(); + historyListeners = new ArrayList<>(); + curFileName = null; + LegupPreferences.getInstance(); + initializeUI(); + } - /** - * Gets the singleton instance of GameBoardFacade - * - * @return single instance of GameBoardFacade - */ - public synchronized static GameBoardFacade getInstance() { - if (instance == null) { - instance = new GameBoardFacade(); - } - return instance; + /** + * Gets the singleton instance of GameBoardFacade + * + * @return single instance of GameBoardFacade + */ + public static synchronized GameBoardFacade getInstance() { + if (instance == null) { + instance = new GameBoardFacade(); } - - public void initializeUI() { - EventQueue.invokeLater(() -> { - legupUI = new LegupUI(); - puzzleSolver = legupUI.getProofEditor(); - puzzleEditor = legupUI.getPuzzleEditor(); - addHistoryListener(legupUI.getProofEditor()); - addHistoryListener(legupUI.getPuzzleEditor()); + return instance; + } + + public void initializeUI() { + EventQueue.invokeLater( + () -> { + legupUI = new LegupUI(); + puzzleSolver = legupUI.getProofEditor(); + puzzleEditor = legupUI.getPuzzleEditor(); + addHistoryListener(legupUI.getProofEditor()); + addHistoryListener(legupUI.getPuzzleEditor()); }); + } + + public void setPuzzle(Puzzle puzzle) { + this.puzzle = puzzle; + this.puzzleSolver.setPuzzleView(puzzle); + this.history.clear(); + } + + public void clearPuzzle() { + this.puzzle = null; + this.curFileName = null; + this.history.clear(); + } + + public static void setupConfig() { + Config config = null; + try { + config = new Config(); + } catch (InvalidConfigException e) { + System.exit(1); } - - public void setPuzzle(Puzzle puzzle) { - this.puzzle = puzzle; - this.puzzleSolver.setPuzzleView(puzzle); - this.history.clear(); + GameBoardFacade.getInstance().setConfig(config); + } + + public void setPuzzleEditor(Puzzle puzzle) { + this.puzzle = puzzle; + this.puzzleEditor.setPuzzleView(puzzle); + } + + public void setConfig(Config config) { + this.config = config; + } + + /** + * Validates the given dimensions for the given puzzle + * + * @param game name of the puzzle + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @return true if it is possible to create a board for the given game with the given number of + * rows and columns, false otherwise + * @throws RuntimeException if any of the given input is invalid + */ + public boolean validateDimensions(String game, int rows, int columns) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + try { + Class c = Class.forName(qualifiedClassName); + Constructor constructor = c.getConstructor(); + Puzzle puzzle = (Puzzle) constructor.newInstance(); + return puzzle.isValidDimensions(rows, columns); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Error validating puzzle dimensions"); } - - public void clearPuzzle() { - this.puzzle = null; - this.curFileName = null; - this.history.clear(); + } + + /** + * Validates the given text input for the given puzzle + * + * @param game the name of the puzzle + * @param statements an array of statements + * @return true if it is possible to create a board for the given game with the given statements, + * false otherwise + * @throws RuntimeException if any of the input is invalid + */ + public boolean validateTextInput(String game, String[] statements) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + try { + Class c = Class.forName(qualifiedClassName); + Constructor constructor = c.getConstructor(); + Puzzle puzzle = (Puzzle) constructor.newInstance(); + return puzzle.isValidTextInput(statements); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Error validating puzzle text input"); } - - public static void setupConfig() { - Config config = null; - try { - config = new Config(); - } - catch (InvalidConfigException e) { - System.exit(1); - } - GameBoardFacade.getInstance().setConfig(config); + } + + /** + * Loads an empty puzzle + * + * @param game name of the puzzle + * @param rows the number of rows on the board + * @param columns the number of columns on the board + */ + public void loadPuzzle(String game, int rows, int columns) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + LOGGER.debug("Loading " + qualifiedClassName); + + try { + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new RuntimeException("Puzzle importer null"); + } + + // Theoretically, this exception should never be thrown, since LEGUP should not be + // allowing the user to give row/column input for a puzzle that doesn't support it + if (!importer.acceptsRowsAndColumnsInput()) { + throw new IllegalArgumentException( + puzzle.getName() + " does not accept rows and columns input"); + } + + setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); + importer.initializePuzzle(rows, columns); + + puzzle.initializeView(); + // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Puzzle creation error"); } - - - public void setPuzzleEditor(Puzzle puzzle) { - this.puzzle = puzzle; - this.puzzleEditor.setPuzzleView(puzzle); + } + + public void loadPuzzle(String game, String[] statements) { + String qualifiedClassName = config.getPuzzleClassForName(game); + LOGGER.debug("Loading " + qualifiedClassName); + + try { + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new RuntimeException("Puzzle importer null"); + } + + // Theoretically, this exception should never be thrown, since LEGUP should not be + // allowing the user to give text input for a puzzle that doesn't support it + if (!importer.acceptsTextInput()) { + throw new IllegalArgumentException(puzzle.getName() + " does not accept text input"); + } + + setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); + importer.initializePuzzle(statements); + + puzzle.initializeView(); + // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Puzzle creation error"); } - - public void setConfig(Config config) { - this.config = config; + } + + /** + * Loads a puzzle file + * + * @param fileName file name of the board file + * @throws InvalidFileFormatException if input is invalid + */ + public void loadPuzzle(String fileName) throws InvalidFileFormatException { + try { + loadPuzzle(new FileInputStream(fileName)); + curFileName = fileName; + setWindowTitle(puzzle.getName(), fileName); + } catch (IOException e) { + LOGGER.error("Invalid file " + fileName, e); + throw new InvalidFileFormatException("Could not find file"); } - - /** - * Validates the given dimensions for the given puzzle - * - * @param game name of the puzzle - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @return true if it is possible to create a board for the given game with the given number of - * rows and columns, false otherwise - * @throws RuntimeException if any of the given input is invalid - */ - public boolean validateDimensions(String game, int rows, int columns) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - try { - Class c = Class.forName(qualifiedClassName); - Constructor constructor = c.getConstructor(); - Puzzle puzzle = (Puzzle) constructor.newInstance(); - return puzzle.isValidDimensions(rows, columns); - } - catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException | - InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Error validating puzzle dimensions"); - } + } + + public void loadPuzzleEditor(String fileName) throws InvalidFileFormatException { + try { + loadPuzzleEditor(new FileInputStream(fileName)); + curFileName = fileName; + setWindowTitle(puzzle.getName(), fileName); + } catch (IOException e) { + LOGGER.error("Invalid file " + fileName, e); + throw new InvalidFileFormatException("Could not find file"); } - - /** - * Validates the given text input for the given puzzle - * - * @param game the name of the puzzle - * @param statements an array of statements - * @return true if it is possible to create a board for the given game with the given statements, - * false otherwise - * @throws RuntimeException if any of the input is invalid - */ - public boolean validateTextInput(String game, String[] statements) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - try { - Class c = Class.forName(qualifiedClassName); - Constructor constructor = c.getConstructor(); - Puzzle puzzle = (Puzzle) constructor.newInstance(); - return puzzle.isValidTextInput(statements); - } - catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException | - InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Error validating puzzle text input"); - } + } + + public void loadPuzzleEditor(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Invalid file", e); + throw new InvalidFileFormatException("Could not find file"); } - /** - * Loads an empty puzzle - * - * @param game name of the puzzle - * @param rows the number of rows on the board - * @param columns the number of columns on the board - */ - public void loadPuzzle(String game, int rows, int columns) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - LOGGER.debug("Loading " + qualifiedClassName); - - try { - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new RuntimeException("Puzzle importer null"); - } - - // Theoretically, this exception should never be thrown, since LEGUP should not be - // allowing the user to give row/column input for a puzzle that doesn't support it - if (!importer.acceptsRowsAndColumnsInput()) { - throw new IllegalArgumentException(puzzle.getName() + " does not accept rows and columns input"); - } - - setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); - importer.initializePuzzle(rows, columns); - - puzzle.initializeView(); -// puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); + Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + try { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + String qualifiedClassName = + config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); + if (qualifiedClassName == null) { + throw new InvalidFileFormatException( + "Puzzle creation error: cannot find puzzle with that name"); } - catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); + // Check if puzzle is a "FileCreationEnabled" puzzle (meaning it is editable). + String[] editablePuzzles = config.getFileCreationEnabledPuzzles().toArray(new String[0]); + boolean isEditablePuzzle = false; + for (int i = 0; i < editablePuzzles.length; i++) { + if (qualifiedClassName.contains(editablePuzzles[i])) { + isEditablePuzzle = true; + break; + } } - catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | - IllegalAccessException | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Puzzle creation error"); + if (!isEditablePuzzle) { + LOGGER.error("Puzzle is not editable"); + throw new InvalidFileFormatException("Puzzle is not editable"); } - } - - public void loadPuzzle(String game, String[] statements) { - String qualifiedClassName = config.getPuzzleClassForName(game); + // If it is editable, start loading it LOGGER.debug("Loading " + qualifiedClassName); - try { - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new RuntimeException("Puzzle importer null"); - } - - // Theoretically, this exception should never be thrown, since LEGUP should not be - // allowing the user to give text input for a puzzle that doesn't support it - if (!importer.acceptsTextInput()) { - throw new IllegalArgumentException(puzzle.getName() + " does not accept text input"); - } - - setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); - importer.initializePuzzle(statements); - - puzzle.initializeView(); -// puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } - catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } - catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | - IllegalAccessException | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Puzzle creation error"); - } + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); - } - - /** - * Loads a puzzle file - * - * @param fileName file name of the board file - * @throws InvalidFileFormatException if input is invalid - */ - public void loadPuzzle(String fileName) throws InvalidFileFormatException { - try { - loadPuzzle(new FileInputStream(fileName)); - curFileName = fileName; - setWindowTitle(puzzle.getName(), fileName); - } - catch (IOException e) { - LOGGER.error("Invalid file " + fileName, e); - throw new InvalidFileFormatException("Could not find file"); + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new InvalidFileFormatException("Puzzle importer null"); } + importer.initializePuzzle(node); + puzzle.initializeView(); + puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new InvalidFileFormatException("Puzzle creation error"); + } + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - - public void loadPuzzleEditor(String fileName) throws InvalidFileFormatException { - try { - loadPuzzleEditor(new FileInputStream(fileName)); - curFileName = fileName; - setWindowTitle(puzzle.getName(), fileName); - } - catch (IOException e) { - LOGGER.error("Invalid file " + fileName, e); - throw new InvalidFileFormatException("Could not find file"); - } + } + + /** + * Loads a puzzle file from the input stream + * + * @throws InvalidFileFormatException if input is invalid + * @param inputStream input stream for the puzzle file + */ + public void loadPuzzle(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Invalid file", e); + throw new InvalidFileFormatException("Could not find file"); } - public void loadPuzzleEditor(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); + Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + try { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + String qualifiedClassName = + config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); + if (qualifiedClassName == null) { + throw new InvalidFileFormatException( + "Puzzle creation error: cannot find puzzle with that name"); } - catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Invalid file", e); - throw new InvalidFileFormatException("Could not find file"); - } - - Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - try { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - String qualifiedClassName = config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); - if (qualifiedClassName == null) { - throw new InvalidFileFormatException("Puzzle creation error: cannot find puzzle with that name"); - } - //Check if puzzle is a "FileCreationEnabled" puzzle (meaning it is editable). - String[] editablePuzzles = config.getFileCreationEnabledPuzzles().toArray(new String[0]); - boolean isEditablePuzzle = false; - for (int i = 0; i < editablePuzzles.length; i++) { - if (qualifiedClassName.contains(editablePuzzles[i])) { - isEditablePuzzle = true; - break; - } - } - if (!isEditablePuzzle) { - LOGGER.error("Puzzle is not editable"); - throw new InvalidFileFormatException("Puzzle is not editable"); - } - //If it is editable, start loading it - LOGGER.debug("Loading " + qualifiedClassName); - - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new InvalidFileFormatException("Puzzle importer null"); - } - importer.initializePuzzle(node); - puzzle.initializeView(); - puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } - catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | - IllegalAccessException | InstantiationException e) { - LOGGER.error(e); - throw new InvalidFileFormatException("Puzzle creation error"); - } - } - else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); - } - } + LOGGER.debug("Loading " + qualifiedClassName); - /** - * Loads a puzzle file from the input stream - * @throws InvalidFileFormatException if input is invalid - * @param inputStream input stream for the puzzle file - */ - public void loadPuzzle(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } - catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Invalid file", e); - throw new InvalidFileFormatException("Could not find file"); - } + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); - Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - try { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - String qualifiedClassName = config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); - if (qualifiedClassName == null) { - throw new InvalidFileFormatException("Puzzle creation error: cannot find puzzle with that name"); - } - LOGGER.debug("Loading " + qualifiedClassName); - - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new InvalidFileFormatException("Puzzle importer null"); - } - importer.initializePuzzle(node); - puzzle.initializeView(); - puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzle(puzzle); - } - catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | - IllegalAccessException | InstantiationException e) { - LOGGER.error(e); - throw new InvalidFileFormatException("Puzzle creation error"); - } + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new InvalidFileFormatException("Puzzle importer null"); } - else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); - } - } - - /** - * Sets the window title to 'PuzzleName - FileName' - * Removes the extension - * - * @param puzzleName puzzle name for the file - * @param fileName file name of the edu.rpi.legup.puzzle - */ - public void setWindowTitle(String puzzleName, String fileName) { - File file = new File(fileName); - legupUI.setTitle(puzzleName + " - " + file.getName()); - } - - /** - * Gets the Config info - * - * @return Config object - */ - public Config getConfig() { - return config; - } - - /** - * Gets the LegupUI - * - * @return LegupUI - */ - public LegupUI getLegupUI() { - return legupUI; - } - - /** - * Gets the initial board state - * - * @return the initial board state - */ - public Board getBoard() { - return puzzle == null ? null : puzzle.getCurrentBoard(); - } - - /** - * Sets the initial board state and the tree - * - * @param board initial board - */ - public void setBoard(Board board) { - puzzle.setCurrentBoard(board); - } - - /** - * Gets the rules tree - * - * @return rules tree - */ - public Tree getTree() { - return puzzle == null ? null : puzzle.getTree(); - } - - /** - * Gets the Puzzle for the board - * - * @return the Puzzle for the board - */ - public Puzzle getPuzzleModule() { - return puzzle; - } - - /** - * Sets the Puzzle for the board - * - * @param puzzle the PuzzleModule for the board - */ - public void setPuzzleModule(Puzzle puzzle) { - this.puzzle = puzzle; - } - - public String getCurFileName() { - return this.curFileName; - } - - /** - * Adds a {@link IHistoryListener} - * - * @param listener listener to add - */ - @Override - public void addHistoryListener(IHistoryListener listener) { - historyListeners.add(listener); - } - - /** - * Adds a {@link IHistoryListener} - * - * @param listener listener to remove - */ - @Override - public void removeHistoryListener(IHistoryListener listener) { - historyListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyHistoryListeners(Consumer algorithm) { - historyListeners.forEach(algorithm); - } - - /** - * Gets the History object for storing changes to the board states - * - * @return History object - */ - public History getHistory() { - return history; + importer.initializePuzzle(node); + puzzle.initializeView(); + puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzle(puzzle); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new InvalidFileFormatException("Puzzle creation error"); + } + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } + } + + /** + * Sets the window title to 'PuzzleName - FileName' Removes the extension + * + * @param puzzleName puzzle name for the file + * @param fileName file name of the edu.rpi.legup.puzzle + */ + public void setWindowTitle(String puzzleName, String fileName) { + File file = new File(fileName); + legupUI.setTitle(puzzleName + " - " + file.getName()); + } + + /** + * Gets the Config info + * + * @return Config object + */ + public Config getConfig() { + return config; + } + + /** + * Gets the LegupUI + * + * @return LegupUI + */ + public LegupUI getLegupUI() { + return legupUI; + } + + /** + * Gets the initial board state + * + * @return the initial board state + */ + public Board getBoard() { + return puzzle == null ? null : puzzle.getCurrentBoard(); + } + + /** + * Sets the initial board state and the tree + * + * @param board initial board + */ + public void setBoard(Board board) { + puzzle.setCurrentBoard(board); + } + + /** + * Gets the rules tree + * + * @return rules tree + */ + public Tree getTree() { + return puzzle == null ? null : puzzle.getTree(); + } + + /** + * Gets the Puzzle for the board + * + * @return the Puzzle for the board + */ + public Puzzle getPuzzleModule() { + return puzzle; + } + + /** + * Sets the Puzzle for the board + * + * @param puzzle the PuzzleModule for the board + */ + public void setPuzzleModule(Puzzle puzzle) { + this.puzzle = puzzle; + } + + public String getCurFileName() { + return this.curFileName; + } + + /** + * Adds a {@link IHistoryListener} + * + * @param listener listener to add + */ + @Override + public void addHistoryListener(IHistoryListener listener) { + historyListeners.add(listener); + } + + /** + * Adds a {@link IHistoryListener} + * + * @param listener listener to remove + */ + @Override + public void removeHistoryListener(IHistoryListener listener) { + historyListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyHistoryListeners(Consumer algorithm) { + historyListeners.forEach(algorithm); + } + + /** + * Gets the History object for storing changes to the board states + * + * @return History object + */ + public History getHistory() { + return history; + } } - diff --git a/src/main/java/edu/rpi/legup/app/InvalidConfigException.java b/src/main/java/edu/rpi/legup/app/InvalidConfigException.java index a570e7d44..03120dffe 100644 --- a/src/main/java/edu/rpi/legup/app/InvalidConfigException.java +++ b/src/main/java/edu/rpi/legup/app/InvalidConfigException.java @@ -1,7 +1,7 @@ package edu.rpi.legup.app; public class InvalidConfigException extends Exception { - public InvalidConfigException(String message) { - super(message); - } + public InvalidConfigException(String message) { + super(message); + } } diff --git a/src/main/java/edu/rpi/legup/app/LegupPreferences.java b/src/main/java/edu/rpi/legup/app/LegupPreferences.java index 578cefc5b..eb5ea5981 100644 --- a/src/main/java/edu/rpi/legup/app/LegupPreferences.java +++ b/src/main/java/edu/rpi/legup/app/LegupPreferences.java @@ -6,113 +6,120 @@ public class LegupPreferences { - private static LegupPreferences instance; - - private static String SAVED_PATH = ""; - - private static final Preferences preferences = Preferences.userNodeForPackage(LegupPreferences.class); - - private static final Map preferencesMap = new HashMap<>(); - private static final Map defaultPreferencesMap = new HashMap<>(); - - public static final String WORK_DIRECTORY = "work-directory"; - public static final String START_FULL_SCREEN = "start-full-screen"; - public static final String AUTO_UPDATE = "auto-update"; - public static final String DARK_MODE = "night-mode"; - public static final String SHOW_MISTAKES = "show-mistakes"; - public static final String SHOW_ANNOTATIONS = "show-annotations"; - public static final String ALLOW_DEFAULT_RULES = "allow-default-rules"; - public static final String AUTO_GENERATE_CASES = "auto-generate-cases"; - public static final String IMMEDIATE_FEEDBACK = "immediate-feedback"; - public static final String COLOR_BLIND = "color-blind"; - - - static { - defaultPreferencesMap.put(WORK_DIRECTORY, System.getProperty("user.home")); - defaultPreferencesMap.put(START_FULL_SCREEN, Boolean.toString(false)); - defaultPreferencesMap.put(AUTO_UPDATE, Boolean.toString(true)); - defaultPreferencesMap.put(DARK_MODE, Boolean.toString(false)); - defaultPreferencesMap.put(SHOW_MISTAKES, Boolean.toString(true)); - defaultPreferencesMap.put(SHOW_ANNOTATIONS, Boolean.toString(false)); - defaultPreferencesMap.put(ALLOW_DEFAULT_RULES, Boolean.toString(false)); - defaultPreferencesMap.put(AUTO_GENERATE_CASES, Boolean.toString(true)); - defaultPreferencesMap.put(IMMEDIATE_FEEDBACK, Boolean.toString(true)); - defaultPreferencesMap.put(COLOR_BLIND, Boolean.toString(false)); + private static LegupPreferences instance; + + private static String SAVED_PATH = ""; + + private static final Preferences preferences = + Preferences.userNodeForPackage(LegupPreferences.class); + + private static final Map preferencesMap = new HashMap<>(); + private static final Map defaultPreferencesMap = new HashMap<>(); + + public static final String WORK_DIRECTORY = "work-directory"; + public static final String START_FULL_SCREEN = "start-full-screen"; + public static final String AUTO_UPDATE = "auto-update"; + public static final String DARK_MODE = "night-mode"; + public static final String SHOW_MISTAKES = "show-mistakes"; + public static final String SHOW_ANNOTATIONS = "show-annotations"; + public static final String ALLOW_DEFAULT_RULES = "allow-default-rules"; + public static final String AUTO_GENERATE_CASES = "auto-generate-cases"; + public static final String IMMEDIATE_FEEDBACK = "immediate-feedback"; + public static final String COLOR_BLIND = "color-blind"; + + static { + defaultPreferencesMap.put(WORK_DIRECTORY, System.getProperty("user.home")); + defaultPreferencesMap.put(START_FULL_SCREEN, Boolean.toString(false)); + defaultPreferencesMap.put(AUTO_UPDATE, Boolean.toString(true)); + defaultPreferencesMap.put(DARK_MODE, Boolean.toString(false)); + defaultPreferencesMap.put(SHOW_MISTAKES, Boolean.toString(true)); + defaultPreferencesMap.put(SHOW_ANNOTATIONS, Boolean.toString(false)); + defaultPreferencesMap.put(ALLOW_DEFAULT_RULES, Boolean.toString(false)); + defaultPreferencesMap.put(AUTO_GENERATE_CASES, Boolean.toString(true)); + defaultPreferencesMap.put(IMMEDIATE_FEEDBACK, Boolean.toString(true)); + defaultPreferencesMap.put(COLOR_BLIND, Boolean.toString(false)); + } + + static { + preferencesMap.put( + WORK_DIRECTORY, preferences.get(WORK_DIRECTORY, defaultPreferencesMap.get(WORK_DIRECTORY))); + preferencesMap.put( + START_FULL_SCREEN, + preferences.get(START_FULL_SCREEN, defaultPreferencesMap.get(START_FULL_SCREEN))); + preferencesMap.put( + AUTO_UPDATE, preferences.get(AUTO_UPDATE, defaultPreferencesMap.get(AUTO_UPDATE))); + preferencesMap.put(DARK_MODE, preferences.get(DARK_MODE, defaultPreferencesMap.get(DARK_MODE))); + preferencesMap.put( + SHOW_MISTAKES, preferences.get(SHOW_MISTAKES, defaultPreferencesMap.get(SHOW_MISTAKES))); + preferencesMap.put( + SHOW_ANNOTATIONS, + preferences.get(SHOW_ANNOTATIONS, defaultPreferencesMap.get(SHOW_ANNOTATIONS))); + preferencesMap.put( + ALLOW_DEFAULT_RULES, + preferences.get(ALLOW_DEFAULT_RULES, defaultPreferencesMap.get(ALLOW_DEFAULT_RULES))); + preferencesMap.put( + AUTO_GENERATE_CASES, + preferences.get(AUTO_GENERATE_CASES, defaultPreferencesMap.get(AUTO_GENERATE_CASES))); + preferencesMap.put( + IMMEDIATE_FEEDBACK, + preferences.get(IMMEDIATE_FEEDBACK, defaultPreferencesMap.get(IMMEDIATE_FEEDBACK))); + preferencesMap.put( + COLOR_BLIND, preferences.get(COLOR_BLIND, defaultPreferencesMap.get(COLOR_BLIND))); + } + + /** + * Gets the legup preferences singleton instance. + * + * @return legup preferences + */ + public static LegupPreferences getInstance() { + if (instance == null) { + instance = new LegupPreferences(); } - - static { - preferencesMap.put(WORK_DIRECTORY, preferences.get(WORK_DIRECTORY, defaultPreferencesMap.get(WORK_DIRECTORY))); - preferencesMap.put(START_FULL_SCREEN, preferences.get(START_FULL_SCREEN, defaultPreferencesMap.get(START_FULL_SCREEN))); - preferencesMap.put(AUTO_UPDATE, preferences.get(AUTO_UPDATE, defaultPreferencesMap.get(AUTO_UPDATE))); - preferencesMap.put(DARK_MODE, preferences.get(DARK_MODE, defaultPreferencesMap.get(DARK_MODE))); - preferencesMap.put(SHOW_MISTAKES, preferences.get(SHOW_MISTAKES, defaultPreferencesMap.get(SHOW_MISTAKES))); - preferencesMap.put(SHOW_ANNOTATIONS, preferences.get(SHOW_ANNOTATIONS, defaultPreferencesMap.get(SHOW_ANNOTATIONS))); - preferencesMap.put(ALLOW_DEFAULT_RULES, preferences.get(ALLOW_DEFAULT_RULES, defaultPreferencesMap.get(ALLOW_DEFAULT_RULES))); - preferencesMap.put(AUTO_GENERATE_CASES, preferences.get(AUTO_GENERATE_CASES, defaultPreferencesMap.get(AUTO_GENERATE_CASES))); - preferencesMap.put(IMMEDIATE_FEEDBACK, preferences.get(IMMEDIATE_FEEDBACK, defaultPreferencesMap.get(IMMEDIATE_FEEDBACK))); - preferencesMap.put(COLOR_BLIND, preferences.get(COLOR_BLIND, defaultPreferencesMap.get(COLOR_BLIND))); - } - - /** - * Gets the legup preferences singleton instance. - * - * @return legup preferences - */ - public static LegupPreferences getInstance() { - if (instance == null) { - instance = new LegupPreferences(); - } - return instance; - } - - /** - * Private LegupPreferences Singleton Constructor - */ - private LegupPreferences() { - + return instance; + } + + /** Private LegupPreferences Singleton Constructor */ + private LegupPreferences() {} + + /** + * Gets the user preference by the string key + * + * @param key key name of the preference + * @return value of the preference + */ + public String getUserPref(String key) { + return preferencesMap.get(key); + } + + /** + * Gets the user preference by the string key, value pair + * + * @param key key name of the preference + * @param value value of the preference + */ + public void setUserPref(String key, String value) { + preferences.put(key, value); + preferencesMap.put(key, value); + } + + public boolean getUserPrefAsBool(String key) { + if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(true))) { + return true; + } else { + if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(false))) { + return false; + } else { + throw new RuntimeException("Cannot get user preference - " + key); + } } + } - /** - * Gets the user preference by the string key - * - * @param key key name of the preference - * @return value of the preference - */ - public String getUserPref(String key) { - return preferencesMap.get(key); - } + public String getSavedPath() { + return SAVED_PATH; + } - /** - * Gets the user preference by the string key, value pair - * - * @param key key name of the preference - * @param value value of the preference - */ - public void setUserPref(String key, String value) { - preferences.put(key, value); - preferencesMap.put(key, value); - } - - public boolean getUserPrefAsBool(String key) { - if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(true))) { - return true; - } - else { - if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(false))) { - return false; - } - else { - throw new RuntimeException("Cannot get user preference - " + key); - } - } - } - - - public String getSavedPath() { - return SAVED_PATH; - } - - public void setSavedPath(String path) { - SAVED_PATH = path; - } + public void setSavedPath(String path) { + SAVED_PATH = path; + } } diff --git a/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java b/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java index 36ffb08aa..4a055ab3a 100644 --- a/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java +++ b/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java @@ -1,113 +1,103 @@ package edu.rpi.legup.app; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.history.ICommand; -import edu.rpi.legup.history.ValidateDirectRuleCommand; import edu.rpi.legup.history.ValidateContradictionRuleCommand; -import edu.rpi.legup.model.rules.DirectRule; +import edu.rpi.legup.history.ValidateDirectRuleCommand; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.Rule; import edu.rpi.legup.model.rules.RuleType; import edu.rpi.legup.ui.proofeditorui.treeview.TreeView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; - -import javax.swing.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.HashMap; import java.util.Map; - -import static edu.rpi.legup.app.GameBoardFacade.getInstance; +import javax.swing.*; public class PuzzleKeyAccelerator implements KeyListener { - private Map keyStrokeMap; - - public PuzzleKeyAccelerator() { - this.keyStrokeMap = new HashMap<>(); - } - - public void addKeyAccelerator(KeyStroke keyStroke, Rule rule) { - keyStrokeMap.put(keyStroke, rule); - } - - public Map getKeyStrokeMap() { - return this.keyStrokeMap; - } - - public void clearKeyMap() { - this.keyStrokeMap.clear(); - } - - /** - * Invoked when a key has been typed. - * See the class description for {@link KeyEvent} for a definition of - * a key typed event. - * - * @param e the event to be processed - */ - @Override - public void keyTyped(KeyEvent e) { - - } - - /** - * Invoked when a key has been pressed. - * See the class description for {@link KeyEvent} for a definition of - * a key pressed event. - * - * @param e the event to be processed - */ - @Override - public void keyPressed(KeyEvent e) { - KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); - Rule rule = keyStrokeMap.get(keyStroke); - if (rule != null) { - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - - String update = ""; - if (rule.getRuleType() == RuleType.CASE) { - // TODO: review this line of code and figure out what it's supposed to do (remove if necessary) -// handleCaseRule((CaseRule)rule); - } - else { - if (rule.getRuleType() == RuleType.CONTRADICTION) { - TreeViewSelection selection = treeView.getSelection(); - - ICommand validate = new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } - else { - update = validate.getError(); - } - } - else { - TreeViewSelection selection = treeView.getSelection(); - - ICommand validate = new ValidateDirectRuleCommand(selection, (DirectRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } - else { - update = validate.getError(); - } - } - } - GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(update); + private Map keyStrokeMap; + + public PuzzleKeyAccelerator() { + this.keyStrokeMap = new HashMap<>(); + } + + public void addKeyAccelerator(KeyStroke keyStroke, Rule rule) { + keyStrokeMap.put(keyStroke, rule); + } + + public Map getKeyStrokeMap() { + return this.keyStrokeMap; + } + + public void clearKeyMap() { + this.keyStrokeMap.clear(); + } + + /** + * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a + * definition of a key typed event. + * + * @param e the event to be processed + */ + @Override + public void keyTyped(KeyEvent e) {} + + /** + * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a + * definition of a key pressed event. + * + * @param e the event to be processed + */ + @Override + public void keyPressed(KeyEvent e) { + KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); + Rule rule = keyStrokeMap.get(keyStroke); + if (rule != null) { + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + + String update = ""; + if (rule.getRuleType() == RuleType.CASE) { + // TODO: review this line of code and figure out what it's supposed to do (remove if + // necessary) + // handleCaseRule((CaseRule)rule); + } else { + if (rule.getRuleType() == RuleType.CONTRADICTION) { + TreeViewSelection selection = treeView.getSelection(); + + ICommand validate = + new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + update = validate.getError(); + } + } else { + TreeViewSelection selection = treeView.getSelection(); + + ICommand validate = new ValidateDirectRuleCommand(selection, (DirectRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + update = validate.getError(); + } } + } + GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(update); } - - /** - * Invoked when a key has been released. - * See the class description for {@link KeyEvent} for a definition of - * a key released event. - * - * @param e the event to be processed - */ - @Override - public void keyReleased(KeyEvent e) { - - } + } + + /** + * Invoked when a key has been released. See the class description for {@link KeyEvent} for a + * definition of a key released event. + * + * @param e the event to be processed + */ + @Override + public void keyReleased(KeyEvent e) {} } diff --git a/src/main/java/edu/rpi/legup/controller/BoardController.java b/src/main/java/edu/rpi/legup/controller/BoardController.java index f9c328a99..f672961d2 100644 --- a/src/main/java/edu/rpi/legup/controller/BoardController.java +++ b/src/main/java/edu/rpi/legup/controller/BoardController.java @@ -3,102 +3,89 @@ import java.awt.*; import java.awt.event.*; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - public class BoardController extends Controller { - protected Point lastLeftMousePoint; - protected Point lastRightMousePoint; - - /** - * BoardController Constructor creates a controller object to listen - * to ui events from a ScrollView - */ - public BoardController() { - super(); - lastLeftMousePoint = null; - lastRightMousePoint = null; - } - - /** - * Mouse Clicked event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) { - - } - - /** - * Mouse Pressed event - sets the cursor to the move cursor and stores - * info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); - } - - /** - * Mouse Released event - sets the cursor back to the default cursor and reset - * info for panning - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - } - - /** - * Mouse Entered event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) { - - } - - /** - * Mouse Exited event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) { - - } - - /** - * Mouse Dragged event - adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - super.mouseDragged(e); - } - - /** - * Mouse Moved event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) { - - } - - /** - * Mouse Wheel Moved event - zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - super.mouseWheelMoved(e); - } + protected Point lastLeftMousePoint; + protected Point lastRightMousePoint; + + /** + * BoardController Constructor creates a controller object to listen to ui events from a + * ScrollView + */ + public BoardController() { + super(); + lastLeftMousePoint = null; + lastRightMousePoint = null; + } + + /** + * Mouse Clicked event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} + + /** + * Mouse Pressed event - sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); + } + + /** + * Mouse Released event - sets the cursor back to the default cursor and reset info for panning + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + } + + /** + * Mouse Entered event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) {} + + /** + * Mouse Exited event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) {} + + /** + * Mouse Dragged event - adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + super.mouseDragged(e); + } + + /** + * Mouse Moved event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) {} + + /** + * Mouse Wheel Moved event - zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + super.mouseWheelMoved(e); + } } diff --git a/src/main/java/edu/rpi/legup/controller/Controller.java b/src/main/java/edu/rpi/legup/controller/Controller.java index 5eef8cc17..cd281fc21 100644 --- a/src/main/java/edu/rpi/legup/controller/Controller.java +++ b/src/main/java/edu/rpi/legup/controller/Controller.java @@ -1,132 +1,121 @@ package edu.rpi.legup.controller; import edu.rpi.legup.ui.ScrollView; - -import javax.swing.*; import java.awt.*; import java.awt.event.*; +import javax.swing.*; public abstract class Controller implements MouseMotionListener, MouseListener, MouseWheelListener { - protected ScrollView viewer; - private int x, y; - private boolean pan; - - /** - * Controller Constructor creates a controller object to listen to ui events from a {@link ScrollView} - */ - public Controller() { - x = y = -1; - pan = false; - } - - public void setViewer(ScrollView viewer) { - this.viewer = viewer; + protected ScrollView viewer; + private int x, y; + private boolean pan; + + /** + * Controller Constructor creates a controller object to listen to ui events from a {@link + * ScrollView} + */ + public Controller() { + x = y = -1; + pan = false; + } + + public void setViewer(ScrollView viewer) { + this.viewer = viewer; + } + + /** + * Mouse Clicked event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} + + /** + * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON2) { + pan = true; + x = e.getX(); + y = e.getY(); + viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } - - /** - * Mouse Clicked event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) { - - } - - /** - * Mouse Pressed event sets the cursor to the move cursor and stores - * info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON2) { - pan = true; - x = e.getX(); - y = e.getY(); - viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); - } + } + + /** + * Mouse Released event sets the cursor back to the default cursor and reset info for panning + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON2) { + pan = false; + viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } - - /** - * Mouse Released event sets the cursor back to the default cursor and reset - * info for panning - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON2) { - pan = false; - viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } + } + + /** + * Mouse Entered event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) {} + + /** + * Mouse Exited event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) {} + + /** + * Mouse Dragged event adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + if (pan) { + JViewport viewport = viewer.getViewport(); + Point position = viewer.getViewport().getViewPosition(); + position.x += (x - e.getX()); + position.y += (y - e.getY()); + viewport.setViewPosition(position); + viewer.revalidate(); } - - /** - * Mouse Entered event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) { - - } - - /** - * Mouse Exited event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) { - - } - - /** - * Mouse Dragged event adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - if (pan) { - JViewport viewport = viewer.getViewport(); - Point position = viewer.getViewport().getViewPosition(); - position.x += (x - e.getX()); - position.y += (y - e.getY()); - viewport.setViewPosition(position); - viewer.revalidate(); - } - } - - /** - * Mouse Moved event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) { - - } - - /** - * Mouse Wheel Moved event zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - // System.out.println(e.getWheelRotation()); - if (e.isControlDown()) { - if (e.getWheelRotation() != 0) { - viewer.zoom(e.getWheelRotation() * 2, e.getPoint()); - } - } - else { - if (e.getWheelRotation() != 0) { - viewer.zoom(e.getWheelRotation(), e.getPoint()); - } - } + } + + /** + * Mouse Moved event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) {} + + /** + * Mouse Wheel Moved event zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + // System.out.println(e.getWheelRotation()); + if (e.isControlDown()) { + if (e.getWheelRotation() != 0) { + viewer.zoom(e.getWheelRotation() * 2, e.getPoint()); + } + } else { + if (e.getWheelRotation() != 0) { + viewer.zoom(e.getWheelRotation(), e.getPoint()); + } } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/controller/CursorController.java b/src/main/java/edu/rpi/legup/controller/CursorController.java index 0c9a644ed..a97f147b8 100644 --- a/src/main/java/edu/rpi/legup/controller/CursorController.java +++ b/src/main/java/edu/rpi/legup/controller/CursorController.java @@ -2,52 +2,53 @@ import java.awt.Component; import java.awt.Cursor; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Timer; import java.util.TimerTask; public class CursorController { - public static final Cursor BUSY_CURSOR = new Cursor(Cursor.WAIT_CURSOR); - public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); - public static final int DELAY = 200; // in milliseconds + public static final Cursor BUSY_CURSOR = new Cursor(Cursor.WAIT_CURSOR); + public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); + public static final int DELAY = 200; // in milliseconds - private CursorController() { - // Intentionally left empty - } + private CursorController() { + // Intentionally left empty + } - /** - * Creates an ActionListener that will still do the same action processing as the given - * ActionListener while also displaying a loading cursor if the time it takes to execute - * the given process exceeds the time (in milliseconds) specified in this.DELAY - *

- * Sources consulted: http://www.catalysoft.com/articles/busycursor.html - * - * @param component The component you want to set the cursor for - * @param mainActionListener The ActionListener that does the intended action processing - * @return An ActionListener object that does the same action processing - * as mainActionListener while also modifying the cursor if needed - */ - public static ActionListener createListener(final Component component, final ActionListener mainActionListener) { - ActionListener actionListener = e -> { - TimerTask timerTask = new TimerTask() { + /** + * Creates an ActionListener that will still do the same action processing as the given + * ActionListener while also displaying a loading cursor if the time it takes to execute the given + * process exceeds the time (in milliseconds) specified in this.DELAY + * + *

Sources consulted: http://www.catalysoft.com/articles/busycursor.html + * + * @param component The component you want to set the cursor for + * @param mainActionListener The ActionListener that does the intended action processing + * @return An ActionListener object that does the same action processing as mainActionListener + * while also modifying the cursor if needed + */ + public static ActionListener createListener( + final Component component, final ActionListener mainActionListener) { + ActionListener actionListener = + e -> { + TimerTask timerTask = + new TimerTask() { @Override public void run() { - component.setCursor(BUSY_CURSOR); + component.setCursor(BUSY_CURSOR); } - }; + }; - Timer timer = new Timer(); - try { - timer.schedule(timerTask, DELAY); - mainActionListener.actionPerformed(e); - } - finally { - timer.cancel(); - component.setCursor(DEFAULT_CURSOR); - } + Timer timer = new Timer(); + try { + timer.schedule(timerTask, DELAY); + mainActionListener.actionPerformed(e); + } finally { + timer.cancel(); + component.setCursor(DEFAULT_CURSOR); + } }; - return actionListener; - } -} \ No newline at end of file + return actionListener; + } +} diff --git a/src/main/java/edu/rpi/legup/controller/EditorElementController.java b/src/main/java/edu/rpi/legup/controller/EditorElementController.java index 80e7dd35a..7aa1fe06c 100644 --- a/src/main/java/edu/rpi/legup/controller/EditorElementController.java +++ b/src/main/java/edu/rpi/legup/controller/EditorElementController.java @@ -1,71 +1,52 @@ package edu.rpi.legup.controller; -import edu.rpi.legup.app.GameBoardFacade; -import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.history.*; -import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.elements.Element; -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.CaseBoard; -import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.*; -import edu.rpi.legup.model.tree.TreeElement; -import edu.rpi.legup.model.tree.TreeElementType; -import edu.rpi.legup.ui.proofeditorui.rulesview.RuleButton; -import edu.rpi.legup.ui.proofeditorui.treeview.TreeElementView; -import edu.rpi.legup.ui.proofeditorui.treeview.TreePanel; -import edu.rpi.legup.ui.proofeditorui.treeview.TreeView; -import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; import edu.rpi.legup.ui.puzzleeditorui.elementsview.ElementButton; - -import javax.swing.*; -import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.util.List; - -import static edu.rpi.legup.app.GameBoardFacade.getInstance; +import javax.swing.*; public class EditorElementController implements ActionListener { - protected Object lastSource; - protected ElementController elementController; - protected ElementButton prevButton; - - public EditorElementController() { - super(); - elementController = null; - prevButton = null; + protected Object lastSource; + protected ElementController elementController; + protected ElementButton prevButton; + + public EditorElementController() { + super(); + elementController = null; + prevButton = null; + } + + public void setElementController(ElementController elementController) { + this.elementController = elementController; + } + + public void buttonPressed(Element element) { + // TODO: implement what happens when element is pressed + + System.out.printf("%s button pressed!\n", element.getElementName()); + if (elementController != null) { + elementController.setSelectedElement(element); } + } - public void setElementController(ElementController elementController) { - this.elementController = elementController; - } + @Override + public void actionPerformed(ActionEvent e) { + lastSource = e.getSource(); + ElementButton button = (ElementButton) lastSource; + buttonPressed(button.getElement()); - public void buttonPressed(Element element) { - // TODO: implement what happens when element is pressed - - System.out.printf("%s button pressed!\n", element.getElementName()); - if (elementController != null) { - elementController.setSelectedElement(element); - } + // reset border in previous selected button + if (this.prevButton != null) { + this.prevButton.resetBorder(); } - @Override - public void actionPerformed(ActionEvent e) { - lastSource = e.getSource(); - ElementButton button = (ElementButton) lastSource; - buttonPressed(button.getElement()); - - // reset border in previous selected button - if (this.prevButton != null) { - this.prevButton.resetBorder(); - } - - // change border color when select a button - button.setBorderToSelected(); + // change border color when select a button + button.setBorderToSelected(); - this.prevButton = button; - - } + this.prevButton = button; + } } diff --git a/src/main/java/edu/rpi/legup/controller/ElementController.java b/src/main/java/edu/rpi/legup/controller/ElementController.java index 50fa7d1b9..f17461ebc 100644 --- a/src/main/java/edu/rpi/legup/controller/ElementController.java +++ b/src/main/java/edu/rpi/legup/controller/ElementController.java @@ -1,10 +1,12 @@ package edu.rpi.legup.controller; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.ui.ScrollView; +import static edu.rpi.legup.app.GameBoardFacade.*; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.history.AutoCaseRuleCommand; +import edu.rpi.legup.history.EditDataCommand; +import edu.rpi.legup.history.ICommand; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.Board; @@ -14,346 +16,334 @@ import edu.rpi.legup.model.tree.TreeElement; import edu.rpi.legup.model.tree.TreeElementType; import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.ui.DynamicView; import edu.rpi.legup.ui.boardview.BoardView; import edu.rpi.legup.ui.boardview.ElementSelection; import edu.rpi.legup.ui.boardview.ElementView; import edu.rpi.legup.ui.boardview.SelectionItemView; import edu.rpi.legup.ui.proofeditorui.treeview.*; -import edu.rpi.legup.history.ICommand; -import edu.rpi.legup.history.EditDataCommand; - import java.awt.*; import java.awt.event.*; -import static edu.rpi.legup.app.GameBoardFacade.*; - -public class ElementController implements MouseListener, MouseMotionListener, ActionListener, KeyListener { - protected BoardView boardView; - private Element selectedElement; - - /** - * ElementController Constructor controller to handles ui events associated interacting with a {@link BoardView} - */ - public ElementController() { - this.boardView = null; - this.selectedElement = null; +public class ElementController + implements MouseListener, MouseMotionListener, ActionListener, KeyListener { + protected BoardView boardView; + private Element selectedElement; + + /** + * ElementController Constructor controller to handles ui events associated interacting with a + * {@link BoardView} + */ + public ElementController() { + this.boardView = null; + this.selectedElement = null; + } + + public void setSelectedElement(Element selectedElement) { + this.selectedElement = selectedElement; + } + + /** + * Sets the {@link BoardView} + * + * @param boardView board view + */ + public void setBoardView(BoardView boardView) { + this.boardView = boardView; + } + + /** + * Invoked when the mouse button has been clicked (pressed and released) on a component. + * + * @param e the event to be processed + */ + @Override + public void mouseClicked(MouseEvent e) {} + + /** + * Invoked when a mouse button has been pressed on a component. + * + * @param e the event to be processed + */ + @Override + public void mousePressed(MouseEvent e) {} + + /** + * Invoked when a mouse button has been released on a component. + * + * @param e the event to be processed + */ + @Override + public void mouseReleased(MouseEvent e) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = null; + if (treePanel != null) { + treeView = treePanel.getTreeView(); } - public void setSelectedElement(Element selectedElement) { - this.selectedElement = selectedElement; + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - - /** - * Sets the {@link BoardView} - * - * @param boardView board view - */ - public void setBoardView(BoardView boardView) { - this.boardView = boardView; + Board board = boardView.getBoard(); + ElementView elementView = boardView.getElement(e.getPoint()); + TreeViewSelection selection = null; + if (treeView != null) { + selection = treeView.getSelection(); } - - /** - * Invoked when the mouse button has been clicked (pressed and released) on a component. - * - * @param e the event to be processed - */ - @Override - public void mouseClicked(MouseEvent e) { - - } - - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e the event to be processed - */ - @Override - public void mousePressed(MouseEvent e) { - - } - - /** - * Invoked when a mouse button has been released on a component. - * - * @param e the event to be processed - */ - @Override - public void mouseReleased(MouseEvent e) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = null; - if (treePanel != null) { - treeView = treePanel.getTreeView(); - } - - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); + // funny + if (elementView != null) { + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + AutoCaseRuleCommand autoCaseRuleCommand = + new AutoCaseRuleCommand(elementView, selection, caseBoard.getCaseRule(), caseBoard, e); + if (autoCaseRuleCommand.canExecute()) { + autoCaseRuleCommand.execute(); + getInstance().getHistory().pushChange(autoCaseRuleCommand); + if (treePanel != null) { + treePanel.updateError(""); + } + } else { + if (treePanel != null) { + treePanel.updateError(autoCaseRuleCommand.getError()); + } } - Board board = boardView.getBoard(); - ElementView elementView = boardView.getElement(e.getPoint()); - TreeViewSelection selection = null; - if (treeView != null) { - selection = treeView.getSelection(); - } - // funny - if (elementView != null) { - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - AutoCaseRuleCommand autoCaseRuleCommand = new AutoCaseRuleCommand(elementView, selection, caseBoard.getCaseRule(), caseBoard, e); - if (autoCaseRuleCommand.canExecute()) { - autoCaseRuleCommand.execute(); - getInstance().getHistory().pushChange(autoCaseRuleCommand); - if (treePanel != null) { - treePanel.updateError(""); - } - } - else { - if (treePanel != null) { - treePanel.updateError(autoCaseRuleCommand.getError()); - } - } + } else { + if (selection != null) { + ICommand edit = new EditDataCommand(elementView, selection, e); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + if (treePanel != null) { + treePanel.updateError(""); } - else { - if (selection != null) { - ICommand edit = new EditDataCommand(elementView, selection, e); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - if (treePanel != null) { - treePanel.updateError(""); - } - } - else { - if (treePanel != null) { - treePanel.updateError(edit.getError()); - } - } - } + } else { + if (treePanel != null) { + treePanel.updateError(edit.getError()); } + } } -// if (selectedElement != null) { - GridBoard b = (GridBoard) this.boardView.getBoard(); - Point point = e.getPoint(); - Point scaledPoint = new Point((int) Math.floor(point.x / (30 * this.boardView.getScale())), (int) Math.floor(point.y / (30 * this.boardView.getScale()))); - if (this.boardView.getBoard() instanceof TreeTentBoard) { - scaledPoint.setLocation(scaledPoint.getX() - 1, scaledPoint.getY() - 1); - } - System.out.printf("selected Element is NOT null, attempting to change board at (%d, %d)\n", scaledPoint.x, scaledPoint.y); -// System.out.println("Before: " + b.getCell(scaledPoint.x, scaledPoint.y).getData()); - b.setCell(scaledPoint.x, scaledPoint.y, this.selectedElement, e); -// System.out.println("After: " + b.getCell(scaledPoint.x, scaledPoint.y).getData()); -// } else { -// System.out.println("selected Element is null!"); -// } - boardView.repaint(); + } } - - /** - * Invoked when the mouse enters a component. - * - * @param e the event to be processed - */ - @Override - public void mouseEntered(MouseEvent e) { - boardView.setFocusable(true); - boardView.requestFocusInWindow(); - TreeElement treeElement = boardView.getTreeElement(); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); - } - Board board = boardView.getBoard(); - ElementView elementView = boardView.getElement(e.getPoint()); - ElementSelection selection = boardView.getSelection(); - String error = null; - if (elementView != null) { - selection.newHover(elementView); - if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { - PuzzleElement element = elementView.getPuzzleElement(); - if (treeElement != null && treeElement.getType() == TreeElementType.TRANSITION && board.getModifiedData().contains(element)) { - TreeTransition transition = (TreeTransition) treeElement; - if (transition.isJustified() && !transition.isCorrect()) { - error = transition.getRule().checkRuleAt(transition, element); - } - } - if (error != null) { - dynamicView.updateError(error); - } - else { - dynamicView.resetStatus(); - } - } - boardView.repaint(); - } + // if (selectedElement != null) { + GridBoard b = (GridBoard) this.boardView.getBoard(); + Point point = e.getPoint(); + Point scaledPoint = + new Point( + (int) Math.floor(point.x / (30 * this.boardView.getScale())), + (int) Math.floor(point.y / (30 * this.boardView.getScale()))); + if (this.boardView.getBoard() instanceof TreeTentBoard) { + scaledPoint.setLocation(scaledPoint.getX() - 1, scaledPoint.getY() - 1); } - - /** - * Invoked when the mouse exits a component. - * - * @param e the event to be processed - */ - @Override - public void mouseExited(MouseEvent e) { - boardView.setFocusable(false); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + System.out.printf( + "selected Element is NOT null, attempting to change board at (%d, %d)\n", + scaledPoint.x, scaledPoint.y); + // System.out.println("Before: " + b.getCell(scaledPoint.x, + // scaledPoint.y).getData()); + b.setCell(scaledPoint.x, scaledPoint.y, this.selectedElement, e); + // System.out.println("After: " + b.getCell(scaledPoint.x, scaledPoint.y).getData()); + // } else { + // System.out.println("selected Element is null!"); + // } + boardView.repaint(); + } + + /** + * Invoked when the mouse enters a component. + * + * @param e the event to be processed + */ + @Override + public void mouseEntered(MouseEvent e) { + boardView.setFocusable(true); + boardView.requestFocusInWindow(); + TreeElement treeElement = boardView.getTreeElement(); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + Board board = boardView.getBoard(); + ElementView elementView = boardView.getElement(e.getPoint()); + ElementSelection selection = boardView.getSelection(); + String error = null; + if (elementView != null) { + selection.newHover(elementView); + if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { + PuzzleElement element = elementView.getPuzzleElement(); + if (treeElement != null + && treeElement.getType() == TreeElementType.TRANSITION + && board.getModifiedData().contains(element)) { + TreeTransition transition = (TreeTransition) treeElement; + if (transition.isJustified() && !transition.isCorrect()) { + error = transition.getRule().checkRuleAt(transition, element); + } } - ElementView element = boardView.getElement(e.getPoint()); - if (element != null) { - boardView.getSelection().clearHover(); - dynamicView.resetStatus(); - boardView.repaint(); + if (error != null) { + dynamicView.updateError(error); + } else { + dynamicView.resetStatus(); } + } + boardView.repaint(); } - - /** - * Invoked when the mouse dragged - * - * @param e the event to be processed - */ - @Override - public void mouseDragged(MouseEvent e) { - + } + + /** + * Invoked when the mouse exits a component. + * + * @param e the event to be processed + */ + @Override + public void mouseExited(MouseEvent e) { + boardView.setFocusable(false); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - - /** - * Invoked when the mouse moved - * - * @param e the event to be processed - */ - @Override - public void mouseMoved(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - TreeElement treeElement = boardView.getTreeElement(); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + ElementView element = boardView.getElement(e.getPoint()); + if (element != null) { + boardView.getSelection().clearHover(); + dynamicView.resetStatus(); + boardView.repaint(); + } + } + + /** + * Invoked when the mouse dragged + * + * @param e the event to be processed + */ + @Override + public void mouseDragged(MouseEvent e) {} + + /** + * Invoked when the mouse moved + * + * @param e the event to be processed + */ + @Override + public void mouseMoved(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + Board board = boardView.getBoard(); + TreeElement treeElement = boardView.getTreeElement(); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + ElementView elementView = boardView.getElement(e.getPoint()); + ElementSelection selection = boardView.getSelection(); + String error = null; + if (elementView != null && elementView != selection.getHover()) { + selection.newHover(elementView); + if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { + PuzzleElement element = elementView.getPuzzleElement(); + if (treeElement != null + && treeElement.getType() == TreeElementType.TRANSITION + && board.getModifiedData().contains(element)) { + TreeTransition transition = (TreeTransition) treeElement; + if (transition.isJustified() && !transition.isCorrect()) { + error = transition.getRule().checkRuleAt(transition, element); + } } - ElementView elementView = boardView.getElement(e.getPoint()); - ElementSelection selection = boardView.getSelection(); - String error = null; - if (elementView != null && elementView != selection.getHover()) { - selection.newHover(elementView); - if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { - PuzzleElement element = elementView.getPuzzleElement(); - if (treeElement != null && treeElement.getType() == TreeElementType.TRANSITION && board.getModifiedData().contains(element)) { - TreeTransition transition = (TreeTransition) treeElement; - if (transition.isJustified() && !transition.isCorrect()) { - error = transition.getRule().checkRuleAt(transition, element); - } - } - if (error != null) { - dynamicView.updateError(error); - } - else { - dynamicView.resetStatus(); - } - } - boardView.repaint(); + if (error != null) { + dynamicView.updateError(error); + } else { + dynamicView.resetStatus(); } + } + boardView.repaint(); } - - public void changeCell(MouseEvent e, PuzzleElement data) { - + } + + public void changeCell(MouseEvent e, PuzzleElement data) {} + + /** + * Invoked when an action occurs. + * + * @param e the event to be processed + */ + @SuppressWarnings("Unchecked") + @Override + public void actionPerformed(ActionEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } + ElementView selectedElement = boardView.getSelection().getFirstSelection(); + PuzzleElement puzzleElement = selectedElement.getPuzzleElement(); - /** - * Invoked when an action occurs. - * - * @param e the event to be processed - */ - @SuppressWarnings("Unchecked") - @Override - public void actionPerformed(ActionEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - ElementView selectedElement = boardView.getSelection().getFirstSelection(); - PuzzleElement puzzleElement = selectedElement.getPuzzleElement(); - - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeTransitionView transitionView = (TreeTransitionView) selectedView; - - Board prevBord = transitionView.getTreeElement().getParents().get(0).getBoard(); - - int value = (Integer) ((SelectionItemView) e.getSource()).getData().getData(); - - puzzleElement.setData(value); - - if (puzzleElement.equalsData(prevBord.getPuzzleElement(puzzleElement))) { - puzzleElement.setModified(false); - } - else { - puzzleElement.setModified(true); - } + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeTransitionView transitionView = (TreeTransitionView) selectedView; - transitionView.getTreeElement().propagateChange(puzzleElement); + Board prevBord = transitionView.getTreeElement().getParents().get(0).getBoard(); - boardView.repaint(); - boardView.getSelection().clearSelection(); - } + int value = (Integer) ((SelectionItemView) e.getSource()).getData().getData(); - /** - * Invoked when a key has been typed. - * See the class description for {@link KeyEvent} for a definition of - * a key typed event. - * - * @param e the event to be processed - */ - @Override - public void keyTyped(KeyEvent e) { + puzzleElement.setData(value); + if (puzzleElement.equalsData(prevBord.getPuzzleElement(puzzleElement))) { + puzzleElement.setModified(false); + } else { + puzzleElement.setModified(true); } - /** - * Invoked when a key has been pressed. - * See the class description for {@link KeyEvent} for a definition of - * a key pressed event. - * - * @param e the event to be processed - */ - @Override - public void keyPressed(KeyEvent e) { - + transitionView.getTreeElement().propagateChange(puzzleElement); + + boardView.repaint(); + boardView.getSelection().clearSelection(); + } + + /** + * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a + * definition of a key typed event. + * + * @param e the event to be processed + */ + @Override + public void keyTyped(KeyEvent e) {} + + /** + * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a + * definition of a key pressed event. + * + * @param e the event to be processed + */ + @Override + public void keyPressed(KeyEvent e) {} + + /** + * Invoked when a key has been released. See the class description for {@link KeyEvent} for a + * definition of a key released event. + * + * @param e the event to be processed + */ + @Override + public void keyReleased(KeyEvent e) { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - - /** - * Invoked when a key has been released. - * See the class description for {@link KeyEvent} for a definition of - * a key released event. - * - * @param e the event to be processed - */ - @Override - public void keyReleased(KeyEvent e) { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { - puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); - } - } + Board board = boardView.getBoard(); + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); + } } + } } diff --git a/src/main/java/edu/rpi/legup/controller/RuleController.java b/src/main/java/edu/rpi/legup/controller/RuleController.java index fef6fca45..f72dddbde 100644 --- a/src/main/java/edu/rpi/legup/controller/RuleController.java +++ b/src/main/java/edu/rpi/legup/controller/RuleController.java @@ -1,5 +1,7 @@ package edu.rpi.legup.controller; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.history.*; @@ -10,113 +12,107 @@ import edu.rpi.legup.ui.proofeditorui.rulesview.RuleButton; import edu.rpi.legup.ui.proofeditorui.rulesview.RulePanel; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class RuleController implements ActionListener { - protected Object lastSource; + protected Object lastSource; - /** - * RuleController Constructor creates a controller object to listen - * to ui events from a {@link RulePanel} - */ - public RuleController() { - super(); - } + /** + * RuleController Constructor creates a controller object to listen to ui events from a {@link + * RulePanel} + */ + public RuleController() { + super(); + } - /** - * Button Pressed event occurs a when a rule button has been pressed - * - * @param rule rule of the button that was pressed - */ - public void buttonPressed(Rule rule) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = treePanel.getTreeView(); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - List selectedViews = selection.getSelectedViews(); + /** + * Button Pressed event occurs a when a rule button has been pressed + * + * @param rule rule of the button that was pressed + */ + public void buttonPressed(Rule rule) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = treePanel.getTreeView(); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + List selectedViews = selection.getSelectedViews(); - String updateErrorString = ""; - if (rule.getRuleType() == RuleType.CASE) { - CaseRule caseRule = (CaseRule) rule; - if (selectedViews.size() == 1) { - TreeElementView elementView = selection.getFirstSelection(); - TreeElement element = elementView.getTreeElement(); - if (element.getType() == TreeElementType.TRANSITION) { - ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); - if (caseRuleCommand.canExecute()) { - caseRuleCommand.execute(); - getInstance().getHistory().pushChange(caseRuleCommand); - } - else { - updateErrorString = caseRuleCommand.getError(); - } - } - else { - if (LegupPreferences.getInstance().getUserPref(LegupPreferences.AUTO_GENERATE_CASES).equalsIgnoreCase(Boolean.toString(true))) { - CaseBoard caseBoard = caseRule.getCaseBoard(element.getBoard()); - if (caseBoard != null && caseBoard.getCount() > 0) { - puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); - } - else { - updateErrorString = "This board cannot be applied with this case rule."; - } - } - else { - updateErrorString = "Auto generated case rules are turned off in preferences."; - } - } - } - else { - ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); - if (caseRuleCommand.canExecute()) { - caseRuleCommand.execute(); - getInstance().getHistory().pushChange(caseRuleCommand); - } - else { - updateErrorString = caseRuleCommand.getError(); - } + String updateErrorString = ""; + if (rule.getRuleType() == RuleType.CASE) { + CaseRule caseRule = (CaseRule) rule; + if (selectedViews.size() == 1) { + TreeElementView elementView = selection.getFirstSelection(); + TreeElement element = elementView.getTreeElement(); + if (element.getType() == TreeElementType.TRANSITION) { + ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); + if (caseRuleCommand.canExecute()) { + caseRuleCommand.execute(); + getInstance().getHistory().pushChange(caseRuleCommand); + } else { + updateErrorString = caseRuleCommand.getError(); + } + } else { + if (LegupPreferences.getInstance() + .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) + .equalsIgnoreCase(Boolean.toString(true))) { + CaseBoard caseBoard = caseRule.getCaseBoard(element.getBoard()); + if (caseBoard != null && caseBoard.getCount() > 0) { + puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); + } else { + updateErrorString = "This board cannot be applied with this case rule."; } + } else { + updateErrorString = "Auto generated case rules are turned off in preferences."; + } } - else { - if (rule.getRuleType() == RuleType.CONTRADICTION) { - ICommand validate = new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } - else { - updateErrorString = validate.getError(); - } - } - else { - boolean def = LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.ALLOW_DEFAULT_RULES); - ICommand validate = def ? new ApplyDefaultDirectRuleCommand(selection, (DirectRule) rule) : new ValidateDirectRuleCommand(selection, (DirectRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } - else { - updateErrorString = validate.getError(); - } - } + } else { + ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); + if (caseRuleCommand.canExecute()) { + caseRuleCommand.execute(); + getInstance().getHistory().pushChange(caseRuleCommand); + } else { + updateErrorString = caseRuleCommand.getError(); } - GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(updateErrorString); + } + } else { + if (rule.getRuleType() == RuleType.CONTRADICTION) { + ICommand validate = + new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + updateErrorString = validate.getError(); + } + } else { + boolean def = + LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.ALLOW_DEFAULT_RULES); + ICommand validate = + def + ? new ApplyDefaultDirectRuleCommand(selection, (DirectRule) rule) + : new ValidateDirectRuleCommand(selection, (DirectRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + updateErrorString = validate.getError(); + } + } } + GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(updateErrorString); + } - /** - * ICommand Performed event occurs when a rule button has been pressed - * - * @param e action event object - */ - @Override - public void actionPerformed(ActionEvent e) { - lastSource = e.getSource(); - RuleButton button = (RuleButton) lastSource; - buttonPressed(button.getRule()); - } + /** + * ICommand Performed event occurs when a rule button has been pressed + * + * @param e action event object + */ + @Override + public void actionPerformed(ActionEvent e) { + lastSource = e.getSource(); + RuleButton button = (RuleButton) lastSource; + buttonPressed(button.getRule()); + } } diff --git a/src/main/java/edu/rpi/legup/controller/ToolbarController.java b/src/main/java/edu/rpi/legup/controller/ToolbarController.java index 2ee4ee25e..489e6b69f 100644 --- a/src/main/java/edu/rpi/legup/controller/ToolbarController.java +++ b/src/main/java/edu/rpi/legup/controller/ToolbarController.java @@ -1,33 +1,27 @@ package edu.rpi.legup.controller; import edu.rpi.legup.ui.LegupUI; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - public class ToolbarController implements ActionListener { - private LegupUI legupUI; - - /** - * ToolbarController Constructor - creates a new {@link ToolbarController} to listen - * for button pressed from the tool mBar - * - * @param legupUI legupUI - */ - public ToolbarController(LegupUI legupUI) { - this.legupUI = legupUI; - } + private LegupUI legupUI; - /** - * ICommand Performed event - - * - * @param e action event - */ - @Override - public void actionPerformed(ActionEvent e) { + /** + * ToolbarController Constructor - creates a new {@link ToolbarController} to listen for button + * pressed from the tool mBar + * + * @param legupUI legupUI + */ + public ToolbarController(LegupUI legupUI) { + this.legupUI = legupUI; + } - } + /** + * ICommand Performed event - + * + * @param e action event + */ + @Override + public void actionPerformed(ActionEvent e) {} } diff --git a/src/main/java/edu/rpi/legup/controller/TreeController.java b/src/main/java/edu/rpi/legup/controller/TreeController.java index 6eae4ac3b..f19b40cb1 100644 --- a/src/main/java/edu/rpi/legup/controller/TreeController.java +++ b/src/main/java/edu/rpi/legup/controller/TreeController.java @@ -1,163 +1,163 @@ package edu.rpi.legup.controller; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.tree.Tree; -import edu.rpi.legup.model.tree.TreeElementType; import edu.rpi.legup.ui.boardview.BoardView; import edu.rpi.legup.ui.proofeditorui.treeview.*; - -import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; - -import static edu.rpi.legup.app.GameBoardFacade.getInstance; +import javax.swing.*; public class TreeController extends Controller { - /** - * TreeController Constructor creates a controller object to listen to ui events from a {@link TreePanel} - */ - public TreeController() { - - } - - /** - * Mouse Clicked event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) { - - } - - /** - * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); - } - - /** - * Mouse Released event sets the cursor back to the default cursor and reset info for panning - * Set board modifiability - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - if (treeElementView != null) { - if (e.isShiftDown()) { - selection.addToSelection(treeElementView); - } - else { - if (e.isControlDown()) { - if (!(selection.getSelectedViews().size() == 1 && treeElementView == selection.getFirstSelection())) { - selection.toggleSelection(treeElementView); - } - } - else { - selection.newSelection(treeElementView); - } - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); + /** + * TreeController Constructor creates a controller object to listen to ui events from a {@link + * TreePanel} + */ + public TreeController() {} + + /** + * Mouse Clicked event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} + + /** + * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); + } + + /** + * Mouse Released event sets the cursor back to the default cursor and reset info for panning Set + * board modifiability + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + if (treeElementView != null) { + if (e.isShiftDown()) { + selection.addToSelection(treeElementView); + } else { + if (e.isControlDown()) { + if (!(selection.getSelectedViews().size() == 1 + && treeElementView == selection.getFirstSelection())) { + selection.toggleSelection(treeElementView); + } + } else { + selection.newSelection(treeElementView); } + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); } - - /** - * Mouse Entered event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - Tree tree = getInstance().getTree(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - if (treeElementView != null) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); - } + } + + /** + * Mouse Entered event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + Tree tree = getInstance().getTree(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + if (treeElementView != null) { + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); } - - /** - * Mouse Exited event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView elementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - - selection.setMousePoint(null); - if (elementView != null) { - TreeElementView selectedView = selection.getFirstSelection(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(selectedView.getTreeElement())); - } - } - - /** - * Mouse Dragged event adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - super.mouseDragged(e); + } + + /** + * Mouse Exited event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView elementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + + selection.setMousePoint(null); + if (elementView != null) { + TreeElementView selectedView = selection.getFirstSelection(); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(selectedView.getTreeElement())); } - - /** - * Mouse Moved event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - if (puzzle != null) { - TreeViewSelection selection = treeView.getSelection(); - selection.setMousePoint(treeView.getActualPoint(e.getPoint())); - if (treeElementView != null && treeElementView != selection.getHover()) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); - selection.newHover(treeElementView); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } - else { - if (treeElementView == null && selection.getHover() != null) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); - selection.clearHover(); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } - } + } + + /** + * Mouse Dragged event adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + super.mouseDragged(e); + } + + /** + * Mouse Moved event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + if (puzzle != null) { + TreeViewSelection selection = treeView.getSelection(); + selection.setMousePoint(treeView.getActualPoint(e.getPoint())); + if (treeElementView != null && treeElementView != selection.getHover()) { + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); + selection.newHover(treeElementView); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } else { + if (treeElementView == null && selection.getHover() != null) { + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); + selection.clearHover(); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } + } } - - /** - * Mouse Wheel Moved event zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - super.viewer.scroll(e.getWheelRotation()); - } + } + + /** + * Mouse Wheel Moved event zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + super.viewer.scroll(e.getWheelRotation()); + } } diff --git a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java index 0aa6f416d..2f9c3e553 100644 --- a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java @@ -6,117 +6,108 @@ import edu.rpi.legup.ui.proofeditorui.treeview.TreeElementView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; - import java.util.HashMap; import java.util.List; import java.util.Map; public class AddTreeElementCommand extends PuzzleCommand { - private TreeViewSelection selection; - - private Map addChild; + private TreeViewSelection selection; - /** - * AddTreeElementCommand Constructor creates a command for adding a tree element to the proof tree - * - * @param selection selection of tree elements views - */ - public AddTreeElementCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - this.addChild = new HashMap<>(); - } + private Map addChild; - /** - * Executes an command - */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement treeElement = view.getTreeElement(); - TreeElement child = addChild.get(treeElement); - if (child == null) { - child = tree.addTreeElement(treeElement); - } - else { - if (treeElement.getType() == TreeElementType.NODE) { - child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); - } - else { - child = tree.addTreeElement((TreeTransition) treeElement, (TreeNode) child); - } - } - addChild.put(treeElement, child); + /** + * AddTreeElementCommand Constructor creates a command for adding a tree element to the proof tree + * + * @param selection selection of tree elements views + */ + public AddTreeElementCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + this.addChild = new HashMap<>(); + } - final TreeElement finalChild = child; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalChild)); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - newSelection.addToSelection(treeView.getElementView(child)); + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement treeElement = view.getTreeElement(); + TreeElement child = addChild.get(treeElement); + if (child == null) { + child = tree.addTreeElement(treeElement); + } else { + if (treeElement.getType() == TreeElementType.NODE) { + child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); + } else { + child = tree.addTreeElement((TreeTransition) treeElement, (TreeNode) child); } + } + addChild.put(treeElement, child); + + final TreeElement finalChild = child; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalChild)); - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + newSelection.addToSelection(treeView.getElementView(child)); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } - else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) element; - if (transition.getChildNode() != null) { - return CommandError.ADD_WITH_CHILD.toString(); - } - } - else { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - TreeTransition transition = node.getChildren().get(0); - if (transition.getParents().size() > 1) { - return CommandError.ADD_TO_MERGE.toString(); - } - } - } + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } else { + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) element; + if (transition.getChildNode() != null) { + return CommandError.ADD_WITH_CHILD.toString(); + } + } else { + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + TreeTransition transition = node.getChildren().get(0); + if (transition.getParents().size() > 1) { + return CommandError.ADD_TO_MERGE.toString(); } + } } - return null; + } } + return null; + } - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - for (TreeElementView view : selection.getSelectedViews()) { - TreeElement element = view.getTreeElement(); - TreeElement child = addChild.get(element); - tree.removeTreeElement(child); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(child)); - newSelection.addToSelection(treeView.getElementView(element)); - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + for (TreeElementView view : selection.getSelectedViews()) { + TreeElement element = view.getTreeElement(); + TreeElement child = addChild.get(element); + tree.removeTreeElement(child); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(child)); + newSelection.addToSelection(treeView.getElementView(element)); } -} \ No newline at end of file + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } +} diff --git a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java index f3bca611e..558cb85d7 100644 --- a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java @@ -6,127 +6,120 @@ import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.*; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.util.HashMap; import java.util.List; import java.util.Map; public class ApplyDefaultDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - private DirectRule rule; - private Map addMap; - - /** - * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a basic rule - * - * @param selection selection of tree element views - * @param rule basic rule for the command - */ - public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.rule = rule; - this.addMap = new HashMap<>(); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_SELECTED_VIEWS.toString(); - } - else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) - { - - - - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); - } - else { - if (rule.getDefaultBoard(node) == null) { - return CommandError.DEFAULT_APPLICATION + " - " + "This selection contains a tree element that this rule cannot be applied to."; - } - } - } - else { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } + private TreeViewSelection selection; + private DirectRule rule; + private Map addMap; + + /** + * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a basic + * rule + * + * @param selection selection of tree element views + * @param rule basic rule for the command + */ + public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.rule = rule; + this.addMap = new HashMap<>(); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_SELECTED_VIEWS.toString(); + } else { + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); + } else { + if (rule.getDefaultBoard(node) == null) { + return CommandError.DEFAULT_APPLICATION + + " - " + + "This selection contains a tree element that this rule cannot be applied to."; } + } + } else { + return CommandError.DEFAULT_APPLICATION + + " - " + + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); } - return null; + } } - - /** - * Executes an command - */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - TreeTransition transition = addMap.get(node); - TreeNode childNode; - if (transition == null) { - transition = (TreeTransition) tree.addTreeElement(node); - childNode = (TreeNode) tree.addTreeElement(transition); - addMap.put(node, transition); - } - else { - tree.addTreeElement(node, transition); - childNode = transition.getChildNode(); - } - - transition.setRule(rule); - Board defaultBoard = rule.getDefaultBoard(node); - transition.setBoard(defaultBoard); - Board copyBoard = defaultBoard.copy(); - copyBoard.setModifiable(false); - childNode.setBoard(copyBoard); - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(childNode)); - } - - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + return null; + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + TreeTransition transition = addMap.get(node); + TreeNode childNode; + if (transition == null) { + transition = (TreeTransition) tree.addTreeElement(node); + childNode = (TreeNode) tree.addTreeElement(transition); + addMap.put(node, transition); + } else { + tree.addTreeElement(node, transition); + childNode = transition.getChildNode(); + } + + transition.setRule(rule); + Board defaultBoard = rule.getDefaultBoard(node); + transition.setBoard(defaultBoard); + Board copyBoard = defaultBoard.copy(); + copyBoard.setModifiable(false); + childNode.setBoard(copyBoard); + + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(childNode)); } - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - final TreeTransition transition = addMap.get(node); + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - } + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + final TreeTransition transition = addMap.get(node); - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java b/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java index a4c157c77..501f1d0a5 100644 --- a/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java @@ -1,5 +1,7 @@ package edu.rpi.legup.history; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.gameboard.Board; @@ -8,137 +10,136 @@ import edu.rpi.legup.model.tree.*; import edu.rpi.legup.ui.boardview.ElementView; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.awt.event.MouseEvent; import java.util.*; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class AutoCaseRuleCommand extends PuzzleCommand { - private ElementView elementView; - private TreeViewSelection selection; - private CaseRule caseRule; - private CaseBoard caseBoard; - private MouseEvent mouseEvent; - - private List caseTrans; - - private static final int MAX_CASES = 10; - - /** - * AutoCaseRuleCommand Constructor creates a command for validating a case rule - * - * @param elementView currently selected puzzle puzzleElement view that is being edited - * @param selection currently selected tree puzzleElement views that is being edited - * @param caseRule currently selected caseRule puzzleElement view that is being edited - * @param caseBoard currently selected caseBoard puzzleElement view that is being edited - * @param mouseEvent currently selected mouseEvent puzzleElement view that is being edited - */ - public AutoCaseRuleCommand(ElementView elementView, TreeViewSelection selection, CaseRule caseRule, CaseBoard caseBoard, MouseEvent mouseEvent) { - this.elementView = elementView; - this.selection = selection.copy(); - this.caseRule = caseRule; - this.caseBoard = caseBoard; - this.mouseEvent = mouseEvent; - this.caseTrans = new ArrayList<>(); + private ElementView elementView; + private TreeViewSelection selection; + private CaseRule caseRule; + private CaseBoard caseBoard; + private MouseEvent mouseEvent; + + private List caseTrans; + + private static final int MAX_CASES = 10; + + /** + * AutoCaseRuleCommand Constructor creates a command for validating a case rule + * + * @param elementView currently selected puzzle puzzleElement view that is being edited + * @param selection currently selected tree puzzleElement views that is being edited + * @param caseRule currently selected caseRule puzzleElement view that is being edited + * @param caseBoard currently selected caseBoard puzzleElement view that is being edited + * @param mouseEvent currently selected mouseEvent puzzleElement view that is being edited + */ + public AutoCaseRuleCommand( + ElementView elementView, + TreeViewSelection selection, + CaseRule caseRule, + CaseBoard caseBoard, + MouseEvent mouseEvent) { + this.elementView = elementView; + this.selection = selection.copy(); + this.caseRule = caseRule; + this.caseBoard = caseBoard; + this.mouseEvent = mouseEvent; + this.caseTrans = new ArrayList<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); + if (caseTrans.isEmpty()) { + List cases = + caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()); + for (Board board : cases) { + final TreeTransition transition = (TreeTransition) tree.addTreeElement(node); + board.setModifiable(false); + transition.setBoard(board); + transition.setRule(caseRule); + transition.setSelection(elementView.getPuzzleElement().copy()); + caseTrans.add(transition); + + TreeNode childNode = (TreeNode) tree.addTreeElement(transition); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + } else { + for (final TreeTransition transition : caseTrans) { + tree.addTreeElement(node, transition); + TreeNode childNode = transition.getChildNode(); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + } + + final TreeElement finalTreeElement = node.getChildren().get(0).getChildNode(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + if (selection.getSelectedViews().size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); } - /** - * Executes an command - */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); - if (caseTrans.isEmpty()) { - List cases = caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()); - for (Board board : cases) { - final TreeTransition transition = (TreeTransition) tree.addTreeElement(node); - board.setModifiable(false); - transition.setBoard(board); - transition.setRule(caseRule); - transition.setSelection(elementView.getPuzzleElement().copy()); - caseTrans.add(transition); - - TreeNode childNode = (TreeNode) tree.addTreeElement(transition); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - newSelection.addToSelection(treeView.getElementView(childNode)); - } - } - else { - for (final TreeTransition transition : caseTrans) { - tree.addTreeElement(node, transition); - TreeNode childNode = transition.getChildNode(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - newSelection.addToSelection(treeView.getElementView(childNode)); - } - } - - final TreeElement finalTreeElement = node.getChildren().get(0).getChildNode(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + TreeElementView treeElementView = selection.getFirstSelection(); + if (treeElementView.getType() != TreeElementType.NODE) { + return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - if (selection.getSelectedViews().size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); - } - - TreeElementView treeElementView = selection.getFirstSelection(); - if (treeElementView.getType() != TreeElementType.NODE) { - return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } - - TreeNodeView nodeView = (TreeNodeView) treeElementView; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.NO_CHILDREN.toString(); - } - - if (!caseBoard.isPickable(elementView.getPuzzleElement(), mouseEvent)) { - return "The selected data element is not pickable with this case rule."; - } - - if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() == 0) { - return "The selection must produce at least one case"; - } - - if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() > MAX_CASES) { - return "The selection can produce a max of " + MAX_CASES + " cases"; - } - - return null; + TreeNodeView nodeView = (TreeNodeView) treeElementView; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.NO_CHILDREN.toString(); } - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (!caseBoard.isPickable(elementView.getPuzzleElement(), mouseEvent)) { + return "The selected data element is not pickable with this case rule."; + } + + if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() == 0) { + return "The selection must produce at least one case"; + } - TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); + if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() + > MAX_CASES) { + return "The selection can produce a max of " + MAX_CASES + " cases"; + } - for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { - final TreeTransition finalTran = it.next(); - it.remove(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); - } + return null; + } - final TreeElement finalTreeElement = node; - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); + + for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { + final TreeTransition finalTran = it.next(); + it.remove(); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); } + + final TreeElement finalTreeElement = node; + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/CommandError.java b/src/main/java/edu/rpi/legup/history/CommandError.java index 90c9db526..7b2bc41ed 100644 --- a/src/main/java/edu/rpi/legup/history/CommandError.java +++ b/src/main/java/edu/rpi/legup/history/CommandError.java @@ -1,30 +1,29 @@ package edu.rpi.legup.history; public enum CommandError { + NO_SELECTED_VIEWS("The selection does not have any tree elements."), + ONE_SELECTED_VIEW("The selection must have exactly one tree element."), + UNMODIFIABLE_BOARD("The selection contains a board which is not modifiable."), + UNMODIFIABLE_DATA("The selection contains a board where the data element is not modifiable."), + CONTAINS_ROOT("The selection contains the root tree node."), + ONE_CHILD("The selection contains a tree node that does not have exactly one child."), + ADD_WITH_CHILD("The selection contains a tree transition that already has a child tree node."), + TWO_TO_MERGE("The selection must have at least two tree nodes to merge."), + CONTAINS_MERGE("The selection contains a merging transition."), + ADD_TO_MERGE("The selection contains a tree node that merges."), + NO_CHILDREN("The selection contains a tree node that has children."), + SELECTION_CONTAINS_NODE("The selection contains a tree node."), + SELECTION_CONTAINS_TRANSITION("The selection contains a tree transition."), + DEFAULT_APPLICATION("[Apply Default Rule Application]"); - NO_SELECTED_VIEWS("The selection does not have any tree elements."), - ONE_SELECTED_VIEW("The selection must have exactly one tree element."), - UNMODIFIABLE_BOARD("The selection contains a board which is not modifiable."), - UNMODIFIABLE_DATA("The selection contains a board where the data element is not modifiable."), - CONTAINS_ROOT("The selection contains the root tree node."), - ONE_CHILD("The selection contains a tree node that does not have exactly one child."), - ADD_WITH_CHILD("The selection contains a tree transition that already has a child tree node."), - TWO_TO_MERGE("The selection must have at least two tree nodes to merge."), - CONTAINS_MERGE("The selection contains a merging transition."), - ADD_TO_MERGE("The selection contains a tree node that merges."), - NO_CHILDREN("The selection contains a tree node that has children."), - SELECTION_CONTAINS_NODE("The selection contains a tree node."), - SELECTION_CONTAINS_TRANSITION("The selection contains a tree transition."), - DEFAULT_APPLICATION("[Apply Default Rule Application]"); + private String value; - private String value; + CommandError(String value) { + this.value = value; + } - CommandError(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/main/java/edu/rpi/legup/history/CommandState.java b/src/main/java/edu/rpi/legup/history/CommandState.java index b7c2ff938..36e4def4f 100644 --- a/src/main/java/edu/rpi/legup/history/CommandState.java +++ b/src/main/java/edu/rpi/legup/history/CommandState.java @@ -1,16 +1,19 @@ package edu.rpi.legup.history; public enum CommandState { - CREATED("Created"), EXECUTED("Executed"), UNDOED("Undoed"), REDOED("Redoed"); + CREATED("Created"), + EXECUTED("Executed"), + UNDOED("Undoed"), + REDOED("Redoed"); - private String value; + private String value; - CommandState(String value) { - this.value = value; - } + CommandState(String value) { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java index 80cad9b24..e301175fe 100644 --- a/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java @@ -5,101 +5,97 @@ import edu.rpi.legup.model.observer.ITreeListener; import edu.rpi.legup.model.tree.*; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.util.List; public class DeleteTreeElementCommand extends PuzzleCommand { - private TreeViewSelection selection; - - /** - * DeleteTreeElementCommand Constructor creates a PuzzleCommand for deleting a tree puzzleElement - * - * @param selection the currently selected tree elements before the command is executed - */ - public DeleteTreeElementCommand(TreeViewSelection selection) { - this.selection = selection.copy(); + private TreeViewSelection selection; + + /** + * DeleteTreeElementCommand Constructor creates a PuzzleCommand for deleting a tree puzzleElement + * + * @param selection the currently selected tree elements before the command is executed + */ + public DeleteTreeElementCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + + TreeElementView firstSelectedView = selectedViews.get(0); + TreeElementView newSelectedView; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + newSelectedView = nodeView.getParentView(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + newSelectedView = transitionView.getParentViews().get(0); } - /** - * Executes an command - */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - - TreeElementView firstSelectedView = selectedViews.get(0); - TreeElementView newSelectedView; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - newSelectedView = nodeView.getParentView(); - } - else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - newSelectedView = transitionView.getParentViews().get(0); - } - - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - tree.removeTreeElement(element); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(element)); - } - - final TreeViewSelection newSelection = new TreeViewSelection(newSelectedView); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(newSelectedView.getTreeElement())); - puzzle.notifyTreeListeners((ITreeListener listener) -> listener.onTreeSelectionChanged(newSelection)); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + tree.removeTreeElement(element); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(element)); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } - - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE && ((TreeNode) element).isRoot()) { - return CommandError.CONTAINS_ROOT.toString(); - } - } - return null; + final TreeViewSelection newSelection = new TreeViewSelection(newSelectedView); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(newSelectedView.getTreeElement())); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - List selectedViews = selection.getSelectedViews(); - - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getParent().setChildNode(node); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(node)); - } - else { - TreeTransition transition = (TreeTransition) element; - transition.getParents().forEach(node -> node.addChild(transition)); - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - } - } - - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE && ((TreeNode) element).isRoot()) { + return CommandError.CONTAINS_ROOT.toString(); + } + } + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + List selectedViews = selection.getSelectedViews(); + + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getParent().setChildNode(node); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(node)); + } else { + TreeTransition transition = (TreeTransition) element; + transition.getParents().forEach(node -> node.addChild(transition)); + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + } } + + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/EditDataCommand.java b/src/main/java/edu/rpi/legup/history/EditDataCommand.java index 328cc050d..6b5f4062f 100644 --- a/src/main/java/edu/rpi/legup/history/EditDataCommand.java +++ b/src/main/java/edu/rpi/legup/history/EditDataCommand.java @@ -1,5 +1,7 @@ package edu.rpi.legup.history; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; @@ -8,170 +10,159 @@ import edu.rpi.legup.ui.boardview.BoardView; import edu.rpi.legup.ui.boardview.ElementView; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.awt.event.MouseEvent; import java.util.List; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class EditDataCommand extends PuzzleCommand { - private TreeTransition transition; - private PuzzleElement savePuzzleElement; - private PuzzleElement puzzleElement; - - private ElementView elementView; - private TreeViewSelection selection; - private MouseEvent event; - - /** - * EditDataCommand Constructor create a puzzle command for editing a board - * - * @param elementView currently selected puzzle puzzleElement view that is being edited - * @param selection currently selected tree puzzleElement views that is being edited - * @param event mouse event - */ - public EditDataCommand(ElementView elementView, TreeViewSelection selection, MouseEvent event) { - this.elementView = elementView; - this.selection = selection.copy(); - this.event = event; - this.puzzleElement = null; - this.savePuzzleElement = null; - this.transition = null; - } - - /** - * Executes a command - */ - @SuppressWarnings("unchecked") - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - Board board = treeElement.getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - if (treeNode.getChildren().isEmpty()) { - if (transition == null) { - transition = tree.addNewTransition(treeNode); - } - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - } - - board = transition.getBoard(); - - puzzleElement = board.getPuzzleElement(selectedPuzzleElement); - savePuzzleElement = puzzleElement.copy(); - } - else { - transition = (TreeTransition) treeElement; - puzzleElement = board.getPuzzleElement(selectedPuzzleElement); - savePuzzleElement = puzzleElement.copy(); + private TreeTransition transition; + private PuzzleElement savePuzzleElement; + private PuzzleElement puzzleElement; + + private ElementView elementView; + private TreeViewSelection selection; + private MouseEvent event; + + /** + * EditDataCommand Constructor create a puzzle command for editing a board + * + * @param elementView currently selected puzzle puzzleElement view that is being edited + * @param selection currently selected tree puzzleElement views that is being edited + * @param event mouse event + */ + public EditDataCommand(ElementView elementView, TreeViewSelection selection, MouseEvent event) { + this.elementView = elementView; + this.selection = selection.copy(); + this.event = event; + this.puzzleElement = null; + this.savePuzzleElement = null; + this.transition = null; + } + + /** Executes a command */ + @SuppressWarnings("unchecked") + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + Board board = treeElement.getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + if (treeNode.getChildren().isEmpty()) { + if (transition == null) { + transition = tree.addNewTransition(treeNode); } + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + } - Board prevBoard = transition.getParents().get(0).getBoard(); + board = transition.getBoard(); - boardView.getElementController().changeCell(event, puzzleElement); + puzzleElement = board.getPuzzleElement(selectedPuzzleElement); + savePuzzleElement = puzzleElement.copy(); + } else { + transition = (TreeTransition) treeElement; + puzzleElement = board.getPuzzleElement(selectedPuzzleElement); + savePuzzleElement = puzzleElement.copy(); + } - if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { - board.removeModifiedData(puzzleElement); - } - else { - board.addModifiedData(puzzleElement); - } - transition.propagateChange(puzzleElement); + Board prevBoard = transition.getParents().get(0).getBoard(); - final TreeElement finalTreeElement = transition; - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); + boardView.getElementController().changeCell(event, puzzleElement); - final TreeViewSelection newSelection = new TreeViewSelection(treeView.getElementView(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { + board.removeModifiedData(puzzleElement); + } else { + board.addModifiedData(puzzleElement); } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); - } - TreeElementView selectedView = selection.getFirstSelection(); - Board board = selectedView.getTreeElement().getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - if (selectedView.getType() == TreeElementType.NODE) { - - TreeNodeView nodeView = (TreeNodeView) selectedView; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - else { - if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); - } - } + transition.propagateChange(puzzleElement); + + final TreeElement finalTreeElement = transition; + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); + + final TreeViewSelection newSelection = + new TreeViewSelection(treeView.getElementView(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); + } + TreeElementView selectedView = selection.getFirstSelection(); + Board board = selectedView.getTreeElement().getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + if (selectedView.getType() == TreeElementType.NODE) { + + TreeNodeView nodeView = (TreeNodeView) selectedView; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } else { + if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); } - else { - TreeTransitionView transitionView = (TreeTransitionView) selectedView; - if (!transitionView.getTreeElement().getBoard().isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - else { - if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); - } - } + } + } else { + TreeTransitionView transitionView = (TreeTransitionView) selectedView; + if (!transitionView.getTreeElement().getBoard().isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } else { + if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); } - return null; + } + } + return null; + } + + /** Undoes an command */ + @SuppressWarnings("unchecked") + @Override + public void undoCommand() { + TreeElementView selectedView = selection.getFirstSelection(); + Tree tree = getInstance().getTree(); + Puzzle puzzle = getInstance().getPuzzleModule(); + + Board board = transition.getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + + if (selectedView.getType() == TreeElementType.NODE) { + tree.removeTreeElement(transition); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeElementRemoved(transition)); } - /** - * Undoes an command - */ - @SuppressWarnings("unchecked") - @Override - public void undoCommand() { - TreeElementView selectedView = selection.getFirstSelection(); - Tree tree = getInstance().getTree(); - Puzzle puzzle = getInstance().getPuzzleModule(); - - Board board = transition.getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - - if (selectedView.getType() == TreeElementType.NODE) { - tree.removeTreeElement(transition); - puzzle.notifyTreeListeners((ITreeListener listener) -> listener.onTreeElementRemoved(transition)); - } - - Board prevBoard = transition.getParents().get(0).getBoard(); + Board prevBoard = transition.getParents().get(0).getBoard(); - puzzleElement.setData(savePuzzleElement.getData()); - board.notifyChange(puzzleElement); + puzzleElement.setData(savePuzzleElement.getData()); + board.notifyChange(puzzleElement); - if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { - board.removeModifiedData(puzzleElement); - } - else { - board.addModifiedData(puzzleElement); - } - transition.propagateChange(puzzleElement); + if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { + board.removeModifiedData(puzzleElement); + } else { + board.addModifiedData(puzzleElement); + } + transition.propagateChange(puzzleElement); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/History.java b/src/main/java/edu/rpi/legup/history/History.java index 77e3fae94..8221449e6 100644 --- a/src/main/java/edu/rpi/legup/history/History.java +++ b/src/main/java/edu/rpi/legup/history/History.java @@ -1,105 +1,98 @@ package edu.rpi.legup.history; import edu.rpi.legup.app.GameBoardFacade; - import java.util.ArrayList; import java.util.List; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class History { - private static final Logger LOGGER = LogManager.getLogger(History.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(History.class.getName()); - private final Object lock = new Object(); - private List history; - private int curIndex; + private final Object lock = new Object(); + private List history; + private int curIndex; - /** - * History Constructor this holds information about changes to the board - * and Tree structure for undoing and redoing operations. Though history is - * an List, it is implemented like a stack. The curIndex points to the - * top of the stack (where the last change was made). - */ - public History() { - history = new ArrayList<>(); - curIndex = -1; - } + /** + * History Constructor this holds information about changes to the board and Tree structure for + * undoing and redoing operations. Though history is an List, it is implemented like a stack. The + * curIndex points to the top of the stack (where the last change was made). + */ + public History() { + history = new ArrayList<>(); + curIndex = -1; + } - /** - * Pushes a change to the history list and increments the current index. - * If the current index does not point to the top of the stack, then at least - * 1 undo operation was called and that information will be lost by the next change - * - * @param command command to be pushed onto the stack - */ - public void pushChange(ICommand command) { - synchronized (lock) { - if (curIndex < history.size() - 1) { - for (int i = history.size() - 1; i > curIndex; i--) { - history.remove(i); - } - } - history.add(command); - curIndex++; - LOGGER.info("Pushed " + command.getClass().getSimpleName() + " to stack."); - GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onPushChange(command)); + /** + * Pushes a change to the history list and increments the current index. If the current index does + * not point to the top of the stack, then at least 1 undo operation was called and that + * information will be lost by the next change + * + * @param command command to be pushed onto the stack + */ + public void pushChange(ICommand command) { + synchronized (lock) { + if (curIndex < history.size() - 1) { + for (int i = history.size() - 1; i > curIndex; i--) { + history.remove(i); } + } + history.add(command); + curIndex++; + LOGGER.info("Pushed " + command.getClass().getSimpleName() + " to stack."); + GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onPushChange(command)); } + } - /** - * Undoes an action - */ - public void undo() { - synchronized (lock) { - if (curIndex > -1) { - ICommand command = history.get(curIndex--); - command.undo(); - LOGGER.info("Undoed " + command.getClass().getSimpleName()); - GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onUndo(curIndex < 0, curIndex == history.size() - 1)); - } - } + /** Undoes an action */ + public void undo() { + synchronized (lock) { + if (curIndex > -1) { + ICommand command = history.get(curIndex--); + command.undo(); + LOGGER.info("Undoed " + command.getClass().getSimpleName()); + GameBoardFacade.getInstance() + .notifyHistoryListeners(l -> l.onUndo(curIndex < 0, curIndex == history.size() - 1)); + } } + } - /** - * Redoes an action - */ - public void redo() { - synchronized (lock) { - if (curIndex < history.size() - 1) { - ICommand command = history.get(++curIndex); - command.redo(); - LOGGER.info("Redoed " + command.getClass().getSimpleName()); - GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onRedo(curIndex < 0, curIndex == history.size() - 1)); - } - } + /** Redoes an action */ + public void redo() { + synchronized (lock) { + if (curIndex < history.size() - 1) { + ICommand command = history.get(++curIndex); + command.redo(); + LOGGER.info("Redoed " + command.getClass().getSimpleName()); + GameBoardFacade.getInstance() + .notifyHistoryListeners(l -> l.onRedo(curIndex < 0, curIndex == history.size() - 1)); + } } + } - /** - * Clears all actions from the history stack - */ - public void clear() { - history.clear(); - curIndex = -1; - LOGGER.debug("History Cleared"); - GameBoardFacade.getInstance().notifyHistoryListeners(IHistoryListener::onClearHistory); - } + /** Clears all actions from the history stack */ + public void clear() { + history.clear(); + curIndex = -1; + LOGGER.debug("History Cleared"); + GameBoardFacade.getInstance().notifyHistoryListeners(IHistoryListener::onClearHistory); + } - /** - * Gets the current index that points to the action at the top of stack - * - * @return index of the action on top of the stack - */ - public int getIndex() { - return curIndex; - } + /** + * Gets the current index that points to the action at the top of stack + * + * @return index of the action on top of the stack + */ + public int getIndex() { + return curIndex; + } - /** - * Gets the amount of actions that have been pushed onto the stack - * - * @return size of the history stack - */ - public int size() { - return history.size(); - } + /** + * Gets the amount of actions that have been pushed onto the stack + * + * @return size of the history stack + */ + public int size() { + return history.size(); + } } diff --git a/src/main/java/edu/rpi/legup/history/ICommand.java b/src/main/java/edu/rpi/legup/history/ICommand.java index bc82c4df5..b10cdc861 100644 --- a/src/main/java/edu/rpi/legup/history/ICommand.java +++ b/src/main/java/edu/rpi/legup/history/ICommand.java @@ -1,32 +1,27 @@ package edu.rpi.legup.history; public interface ICommand { - /** - * Executes a command - */ - void execute(); + /** Executes a command */ + void execute(); - /** - * Determines whether this command can be executed - * @return true if can execute, false otherwise - */ - boolean canExecute(); + /** + * Determines whether this command can be executed + * + * @return true if can execute, false otherwise + */ + boolean canExecute(); - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - String getError(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + String getError(); - /** - * Undoes a command - */ - void undo(); + /** Undoes a command */ + void undo(); - /** - * Redoes a command - */ - void redo(); -} \ No newline at end of file + /** Redoes a command */ + void redo(); +} diff --git a/src/main/java/edu/rpi/legup/history/IHistoryListener.java b/src/main/java/edu/rpi/legup/history/IHistoryListener.java index 5201a09c5..1b3253b9f 100644 --- a/src/main/java/edu/rpi/legup/history/IHistoryListener.java +++ b/src/main/java/edu/rpi/legup/history/IHistoryListener.java @@ -1,31 +1,29 @@ package edu.rpi.legup.history; public interface IHistoryListener { - /** - * Called when a action is pushed onto the edu.rpi.legup.history stack - * - * @param command action to push onto the stack - */ - void onPushChange(ICommand command); + /** + * Called when a action is pushed onto the edu.rpi.legup.history stack + * + * @param command action to push onto the stack + */ + void onPushChange(ICommand command); - /** - * Called when an action is undone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - void onUndo(boolean isBottom, boolean isTop); + /** + * Called when an action is undone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + void onUndo(boolean isBottom, boolean isTop); - /** - * Called when an action is redone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - void onRedo(boolean isBottom, boolean isTop); + /** + * Called when an action is redone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + void onRedo(boolean isBottom, boolean isTop); - /** - * Called when the edu.rpi.legup.history is cleared - */ - void onClearHistory(); + /** Called when the edu.rpi.legup.history is cleared */ + void onClearHistory(); } diff --git a/src/main/java/edu/rpi/legup/history/IHistorySubject.java b/src/main/java/edu/rpi/legup/history/IHistorySubject.java index 78fefff00..63acfa4c6 100644 --- a/src/main/java/edu/rpi/legup/history/IHistorySubject.java +++ b/src/main/java/edu/rpi/legup/history/IHistorySubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface IHistorySubject { - /** - * Adds a history listener - * - * @param listener listener to add - */ - void addHistoryListener(IHistoryListener listener); + /** + * Adds a history listener + * + * @param listener listener to add + */ + void addHistoryListener(IHistoryListener listener); - /** - * Removes a history listener - * - * @param listener listener to remove - */ - void removeHistoryListener(IHistoryListener listener); + /** + * Removes a history listener + * + * @param listener listener to remove + */ + void removeHistoryListener(IHistoryListener listener); - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - void notifyHistoryListeners(Consumer algorithm); + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + void notifyHistoryListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java b/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java index 7e79814a6..42a547e84 100644 --- a/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java +++ b/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java @@ -2,7 +2,14 @@ public class InvalidCommandStateTransition extends RuntimeException { - public InvalidCommandStateTransition(PuzzleCommand puzzleCommand, CommandState from, CommandState to) { - super("PuzzleCommand - " + puzzleCommand.getClass().getSimpleName() + " - Attempted invalid command state transition from " + from + " to " + to); - } + public InvalidCommandStateTransition( + PuzzleCommand puzzleCommand, CommandState from, CommandState to) { + super( + "PuzzleCommand - " + + puzzleCommand.getClass().getSimpleName() + + " - Attempted invalid command state transition from " + + from + + " to " + + to); + } } diff --git a/src/main/java/edu/rpi/legup/history/MergeCommand.java b/src/main/java/edu/rpi/legup/history/MergeCommand.java index 2091ecf0a..e170e9856 100644 --- a/src/main/java/edu/rpi/legup/history/MergeCommand.java +++ b/src/main/java/edu/rpi/legup/history/MergeCommand.java @@ -6,139 +6,133 @@ import edu.rpi.legup.model.rules.MergeRule; import edu.rpi.legup.model.tree.*; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.util.ArrayList; import java.util.List; import java.util.Set; public class MergeCommand extends PuzzleCommand { - private TreeViewSelection selection; - private TreeTransition transition; - - /** - * Merge Command Constructor create a command for merging tree nodes. - * - * @param selection selection of tree elements - */ - public MergeCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - this.transition = null; + private TreeViewSelection selection; + private TreeTransition transition; + + /** + * Merge Command Constructor create a command for merging tree nodes. + * + * @param selection selection of tree elements + */ + public MergeCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + this.transition = null; + } + + /** Executes an command */ + @Override + public void executeCommand() { + List selectedViews = selection.getSelectedViews(); + + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeNode mergedNode; + if (transition == null) { + List mergingNodes = new ArrayList<>(); + List mergingBoards = new ArrayList<>(); + for (TreeElementView view : selectedViews) { + TreeNode node = ((TreeNodeView) view).getTreeElement(); + mergingNodes.add(node); + mergingBoards.add(node.getBoard()); + } + + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + Board lcaBoard = lca.getBoard(); + + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + mergedNode = new TreeNode(mergedBoard.copy()); + transition = new TreeTransition(mergedBoard); + transition.setRule(new MergeRule()); + transition.setChildNode(mergedNode); + mergedNode.setParent(transition); + } else { + mergedNode = transition.getChildNode(); } - /** - * Executes an command - */ - @Override - public void executeCommand() { - List selectedViews = selection.getSelectedViews(); - - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeNode mergedNode; - if (transition == null) { - List mergingNodes = new ArrayList<>(); - List mergingBoards = new ArrayList<>(); - for (TreeElementView view : selectedViews) { - TreeNode node = ((TreeNodeView) view).getTreeElement(); - mergingNodes.add(node); - mergingBoards.add(node.getBoard()); - } - - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - Board lcaBoard = lca.getBoard(); - - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); - - mergedNode = new TreeNode(mergedBoard.copy()); - transition = new TreeTransition(mergedBoard); - transition.setRule(new MergeRule()); - transition.setChildNode(mergedNode); - mergedNode.setParent(transition); - } - else { - mergedNode = transition.getChildNode(); - } - - transition.getParents().clear(); - for (TreeElementView elementView : selectedViews) { - TreeNode node = (TreeNode) elementView.getTreeElement(); - - node.addChild(transition); - transition.addParent(node); - } + transition.getParents().clear(); + for (TreeElementView elementView : selectedViews) { + TreeNode node = (TreeNode) elementView.getTreeElement(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - - final TreeViewSelection newSelection = new TreeViewSelection(); - newSelection.addToSelection(treeView.getElementView(mergedNode)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + node.addChild(transition); + transition.addParent(node); } - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeTransition transition = ((TreeNode) selection.getFirstSelection().getTreeElement()).getChildren().get(0); - tree.removeTreeElement(transition); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + + final TreeViewSelection newSelection = new TreeViewSelection(); + newSelection.addToSelection(treeView.getElementView(mergedNode)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeTransition transition = + ((TreeNode) selection.getFirstSelection().getTreeElement()).getChildren().get(0); + tree.removeTreeElement(transition); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + Tree tree = GameBoardFacade.getInstance().getTree(); + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() < 2) { + return CommandError.TWO_TO_MERGE.toString(); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - Tree tree = GameBoardFacade.getInstance().getTree(); - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() < 2) { - return CommandError.TWO_TO_MERGE.toString(); - } - - List nodeList = new ArrayList<>(); - for (TreeElementView view : selection.getSelectedViews()) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.NO_CHILDREN.toString(); - } - nodeList.add(nodeView.getTreeElement()); - } - else { - return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } - } - - List mergingNodes = new ArrayList<>(); - for (TreeElementView view : selectedViews) { - TreeNode node = ((TreeNodeView) view).getTreeElement(); - mergingNodes.add(node); + List nodeList = new ArrayList<>(); + for (TreeElementView view : selection.getSelectedViews()) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.NO_CHILDREN.toString(); } + nodeList.add(nodeView.getTreeElement()); + } else { + return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + } - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - return "Unable to merge tree elements."; - } - Set leafNodes = tree.getLeafTreeElements(lca); - if (leafNodes.size() != mergingNodes.size()) { -// return "Unable to merge tree elements."; - } + List mergingNodes = new ArrayList<>(); + for (TreeElementView view : selectedViews) { + TreeNode node = ((TreeNodeView) view).getTreeElement(); + mergingNodes.add(node); + } - for (TreeNode node : mergingNodes) { - if (!leafNodes.contains(node)) { -// return "Unable to merge tree elements."; - } - } + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + return "Unable to merge tree elements."; + } + Set leafNodes = tree.getLeafTreeElements(lca); + if (leafNodes.size() != mergingNodes.size()) { + // return "Unable to merge tree elements."; + } - return null; + for (TreeNode node : mergingNodes) { + if (!leafNodes.contains(node)) { + // return "Unable to merge tree elements."; + } } + + return null; + } } diff --git a/src/main/java/edu/rpi/legup/history/PuzzleCommand.java b/src/main/java/edu/rpi/legup/history/PuzzleCommand.java index 0c96b16f5..482c11cc7 100644 --- a/src/main/java/edu/rpi/legup/history/PuzzleCommand.java +++ b/src/main/java/edu/rpi/legup/history/PuzzleCommand.java @@ -1,114 +1,91 @@ package edu.rpi.legup.history; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - public abstract class PuzzleCommand implements ICommand { - private CommandState state; - private boolean isCached; - private String cachedError; + private CommandState state; + private boolean isCached; + private String cachedError; - /** - * Puzzle Command Constructor for creating an undoable and redoable change to the model. - */ - protected PuzzleCommand() { - this.state = CommandState.CREATED; - this.isCached = false; - this.cachedError = null; - } + /** Puzzle Command Constructor for creating an undoable and redoable change to the model. */ + protected PuzzleCommand() { + this.state = CommandState.CREATED; + this.isCached = false; + this.cachedError = null; + } - /** - * Executes an command - */ - @Override - public final void execute() { - if (canExecute()) { - executeCommand(); - state = CommandState.EXECUTED; - } + /** Executes an command */ + @Override + public final void execute() { + if (canExecute()) { + executeCommand(); + state = CommandState.EXECUTED; } + } - /** - * Determines whether this command can be executed - */ - @Override - public final boolean canExecute() { - cachedError = getError(); - isCached = true; - return cachedError == null; - } + /** Determines whether this command can be executed */ + @Override + public final boolean canExecute() { + cachedError = getError(); + isCached = true; + return cachedError == null; + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public final String getError() { - if (isCached) { - return cachedError; - } - else { - return getErrorString(); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public final String getError() { + if (isCached) { + return cachedError; + } else { + return getErrorString(); } + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - public abstract String getErrorString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + public abstract String getErrorString(); - /** - * Executes an command - */ - public abstract void executeCommand(); + /** Executes an command */ + public abstract void executeCommand(); - /** - * Undoes an command - */ - public abstract void undoCommand(); + /** Undoes an command */ + public abstract void undoCommand(); - /** - * Redoes an command - */ - public void redoCommand() { - if (state == CommandState.UNDOED) { - executeCommand(); - state = CommandState.REDOED; - } - else { - throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); - } + /** Redoes an command */ + public void redoCommand() { + if (state == CommandState.UNDOED) { + executeCommand(); + state = CommandState.REDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); } + } - /** - * Undoes an command - */ - @Override - public final void undo() { - if (state == CommandState.EXECUTED || state == CommandState.REDOED) { - undoCommand(); - state = CommandState.UNDOED; - } - else { - throw new InvalidCommandStateTransition(this, state, CommandState.UNDOED); - } + /** Undoes an command */ + @Override + public final void undo() { + if (state == CommandState.EXECUTED || state == CommandState.REDOED) { + undoCommand(); + state = CommandState.UNDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.UNDOED); } + } - /** - * Redoes an command - */ - public final void redo() { - if (state == CommandState.UNDOED) { - redoCommand(); - state = CommandState.REDOED; - } - else { - throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); - } + /** Redoes an command */ + public final void redo() { + if (state == CommandState.UNDOED) { + redoCommand(); + state = CommandState.REDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java index 398f17478..4718a56c8 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java @@ -1,139 +1,131 @@ package edu.rpi.legup.history; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.rules.Rule; import edu.rpi.legup.model.tree.*; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.util.HashMap; import java.util.List; import java.util.Map; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class ValidateCaseRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - private CaseRule caseRule; - - private Map oldRule; - private Map addNode; - - /** - * AutoCaseRuleCommand Constructor creates a command for verifying a case rule - * - * @param selection currently selected tree puzzleElement views that is being edited - * @param caseRule currently selected caseRule puzzleElement view that is being edited - */ - public ValidateCaseRuleCommand(TreeViewSelection selection, CaseRule caseRule) { - this.selection = selection.copy(); - this.caseRule = caseRule; - this.oldRule = new HashMap<>(); - this.addNode = new HashMap<>(); - } - - /** - * Executes an command - */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeTransition transition = (TreeTransition) element; - oldRule.put(transition, transition.getRule()); - - transition.setRule(caseRule); - - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); - } - else { - childNode = (TreeNode) tree.addTreeElement(transition, childNode); - } - - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - newSelection.addToSelection(treeView.getElementView(childNode)); + private TreeViewSelection selection; + private CaseRule caseRule; + + private Map oldRule; + private Map addNode; + + /** + * AutoCaseRuleCommand Constructor creates a command for verifying a case rule + * + * @param selection currently selected tree puzzleElement views that is being edited + * @param caseRule currently selected caseRule puzzleElement view that is being edited + */ + public ValidateCaseRuleCommand(TreeViewSelection selection, CaseRule caseRule) { + this.selection = selection.copy(); + this.caseRule = caseRule; + this.oldRule = new HashMap<>(); + this.addNode = new HashMap<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeTransition transition = (TreeTransition) element; + oldRule.put(transition, transition.getRule()); + + transition.setRule(caseRule); + + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); + } else { + childNode = (TreeNode) tree.addTreeElement(transition, childNode); } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } - else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); - } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + newSelection.addToSelection(treeView.getElementView(childNode)); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } - - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - return CommandError.SELECTION_CONTAINS_NODE.toString(); - } - else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); - } - } - } - return null; + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); + } + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeTransition transition = (TreeTransition) element; - - transition.setRule(oldRule.get(transition)); - - final TreeNode childNode = transition.getChildNode(); - if (addNode.get(transition) != null) { - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + return CommandError.SELECTION_CONTAINS_NODE.toString(); + } else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); } - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } -} \ No newline at end of file + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeTransition transition = (TreeTransition) element; + + transition.setRule(oldRule.get(transition)); + + final TreeNode childNode = transition.getChildNode(); + if (addNode.get(transition) != null) { + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } +} diff --git a/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java index 23f8dce21..cc60029bf 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java @@ -5,158 +5,153 @@ import edu.rpi.legup.model.rules.ContradictionRule; import edu.rpi.legup.model.tree.*; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ValidateContradictionRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - - private Map> saveElements; - private ContradictionRule newRule; - private Map addTran; - - /** - * ValidateContradictionRuleCommand Constructor creates a puzzle command for verifying a contradiction rule - * - * @param selection currently selected tree puzzleElement views - * @param rule contradiction rule to be set to all the tree elements - */ - public ValidateContradictionRuleCommand(TreeViewSelection selection, ContradictionRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.saveElements = new HashMap<>(); - this.addTran = new HashMap<>(); + private TreeViewSelection selection; + + private Map> saveElements; + private ContradictionRule newRule; + private Map addTran; + + /** + * ValidateContradictionRuleCommand Constructor creates a puzzle command for verifying a + * contradiction rule + * + * @param selection currently selected tree puzzleElement views + * @param rule contradiction rule to be set to all the tree elements + */ + public ValidateContradictionRuleCommand(TreeViewSelection selection, ContradictionRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.saveElements = new HashMap<>(); + this.addTran = new HashMap<>(); + } + + /** Executes a command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement treeElement = view.getTreeElement(); + TreeNode treeNode; + if (treeElement.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) treeElement; + treeNode = transition.getParents().get(0); + } else { + treeNode = (TreeNode) treeElement; + } + + if (!treeNode.getChildren().isEmpty()) { + ArrayList save = new ArrayList<>(treeNode.getChildren()); + saveElements.put(treeNode, save); + } + + treeNode + .getChildren() + .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); + + treeNode.getChildren().clear(); + + TreeTransition transition = addTran.get(treeElement); + if (transition == null) { + transition = tree.addNewTransition(treeNode); + transition.setRule(newRule); + transition.getBoard().setModifiable(false); + tree.addTreeElement(transition); + } else { + transition.getBoard().setModifiable(false); + tree.addTreeElement(treeNode, transition); + } + + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(transition)); } - /** - * Executes a command - */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement treeElement = view.getTreeElement(); - TreeNode treeNode; - if (treeElement.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) treeElement; - treeNode = transition.getParents().get(0); - } - else { - treeNode = (TreeNode) treeElement; - } - - if (!treeNode.getChildren().isEmpty()) { - ArrayList save = new ArrayList<>(treeNode.getChildren()); - saveElements.put(treeNode, save); - } - - treeNode.getChildren().forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); - - treeNode.getChildren().clear(); - - TreeTransition transition = addTran.get(treeElement); - if (transition == null) { - transition = tree.addNewTransition(treeNode); - transition.setRule(newRule); - transition.getBoard().setModifiable(false); - tree.addTreeElement(transition); - } - else { - transition.getBoard().setModifiable(false); - tree.addTreeElement(treeNode, transition); - } - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(transition)); - } - - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } - else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - if (transitionView.getChildView() != null) { - finalTreeElement = transitionView.getChildView().getTreeElement(); - } - else { - finalTreeElement = null; - } - } - - if (finalTreeElement != null) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + if (transitionView.getChildView() != null) { + finalTreeElement = transitionView.getChildView().getTreeElement(); + } else { + finalTreeElement = null; + } } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } - - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.TRANSITION) { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); - } - } - } - return null; + if (finalTreeElement != null) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - /** - * Undoes a command - */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeNode node; - if (element.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) element; - node = transition.getParents().get(0); - } - else { - node = (TreeNode) element; - } - node.getChildren().forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); - node.getChildren().clear(); - - ArrayList save = saveElements.get(node); - - if (save != null) { - node.getChildren().addAll(save); - node.getChildren().forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(n))); - } + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.TRANSITION) { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); } - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } + } + return null; + } + + /** Undoes a command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeNode node; + if (element.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) element; + node = transition.getParents().get(0); + } else { + node = (TreeNode) element; + } + node.getChildren() + .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); + node.getChildren().clear(); + + ArrayList save = saveElements.get(node); + + if (save != null) { + node.getChildren().addAll(save); + node.getChildren() + .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(n))); + } } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java index 970af49a0..0fe35218f 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java @@ -6,147 +6,137 @@ import edu.rpi.legup.model.rules.Rule; import edu.rpi.legup.model.tree.*; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.util.HashMap; import java.util.List; import java.util.Map; public class ValidateDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - - private Map oldRules; - private Map addNode; - private DirectRule newRule; + private TreeViewSelection selection; + + private Map oldRules; + private Map addNode; + private DirectRule newRule; + + /** + * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule + * + * @param selection selection of tree elements + * @param rule basic rule + */ + public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.oldRules = new HashMap<>(); + this.addNode = new HashMap<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); + + oldRules.put(transition, transition.getRule()); + transition.setRule(newRule); + + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); + } else { + tree.addTreeElement(transition, childNode); + } - /** - * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule - * - * @param selection selection of tree elements - * @param rule basic rule - */ - public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.oldRules = new HashMap<>(); - this.addNode = new HashMap<>(); + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + newSelection.addToSelection(treeView.getElementView(childNode)); } - - /** - * Executes an command - */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } - else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); - - oldRules.put(transition, transition.getRule()); - transition.setRule(newRule); - - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); - } - else { - tree.addTreeElement(transition, childNode); - } - - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - newSelection.addToSelection(treeView.getElementView(childNode)); - } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } - else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); - } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); + } + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (nodeView.getChildrenViews().size() != 1) { + return CommandError.ONE_CHILD.toString(); } - - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (nodeView.getChildrenViews().size() != 1) { - return CommandError.ONE_CHILD.toString(); - } - } - else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); - } - } + } else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); } - return null; + } } - - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } - else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); - transition.setRule(oldRules.get(transition)); - - if (addNode.get(transition) != null) { - final TreeNode childNode = transition.getChildNode(); - tree.removeTreeElement(childNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - } - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); + transition.setRule(oldRules.get(transition)); + + if (addNode.get(transition) != null) { + final TreeNode childNode = transition.getChildNode(); + tree.removeTreeElement(childNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/model/Puzzle.java b/src/main/java/edu/rpi/legup/model/Puzzle.java index 18614131b..ed39d0fe6 100644 --- a/src/main/java/edu/rpi/legup/model/Puzzle.java +++ b/src/main/java/edu/rpi/legup/model/Puzzle.java @@ -1,6 +1,7 @@ package edu.rpi.legup.model; import edu.rpi.legup.model.elements.*; +import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.observer.IBoardListener; @@ -12,649 +13,633 @@ import edu.rpi.legup.model.tree.TreeElement; import edu.rpi.legup.model.tree.TreeElementType; import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; -import edu.rpi.legup.ui.puzzleeditorui.elementsview.NonPlaceableElementPanel; -import edu.rpi.legup.utility.LegupUtils; -import org.w3c.dom.Document; -import edu.rpi.legup.model.elements.Element; -import org.w3c.dom.Node; import edu.rpi.legup.save.InvalidFileFormatException; import edu.rpi.legup.ui.boardview.BoardView; -import org.xml.sax.SAXException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; +import edu.rpi.legup.utility.LegupUtils; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; - +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; public abstract class Puzzle implements IBoardSubject, ITreeSubject { - private static final Logger LOGGER = LogManager.getLogger(Puzzle.class.getName()); - - protected String name; - protected Board currentBoard; - protected Tree tree; - protected BoardView boardView; - protected PuzzleImporter importer; - protected PuzzleExporter exporter; - protected ElementFactory factory; - - private List boardListeners; - private List treeListeners; - - protected List directRules; - protected List contradictionRules; - protected List caseRules; - protected List placeableElements; - protected List nonPlaceableElements; - - /** - * Puzzle Constructor - creates a new Puzzle - */ - public Puzzle() { - this.boardListeners = new ArrayList<>(); - this.treeListeners = new ArrayList<>(); - - this.directRules = new ArrayList<>(); - this.contradictionRules = new ArrayList<>(); - this.caseRules = new ArrayList<>(); - - this.placeableElements = new ArrayList<>(); - this.nonPlaceableElements = new ArrayList<>(); - - registerRules(); - registerPuzzleElements(); - } - - private void registerPuzzleElements() { - String packageName = this.getClass().getPackage().toString().replace("package ", ""); - - try { - Class[] possElements = LegupUtils.getClasses(packageName); - - for (Class c : possElements) { - - System.out.println("possible element: " + c.getName()); - - //check that the element is not abstract - if (Modifier.isAbstract(c.getModifiers())) continue; - - for (Annotation a : c.getAnnotations()) { - if (a.annotationType() == RegisterElement.class) { - RegisterElement registerElement = (RegisterElement) a; - Constructor cons = c.getConstructor(); - try { - Element element = (Element) cons.newInstance(); - - switch (element.getElementType()) { - case PLACEABLE: - this.addPlaceableElement((PlaceableElement) element); - break; - case NONPLACEABLE: - this.addNonPlaceableElement((NonPlaceableElement) element); - break; - default: - break; - } - } - catch (InvocationTargetException e) { - System.out.println(" Failed "); - e.getTargetException().printStackTrace(); - } - } - } + private static final Logger LOGGER = LogManager.getLogger(Puzzle.class.getName()); + + protected String name; + protected Board currentBoard; + protected Tree tree; + protected BoardView boardView; + protected PuzzleImporter importer; + protected PuzzleExporter exporter; + protected ElementFactory factory; + + private List boardListeners; + private List treeListeners; + + protected List directRules; + protected List contradictionRules; + protected List caseRules; + protected List placeableElements; + protected List nonPlaceableElements; + + /** Puzzle Constructor - creates a new Puzzle */ + public Puzzle() { + this.boardListeners = new ArrayList<>(); + this.treeListeners = new ArrayList<>(); + + this.directRules = new ArrayList<>(); + this.contradictionRules = new ArrayList<>(); + this.caseRules = new ArrayList<>(); + + this.placeableElements = new ArrayList<>(); + this.nonPlaceableElements = new ArrayList<>(); + + registerRules(); + registerPuzzleElements(); + } + + private void registerPuzzleElements() { + String packageName = this.getClass().getPackage().toString().replace("package ", ""); + + try { + Class[] possElements = LegupUtils.getClasses(packageName); + + for (Class c : possElements) { + + System.out.println("possible element: " + c.getName()); + + // check that the element is not abstract + if (Modifier.isAbstract(c.getModifiers())) continue; + + for (Annotation a : c.getAnnotations()) { + if (a.annotationType() == RegisterElement.class) { + RegisterElement registerElement = (RegisterElement) a; + Constructor cons = c.getConstructor(); + try { + Element element = (Element) cons.newInstance(); + + switch (element.getElementType()) { + case PLACEABLE: + this.addPlaceableElement((PlaceableElement) element); + break; + case NONPLACEABLE: + this.addNonPlaceableElement((NonPlaceableElement) element); + break; + default: + break; + } + } catch (InvocationTargetException e) { + System.out.println(" Failed "); + e.getTargetException().printStackTrace(); } - -// } catch (IOException | ClassNotFoundException | NoSuchMethodException | -// InstantiationException | IllegalAccessException | InvocationTargetException e) { -// LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); -// } + } } - catch (Exception e) { - LOGGER.error("Unable to find elements for " + this.getClass().getSimpleName(), e); - } - } - - private void registerRules() { - String packageName = this.getClass().getPackage().toString().replace("package ", ""); - - try { - Class[] possRules = LegupUtils.getClasses(packageName); - - for (Class c : possRules) { - - System.out.println("possible rule: " + c.getName()); - - //check that the rule is not abstract - if (Modifier.isAbstract(c.getModifiers())) continue; - - for (Annotation a : c.getAnnotations()) { - if (a.annotationType() == RegisterRule.class) { - RegisterRule registerRule = (RegisterRule) a; - Constructor cons = c.getConstructor(); - try { - Rule rule = (Rule) cons.newInstance(); - - switch (rule.getRuleType()) { - case BASIC: - this.addDirectRule((DirectRule) rule); - break; - case CASE: - this.addCaseRule((CaseRule) rule); - break; - case CONTRADICTION: - this.addContradictionRule((ContradictionRule) rule); - break; - case MERGE: - break; - default: - break; - } - } - catch (InvocationTargetException e) { - System.out.println(" Failed "); - e.getTargetException().printStackTrace(); - } - } - } + } + + // } catch (IOException | ClassNotFoundException | NoSuchMethodException | + // InstantiationException | IllegalAccessException | InvocationTargetException + // e) { + // LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); + // } + } catch (Exception e) { + LOGGER.error("Unable to find elements for " + this.getClass().getSimpleName(), e); + } + } + + private void registerRules() { + String packageName = this.getClass().getPackage().toString().replace("package ", ""); + + try { + Class[] possRules = LegupUtils.getClasses(packageName); + + for (Class c : possRules) { + + System.out.println("possible rule: " + c.getName()); + + // check that the rule is not abstract + if (Modifier.isAbstract(c.getModifiers())) continue; + + for (Annotation a : c.getAnnotations()) { + if (a.annotationType() == RegisterRule.class) { + RegisterRule registerRule = (RegisterRule) a; + Constructor cons = c.getConstructor(); + try { + Rule rule = (Rule) cons.newInstance(); + + switch (rule.getRuleType()) { + case BASIC: + this.addDirectRule((DirectRule) rule); + break; + case CASE: + this.addCaseRule((CaseRule) rule); + break; + case CONTRADICTION: + this.addContradictionRule((ContradictionRule) rule); + break; + case MERGE: + break; + default: + break; + } + } catch (InvocationTargetException e) { + System.out.println(" Failed "); + e.getTargetException().printStackTrace(); } - -// } catch (IOException | ClassNotFoundException | NoSuchMethodException | -// InstantiationException | IllegalAccessException | InvocationTargetException e) { -// LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); -// } + } } - catch (Exception e) { - LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); + } + + // } catch (IOException | ClassNotFoundException | NoSuchMethodException | + // InstantiationException | IllegalAccessException | InvocationTargetException + // e) { + // LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); + // } + } catch (Exception e) { + LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); + } + } + + /** Initializes the view. Called by the invoker of the class */ + public abstract void initializeView(); + + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + public abstract Board generatePuzzle(int difficulty); + + /** + * Checks if the given height and width are valid board dimensions for the given puzzle + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @return true if the given dimensions are valid for the given puzzle, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows > 0 && columns > 0; + } + + /** + * Checks if the given array of statements is valid text input for the given puzzle + * + * @param statements + * @return + */ + public boolean isValidTextInput(String[] statements) { + return statements.length > 0; + } + + /** + * Determines if the edu.rpi.legup.puzzle was solves correctly + * + * @return true if the board was solved correctly, false otherwise + */ + public boolean isPuzzleComplete() { + if (tree == null) { + return false; + } + + boolean isComplete = tree.isValid(); + if (isComplete) { + for (TreeElement leaf : tree.getLeafTreeElements()) { + if (leaf.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) leaf; + if (!node.isRoot()) { + isComplete &= + node.getParent().isContradictoryBranch() || isBoardComplete(node.getBoard()); + } else { + isComplete &= isBoardComplete(node.getBoard()); + } + } else { + isComplete = false; } - } - - /** - * Initializes the view. Called by the invoker of the class - */ - public abstract void initializeView(); - - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - public abstract Board generatePuzzle(int difficulty); - - /** - * Checks if the given height and width are valid board dimensions for the given puzzle - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @return true if the given dimensions are valid for the given puzzle, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows > 0 && columns > 0; - } - - /** - * Checks if the given array of statements is valid text input for the given puzzle - * - * @param statements - * @return - */ - public boolean isValidTextInput(String[] statements) { - return statements.length > 0; - } - - /** - * Determines if the edu.rpi.legup.puzzle was solves correctly - * - * @return true if the board was solved correctly, false otherwise - */ - public boolean isPuzzleComplete() { - if (tree == null) { - return false; - } - - boolean isComplete = tree.isValid(); - if (isComplete) { - for (TreeElement leaf : tree.getLeafTreeElements()) { - if (leaf.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) leaf; - if (!node.isRoot()) { - isComplete &= node.getParent().isContradictoryBranch() || isBoardComplete(node.getBoard()); - } - else { - isComplete &= isBoardComplete(node.getBoard()); - } - } - else { - isComplete = false; - } - } - } - return isComplete; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - public abstract boolean isBoardComplete(Board board); - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - public abstract void onBoardChange(Board board); - - /** - * Imports the board using the file stream - * - * @param fileName the file that is imported - * @throws InvalidFileFormatException if file is invalid - */ - public void importPuzzle(String fileName) throws InvalidFileFormatException { - try { - importPuzzle(new FileInputStream(fileName)); - } - catch (IOException e) { - LOGGER.error("Importing puzzle error", e); - throw new InvalidFileFormatException("Could not find file"); - } - } - - /** - * Imports the board using the file stream - * - * @param inputStream the file stream that is imported - * @throws InvalidFileFormatException if file stream is invalid - */ - public void importPuzzle(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } - catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Importing puzzle error", e); - throw new InvalidFileFormatException("Could not find file"); - } - - org.w3c.dom.Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - if (importer == null) { - throw new InvalidFileFormatException("Puzzle importer null"); - } - importer.initializePuzzle(node); - } - else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); - } - } - - /** - * Gets the edu.rpi.legup.puzzle importer for importing edu.rpi.legup.puzzle files - * - * @return edu.rpi.legup.puzzle importer - */ - public PuzzleImporter getImporter() { - return importer; - } - - /** - * Gets the edu.rpi.legup.puzzle exporter for exporting edu.rpi.legup.puzzle files - * - * @return edu.rpi.legup.puzzle exporter - */ - public PuzzleExporter getExporter() { - return exporter; - } - - /** - * Gets the name of the edu.rpi.legup.puzzle - * - * @return name of the edu.rpi.legup.puzzle - */ - public String getName() { - return name; - } - - /** - * Gets the list of direct rules - * - * @return list of basic rules - */ - public List getDirectRules() { - return directRules; - } - - public List getPlaceableElements() { - return placeableElements; - } - - public List getNonPlaceableElements() { - return nonPlaceableElements; - } - - - /** - * Sets the list of direct rules - * - * @param directRules list of basic rules - */ - public void setDirectRules(List directRules) { - this.directRules = directRules; - } - - /** - * Adds a basic rule to this Puzzle - * - * @param rule basic rule to add - */ - public void addDirectRule(DirectRule rule) { - directRules.add(rule); - } - - public void addPlaceableElement(PlaceableElement element) { - placeableElements.add(element); - } - - public void addNonPlaceableElement(NonPlaceableElement element) { - nonPlaceableElements.add(element); - } - - /** - * Remove a basic rule from this Puzzle - * - * @param rule basic rule to remove - */ - public void removeDirectRule(DirectRule rule) { - directRules.remove(rule); - } - - /** - * Gets the list of contradiction rules - * - * @return list of contradiction rules - */ - public List getContradictionRules() { - return contradictionRules; - } - - /** - * Sets the list of contradiction rules - * - * @param contradictionRules list of contradiction rules - */ - public void setContradictionRules(List contradictionRules) { - this.contradictionRules = contradictionRules; - } - - /** - * Adds a contradiction rule to this Puzzle - * - * @param rule contradiction rule to add - */ - public void addContradictionRule(ContradictionRule rule) { - contradictionRules.add(rule); - } - - /** - * Remove a contradiction rule from this Puzzle - * - * @param rule contradiction rule to remove - */ - public void removeContradictionRule(ContradictionRule rule) { - contradictionRules.remove(rule); - } - - /** - * Gets the list of case rules - * - * @return list of case rules - */ - public List getCaseRules() { - return caseRules; - } - - /** - * Sets the list of case rules - * - * @param caseRules list of case rules - */ - public void setCaseRules(List caseRules) { - this.caseRules = caseRules; - } - - /** - * Adds a case rule to this Puzzle - * - * @param rule case rule to add - */ - public void addCaseRule(CaseRule rule) { - caseRules.add(rule); - } - - /** - * Removes a case rule from this Puzzle - * - * @param rule case rule to remove - */ - public void removeCaseRule(CaseRule rule) { - caseRules.remove(rule); - } - - /** - * Gets the rule using the specified name - * - * @param name name of the rule - * @return Rule - */ - public Rule getRuleByName(String name) { - for (Rule rule : directRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - for (Rule rule : contradictionRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - for (Rule rule : caseRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - Rule mergeRule = new MergeRule(); - if (mergeRule.getRuleName().equals(name)) { - return mergeRule; - } - return null; - } - - /** - * Gets the rule using the specified name - * - * @param id name of the rule - * @return Rule - */ - public Rule getRuleByID(String id) { - for (Rule rule : directRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - for (Rule rule : contradictionRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - for (Rule rule : caseRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - Rule mergeRule = new MergeRule(); - if (mergeRule.getRuleID().equals(id)) { - return mergeRule; - } - return null; - } - - /** - * Gets the current board - * - * @return current board - */ - public Board getCurrentBoard() { - return currentBoard; - } - - /** - * Sets the current board - * - * @param currentBoard the current board - */ - public void setCurrentBoard(Board currentBoard) { - this.currentBoard = currentBoard; - } - - /** - * Gets the Tree for keeping the board states - * - * @return Tree - */ - public Tree getTree() { - return tree; - } - - /** - * Sets the Tree for keeping the board states - * - * @param tree tree of board states - */ - public void setTree(Tree tree) { - this.tree = tree; - } - - /** - * Gets the board view that displays the board - * - * @return board view - */ - public BoardView getBoardView() { - return boardView; - } - - /** - * Sets the board view that displays the board - * - * @param boardView board view - */ - public void setBoardView(BoardView boardView) { - this.boardView = boardView; - } - - /** - * Gets the ElementFactory associated with this edu.rpi.legup.puzzle - * - * @return ElementFactory associated with this edu.rpi.legup.puzzle - */ - public ElementFactory getFactory() { - return factory; - } - - /** - * Sets the ElementFactory associated with this edu.rpi.legup.puzzle - * - * @param factory ElementFactory associated with this edu.rpi.legup.puzzle - */ - public void setFactory(ElementFactory factory) { - this.factory = factory; - } - - /** - * Adds a board listener - * - * @param listener listener to add - */ - @Override - public void addBoardListener(IBoardListener listener) { - boardListeners.add(listener); - } - - /** - * Removes a board listener - * - * @param listener listener to remove - */ - @Override - public void removeBoardListener(IBoardListener listener) { - boardListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyBoardListeners(Consumer algorithm) { - boardListeners.forEach(algorithm); - } - - /** - * Adds a board listener - * - * @param listener listener to add - */ - @Override - public void addTreeListener(ITreeListener listener) { - treeListeners.add(listener); - } - - /** - * Removes a tree listener - * - * @param listener listener to remove - */ - @Override - public void removeTreeListener(ITreeListener listener) { - treeListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyTreeListeners(Consumer algorithm) { - treeListeners.forEach(algorithm); - } - - /** - * Check if the puzzle is valid - * - * @return if the puzzle is valid - */ - public boolean checkValidity() { - return true; - } + } + } + return isComplete; + } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + public abstract boolean isBoardComplete(Board board); + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + public abstract void onBoardChange(Board board); + + /** + * Imports the board using the file stream + * + * @param fileName the file that is imported + * @throws InvalidFileFormatException if file is invalid + */ + public void importPuzzle(String fileName) throws InvalidFileFormatException { + try { + importPuzzle(new FileInputStream(fileName)); + } catch (IOException e) { + LOGGER.error("Importing puzzle error", e); + throw new InvalidFileFormatException("Could not find file"); + } + } + + /** + * Imports the board using the file stream + * + * @param inputStream the file stream that is imported + * @throws InvalidFileFormatException if file stream is invalid + */ + public void importPuzzle(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Importing puzzle error", e); + throw new InvalidFileFormatException("Could not find file"); + } + + org.w3c.dom.Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + if (importer == null) { + throw new InvalidFileFormatException("Puzzle importer null"); + } + importer.initializePuzzle(node); + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); + } + } + + /** + * Gets the edu.rpi.legup.puzzle importer for importing edu.rpi.legup.puzzle files + * + * @return edu.rpi.legup.puzzle importer + */ + public PuzzleImporter getImporter() { + return importer; + } + + /** + * Gets the edu.rpi.legup.puzzle exporter for exporting edu.rpi.legup.puzzle files + * + * @return edu.rpi.legup.puzzle exporter + */ + public PuzzleExporter getExporter() { + return exporter; + } + + /** + * Gets the name of the edu.rpi.legup.puzzle + * + * @return name of the edu.rpi.legup.puzzle + */ + public String getName() { + return name; + } + + /** + * Gets the list of direct rules + * + * @return list of basic rules + */ + public List getDirectRules() { + return directRules; + } + + public List getPlaceableElements() { + return placeableElements; + } + + public List getNonPlaceableElements() { + return nonPlaceableElements; + } + + /** + * Sets the list of direct rules + * + * @param directRules list of basic rules + */ + public void setDirectRules(List directRules) { + this.directRules = directRules; + } + + /** + * Adds a basic rule to this Puzzle + * + * @param rule basic rule to add + */ + public void addDirectRule(DirectRule rule) { + directRules.add(rule); + } + + public void addPlaceableElement(PlaceableElement element) { + placeableElements.add(element); + } + + public void addNonPlaceableElement(NonPlaceableElement element) { + nonPlaceableElements.add(element); + } + + /** + * Remove a basic rule from this Puzzle + * + * @param rule basic rule to remove + */ + public void removeDirectRule(DirectRule rule) { + directRules.remove(rule); + } + + /** + * Gets the list of contradiction rules + * + * @return list of contradiction rules + */ + public List getContradictionRules() { + return contradictionRules; + } + + /** + * Sets the list of contradiction rules + * + * @param contradictionRules list of contradiction rules + */ + public void setContradictionRules(List contradictionRules) { + this.contradictionRules = contradictionRules; + } + + /** + * Adds a contradiction rule to this Puzzle + * + * @param rule contradiction rule to add + */ + public void addContradictionRule(ContradictionRule rule) { + contradictionRules.add(rule); + } + + /** + * Remove a contradiction rule from this Puzzle + * + * @param rule contradiction rule to remove + */ + public void removeContradictionRule(ContradictionRule rule) { + contradictionRules.remove(rule); + } + + /** + * Gets the list of case rules + * + * @return list of case rules + */ + public List getCaseRules() { + return caseRules; + } + + /** + * Sets the list of case rules + * + * @param caseRules list of case rules + */ + public void setCaseRules(List caseRules) { + this.caseRules = caseRules; + } + + /** + * Adds a case rule to this Puzzle + * + * @param rule case rule to add + */ + public void addCaseRule(CaseRule rule) { + caseRules.add(rule); + } + + /** + * Removes a case rule from this Puzzle + * + * @param rule case rule to remove + */ + public void removeCaseRule(CaseRule rule) { + caseRules.remove(rule); + } + + /** + * Gets the rule using the specified name + * + * @param name name of the rule + * @return Rule + */ + public Rule getRuleByName(String name) { + for (Rule rule : directRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + for (Rule rule : contradictionRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + for (Rule rule : caseRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + Rule mergeRule = new MergeRule(); + if (mergeRule.getRuleName().equals(name)) { + return mergeRule; + } + return null; + } + + /** + * Gets the rule using the specified name + * + * @param id name of the rule + * @return Rule + */ + public Rule getRuleByID(String id) { + for (Rule rule : directRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + for (Rule rule : contradictionRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + for (Rule rule : caseRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + Rule mergeRule = new MergeRule(); + if (mergeRule.getRuleID().equals(id)) { + return mergeRule; + } + return null; + } + + /** + * Gets the current board + * + * @return current board + */ + public Board getCurrentBoard() { + return currentBoard; + } + + /** + * Sets the current board + * + * @param currentBoard the current board + */ + public void setCurrentBoard(Board currentBoard) { + this.currentBoard = currentBoard; + } + + /** + * Gets the Tree for keeping the board states + * + * @return Tree + */ + public Tree getTree() { + return tree; + } + + /** + * Sets the Tree for keeping the board states + * + * @param tree tree of board states + */ + public void setTree(Tree tree) { + this.tree = tree; + } + + /** + * Gets the board view that displays the board + * + * @return board view + */ + public BoardView getBoardView() { + return boardView; + } + + /** + * Sets the board view that displays the board + * + * @param boardView board view + */ + public void setBoardView(BoardView boardView) { + this.boardView = boardView; + } + + /** + * Gets the ElementFactory associated with this edu.rpi.legup.puzzle + * + * @return ElementFactory associated with this edu.rpi.legup.puzzle + */ + public ElementFactory getFactory() { + return factory; + } + + /** + * Sets the ElementFactory associated with this edu.rpi.legup.puzzle + * + * @param factory ElementFactory associated with this edu.rpi.legup.puzzle + */ + public void setFactory(ElementFactory factory) { + this.factory = factory; + } + + /** + * Adds a board listener + * + * @param listener listener to add + */ + @Override + public void addBoardListener(IBoardListener listener) { + boardListeners.add(listener); + } + + /** + * Removes a board listener + * + * @param listener listener to remove + */ + @Override + public void removeBoardListener(IBoardListener listener) { + boardListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyBoardListeners(Consumer algorithm) { + boardListeners.forEach(algorithm); + } + + /** + * Adds a board listener + * + * @param listener listener to add + */ + @Override + public void addTreeListener(ITreeListener listener) { + treeListeners.add(listener); + } + + /** + * Removes a tree listener + * + * @param listener listener to remove + */ + @Override + public void removeTreeListener(ITreeListener listener) { + treeListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyTreeListeners(Consumer algorithm) { + treeListeners.forEach(algorithm); + } + + /** + * Check if the puzzle is valid + * + * @return if the puzzle is valid + */ + public boolean checkValidity() { + return true; + } } diff --git a/src/main/java/edu/rpi/legup/model/PuzzleExporter.java b/src/main/java/edu/rpi/legup/model/PuzzleExporter.java index 613d2ed1c..cccf0155c 100644 --- a/src/main/java/edu/rpi/legup/model/PuzzleExporter.java +++ b/src/main/java/edu/rpi/legup/model/PuzzleExporter.java @@ -3,147 +3,143 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.w3c.dom.Document; import edu.rpi.legup.save.ExportFileException; - +import java.io.File; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import java.io.File; -import java.util.*; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.ZoneId; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.w3c.dom.Document; import org.w3c.dom.Element; public abstract class PuzzleExporter { - private static final Logger LOGGER = LogManager.getLogger(PuzzleExporter.class.getName()); - - protected Puzzle puzzle; - - /** - * PuzzleExporter Constructor exports the puzzle object to a file - * - * @param puzzle puzzle that is to be exported - */ - public PuzzleExporter(Puzzle puzzle) { - this.puzzle = puzzle; + private static final Logger LOGGER = LogManager.getLogger(PuzzleExporter.class.getName()); + + protected Puzzle puzzle; + + /** + * PuzzleExporter Constructor exports the puzzle object to a file + * + * @param puzzle puzzle that is to be exported + */ + public PuzzleExporter(Puzzle puzzle) { + this.puzzle = puzzle; + } + + /** + * Exports the puzzle to an xml formatted file + * + * @param fileName name of file to be exported + * @throws ExportFileException if puzzle can not be exported + */ + public void exportPuzzle(String fileName) throws ExportFileException { + try { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + Document newDocument = docBuilder.newDocument(); + + org.w3c.dom.Element legupElement = newDocument.createElement("Legup"); + legupElement.setAttribute("version", "3.0.0"); + newDocument.appendChild(legupElement); + + org.w3c.dom.Element timeSavedElement = newDocument.createElement("saved"); + legupElement.appendChild(timeSavedElement); + + org.w3c.dom.Element puzzleElement = newDocument.createElement("puzzle"); + puzzleElement.setAttribute("name", puzzle.getName()); + legupElement.appendChild(puzzleElement); + + puzzleElement.appendChild(createBoardElement(newDocument)); + if (puzzle.getTree() != null && !puzzle.getTree().getRootNode().getChildren().isEmpty()) { + puzzleElement.appendChild(createProofElement(newDocument)); + } + + org.w3c.dom.Element statusElement = newDocument.createElement("solved"); + String isSolved = "false"; + if (puzzle.isPuzzleComplete()) { + isSolved = "true"; + } + statusElement.setAttribute("isSolved", isSolved); + LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/New_York")); + String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + statusElement.setAttribute("lastSaved", time); + legupElement.appendChild(statusElement); + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + + DOMSource source = new DOMSource(newDocument); + StreamResult result = new StreamResult(new File(fileName)); + + transformer.transform(source, result); + } catch (ParserConfigurationException | TransformerException e) { + throw new ExportFileException("Puzzle Exporter: parser configuration exception"); + } catch (Exception e) { + throw e; + // throw new ExportFileException(e.getMessage()); } - - /** - * Exports the puzzle to an xml formatted file - * - * @param fileName name of file to be exported - * @throws ExportFileException if puzzle can not be exported - */ - public void exportPuzzle(String fileName) throws ExportFileException { - try { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document newDocument = docBuilder.newDocument(); - - org.w3c.dom.Element legupElement = newDocument.createElement("Legup"); - legupElement.setAttribute("version", "3.0.0"); - newDocument.appendChild(legupElement); - - org.w3c.dom.Element timeSavedElement = newDocument.createElement("saved"); - legupElement.appendChild(timeSavedElement); - - org.w3c.dom.Element puzzleElement = newDocument.createElement("puzzle"); - puzzleElement.setAttribute("name", puzzle.getName()); - legupElement.appendChild(puzzleElement); - - puzzleElement.appendChild(createBoardElement(newDocument)); - if (puzzle.getTree() != null && !puzzle.getTree().getRootNode().getChildren().isEmpty()) { - puzzleElement.appendChild(createProofElement(newDocument)); - } - - org.w3c.dom.Element statusElement = newDocument.createElement("solved"); - String isSolved = "false"; - if (puzzle.isPuzzleComplete()) { - isSolved = "true"; - } - statusElement.setAttribute("isSolved", isSolved); - LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/New_York")); - String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - statusElement.setAttribute("lastSaved", time); - legupElement.appendChild(statusElement); - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - DOMSource source = new DOMSource(newDocument); - StreamResult result = new StreamResult(new File(fileName)); - - transformer.transform(source, result); - } - catch (ParserConfigurationException | TransformerException e) { - throw new ExportFileException("Puzzle Exporter: parser configuration exception"); + } + + protected abstract Element createBoardElement(Document newDocument); + + protected Element createProofElement(Document newDocument) { + org.w3c.dom.Element proofElement = newDocument.createElement("proof"); + org.w3c.dom.Element treeElement = createTreeElement(newDocument); + proofElement.appendChild(treeElement); + return proofElement; + } + + protected Element createTreeElement(Document newDocument) { + org.w3c.dom.Element treeElement = newDocument.createElement("tree"); + + Set visited = new HashSet<>(); + List nodes = new ArrayList<>(); + nodes.add(puzzle.getTree().getRootNode()); + while (!nodes.isEmpty()) { + TreeNode treeNode = nodes.get(nodes.size() - 1); + nodes.remove(treeNode); + if (!visited.contains(treeNode)) { + visited.add(treeNode); + + org.w3c.dom.Element nodeElement = newDocument.createElement("node"); + nodeElement.setAttribute("id", String.valueOf(treeNode.hashCode())); + if (treeNode.isRoot()) { + nodeElement.setAttribute("root", "true"); } - catch (Exception e) { - throw e; - //throw new ExportFileException(e.getMessage()); - } - } - - protected abstract Element createBoardElement(Document newDocument); - - protected Element createProofElement(Document newDocument) { - org.w3c.dom.Element proofElement = newDocument.createElement("proof"); - org.w3c.dom.Element treeElement = createTreeElement(newDocument); - proofElement.appendChild(treeElement); - return proofElement; - } - protected Element createTreeElement(Document newDocument) { - org.w3c.dom.Element treeElement = newDocument.createElement("tree"); - - Set visited = new HashSet<>(); - List nodes = new ArrayList<>(); - nodes.add(puzzle.getTree().getRootNode()); - while (!nodes.isEmpty()) { - TreeNode treeNode = nodes.get(nodes.size() - 1); - nodes.remove(treeNode); - if (!visited.contains(treeNode)) { - visited.add(treeNode); - - org.w3c.dom.Element nodeElement = newDocument.createElement("node"); - nodeElement.setAttribute("id", String.valueOf(treeNode.hashCode())); - if (treeNode.isRoot()) { - nodeElement.setAttribute("root", "true"); - } - - for (TreeTransition transition : treeNode.getChildren()) { - org.w3c.dom.Element transElement = newDocument.createElement("transition"); - transElement.setAttribute("id", String.valueOf(transition.hashCode())); - - TreeNode child = transition.getChildNode(); - if (child != null) { - transElement.setAttribute("child", String.valueOf(child.hashCode())); - nodes.add(child); - } - - if (transition.isJustified()) { - transElement.setAttribute("rule", transition.getRule().getRuleName()); - transElement.setAttribute("rule_id", transition.getRule().getRuleID()); - } - - for (PuzzleElement data : transition.getBoard().getModifiedData()) { - transElement.appendChild(puzzle.getFactory().exportCell(newDocument, data)); - } - nodeElement.appendChild(transElement); - } - treeElement.appendChild(nodeElement); - } + for (TreeTransition transition : treeNode.getChildren()) { + org.w3c.dom.Element transElement = newDocument.createElement("transition"); + transElement.setAttribute("id", String.valueOf(transition.hashCode())); + + TreeNode child = transition.getChildNode(); + if (child != null) { + transElement.setAttribute("child", String.valueOf(child.hashCode())); + nodes.add(child); + } + + if (transition.isJustified()) { + transElement.setAttribute("rule", transition.getRule().getRuleName()); + transElement.setAttribute("rule_id", transition.getRule().getRuleID()); + } + + for (PuzzleElement data : transition.getBoard().getModifiedData()) { + transElement.appendChild(puzzle.getFactory().exportCell(newDocument, data)); + } + nodeElement.appendChild(transElement); } - return treeElement; + treeElement.appendChild(nodeElement); + } } + return treeElement; + } } diff --git a/src/main/java/edu/rpi/legup/model/PuzzleImporter.java b/src/main/java/edu/rpi/legup/model/PuzzleImporter.java index 327a92773..35a3cd6be 100644 --- a/src/main/java/edu/rpi/legup/model/PuzzleImporter.java +++ b/src/main/java/edu/rpi/legup/model/PuzzleImporter.java @@ -6,396 +6,406 @@ import edu.rpi.legup.model.rules.Rule; import edu.rpi.legup.model.tree.*; import edu.rpi.legup.save.InvalidFileFormatException; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.util.*; - public abstract class PuzzleImporter { - private static final Logger LOGGER = LogManager.getLogger(PuzzleImporter.class.getName()); - - protected Puzzle puzzle; - - /** - * PuzzleImporter Constructor creates the puzzle object - * - * @param puzzle puzzle that is imported - */ - public PuzzleImporter(Puzzle puzzle) { - this.puzzle = puzzle; - } - - public abstract boolean acceptsRowsAndColumnsInput(); - - public abstract boolean acceptsTextInput(); - - /** - * Initializes an empty puzzle - * - * @param rows number of rows on the puzzle - * @param columns number of columns on the puzzle - * @throws RuntimeException if puzzle can not be made - */ - public void initializePuzzle(int rows, int columns) throws RuntimeException { - if (this.puzzle.isValidDimensions(rows, columns)) { - initializeBoard(rows, columns); - } - else { - throw new IllegalArgumentException("Invalid dimensions provided"); - } - } - - public void initializePuzzle(String[] statements) throws InputMismatchException, IllegalArgumentException { - // Note: Error checking for the statements will be left up to the puzzles that support - // text input. For example, some puzzles may be okay with "blank" statements (Strings with - // length = 0) while others may not. - initializeBoard(statements); + private static final Logger LOGGER = LogManager.getLogger(PuzzleImporter.class.getName()); + + protected Puzzle puzzle; + + /** + * PuzzleImporter Constructor creates the puzzle object + * + * @param puzzle puzzle that is imported + */ + public PuzzleImporter(Puzzle puzzle) { + this.puzzle = puzzle; + } + + public abstract boolean acceptsRowsAndColumnsInput(); + + public abstract boolean acceptsTextInput(); + + /** + * Initializes an empty puzzle + * + * @param rows number of rows on the puzzle + * @param columns number of columns on the puzzle + * @throws RuntimeException if puzzle can not be made + */ + public void initializePuzzle(int rows, int columns) throws RuntimeException { + if (this.puzzle.isValidDimensions(rows, columns)) { + initializeBoard(rows, columns); + } else { + throw new IllegalArgumentException("Invalid dimensions provided"); } - - /** - * Initializes the puzzle attributes - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public void initializePuzzle(Node node) throws InvalidFileFormatException { - if (node.getNodeName().equalsIgnoreCase("puzzle")) { - org.w3c.dom.Element puzzleElement = (org.w3c.dom.Element) node; - - boolean initBoard = false; - boolean initProof = false; - NodeList childNodes = puzzleElement.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - Node n = childNodes.item(i); - if (n.getNodeName().equalsIgnoreCase("board")) { - if (initBoard) { - throw new InvalidFileFormatException("Puzzle creation error: duplicate board puzzleElement found"); - } - initializeBoard(n); - initBoard = true; - } - else { - if (n.getNodeName().equalsIgnoreCase("proof")) { - if (initProof) { - throw new InvalidFileFormatException("Puzzle creation error: duplicate proof puzzleElement found"); - } - if (!initBoard) { - throw new InvalidFileFormatException("Puzzle creation error: could not find board puzzleElement"); - } - initializeProof(n); - initProof = true; - } - else { - if (!n.getNodeName().equalsIgnoreCase("#text")) { - throw new InvalidFileFormatException("Puzzle creation error: unknown node found in file"); - } - } - } + } + + public void initializePuzzle(String[] statements) + throws InputMismatchException, IllegalArgumentException { + // Note: Error checking for the statements will be left up to the puzzles that support + // text input. For example, some puzzles may be okay with "blank" statements (Strings with + // length = 0) while others may not. + initializeBoard(statements); + } + + /** + * Initializes the puzzle attributes + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public void initializePuzzle(Node node) throws InvalidFileFormatException { + if (node.getNodeName().equalsIgnoreCase("puzzle")) { + org.w3c.dom.Element puzzleElement = (org.w3c.dom.Element) node; + + boolean initBoard = false; + boolean initProof = false; + NodeList childNodes = puzzleElement.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node n = childNodes.item(i); + if (n.getNodeName().equalsIgnoreCase("board")) { + if (initBoard) { + throw new InvalidFileFormatException( + "Puzzle creation error: duplicate board puzzleElement found"); + } + initializeBoard(n); + initBoard = true; + } else { + if (n.getNodeName().equalsIgnoreCase("proof")) { + if (initProof) { + throw new InvalidFileFormatException( + "Puzzle creation error: duplicate proof puzzleElement found"); } - if (!initBoard) { - throw new InvalidFileFormatException("Puzzle creation error: could not find board puzzleElement"); + throw new InvalidFileFormatException( + "Puzzle creation error: could not find board puzzleElement"); } - if (!initProof) { - createDefaultTree(); + initializeProof(n); + initProof = true; + } else { + if (!n.getNodeName().equalsIgnoreCase("#text")) { + throw new InvalidFileFormatException( + "Puzzle creation error: unknown node found in file"); } + } } - else { - throw new InvalidFileFormatException("Invalid file format; does not contain \"puzzle\" node"); - } + } + + if (!initBoard) { + throw new InvalidFileFormatException( + "Puzzle creation error: could not find board puzzleElement"); + } + if (!initProof) { + createDefaultTree(); + } + } else { + throw new InvalidFileFormatException("Invalid file format; does not contain \"puzzle\" node"); } - - /** - * Creates the board for building - * - * @param rows number of rows on the puzzle - * @param columns number of columns on the puzzle - * @throws RuntimeException if board can not be created - */ - public abstract void initializeBoard(int rows, int columns); - - /** - * Creates an empty board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public abstract void initializeBoard(Node node) throws InvalidFileFormatException; - - public abstract void initializeBoard(String[] statements) throws UnsupportedOperationException, IllegalArgumentException; - - /** - * Creates the proof for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public void initializeProof(Node node) throws InvalidFileFormatException { - if (node.getNodeName().equalsIgnoreCase("proof")) { - org.w3c.dom.Element proofElement = (org.w3c.dom.Element) node; - NodeList treeList = proofElement.getElementsByTagName("tree"); - - boolean initTree = false; - for (int i = 0; i < treeList.getLength(); i++) { - Node n = treeList.item(i); - if (n.getNodeName().equalsIgnoreCase("tree")) { - if (initTree) { - throw new InvalidFileFormatException("Proof Tree construction error: duplicate tree puzzleElement"); - } - createTree(n); - initTree = true; - } - else { - throw new InvalidFileFormatException("Proof Tree construction error: unknown puzzleElement found"); - } - } - if (!initTree) { - createDefaultTree(); - } - } - else { - throw new InvalidFileFormatException("Invalid file format; does not contain \"proof\" node"); + } + + /** + * Creates the board for building + * + * @param rows number of rows on the puzzle + * @param columns number of columns on the puzzle + * @throws RuntimeException if board can not be created + */ + public abstract void initializeBoard(int rows, int columns); + + /** + * Creates an empty board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public abstract void initializeBoard(Node node) throws InvalidFileFormatException; + + public abstract void initializeBoard(String[] statements) + throws UnsupportedOperationException, IllegalArgumentException; + + /** + * Creates the proof for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public void initializeProof(Node node) throws InvalidFileFormatException { + if (node.getNodeName().equalsIgnoreCase("proof")) { + org.w3c.dom.Element proofElement = (org.w3c.dom.Element) node; + NodeList treeList = proofElement.getElementsByTagName("tree"); + + boolean initTree = false; + for (int i = 0; i < treeList.getLength(); i++) { + Node n = treeList.item(i); + if (n.getNodeName().equalsIgnoreCase("tree")) { + if (initTree) { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate tree puzzleElement"); + } + createTree(n); + initTree = true; + } else { + throw new InvalidFileFormatException( + "Proof Tree construction error: unknown puzzleElement found"); } + } + if (!initTree) { + createDefaultTree(); + } + } else { + throw new InvalidFileFormatException("Invalid file format; does not contain \"proof\" node"); } - - /** - * Sets the puzzleElement from the xml document node - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - protected void setCells(Node node) throws InvalidFileFormatException { - NodeList dataList = ((org.w3c.dom.Element) node).getElementsByTagName("cell"); - Board board = puzzle.getCurrentBoard(); - for (int i = 0; i < dataList.getLength(); i++) { - PuzzleElement data = puzzle.getFactory().importCell(dataList.item(i), puzzle.getCurrentBoard()); - board.setPuzzleElement(data.getIndex(), data); + } + + /** + * Sets the puzzleElement from the xml document node + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + protected void setCells(Node node) throws InvalidFileFormatException { + NodeList dataList = ((org.w3c.dom.Element) node).getElementsByTagName("cell"); + Board board = puzzle.getCurrentBoard(); + for (int i = 0; i < dataList.getLength(); i++) { + PuzzleElement data = + puzzle.getFactory().importCell(dataList.item(i), puzzle.getCurrentBoard()); + board.setPuzzleElement(data.getIndex(), data); + } + } + + /** + * Creates the tree for the edu.rpi.legup.puzzle + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + protected void createTree(Node node) throws InvalidFileFormatException { + Element treeElement = (org.w3c.dom.Element) node; + + Tree tree = new Tree(); + puzzle.setTree(tree); + + NodeList nodeList = ((org.w3c.dom.Element) node).getElementsByTagName("node"); + + HashMap treeNodes = new HashMap<>(); + HashMap treeTransitions = new HashMap<>(); + HashMap nodeChanges = new HashMap<>(); + + for (int i = 0; i < nodeList.getLength(); i++) { + org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); + String nodeId = treeNodeElement.getAttribute("id"); + String isRoot = treeNodeElement.getAttribute("root"); + if (nodeId.isEmpty()) { + throw new InvalidFileFormatException("Proof Tree construction error: cannot find node ID"); + } + if (treeNodes.containsKey(nodeId)) { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate tree node ID found"); + } + TreeNode treeNode = new TreeNode(puzzle.getCurrentBoard().copy()); + if (isRoot.equalsIgnoreCase("true")) { + if (tree.getRootNode() != null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: multiple root nodes declared"); } + treeNode.setRoot(true); + tree.setRootNode(treeNode); + } + treeNodes.put(nodeId, treeNode); } - /** - * Creates the tree for the edu.rpi.legup.puzzle - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - protected void createTree(Node node) throws InvalidFileFormatException { - Element treeElement = (org.w3c.dom.Element) node; - - Tree tree = new Tree(); - puzzle.setTree(tree); - - NodeList nodeList = ((org.w3c.dom.Element) node).getElementsByTagName("node"); - - HashMap treeNodes = new HashMap<>(); - HashMap treeTransitions = new HashMap<>(); - HashMap nodeChanges = new HashMap<>(); - - for (int i = 0; i < nodeList.getLength(); i++) { - org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); - String nodeId = treeNodeElement.getAttribute("id"); - String isRoot = treeNodeElement.getAttribute("root"); - if (nodeId.isEmpty()) { - throw new InvalidFileFormatException("Proof Tree construction error: cannot find node ID"); - } - if (treeNodes.containsKey(nodeId)) { - throw new InvalidFileFormatException("Proof Tree construction error: duplicate tree node ID found"); - } - TreeNode treeNode = new TreeNode(puzzle.getCurrentBoard().copy()); - if (isRoot.equalsIgnoreCase("true")) { - if (tree.getRootNode() != null) { - throw new InvalidFileFormatException("Proof Tree construction error: multiple root nodes declared"); - } - treeNode.setRoot(true); - tree.setRootNode(treeNode); - } - treeNodes.put(nodeId, treeNode); + for (int i = 0; i < nodeList.getLength(); i++) { + org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); + String nodeId = treeNodeElement.getAttribute("id"); + TreeNode treeNode = treeNodes.get(nodeId); + + NodeList transList = treeNodeElement.getElementsByTagName("transition"); + for (int k = 0; k < transList.getLength(); k++) { + org.w3c.dom.Element trans = (org.w3c.dom.Element) transList.item(k); + String transId = trans.getAttribute("id"); + TreeTransition transition = treeTransitions.get(transId); + if (transition != null) { + if (transition.getRule() instanceof MergeRule) { + transition.addParent(treeNode); + treeNode.addChild(transition); + continue; + } else { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate transition ID found"); + } } + String childId = trans.getAttribute("child"); + String ruleName = trans.getAttribute("rule"); + String ruleId = trans.getAttribute("rule_id"); - for (int i = 0; i < nodeList.getLength(); i++) { - org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); - String nodeId = treeNodeElement.getAttribute("id"); - TreeNode treeNode = treeNodes.get(nodeId); - - NodeList transList = treeNodeElement.getElementsByTagName("transition"); - for (int k = 0; k < transList.getLength(); k++) { - org.w3c.dom.Element trans = (org.w3c.dom.Element) transList.item(k); - String transId = trans.getAttribute("id"); - TreeTransition transition = treeTransitions.get(transId); - if (transition != null) { - if (transition.getRule() instanceof MergeRule) { - transition.addParent(treeNode); - treeNode.addChild(transition); - continue; - } - else { - throw new InvalidFileFormatException("Proof Tree construction error: duplicate transition ID found"); - } - - } - - String childId = trans.getAttribute("child"); - String ruleName = trans.getAttribute("rule"); - String ruleId = trans.getAttribute("rule_id"); - - TreeNode child = treeNodes.get(childId); - - transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - - Rule rule; - if (!ruleName.isEmpty()) { - rule = puzzle.getRuleByID(ruleId); - if (rule == null) { - throw new InvalidFileFormatException("Proof Tree construction error: could not find rule by ID"); - } - transition.setRule(rule); - } - - treeNode.addChild(transition); - if (child != null) { - child.setParent(transition); - transition.setChildNode(child); - } - - nodeChanges.put(transition, trans); - treeTransitions.put(transId, transition); - } - } - - //validateTreeStructure(treeNodes, treeTransitions); - System.err.println("Tree Size: " + treeTransitions.size()); - for (Map.Entry entry : nodeChanges.entrySet()) { - makeTransitionChanges(entry.getKey(), entry.getValue()); - } - } + TreeNode child = treeNodes.get(childId); - protected void validateTreeStructure(HashMap nodes, HashMap transitions) throws InvalidFileFormatException { - Tree tree = puzzle.getTree(); + transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - if (tree == null) { - throw new InvalidFileFormatException("Proof Tree construction error: invalid tree"); + Rule rule; + if (!ruleName.isEmpty()) { + rule = puzzle.getRuleByID(ruleId); + if (rule == null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: could not find rule by ID"); + } + transition.setRule(rule); } - HashMap connectedNodes = new HashMap<>(); - HashMap connectedTransitions = new HashMap<>(); - - for (TreeNode node : nodes.values()) { - connectedNodes.put(node, false); + treeNode.addChild(transition); + if (child != null) { + child.setParent(transition); + transition.setChildNode(child); } - for (TreeTransition trans : transitions.values()) { - connectedTransitions.put(trans, false); - } + nodeChanges.put(transition, trans); + treeTransitions.put(transId, transition); + } + } - ArrayList treeElements = new ArrayList<>(); - treeElements.add(tree.getRootNode()); - while (!treeElements.isEmpty()) { - TreeElement element = treeElements.get(treeElements.size() - 1); - treeElements.remove(element); - if (element.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) element; - - if (connectedNodes.get(treeNode)) { -// for(TreeTransition trans : treeNode.getParents()) -// { -// if(!(trans.getRule() instanceof MergeRule)) -// { -// throw new InvalidFileFormatException("Proof Tree structure validation error: cyclic tree detected"); -// } -// } - } - connectedNodes.replace(treeNode, true); - - for (TreeTransition trans : treeNode.getChildren()) { - treeElements.add(trans); - } - } - else { - TreeTransition treeTransition = (TreeTransition) element; + // validateTreeStructure(treeNodes, treeTransitions); + System.err.println("Tree Size: " + treeTransitions.size()); + for (Map.Entry entry : nodeChanges.entrySet()) { + makeTransitionChanges(entry.getKey(), entry.getValue()); + } + } - if (connectedTransitions.get(treeTransition)) { - throw new InvalidFileFormatException("Proof Tree structure validation error: cyclic tree detected"); - } - connectedTransitions.replace(treeTransition, true); + protected void validateTreeStructure( + HashMap nodes, HashMap transitions) + throws InvalidFileFormatException { + Tree tree = puzzle.getTree(); - if (treeTransition.getChildNode() != null) { - treeElements.add(treeTransition.getChildNode()); - } - } - } + if (tree == null) { + throw new InvalidFileFormatException("Proof Tree construction error: invalid tree"); + } - for (TreeNode node : nodes.values()) { - if (!connectedNodes.get(node)) { - throw new InvalidFileFormatException("Proof Tree structure validation error: disjoint node detected"); - } - } + HashMap connectedNodes = new HashMap<>(); + HashMap connectedTransitions = new HashMap<>(); - for (TreeTransition trans : transitions.values()) { - if (!connectedTransitions.get(trans)) { - throw new InvalidFileFormatException("Proof Tree structure validation error: disjoint transition detected"); - } - } + for (TreeNode node : nodes.values()) { + connectedNodes.put(node, false); } - protected void makeTransitionChanges(TreeTransition transition, Node transElement) throws InvalidFileFormatException { - if (transition.getRule() instanceof MergeRule) { - List mergingNodes = transition.getParents(); - List mergingBoards = new ArrayList<>(); - mergingNodes.forEach(n -> mergingBoards.add(n.getBoard())); + for (TreeTransition trans : transitions.values()) { + connectedTransitions.put(trans, false); + } - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - throw new InvalidFileFormatException("Proof Tree construction error: unable to find merge node"); - } - Board lcaBoard = lca.getBoard(); + ArrayList treeElements = new ArrayList<>(); + treeElements.add(tree.getRootNode()); + while (!treeElements.isEmpty()) { + TreeElement element = treeElements.get(treeElements.size() - 1); + treeElements.remove(element); + if (element.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) element; + + if (connectedNodes.get(treeNode)) { + // for(TreeTransition trans : treeNode.getParents()) + // { + // if(!(trans.getRule() instanceof MergeRule)) + // { + // throw new InvalidFileFormatException("Proof Tree structure + // validation error: cyclic tree detected"); + // } + // } + } + connectedNodes.replace(treeNode, true); - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + for (TreeTransition trans : treeNode.getChildren()) { + treeElements.add(trans); + } + } else { + TreeTransition treeTransition = (TreeTransition) element; - transition.setBoard(mergedBoard); - TreeNode childNode = transition.getChildNode(); - if (childNode != null) { - childNode.setBoard(mergedBoard.copy()); - } + if (connectedTransitions.get(treeTransition)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: cyclic tree detected"); } - else { - NodeList cellList = transElement.getChildNodes(); - for (int i = 0; i < cellList.getLength(); i++) { - Node node = cellList.item(i); - if (node.getNodeName().equalsIgnoreCase("cell")) { - Board board = transition.getBoard(); - PuzzleElement cell = puzzle.getFactory().importCell(node, board); - - board.setPuzzleElement(cell.getIndex(), cell); - board.addModifiedData(cell); - transition.propagateChange(cell); - } - else { - if (!node.getNodeName().equalsIgnoreCase("#text")) { - throw new InvalidFileFormatException("Proof Tree construction error: unknown node in transition"); - } - } - } + connectedTransitions.replace(treeTransition, true); + + if (treeTransition.getChildNode() != null) { + treeElements.add(treeTransition.getChildNode()); } + } } - protected void createDefaultTree() { - TreeNode root = new TreeNode(puzzle.getCurrentBoard()); - root.setRoot(true); - Tree tree = new Tree(); - tree.setRootNode(root); - puzzle.setTree(tree); + for (TreeNode node : nodes.values()) { + if (!connectedNodes.get(node)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: disjoint node detected"); + } } - /** - * Gets the result of building the Puzzle - * - * @return puzzle - */ - public Puzzle getPuzzle() { - return puzzle; + for (TreeTransition trans : transitions.values()) { + if (!connectedTransitions.get(trans)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: disjoint transition detected"); + } + } + } + + protected void makeTransitionChanges(TreeTransition transition, Node transElement) + throws InvalidFileFormatException { + if (transition.getRule() instanceof MergeRule) { + List mergingNodes = transition.getParents(); + List mergingBoards = new ArrayList<>(); + mergingNodes.forEach(n -> mergingBoards.add(n.getBoard())); + + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: unable to find merge node"); + } + Board lcaBoard = lca.getBoard(); + + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + transition.setBoard(mergedBoard); + TreeNode childNode = transition.getChildNode(); + if (childNode != null) { + childNode.setBoard(mergedBoard.copy()); + } + } else { + NodeList cellList = transElement.getChildNodes(); + for (int i = 0; i < cellList.getLength(); i++) { + Node node = cellList.item(i); + if (node.getNodeName().equalsIgnoreCase("cell")) { + Board board = transition.getBoard(); + PuzzleElement cell = puzzle.getFactory().importCell(node, board); + + board.setPuzzleElement(cell.getIndex(), cell); + board.addModifiedData(cell); + transition.propagateChange(cell); + } else { + if (!node.getNodeName().equalsIgnoreCase("#text")) { + throw new InvalidFileFormatException( + "Proof Tree construction error: unknown node in transition"); + } + } + } } + } + + protected void createDefaultTree() { + TreeNode root = new TreeNode(puzzle.getCurrentBoard()); + root.setRoot(true); + Tree tree = new Tree(); + tree.setRootNode(root); + puzzle.setTree(tree); + } + + /** + * Gets the result of building the Puzzle + * + * @return puzzle + */ + public Puzzle getPuzzle() { + return puzzle; + } } diff --git a/src/main/java/edu/rpi/legup/model/RegisterPuzzle.java b/src/main/java/edu/rpi/legup/model/RegisterPuzzle.java index 32f01edbc..c4c1ed273 100644 --- a/src/main/java/edu/rpi/legup/model/RegisterPuzzle.java +++ b/src/main/java/edu/rpi/legup/model/RegisterPuzzle.java @@ -7,6 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface RegisterPuzzle { - -} +public @interface RegisterPuzzle {} diff --git a/src/main/java/edu/rpi/legup/model/elements/Element.java b/src/main/java/edu/rpi/legup/model/elements/Element.java index 7ab502c63..5ad31782a 100644 --- a/src/main/java/edu/rpi/legup/model/elements/Element.java +++ b/src/main/java/edu/rpi/legup/model/elements/Element.java @@ -1,78 +1,76 @@ package edu.rpi.legup.model.elements; -import edu.rpi.legup.model.rules.RuleType; - -import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; +import javax.swing.*; @RegisterElement public abstract class Element { - protected String elementID; - protected String elementName; - protected String description; + protected String elementID; + protected String elementName; + protected String description; - protected String imageName; - protected ImageIcon image; + protected String imageName; + protected ImageIcon image; - protected ElementType elementType; + protected ElementType elementType; - private final String INVALID_USE_MESSAGE; + private final String INVALID_USE_MESSAGE; - public Element(String elementID, String elementName, String description, String imageName) { - this.elementID = elementID; - this.elementName = elementName; - this.description = description; - this.imageName = imageName; - this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.elementName; - loadImage(); - } + public Element(String elementID, String elementName, String description, String imageName) { + this.elementID = elementID; + this.elementName = elementName; + this.description = description; + this.imageName = imageName; + this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.elementName; + loadImage(); + } - private void loadImage() { - if (imageName != null) { - this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(imageName)); - //Resize images to be 100px wide - Image image = this.image.getImage(); - if (this.image.getIconWidth() < 120) return; - int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); - if (height == 0) { - System.out.println("height is 0 error"); - System.out.println("height: " + this.image.getIconHeight()); - System.out.println("width: " + this.image.getIconWidth()); - return; - } - BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = bimage.createGraphics(); - g.drawImage(image, 0, 0, 100, height, null); - this.image = new ImageIcon(bimage); - } + private void loadImage() { + if (imageName != null) { + this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(imageName)); + // Resize images to be 100px wide + Image image = this.image.getImage(); + if (this.image.getIconWidth() < 120) return; + int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); + if (height == 0) { + System.out.println("height is 0 error"); + System.out.println("height: " + this.image.getIconHeight()); + System.out.println("width: " + this.image.getIconWidth()); + return; + } + BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = bimage.createGraphics(); + g.drawImage(image, 0, 0, 100, height, null); + this.image = new ImageIcon(bimage); } + } - public String getElementName() { - return elementName; - } + public String getElementName() { + return elementName; + } - public void setElementName(String elementName) { - this.elementName = elementName; - } + public void setElementName(String elementName) { + this.elementName = elementName; + } - public String getElementID() { - return elementID; - } + public String getElementID() { + return elementID; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public ImageIcon getImageIcon() { - return image; - } + public ImageIcon getImageIcon() { + return image; + } - public ElementType getElementType() { - return elementType; - } + public ElementType getElementType() { + return elementType; + } - public String getInvalidUseOfRuleMessage() { - return this.INVALID_USE_MESSAGE; - } + public String getInvalidUseOfRuleMessage() { + return this.INVALID_USE_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/ElementType.java b/src/main/java/edu/rpi/legup/model/elements/ElementType.java index ea47ca0eb..1e32e6adf 100644 --- a/src/main/java/edu/rpi/legup/model/elements/ElementType.java +++ b/src/main/java/edu/rpi/legup/model/elements/ElementType.java @@ -1,5 +1,6 @@ package edu.rpi.legup.model.elements; public enum ElementType { - PLACEABLE, NONPLACEABLE + PLACEABLE, + NONPLACEABLE } diff --git a/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java b/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java index 87859991f..94d14c4b5 100644 --- a/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java @@ -1,8 +1,9 @@ package edu.rpi.legup.model.elements; public abstract class NonPlaceableElement extends Element { - public NonPlaceableElement(String elementID, String elementName, String description, String imageName) { - super(elementID, elementName, description, imageName); - this.elementType = ElementType.NONPLACEABLE; - } + public NonPlaceableElement( + String elementID, String elementName, String description, String imageName) { + super(elementID, elementName, description, imageName); + this.elementType = ElementType.NONPLACEABLE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java b/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java index 2d018ddbb..b79fbf407 100644 --- a/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java @@ -1,8 +1,9 @@ package edu.rpi.legup.model.elements; public abstract class PlaceableElement extends Element { - public PlaceableElement(String elementID, String elementName, String description, String imageName) { - super(elementID, elementName, description, imageName); - this.elementType = ElementType.PLACEABLE; - } + public PlaceableElement( + String elementID, String elementName, String description, String imageName) { + super(elementID, elementName, description, imageName); + this.elementType = ElementType.PLACEABLE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/RegisterElement.java b/src/main/java/edu/rpi/legup/model/elements/RegisterElement.java index bda3f3070..368ecc8d1 100644 --- a/src/main/java/edu/rpi/legup/model/elements/RegisterElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/RegisterElement.java @@ -6,6 +6,4 @@ @Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface RegisterElement { - -} +public @interface RegisterElement {} diff --git a/src/main/java/edu/rpi/legup/model/gameboard/Board.java b/src/main/java/edu/rpi/legup/model/gameboard/Board.java index 4bf2ff548..453f698b4 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/Board.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/Board.java @@ -7,213 +7,209 @@ public abstract class Board { - protected List puzzleElements; - protected Set modifiedData; - protected boolean isModifiable; - - /** - * Board Constructor creates an empty board. - */ - public Board() { - this.puzzleElements = new ArrayList<>(); - this.modifiedData = new HashSet<>(); - this.isModifiable = true; - } - - /** - * Board Constructor creates a board with null elements. - * - * @param size number of elements for the board - */ - public Board(int size) { - this(); - for (int i = 0; i < size; i++) { - puzzleElements.add(null); - } - } - - /** - * Gets a specific {@link PuzzleElement} on this board. - * - * @param puzzleElement equivalent puzzleElement - * @return equivalent puzzleElement on this board - */ - public PuzzleElement getPuzzleElement(PuzzleElement puzzleElement) { - int index = puzzleElement.getIndex(); - return index < puzzleElements.size() ? puzzleElements.get(index) : null; - } - - /** - * Sets a specific {@link PuzzleElement} on the board. - * - * @param index index of the puzzleElement - * @param puzzleElement new puzzleElement at the index - */ - public void setPuzzleElement(int index, PuzzleElement puzzleElement) { - if (index < puzzleElements.size()) { - puzzleElements.set(index, puzzleElement); - } - } - - /** - * Gets the number of elements on the board. - * - * @return number of elements on the board - */ - public int getElementCount() { - return puzzleElements.size(); - } - - /** - * Gets the {@link PuzzleElement} on the board. - * - * @return puzzle elements on the board - */ - public List getPuzzleElements() { - return puzzleElements; - } - - /** - * Sets the {@link PuzzleElement} on the board. - * - * @param puzzleElements elements on the board - */ - public void setPuzzleElements(List puzzleElements) { - this.puzzleElements = puzzleElements; - } - - /** - * Gets the modifiable attribute for the board. - * - * @return true if the board is modifiable, false otherwise - */ - public boolean isModifiable() { - return isModifiable; - } - - /** - * Sets the modifiable attribute for the board. - * - * @param isModifiable true if the board is modifiable, false otherwise - */ - public void setModifiable(boolean isModifiable) { - this.isModifiable = isModifiable; - } - - /** - * Gets whether any of {@link PuzzleElement} of this board has been modified by the user. - * - * @return true if the board has been modified, false otherwise - */ - public boolean isModified() { - return !modifiedData.isEmpty(); - } - - /** - * Gets the set of modified {@link PuzzleElement} of the board. - * - * @return set of modified puzzle element of the board - */ - public Set getModifiedData() { - return modifiedData; - } - - /** - * Adds a {@link PuzzleElement} that has been modified to the list. - * - * @param puzzleElement puzzleElement that has been modified - */ - public void addModifiedData(PuzzleElement puzzleElement) { - modifiedData.add(puzzleElement); - puzzleElement.setModified(true); - } - - /** - * Removes a {@link PuzzleElement} that is no longer modified. - * - * @param data puzzleElement that is no longer modified - */ - public void removeModifiedData(PuzzleElement data) { - modifiedData.remove(data); - data.setModified(false); - } - - /** - * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent puzzle element with - * the new data. - * - * @param puzzleElement equivalent puzzle element with the new data. - */ - @SuppressWarnings("unchecked") - public void notifyChange(PuzzleElement puzzleElement) { - puzzleElements.set(puzzleElement.getIndex(), puzzleElement); - } - - /** - * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - public void notifyAddition(PuzzleElement puzzleElement) { - - } - - /** - * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - public void notifyDeletion(PuzzleElement puzzleElement) { - - } - - @SuppressWarnings("unchecked") - public Board mergedBoard(Board lca, List boards) { - if (lca == null || boards.isEmpty()) { - return null; - } - - Board mergedBoard = lca.copy(); - - Board firstBoard = boards.get(0); - for (PuzzleElement lcaData : lca.getPuzzleElements()) { - PuzzleElement mData = firstBoard.getPuzzleElement(lcaData); - - boolean isSame = true; - for (Board board : boards) { - isSame &= mData.equalsData(board.getPuzzleElement(lcaData)); - } - - if (isSame && !lcaData.equalsData(mData)) { - PuzzleElement mergedData = mergedBoard.getPuzzleElement(lcaData); - mergedData.setData(mData.getData()); - mergedBoard.addModifiedData(mergedData); - } - } - - return mergedBoard; - } - - /** - * Determines if this board contains the equivalent puzzle elements as the one specified - * - * @param board board to check equivalence - * @return true if the boards are equivalent, false otherwise - */ - @SuppressWarnings("unchecked") - public boolean equalsBoard(Board board) { - for (PuzzleElement element : puzzleElements) { - if (!element.equalsData(board.getPuzzleElement(element))) { - return false; - } - } - return true; - } - - /** - * Performs a deep copy of this board. - * - * @return a new copy of the board that is independent of this one - */ - public abstract Board copy(); + protected List puzzleElements; + protected Set modifiedData; + protected boolean isModifiable; + + /** Board Constructor creates an empty board. */ + public Board() { + this.puzzleElements = new ArrayList<>(); + this.modifiedData = new HashSet<>(); + this.isModifiable = true; + } + + /** + * Board Constructor creates a board with null elements. + * + * @param size number of elements for the board + */ + public Board(int size) { + this(); + for (int i = 0; i < size; i++) { + puzzleElements.add(null); + } + } + + /** + * Gets a specific {@link PuzzleElement} on this board. + * + * @param puzzleElement equivalent puzzleElement + * @return equivalent puzzleElement on this board + */ + public PuzzleElement getPuzzleElement(PuzzleElement puzzleElement) { + int index = puzzleElement.getIndex(); + return index < puzzleElements.size() ? puzzleElements.get(index) : null; + } + + /** + * Sets a specific {@link PuzzleElement} on the board. + * + * @param index index of the puzzleElement + * @param puzzleElement new puzzleElement at the index + */ + public void setPuzzleElement(int index, PuzzleElement puzzleElement) { + if (index < puzzleElements.size()) { + puzzleElements.set(index, puzzleElement); + } + } + + /** + * Gets the number of elements on the board. + * + * @return number of elements on the board + */ + public int getElementCount() { + return puzzleElements.size(); + } + + /** + * Gets the {@link PuzzleElement} on the board. + * + * @return puzzle elements on the board + */ + public List getPuzzleElements() { + return puzzleElements; + } + + /** + * Sets the {@link PuzzleElement} on the board. + * + * @param puzzleElements elements on the board + */ + public void setPuzzleElements(List puzzleElements) { + this.puzzleElements = puzzleElements; + } + + /** + * Gets the modifiable attribute for the board. + * + * @return true if the board is modifiable, false otherwise + */ + public boolean isModifiable() { + return isModifiable; + } + + /** + * Sets the modifiable attribute for the board. + * + * @param isModifiable true if the board is modifiable, false otherwise + */ + public void setModifiable(boolean isModifiable) { + this.isModifiable = isModifiable; + } + + /** + * Gets whether any of {@link PuzzleElement} of this board has been modified by the user. + * + * @return true if the board has been modified, false otherwise + */ + public boolean isModified() { + return !modifiedData.isEmpty(); + } + + /** + * Gets the set of modified {@link PuzzleElement} of the board. + * + * @return set of modified puzzle element of the board + */ + public Set getModifiedData() { + return modifiedData; + } + + /** + * Adds a {@link PuzzleElement} that has been modified to the list. + * + * @param puzzleElement puzzleElement that has been modified + */ + public void addModifiedData(PuzzleElement puzzleElement) { + modifiedData.add(puzzleElement); + puzzleElement.setModified(true); + } + + /** + * Removes a {@link PuzzleElement} that is no longer modified. + * + * @param data puzzleElement that is no longer modified + */ + public void removeModifiedData(PuzzleElement data) { + modifiedData.remove(data); + data.setModified(false); + } + + /** + * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent + * puzzle element with the new data. + * + * @param puzzleElement equivalent puzzle element with the new data. + */ + @SuppressWarnings("unchecked") + public void notifyChange(PuzzleElement puzzleElement) { + puzzleElements.set(puzzleElement.getIndex(), puzzleElement); + } + + /** + * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element + * with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + public void notifyAddition(PuzzleElement puzzleElement) {} + + /** + * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + public void notifyDeletion(PuzzleElement puzzleElement) {} + + @SuppressWarnings("unchecked") + public Board mergedBoard(Board lca, List boards) { + if (lca == null || boards.isEmpty()) { + return null; + } + + Board mergedBoard = lca.copy(); + + Board firstBoard = boards.get(0); + for (PuzzleElement lcaData : lca.getPuzzleElements()) { + PuzzleElement mData = firstBoard.getPuzzleElement(lcaData); + + boolean isSame = true; + for (Board board : boards) { + isSame &= mData.equalsData(board.getPuzzleElement(lcaData)); + } + + if (isSame && !lcaData.equalsData(mData)) { + PuzzleElement mergedData = mergedBoard.getPuzzleElement(lcaData); + mergedData.setData(mData.getData()); + mergedBoard.addModifiedData(mergedData); + } + } + + return mergedBoard; + } + + /** + * Determines if this board contains the equivalent puzzle elements as the one specified + * + * @param board board to check equivalence + * @return true if the boards are equivalent, false otherwise + */ + @SuppressWarnings("unchecked") + public boolean equalsBoard(Board board) { + for (PuzzleElement element : puzzleElements) { + if (!element.equalsData(board.getPuzzleElement(element))) { + return false; + } + } + return true; + } + + /** + * Performs a deep copy of this board. + * + * @return a new copy of the board that is independent of this one + */ + public abstract Board copy(); } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java b/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java index 799825025..93176b941 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java @@ -1,55 +1,54 @@ package edu.rpi.legup.model.gameboard; import edu.rpi.legup.model.rules.CaseRule; - import java.awt.event.MouseEvent; import java.util.HashSet; import java.util.Set; public class CaseBoard extends Board { - protected Board baseBoard; - protected CaseRule caseRule; - protected Set pickablePuzzleElements; - - public CaseBoard(Board baseBoard, CaseRule caseRule) { - this.baseBoard = baseBoard; - this.caseRule = caseRule; - this.pickablePuzzleElements = new HashSet<>(); - } - - public void addPickableElement(PuzzleElement puzzleElement) { - pickablePuzzleElements.add(puzzleElement); - } - - public void removePickableElement(PuzzleElement puzzleElement) { - pickablePuzzleElements.remove(puzzleElement); - } - - public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { - return pickablePuzzleElements.contains(baseBoard.getPuzzleElement(puzzleElement)); - } - - public Board getBaseBoard() { - return baseBoard; - } - - public void setBaseBoard(Board baseBoard) { - this.baseBoard = baseBoard; - } - - public CaseRule getCaseRule() { - return caseRule; - } - - public void setCaseRule(CaseRule caseRule) { - this.caseRule = caseRule; - } - - public int getCount() { - return pickablePuzzleElements.size(); - } - - public CaseBoard copy() { - return null; - } + protected Board baseBoard; + protected CaseRule caseRule; + protected Set pickablePuzzleElements; + + public CaseBoard(Board baseBoard, CaseRule caseRule) { + this.baseBoard = baseBoard; + this.caseRule = caseRule; + this.pickablePuzzleElements = new HashSet<>(); + } + + public void addPickableElement(PuzzleElement puzzleElement) { + pickablePuzzleElements.add(puzzleElement); + } + + public void removePickableElement(PuzzleElement puzzleElement) { + pickablePuzzleElements.remove(puzzleElement); + } + + public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { + return pickablePuzzleElements.contains(baseBoard.getPuzzleElement(puzzleElement)); + } + + public Board getBaseBoard() { + return baseBoard; + } + + public void setBaseBoard(Board baseBoard) { + this.baseBoard = baseBoard; + } + + public CaseRule getCaseRule() { + return caseRule; + } + + public void setCaseRule(CaseRule caseRule) { + this.caseRule = caseRule; + } + + public int getCount() { + return pickablePuzzleElements.size(); + } + + public CaseBoard copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java b/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java index 99e9bf65a..f0ea22dbe 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java @@ -1,28 +1,30 @@ package edu.rpi.legup.model.gameboard; +import edu.rpi.legup.save.InvalidFileFormatException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import edu.rpi.legup.save.InvalidFileFormatException; public abstract class ElementFactory { - /** - * Creates a {@link PuzzleElement} based on the xml document Node and adds it to the board. - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException thrown if the xml node is invalid for the specific puzzle element - */ - public abstract PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException; + /** + * Creates a {@link PuzzleElement} based on the xml document Node and adds it to the board. + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException thrown if the xml node is invalid for the specific puzzle + * element + */ + public abstract PuzzleElement importCell(Node node, Board board) + throws InvalidFileFormatException; - /** - * Creates a xml document {@link PuzzleElement} from a cell for exporting. - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public abstract Element exportCell(Document document, PuzzleElement puzzleElement); -} \ No newline at end of file + /** + * Creates a xml document {@link PuzzleElement} from a cell for exporting. + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public abstract Element exportCell(Document document, PuzzleElement puzzleElement); +} diff --git a/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java b/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java index d31e8185a..5c66250ce 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java @@ -1,166 +1,167 @@ package edu.rpi.legup.model.gameboard; import edu.rpi.legup.model.elements.Element; -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.TreeTentClue; - import java.awt.*; import java.awt.event.MouseEvent; public class GridBoard extends Board { - protected Dimension dimension; + protected Dimension dimension; - /** - * GridBoard Constructor creates a board for grid using puzzles from a width and height. - * - * @param width width of the board - * @param height height of the board - */ - public GridBoard(int width, int height) { - this.dimension = new Dimension(width, height); + /** + * GridBoard Constructor creates a board for grid using puzzles from a width and height. + * + * @param width width of the board + * @param height height of the board + */ + public GridBoard(int width, int height) { + this.dimension = new Dimension(width, height); - for (int i = 0; i < width * height; i++) { - puzzleElements.add(null); - } + for (int i = 0; i < width * height; i++) { + puzzleElements.add(null); } + } - /** - * GridBoard Constructor creates a board for grid using puzzles from a size. - * - * @param size width and height of the GridBoard - */ - public GridBoard(int size) { - this(size, size); - } + /** + * GridBoard Constructor creates a board for grid using puzzles from a size. + * + * @param size width and height of the GridBoard + */ + public GridBoard(int size) { + this(size, size); + } - /** - * Gets a {@link GridCell} from the board. - * - * @param x x location of the cell - * @param y y location of the cell - * @return grid cell at location (x, y) - */ - public GridCell getCell(int x, int y) { - if (y * dimension.width + x >= puzzleElements.size() || x >= dimension.width || - y >= dimension.height || x < 0 || y < 0) { - System.err.printf("not in bounds, bounds are %dx%d\n", dimension.width, dimension.height); - return null; - } - return (GridCell) puzzleElements.get(y * dimension.width + x); + /** + * Gets a {@link GridCell} from the board. + * + * @param x x location of the cell + * @param y y location of the cell + * @return grid cell at location (x, y) + */ + public GridCell getCell(int x, int y) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + System.err.printf("not in bounds, bounds are %dx%d\n", dimension.width, dimension.height); + return null; } + return (GridCell) puzzleElements.get(y * dimension.width + x); + } - /** - * Sets the {@link GridCell} at the location (x,y). This method does not set the cell if the location specified is - * out of bounds. - * - * @param x x location of the cell - * @param y y location of the cell - * @param cell grid cell to set at location (x,y) - */ - public void setCell(int x, int y, GridCell cell) { - if (y * dimension.width + x >= puzzleElements.size() || x >= dimension.width || - y >= dimension.height || x < 0 || y < 0) { - return; - } - puzzleElements.set(y * dimension.width + x, cell); + /** + * Sets the {@link GridCell} at the location (x,y). This method does not set the cell if the + * location specified is out of bounds. + * + * @param x x location of the cell + * @param y y location of the cell + * @param cell grid cell to set at location (x,y) + */ + public void setCell(int x, int y, GridCell cell) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return; } + puzzleElements.set(y * dimension.width + x, cell); + } - public void setCell(int x, int y, Element e, MouseEvent m) { - if (this instanceof TreeTentBoard && ((y == dimension.height && 0 <= x && x < dimension.width) || (x == dimension.width && 0 <= y && y < dimension.height))) { - TreeTentBoard treeTentBoard = ((TreeTentBoard) this); - TreeTentClue clue = treeTentBoard.getClue(x, y); - if (y == dimension.height) { - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.height) { - clue.setData(clue.getData() + 1); - } - else { - clue.setData(0); - } - } - else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } - else { - clue.setData(dimension.height); - } - } - } - else { //x == dimension.width - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.width) { - clue.setData(clue.getData() + 1); - } - else { - clue.setData(0); - } - } - else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } - else { - clue.setData(dimension.width); - } - } - } + public void setCell(int x, int y, Element e, MouseEvent m) { + if (this instanceof TreeTentBoard + && ((y == dimension.height && 0 <= x && x < dimension.width) + || (x == dimension.width && 0 <= y && y < dimension.height))) { + TreeTentBoard treeTentBoard = ((TreeTentBoard) this); + TreeTentClue clue = treeTentBoard.getClue(x, y); + if (y == dimension.height) { + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.height) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.height); + } } - else { - if (e != null && y * dimension.width + x >= puzzleElements.size() || x >= dimension.width || - y >= dimension.height || x < 0 || y < 0) { - return; - } - else { - if (e != null) { - puzzleElements.get(y * dimension.width + x).setType(e, m); - } - } + } else { // x == dimension.width + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.width) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.width); + } } -// puzzleElements.set(y * dimension.width + x, puzzleElements.get(y * dimension.width + x)); + } + } else { + if (e != null && y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return; + } else { + if (e != null) { + puzzleElements.get(y * dimension.width + x).setType(e, m); + } + } } + // puzzleElements.set(y * dimension.width + x, puzzleElements.get(y * dimension.width + + // x)); + } - /** - * Gets the width of the board. - * - * @return width of the board - */ - public int getWidth() { - return dimension.width; - } + /** + * Gets the width of the board. + * + * @return width of the board + */ + public int getWidth() { + return dimension.width; + } - /** - * Gets the height of the board. - * - * @return height of the board - */ - public int getHeight() { - return dimension.height; - } + /** + * Gets the height of the board. + * + * @return height of the board + */ + public int getHeight() { + return dimension.height; + } - /** - * Gets the dimension of the grid board - * - * @return the dimension of the grid board - */ - public Dimension getDimension() { - return dimension; - } + /** + * Gets the dimension of the grid board + * + * @return the dimension of the grid board + */ + public Dimension getDimension() { + return dimension; + } - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - public GridBoard copy() { - GridBoard newGridBoard = new GridBoard(this.dimension.width, this.dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - newGridBoard.setCell(x, y, getCell(x, y).copy()); - } - } - return newGridBoard; + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + public GridBoard copy() { + GridBoard newGridBoard = new GridBoard(this.dimension.width, this.dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + newGridBoard.setCell(x, y, getCell(x, y).copy()); + } } -} \ No newline at end of file + return newGridBoard; + } +} diff --git a/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java b/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java index 8209c0b6f..9cc3d0768 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java @@ -3,60 +3,59 @@ import java.awt.*; public class GridCell extends PuzzleElement { - protected Point location; - - /** - * GridCell Constructor creates a grid cell at the specified location given as a {@link Point} - * - * @param value data value that represents the grid cell - * @param location location on the board - */ - public GridCell(T value, Point location) { - super(value); - this.location = location; - } - - /** - * GridCell Constructor creates a grid cell at the specified location given as x,y pair - * - * @param value data value that represents the grid cell - * @param x x location - * @param y y location - */ - public GridCell(T value, int x, int y) { - this(value, new Point(x, y)); - } - - /** - * Gets the location of the grid cell on the board - * - * @return location of the grid cell - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the grid cell on the board - * - * @param location location of the grid cell - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Performs a deep copy on the grid cell - * - * @return a new copy of the grid cell that is independent of this one - */ - public GridCell copy() { - GridCell copy = new GridCell<>(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setModified(isModified); - copy.setGiven(isGiven); - return copy; - } + protected Point location; + + /** + * GridCell Constructor creates a grid cell at the specified location given as a {@link Point} + * + * @param value data value that represents the grid cell + * @param location location on the board + */ + public GridCell(T value, Point location) { + super(value); + this.location = location; + } + + /** + * GridCell Constructor creates a grid cell at the specified location given as x,y pair + * + * @param value data value that represents the grid cell + * @param x x location + * @param y y location + */ + public GridCell(T value, int x, int y) { + this(value, new Point(x, y)); + } + + /** + * Gets the location of the grid cell on the board + * + * @return location of the grid cell + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the grid cell on the board + * + * @param location location of the grid cell + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Performs a deep copy on the grid cell + * + * @return a new copy of the grid cell that is independent of this one + */ + public GridCell copy() { + GridCell copy = new GridCell<>(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setModified(isModified); + copy.setGiven(isGiven); + return copy; + } } - diff --git a/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java b/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java index 3d84287e3..215419d54 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java @@ -1,187 +1,184 @@ package edu.rpi.legup.model.gameboard; import edu.rpi.legup.model.elements.Element; - import java.awt.event.MouseEvent; public abstract class PuzzleElement { - protected int index; - protected T data; - protected boolean isModifiable; - protected boolean isModified; - protected boolean isGiven; - protected boolean isValid; - protected int casesDepended; - - /** - * PuzzleElement Constructor creates a new puzzle element. - */ - public PuzzleElement() { - this.index = -1; - this.data = null; - this.isModifiable = true; - this.isModified = false; - this.isGiven = false; - this.isValid = true; - this.casesDepended = 0; - } - - /** - * PuzzleElement Constructor creates a new puzzle element from the specified data. - * - * @param data data used to create the puzzle element - */ - public PuzzleElement(T data) { - this(); - this.data = data; - } - - /** - * Gets the data that represents this puzzle element. - * - * @return data value - */ - public T getData() { - return data; - } - - /** - * Sets the data value that represents this puzzle element. - * - * @param data data value that represents this puzzle element - */ - public void setData(T data) { - this.data = data; - } - - public void setType(Element e, MouseEvent m) { - return; - } - - /** - * Gets whether this puzzle element is modifiable. - * - * @return true if this puzzle element is modifiable, false otherwise - */ - public boolean isModifiable() { - return isModifiable; - } - - /** - * Sets whether this puzzle element is modifiable. - * - * @param isModifiable true if this puzzle element is modifiable, false otherwise - */ - public void setModifiable(boolean isModifiable) { - this.isModifiable = isModifiable; - } - - /** - * Gets whether the puzzle element has been modified. - * - * @return true if the puzzle element has been modified, false otherwise - */ - public boolean isModified() { - return isModified; - } - - /** - * Sets whether the puzzle element has been modified. - * - * @param isModified true if the puzzle element has been modified, false otherwise - */ - public void setModified(boolean isModified) { - this.isModified = isModified; - } - - /** - * Gets the index of this puzzle element - * - * @return index of this puzzle element - */ - public int getIndex() { - return index; - } - - /** - * Sets the index of this puzzle element - * - * @param index index of this puzzle element - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Gets whether this puzzle element is given - * - * @return true if the puzzle element is given, false otherwise - */ - public boolean isGiven() { - return isGiven; - } - - /** - * Sets whether this puzzle element is given - * - * @param given true if the puzzle element is given, false otherwise - */ - public void setGiven(boolean given) { - isGiven = given; - } - - /** - * Get whether this puzzle element data is a valid change according to the rule applied to the transition that - * this puzzle element is contained in. - * - * @return true if the puzzle element logically follows from the rule, otherwise false. - */ - public boolean isValid() { - return this.isValid; - } - - /** - * Sets whether this puzzle element data is a valid change according to the rule applied to the transition that - * this puzzle element is contained in. - * - * @param isValid true if the puzzle element logically follows from the rule, otherwise false. - */ - public void setValid(boolean isValid) { - this.isValid = isValid; - } - - /** - * Get the number of case rules that depend upon the state of this element - * - * @return number of cases - */ - public int getCasesDepended() { - return this.casesDepended; - } - - /** - * Sets the number of case rules that depend upon the state of this element - * - * @param cases number of cases - */ - public void setCasesDepended(int cases) { - this.casesDepended = cases; - } - - /** - * Tests whether two puzzle elements objects have the same puzzle element - * - * @param puzzleElement puzzle element to check for equality - * @return true if the puzzle element are equal, false otherwise - */ - public boolean equalsData(PuzzleElement puzzleElement) { - return data.equals(puzzleElement.data); - } - - /** - * Copies this puzzle element to a new puzzle element object - * - * @return copied puzzle element object - */ - public abstract PuzzleElement copy(); + protected int index; + protected T data; + protected boolean isModifiable; + protected boolean isModified; + protected boolean isGiven; + protected boolean isValid; + protected int casesDepended; + + /** PuzzleElement Constructor creates a new puzzle element. */ + public PuzzleElement() { + this.index = -1; + this.data = null; + this.isModifiable = true; + this.isModified = false; + this.isGiven = false; + this.isValid = true; + this.casesDepended = 0; + } + + /** + * PuzzleElement Constructor creates a new puzzle element from the specified data. + * + * @param data data used to create the puzzle element + */ + public PuzzleElement(T data) { + this(); + this.data = data; + } + + /** + * Gets the data that represents this puzzle element. + * + * @return data value + */ + public T getData() { + return data; + } + + /** + * Sets the data value that represents this puzzle element. + * + * @param data data value that represents this puzzle element + */ + public void setData(T data) { + this.data = data; + } + + public void setType(Element e, MouseEvent m) { + return; + } + + /** + * Gets whether this puzzle element is modifiable. + * + * @return true if this puzzle element is modifiable, false otherwise + */ + public boolean isModifiable() { + return isModifiable; + } + + /** + * Sets whether this puzzle element is modifiable. + * + * @param isModifiable true if this puzzle element is modifiable, false otherwise + */ + public void setModifiable(boolean isModifiable) { + this.isModifiable = isModifiable; + } + + /** + * Gets whether the puzzle element has been modified. + * + * @return true if the puzzle element has been modified, false otherwise + */ + public boolean isModified() { + return isModified; + } + + /** + * Sets whether the puzzle element has been modified. + * + * @param isModified true if the puzzle element has been modified, false otherwise + */ + public void setModified(boolean isModified) { + this.isModified = isModified; + } + + /** + * Gets the index of this puzzle element + * + * @return index of this puzzle element + */ + public int getIndex() { + return index; + } + + /** + * Sets the index of this puzzle element + * + * @param index index of this puzzle element + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Gets whether this puzzle element is given + * + * @return true if the puzzle element is given, false otherwise + */ + public boolean isGiven() { + return isGiven; + } + + /** + * Sets whether this puzzle element is given + * + * @param given true if the puzzle element is given, false otherwise + */ + public void setGiven(boolean given) { + isGiven = given; + } + + /** + * Get whether this puzzle element data is a valid change according to the rule applied to the + * transition that this puzzle element is contained in. + * + * @return true if the puzzle element logically follows from the rule, otherwise false. + */ + public boolean isValid() { + return this.isValid; + } + + /** + * Sets whether this puzzle element data is a valid change according to the rule applied to the + * transition that this puzzle element is contained in. + * + * @param isValid true if the puzzle element logically follows from the rule, otherwise false. + */ + public void setValid(boolean isValid) { + this.isValid = isValid; + } + + /** + * Get the number of case rules that depend upon the state of this element + * + * @return number of cases + */ + public int getCasesDepended() { + return this.casesDepended; + } + + /** + * Sets the number of case rules that depend upon the state of this element + * + * @param cases number of cases + */ + public void setCasesDepended(int cases) { + this.casesDepended = cases; + } + + /** + * Tests whether two puzzle elements objects have the same puzzle element + * + * @param puzzleElement puzzle element to check for equality + * @return true if the puzzle element are equal, false otherwise + */ + public boolean equalsData(PuzzleElement puzzleElement) { + return data.equals(puzzleElement.data); + } + + /** + * Copies this puzzle element to a new puzzle element object + * + * @return copied puzzle element object + */ + public abstract PuzzleElement copy(); } diff --git a/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java b/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java index 461128562..b5c712ead 100644 --- a/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java +++ b/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java @@ -5,24 +5,24 @@ import edu.rpi.legup.model.tree.TreeElement; public interface IBoardListener { - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - void onTreeElementChanged(TreeElement treeElement); + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + void onTreeElementChanged(TreeElement treeElement); - /** - * Called when the a case board has been added to the view. - * - * @param caseBoard case board to be added - */ - void onCaseBoardAdded(CaseBoard caseBoard); + /** + * Called when the a case board has been added to the view. + * + * @param caseBoard case board to be added + */ + void onCaseBoardAdded(CaseBoard caseBoard); - /** - * Called when a {@link PuzzleElement}'s data on the board has changed. - * - * @param puzzleElement puzzleElement that has changed - */ - void onBoardDataChanged(PuzzleElement puzzleElement); + /** + * Called when a {@link PuzzleElement}'s data on the board has changed. + * + * @param puzzleElement puzzleElement that has changed + */ + void onBoardDataChanged(PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java b/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java index c7bf13141..73bd2b6f8 100644 --- a/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java +++ b/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface IBoardSubject { - /** - * Adds a board listener. - * - * @param listener listener to add - */ - void addBoardListener(IBoardListener listener); + /** + * Adds a board listener. + * + * @param listener listener to add + */ + void addBoardListener(IBoardListener listener); - /** - * Removes a board listener. - * - * @param listener listener to remove - */ - void removeBoardListener(IBoardListener listener); + /** + * Removes a board listener. + * + * @param listener listener to remove + */ + void removeBoardListener(IBoardListener listener); - /** - * Notifies all of the listeners using the specified algorithm. - * - * @param algorithm algorithm used to notify the listeners - */ - void notifyBoardListeners(Consumer algorithm); + /** + * Notifies all of the listeners using the specified algorithm. + * + * @param algorithm algorithm used to notify the listeners + */ + void notifyBoardListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java b/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java index d8fa24166..915b0adc9 100644 --- a/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java +++ b/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java @@ -4,29 +4,27 @@ import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; public interface ITreeListener { - /** - * Called when a {@link TreeElement} is added to the tree. - * - * @param treeElement tree element that was added to the tree - */ - void onTreeElementAdded(TreeElement treeElement); + /** + * Called when a {@link TreeElement} is added to the tree. + * + * @param treeElement tree element that was added to the tree + */ + void onTreeElementAdded(TreeElement treeElement); - /** - * Called when a {@link TreeElement} is removed from the tree. - * - * @param element TreeElement that was removed to the tree - */ - void onTreeElementRemoved(TreeElement element); + /** + * Called when a {@link TreeElement} is removed from the tree. + * + * @param element TreeElement that was removed to the tree + */ + void onTreeElementRemoved(TreeElement element); - /** - * Called when the {@link TreeViewSelection} was changed. - * - * @param selection tree view selection that was changed - */ - void onTreeSelectionChanged(TreeViewSelection selection); + /** + * Called when the {@link TreeViewSelection} was changed. + * + * @param selection tree view selection that was changed + */ + void onTreeSelectionChanged(TreeViewSelection selection); - /** - * Called when the model has finished updating the tree. - */ - void onUpdateTree(); + /** Called when the model has finished updating the tree. */ + void onUpdateTree(); } diff --git a/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java b/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java index 66d5d9a5e..7cf1bb1ef 100644 --- a/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java +++ b/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface ITreeSubject { - /** - * Adds a board listener. - * - * @param listener listener to add - */ - void addTreeListener(ITreeListener listener); + /** + * Adds a board listener. + * + * @param listener listener to add + */ + void addTreeListener(ITreeListener listener); - /** - * Removes a tree listener. - * - * @param listener listener to remove - */ - void removeTreeListener(ITreeListener listener); + /** + * Removes a tree listener. + * + * @param listener listener to remove + */ + void removeTreeListener(ITreeListener listener); - /** - * Notifies all of the listeners using the specified algorithm. - * - * @param algorithm algorithm used to notify the listeners - */ - void notifyTreeListeners(Consumer algorithm); + /** + * Notifies all of the listeners using the specified algorithm. + * + * @param algorithm algorithm used to notify the listeners + */ + void notifyTreeListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/model/rules/CaseRule.java b/src/main/java/edu/rpi/legup/model/rules/CaseRule.java index a01db2b6d..4fcd69065 100644 --- a/src/main/java/edu/rpi/legup/model/rules/CaseRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/CaseRule.java @@ -1,145 +1,147 @@ package edu.rpi.legup.model.rules; +import static edu.rpi.legup.model.rules.RuleType.CASE; + import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.CaseBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.ArrayList; import java.util.List; import java.util.Set; -import static edu.rpi.legup.model.rules.RuleType.CASE; - public abstract class CaseRule extends Rule { - private final String INVALID_USE_MESSAGE; - - /** - * CaseRule Constructor creates a new case rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public CaseRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = CASE; - this.INVALID_USE_MESSAGE = "Invalid use of the case rule " + this.ruleName; + private final String INVALID_USE_MESSAGE; + + /** + * CaseRule Constructor creates a new case rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public CaseRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = CASE; + this.INVALID_USE_MESSAGE = "Invalid use of the case rule " + this.ruleName; + } + + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + public abstract CaseBoard getCaseBoard(Board board); + + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + public abstract List getCases(Board board, PuzzleElement puzzleElement); + + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + List parentNodes = transition.getParents(); + if (parentNodes.size() != 1) { + return "Must not have multiple parent nodes"; } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - public abstract CaseBoard getCaseBoard(Board board); - - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - public abstract List getCases(Board board, PuzzleElement puzzleElement); - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - List parentNodes = transition.getParents(); - if (parentNodes.size() != 1) { - return "Must not have multiple parent nodes"; - } - - for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { - if (childTrans.getRule() == null || !childTrans.getRule().getClass().equals(this.getClass())) { - return "All children nodes must be justified with the same case rule."; - } - } - - String check = checkRuleRaw(transition); - - // Mark transition and new data as valid or not - boolean isCorrect = (check == null); - for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { - childTrans.setCorrect(isCorrect); - for (PuzzleElement element : childTrans.getBoard().getModifiedData()) { - element.setValid(isCorrect); - } - } - - return check; + for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { + if (childTrans.getRule() == null + || !childTrans.getRule().getClass().equals(this.getClass())) { + return "All children nodes must be justified with the same case rule."; + } } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public abstract String checkRuleRaw(TreeTransition transition); - - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return this.INVALID_USE_MESSAGE; + String check = checkRuleRaw(transition); + + // Mark transition and new data as valid or not + boolean isCorrect = (check == null); + for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { + childTrans.setCorrect(isCorrect); + for (PuzzleElement element : childTrans.getBoard().getModifiedData()) { + element.setValid(isCorrect); + } } - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be valid - * Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends upon. - * Defaults to any element modified by any case - */ - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - List cases = getCases(board,puzzleElement); - for (Board caseBoard : cases) { - Set data = caseBoard.getModifiedData(); - for (PuzzleElement element : data) { - if(!elements.contains(board.getPuzzleElement(element))){ - elements.add(board.getPuzzleElement(element)); - } - } + return check; + } + + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public abstract String checkRuleRaw(TreeTransition transition); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return this.INVALID_USE_MESSAGE; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + List cases = getCases(board, puzzleElement); + for (Board caseBoard : cases) { + Set data = caseBoard.getModifiedData(); + for (PuzzleElement element : data) { + if (!elements.contains(board.getPuzzleElement(element))) { + elements.add(board.getPuzzleElement(element)); } - - return elements; + } } -} - + return elements; + } +} diff --git a/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java b/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java index 0d3a79a98..8ae3f02c6 100644 --- a/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java @@ -1,108 +1,109 @@ package edu.rpi.legup.model.rules; +import static edu.rpi.legup.model.rules.RuleType.CONTRADICTION; + import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.tree.TreeTransition; -import static edu.rpi.legup.model.rules.RuleType.CONTRADICTION; - public abstract class ContradictionRule extends Rule { - private final String NO_CONTRADICTION_MESSAGE = "No instance of the contradiction " + this.ruleName + " here"; + private final String NO_CONTRADICTION_MESSAGE = + "No instance of the contradiction " + this.ruleName + " here"; - /** - * ContradictionRule Constructor creates a new contradiction rule - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public ContradictionRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - ruleType = CONTRADICTION; - } + /** + * ContradictionRule Constructor creates a new contradiction rule + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public ContradictionRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + ruleType = CONTRADICTION; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - return checkContradiction(transition.getBoard()); - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + return checkContradiction(transition.getBoard()); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkContradictionAt(transition.getBoard(), puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkContradictionAt(transition.getBoard(), puzzleElement); + } - /** - * Checks whether the transition logically follows from the parent node using this rule. - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return checkContradiction(transition.getBoard()); - } + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return checkContradiction(transition.getBoard()); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkContradictionAt(transition.getBoard(), puzzleElement); - } - - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - public String checkContradiction(Board board) { - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - String checkStr = checkContradictionAt(board, puzzleElement); - if (checkStr == null) { - return checkStr; - } - } - return this.NO_CONTRADICTION_MESSAGE; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkContradictionAt(transition.getBoard(), puzzleElement); + } - public String getNoContradictionMessage() { - return this.NO_CONTRADICTION_MESSAGE; + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + public String checkContradiction(Board board) { + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + String checkStr = checkContradictionAt(board, puzzleElement); + if (checkStr == null) { + return checkStr; + } } + return this.NO_CONTRADICTION_MESSAGE; + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - public abstract String checkContradictionAt(Board board, PuzzleElement puzzleElement); + public String getNoContradictionMessage() { + return this.NO_CONTRADICTION_MESSAGE; + } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + public abstract String checkContradictionAt(Board board, PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java index be6a0f160..1ce44318a 100644 --- a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java @@ -1,106 +1,103 @@ package edu.rpi.legup.model.rules; +import static edu.rpi.legup.model.rules.RuleType.BASIC; + import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import static edu.rpi.legup.model.rules.RuleType.BASIC; - public abstract class DirectRule extends Rule { - /** - * DirectRule Constructor creates a new basic rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public DirectRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = BASIC; - } + /** + * DirectRule Constructor creates a new basic rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public DirectRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = BASIC; + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRule(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - // System.out.println(finalBoard.getModifiedData().size()); - if (transition.getParents().size() != 1 || - transition.getParents().get(0).getChildren().size() != 1) { - return "State must have only 1 parent and 1 child"; - } - else if (finalBoard.getModifiedData().isEmpty()) { - // null transition - return null; - } - else { - return checkRuleRaw(transition); - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRule(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + // System.out.println(finalBoard.getModifiedData().size()); + if (transition.getParents().size() != 1 + || transition.getParents().get(0).getChildren().size() != 1) { + return "State must have only 1 parent and 1 child"; + } else if (finalBoard.getModifiedData().isEmpty()) { + // null transition + return null; + } else { + return checkRuleRaw(transition); } + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRuleRaw(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - String checkStr = null; + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRuleRaw(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + String checkStr = null; - // Go directly to specific direct rule's judgement if no cell's are edited - if (finalBoard.getModifiedData().size() == 0) { - checkStr = checkRuleRawAt(transition, null); - } - for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { - String tempStr = checkRuleAt(transition, puzzleElement); - if (tempStr != null) { - checkStr = tempStr; - } - } - return checkStr; + // Go directly to specific direct rule's judgement if no cell's are edited + if (finalBoard.getModifiedData().size() == 0) { + checkStr = checkRuleRawAt(transition, null); + } + for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { + String tempStr = checkRuleAt(transition, puzzleElement); + if (tempStr != null) { + checkStr = tempStr; + } } + return checkStr; + } - /** - * Checks whether the child node logically follows from the parent node at the specific {@link PuzzleElement} using - * this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - Board finalBoard = transition.getBoard(); - puzzleElement = finalBoard.getPuzzleElement(puzzleElement); - String checkStr; - if (!puzzleElement.isModified()) { - checkStr = "PuzzleElement must be modified"; - } - else { - if (transition.getParents().size() != 1 || - transition.getParents().get(0).getChildren().size() != 1) { - checkStr = "State must have only 1 parent and 1 child"; - } - else { - checkStr = checkRuleRawAt(transition, puzzleElement); - } - } - puzzleElement.setValid(checkStr == null); - return checkStr; + /** + * Checks whether the child node logically follows from the parent node at the specific {@link + * PuzzleElement} using this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + Board finalBoard = transition.getBoard(); + puzzleElement = finalBoard.getPuzzleElement(puzzleElement); + String checkStr; + if (!puzzleElement.isModified()) { + checkStr = "PuzzleElement must be modified"; + } else { + if (transition.getParents().size() != 1 + || transition.getParents().get(0).getChildren().size() != 1) { + checkStr = "State must have only 1 parent and 1 child"; + } else { + checkStr = checkRuleRawAt(transition, puzzleElement); + } } + puzzleElement.setValid(checkStr == null); + return checkStr; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - public abstract Board getDefaultBoard(TreeNode node); + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + public abstract Board getDefaultBoard(TreeNode node); } diff --git a/src/main/java/edu/rpi/legup/model/rules/MergeRule.java b/src/main/java/edu/rpi/legup/model/rules/MergeRule.java index 9ae18648e..25c543abb 100644 --- a/src/main/java/edu/rpi/legup/model/rules/MergeRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/MergeRule.java @@ -1,102 +1,98 @@ package edu.rpi.legup.model.rules; +import static edu.rpi.legup.model.rules.RuleType.MERGE; + import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.tree.Tree; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import static edu.rpi.legup.model.rules.RuleType.MERGE; - public class MergeRule extends Rule { - /** - * MergeRule Constructor merges to board states together - */ - public MergeRule() { - super("MERGE", "Merge Rule", - "Merge any number of nodes into one", - "edu/rpi/legup/images/Legup/MergeRule.png"); - this.ruleType = MERGE; - } + /** MergeRule Constructor merges to board states together */ + public MergeRule() { + super( + "MERGE", + "Merge Rule", + "Merge any number of nodes into one", + "edu/rpi/legup/images/Legup/MergeRule.png"); + this.ruleType = MERGE; + } - /** - * Checks whether the transition logically follows from the parent node using this rule. - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @SuppressWarnings("unchecked") - @Override - public String checkRuleRaw(TreeTransition transition) { - Board board = transition.getBoard(); - List mergingNodes = new ArrayList<>(); - List mergingBoards = new ArrayList<>(); - for (TreeNode treeNode : transition.getParents()) { - mergingNodes.add(treeNode); - mergingBoards.add(treeNode.getBoard()); - } - - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - return "Merge was not correctly created."; - } - Board lcaBoard = lca.getBoard(); + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @SuppressWarnings("unchecked") + @Override + public String checkRuleRaw(TreeTransition transition) { + Board board = transition.getBoard(); + List mergingNodes = new ArrayList<>(); + List mergingBoards = new ArrayList<>(); + for (TreeNode treeNode : transition.getParents()) { + mergingNodes.add(treeNode); + mergingBoards.add(treeNode.getBoard()); + } - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + return "Merge was not correctly created."; + } + Board lcaBoard = lca.getBoard(); - for (PuzzleElement m : mergedBoard.getPuzzleElements()) { - if (!m.equalsData(board.getPuzzleElement(m))) { - return "Merge was not correctly created."; - } - } + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); - return null; + for (PuzzleElement m : mergedBoard.getPuzzleElements()) { + if (!m.equalsData(board.getPuzzleElement(m))) { + return "Merge was not correctly created."; + } } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRule(transition); - } + return null; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - return checkRuleRaw(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRule(transition); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRawAt(transition, puzzleElement); - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + return checkRuleRaw(transition); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRawAt(transition, puzzleElement); + } } diff --git a/src/main/java/edu/rpi/legup/model/rules/RegisterRule.java b/src/main/java/edu/rpi/legup/model/rules/RegisterRule.java index 40def6edd..c1fe0b88c 100644 --- a/src/main/java/edu/rpi/legup/model/rules/RegisterRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/RegisterRule.java @@ -5,6 +5,4 @@ @Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface RegisterRule { - -} +public @interface RegisterRule {} diff --git a/src/main/java/edu/rpi/legup/model/rules/Rule.java b/src/main/java/edu/rpi/legup/model/rules/Rule.java index 50f2cf962..d15b79e5e 100644 --- a/src/main/java/edu/rpi/legup/model/rules/Rule.java +++ b/src/main/java/edu/rpi/legup/model/rules/Rule.java @@ -1,169 +1,163 @@ package edu.rpi.legup.model.rules; +import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.tree.TreeTransition; - -import edu.rpi.legup.app.LegupPreferences; - -import javax.swing.ImageIcon; -import java.awt.image.BufferedImage; -import java.awt.Image; import java.awt.Graphics2D; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import java.awt.Image; +import java.awt.image.BufferedImage; +import javax.swing.ImageIcon; @RegisterRule public abstract class Rule { - protected String ruleID; - protected String ruleName; - protected String description; - protected String imageName; - protected ImageIcon image; - protected RuleType ruleType; - - private final String INVALID_USE_MESSAGE; - - /** - * Rule Constructor creates a new rule - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public Rule(String ruleID, String ruleName, String description, String imageName) { - this.ruleID = ruleID; - this.ruleName = ruleName; - this.description = description; - this.imageName = imageName; - this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.ruleName; - loadImage(); - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public abstract String checkRule(TreeTransition transition); - - /** - * Checks whether the transition logically follows from the parent node using this rule. - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - protected abstract String checkRuleRaw(TreeTransition transition); - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public abstract String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - protected abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Loads the image file - */ - public void loadImage() { - if (imageName != null) { - String name = imageName; - LegupPreferences prefs = LegupPreferences.getInstance(); - if (name.contains("shorttruthtable") && prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - name = name.replace("ruleimages", "ruleimages_cb"); - } - this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(name)); - //Resize images to be 100px wide - Image image = this.image.getImage(); - if (this.image.getIconWidth() < 120) return; - int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); - if (height == 0) { - System.out.println("height is 0 error"); - System.out.println("height: " + this.image.getIconHeight()); - System.out.println("width: " + this.image.getIconWidth()); - return; - } - BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = bimage.createGraphics(); - g.drawImage(image, 0, 0, 100, height, null); - this.image = new ImageIcon(bimage); - } - } - - /** - * Gets the name of the rule - * - * @return name of the rule - */ - public String getRuleName() { - return ruleName; - } - - /** - * Gets the name of the rule - * - * @return name of the rule - */ - public String getRuleID() { - return ruleID; - } - - /** - * Sets the rule name - * - * @param ruleName new name of the rule - */ - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - - /** - * Gets the description of the rule - * - * @return the description of the rule - */ - public String getDescription() { - return description; - } - - /** - * Gets the image icon of the rule - * - * @return image icon of the rule - */ - public ImageIcon getImageIcon() { - return image; - } - - /** - * Gets the rule type - * - * @return rule type - */ - public RuleType getRuleType() { - return ruleType; - } - - public String getInvalidUseOfRuleMessage() { - return this.INVALID_USE_MESSAGE; + protected String ruleID; + protected String ruleName; + protected String description; + protected String imageName; + protected ImageIcon image; + protected RuleType ruleType; + + private final String INVALID_USE_MESSAGE; + + /** + * Rule Constructor creates a new rule + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public Rule(String ruleID, String ruleName, String description, String imageName) { + this.ruleID = ruleID; + this.ruleName = ruleName; + this.description = description; + this.imageName = imageName; + this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.ruleName; + loadImage(); + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public abstract String checkRule(TreeTransition transition); + + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + protected abstract String checkRuleRaw(TreeTransition transition); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public abstract String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + protected abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** Loads the image file */ + public void loadImage() { + if (imageName != null) { + String name = imageName; + LegupPreferences prefs = LegupPreferences.getInstance(); + if (name.contains("shorttruthtable") + && prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + name = name.replace("ruleimages", "ruleimages_cb"); + } + this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(name)); + // Resize images to be 100px wide + Image image = this.image.getImage(); + if (this.image.getIconWidth() < 120) return; + int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); + if (height == 0) { + System.out.println("height is 0 error"); + System.out.println("height: " + this.image.getIconHeight()); + System.out.println("width: " + this.image.getIconWidth()); + return; + } + BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = bimage.createGraphics(); + g.drawImage(image, 0, 0, 100, height, null); + this.image = new ImageIcon(bimage); } -} \ No newline at end of file + } + + /** + * Gets the name of the rule + * + * @return name of the rule + */ + public String getRuleName() { + return ruleName; + } + + /** + * Gets the name of the rule + * + * @return name of the rule + */ + public String getRuleID() { + return ruleID; + } + + /** + * Sets the rule name + * + * @param ruleName new name of the rule + */ + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + + /** + * Gets the description of the rule + * + * @return the description of the rule + */ + public String getDescription() { + return description; + } + + /** + * Gets the image icon of the rule + * + * @return image icon of the rule + */ + public ImageIcon getImageIcon() { + return image; + } + + /** + * Gets the rule type + * + * @return rule type + */ + public RuleType getRuleType() { + return ruleType; + } + + public String getInvalidUseOfRuleMessage() { + return this.INVALID_USE_MESSAGE; + } +} diff --git a/src/main/java/edu/rpi/legup/model/rules/RuleType.java b/src/main/java/edu/rpi/legup/model/rules/RuleType.java index b7ce315cf..48589e836 100644 --- a/src/main/java/edu/rpi/legup/model/rules/RuleType.java +++ b/src/main/java/edu/rpi/legup/model/rules/RuleType.java @@ -1,5 +1,8 @@ package edu.rpi.legup.model.rules; public enum RuleType { - BASIC, CASE, CONTRADICTION, MERGE + BASIC, + CASE, + CONTRADICTION, + MERGE } diff --git a/src/main/java/edu/rpi/legup/model/tree/Tree.java b/src/main/java/edu/rpi/legup/model/tree/Tree.java index 79c0bcece..2e5604a2c 100644 --- a/src/main/java/edu/rpi/legup/model/tree/Tree.java +++ b/src/main/java/edu/rpi/legup/model/tree/Tree.java @@ -1,200 +1,191 @@ package edu.rpi.legup.model.tree; import edu.rpi.legup.model.gameboard.Board; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Tree { - private TreeNode rootNode; - - /** - * Tree Constructor creates the tree structure from the initial {@link Board} - * - * @param initBoard initial board - */ - public Tree(Board initBoard) { - this.rootNode = new TreeNode(initBoard); - this.rootNode.setRoot(true); - } - - /** - * Tree Constructor creates the tree structure with null root node - */ - public Tree() { - this.rootNode = null; + private TreeNode rootNode; + + /** + * Tree Constructor creates the tree structure from the initial {@link Board} + * + * @param initBoard initial board + */ + public Tree(Board initBoard) { + this.rootNode = new TreeNode(initBoard); + this.rootNode.setRoot(true); + } + + /** Tree Constructor creates the tree structure with null root node */ + public Tree() { + this.rootNode = null; + } + + public TreeTransition addNewTransition(TreeNode treeNode) { + TreeTransition transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + treeNode.addChild(transition); + treeNode.getChildren().forEach(TreeTransition::reverify); + return transition; + } + + public TreeNode addNode(TreeTransition transition) { + TreeNode treeNode = new TreeNode(transition.getBoard().copy()); + transition.setChildNode(treeNode); + treeNode.setParent(transition); + return treeNode; + } + + public TreeElement addTreeElement(TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) element; + return addTreeElement(treeNode, new TreeTransition(treeNode, treeNode.getBoard().copy())); + } else { + TreeTransition transition = (TreeTransition) element; + Board copyBoard = transition.board.copy(); + copyBoard.setModifiable(false); + return addTreeElement(transition, new TreeNode(copyBoard)); } - - public TreeTransition addNewTransition(TreeNode treeNode) { - TreeTransition transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - treeNode.addChild(transition); - treeNode.getChildren().forEach(TreeTransition::reverify); - return transition; + } + + public TreeElement addTreeElement(TreeNode treeNode, TreeTransition transition) { + treeNode.addChild(transition); + treeNode.getChildren().forEach(TreeTransition::reverify); + return transition; + } + + public TreeElement addTreeElement(TreeTransition transition, TreeNode treeNode) { + transition.setChildNode(treeNode); + treeNode.setParent(transition); + return treeNode; + } + + public void removeTreeElement(TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getParent().setChildNode(null); + } else { + TreeTransition transition = (TreeTransition) element; + transition.getParents().forEach(n -> n.removeChild(transition)); + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); } - - public TreeNode addNode(TreeTransition transition) { - TreeNode treeNode = new TreeNode(transition.getBoard().copy()); - transition.setChildNode(treeNode); - treeNode.setParent(transition); - return treeNode; + } + + /** + * Determines if the tree is valid by checking whether this tree puzzleElement and all descendants + * of this tree puzzleElement is justified and justified correctly + * + * @return true if tree is valid, false otherwise + */ + public boolean isValid() { + return rootNode.isValidBranch(); + } + + /** + * Gets a Set of TreeNodes that are leaf nodes + * + * @return Set of TreeNodes that are leaf nodes + */ + public Set getLeafTreeElements() { + Set leafs = new HashSet<>(); + getLeafTreeElements(leafs, rootNode); + return leafs; + } + + /** + * Gets a Set of TreeNodes that are leaf nodes from the sub tree rooted at the specified node + * + * @param node node that is input + * @return Set of TreeNodes that are leaf nodes from the sub tree + */ + public Set getLeafTreeElements(TreeNode node) { + Set leafs = new HashSet<>(); + getLeafTreeElements(leafs, node); + return leafs; + } + + /** + * Recursively gets a Set of TreeNodes that are leaf nodes + * + * @param leafs Set of TreeNodes that are leaf nodes + * @param element current TreeNode being evaluated + */ + private void getLeafTreeElements(Set leafs, TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + List childTrans = node.getChildren(); + if (childTrans.isEmpty()) { + leafs.add(node); + } else { + childTrans.forEach(t -> getLeafTreeElements(leafs, t)); + } + } else { + TreeTransition transition = (TreeTransition) element; + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + leafs.add(transition); + } else { + getLeafTreeElements(leafs, childNode); + } } - - public TreeElement addTreeElement(TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) element; - return addTreeElement(treeNode, new TreeTransition(treeNode, treeNode.getBoard().copy())); + } + + /** + * Gets the lowest common ancestor (LCA) among the list of {@link TreeNode} passed into the + * function. This lowest common ancestor is the most immediate ancestor node such that the list of + * tree nodes specified are descendants of the node. This will return null if no such ancestor + * exists + * + * @param nodes list of tree nodes to find the LCA + * @return the first ancestor node that all tree nodes have in common, otherwise null if none + * exists + */ + public static TreeNode getLowestCommonAncestor(List nodes) { + if (nodes.isEmpty()) { + return null; + } else { + if (nodes.size() == 1) { + return nodes.get(0); + } else { + List> ancestors = new ArrayList<>(); + for (TreeNode node : nodes) { + ancestors.add(node.getAncestors()); } - else { - TreeTransition transition = (TreeTransition) element; - Board copyBoard = transition.board.copy(); - copyBoard.setModifiable(false); - return addTreeElement(transition, new TreeNode(copyBoard)); - } - } - public TreeElement addTreeElement(TreeNode treeNode, TreeTransition transition) { - treeNode.addChild(transition); - treeNode.getChildren().forEach(TreeTransition::reverify); - return transition; - } + List first = ancestors.get(0); - public TreeElement addTreeElement(TreeTransition transition, TreeNode treeNode) { - transition.setChildNode(treeNode); - treeNode.setParent(transition); - return treeNode; - } + for (TreeNode node : first) { + boolean isCommon = true; + for (List nList : ancestors) { + isCommon &= nList.contains(node); + } - public void removeTreeElement(TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getParent().setChildNode(null); + if (isCommon) { + return node; + } } - else { - TreeTransition transition = (TreeTransition) element; - transition.getParents().forEach(n -> n.removeChild(transition)); - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - } - } - - /** - * Determines if the tree is valid by checking whether this tree puzzleElement and - * all descendants of this tree puzzleElement is justified and justified correctly - * - * @return true if tree is valid, false otherwise - */ - public boolean isValid() { - return rootNode.isValidBranch(); - } - - /** - * Gets a Set of TreeNodes that are leaf nodes - * - * @return Set of TreeNodes that are leaf nodes - */ - public Set getLeafTreeElements() { - Set leafs = new HashSet<>(); - getLeafTreeElements(leafs, rootNode); - return leafs; - } - - /** - * Gets a Set of TreeNodes that are leaf nodes from the sub tree rooted at the specified node - * - * @param node node that is input - * @return Set of TreeNodes that are leaf nodes from the sub tree - */ - public Set getLeafTreeElements(TreeNode node) { - Set leafs = new HashSet<>(); - getLeafTreeElements(leafs, node); - return leafs; - } - - /** - * Recursively gets a Set of TreeNodes that are leaf nodes - * - * @param leafs Set of TreeNodes that are leaf nodes - * @param element current TreeNode being evaluated - */ - private void getLeafTreeElements(Set leafs, TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - List childTrans = node.getChildren(); - if (childTrans.isEmpty()) { - leafs.add(node); - } - else { - childTrans.forEach(t -> getLeafTreeElements(leafs, t)); - } - } - else { - TreeTransition transition = (TreeTransition) element; - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - leafs.add(transition); - } - else { - getLeafTreeElements(leafs, childNode); - } - } - } - - /** - * Gets the lowest common ancestor (LCA) among the list of {@link TreeNode} passed into - * the function. This lowest common ancestor is the most immediate ancestor - * node such that the list of tree nodes specified are descendants of the node. - * This will return null if no such ancestor exists - * - * @param nodes list of tree nodes to find the LCA - * @return the first ancestor node that all tree nodes have in common, otherwise null if none exists - */ - public static TreeNode getLowestCommonAncestor(List nodes) { - if (nodes.isEmpty()) { - return null; - } - else { - if (nodes.size() == 1) { - return nodes.get(0); - } - else { - List> ancestors = new ArrayList<>(); - for (TreeNode node : nodes) { - ancestors.add(node.getAncestors()); - } - - List first = ancestors.get(0); - - for (TreeNode node : first) { - boolean isCommon = true; - for (List nList : ancestors) { - isCommon &= nList.contains(node); - } - - if (isCommon) { - return node; - } - } - } - } - return null; - } - - /** - * Gets the root node of this tree - * - * @return the root node of the tree - */ - public TreeNode getRootNode() { - return rootNode; - } - - /** - * Sets the root node of this tree - * - * @param rootNode the root node of the tree - */ - public void setRootNode(TreeNode rootNode) { - this.rootNode = rootNode; + } } + return null; + } + + /** + * Gets the root node of this tree + * + * @return the root node of the tree + */ + public TreeNode getRootNode() { + return rootNode; + } + + /** + * Sets the root node of this tree + * + * @param rootNode the root node of the tree + */ + public void setRootNode(TreeNode rootNode) { + this.rootNode = rootNode; + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeElement.java b/src/main/java/edu/rpi/legup/model/tree/TreeElement.java index 17168ac98..d7f21c3b7 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeElement.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeElement.java @@ -3,60 +3,61 @@ import edu.rpi.legup.model.gameboard.Board; public abstract class TreeElement { - protected TreeElementType type; - protected Board board; - - /** - * TreeElement Constructor creates a tree puzzleElement that is part of a tree - * - * @param type type of tree puzzleElement (NODE or TRANSITION) - */ - public TreeElement(TreeElementType type) { - this.type = type; - } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node - * must lead to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - public abstract boolean isContradictoryBranch(); - - /** - * Recursively determines if the sub-tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified - * and justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is valid, - * false otherwise - */ - public abstract boolean isValidBranch(); - - /** - * Gets the type of tree puzzleElement - * - * @return NODE if this tree puzzleElement is a tree node, TRANSITION, if this tree puzzleElement is a transition - */ - public TreeElementType getType() { - return type; - } - - /** - * Gets the board at this TreeElement - * - * @return the board at this TreeElement - */ - public Board getBoard() { - return board; - } - - /** - * Sets the board at this TreeElement - * - * @param board the board at this TreeElement - */ - public void setBoard(Board board) { - this.board = board; - } + protected TreeElementType type; + protected Board board; + + /** + * TreeElement Constructor creates a tree puzzleElement that is part of a tree + * + * @param type type of tree puzzleElement (NODE or TRANSITION) + */ + public TreeElement(TreeElementType type) { + this.type = type; + } + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must lead + * to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + public abstract boolean isContradictoryBranch(); + + /** + * Recursively determines if the sub-tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and + * justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + public abstract boolean isValidBranch(); + + /** + * Gets the type of tree puzzleElement + * + * @return NODE if this tree puzzleElement is a tree node, TRANSITION, if this tree puzzleElement + * is a transition + */ + public TreeElementType getType() { + return type; + } + + /** + * Gets the board at this TreeElement + * + * @return the board at this TreeElement + */ + public Board getBoard() { + return board; + } + + /** + * Sets the board at this TreeElement + * + * @param board the board at this TreeElement + */ + public void setBoard(Board board) { + this.board = board; + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java b/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java index ad93f16b6..42eeb6c34 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java @@ -1,5 +1,6 @@ package edu.rpi.legup.model.tree; public enum TreeElementType { - NODE, TRANSITION + NODE, + TRANSITION } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeNode.java b/src/main/java/edu/rpi/legup/model/tree/TreeNode.java index 59f6e736e..4d1652a3c 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeNode.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeNode.java @@ -2,335 +2,331 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.utility.DisjointSets; - import java.util.*; public class TreeNode extends TreeElement { - private TreeTransition parent; - private List children; - private boolean isRoot; - - /** - * TreeNode Constructor creates a tree node whenever a rule has been made - * - * @param board board associated with this tree node - */ - public TreeNode(Board board) { - super(TreeElementType.NODE); - this.board = board; - this.parent = null; - this.children = new ArrayList<>(); - this.isRoot = false; + private TreeTransition parent; + private List children; + private boolean isRoot; + + /** + * TreeNode Constructor creates a tree node whenever a rule has been made + * + * @param board board associated with this tree node + */ + public TreeNode(Board board) { + super(TreeElementType.NODE); + this.board = board; + this.parent = null; + this.children = new ArrayList<>(); + this.isRoot = false; + } + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must lead + * to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + @Override + public boolean isContradictoryBranch() { + boolean leadsToContra = true; + for (TreeTransition child : children) { + leadsToContra &= child.isContradictoryBranch(); } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node - * must lead to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - @Override - public boolean isContradictoryBranch() { - boolean leadsToContra = true; - for (TreeTransition child : children) { - leadsToContra &= child.isContradictoryBranch(); - } - return leadsToContra && !children.isEmpty(); + return leadsToContra && !children.isEmpty(); + } + + /** + * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and + * justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + @Override + public boolean isValidBranch() { + for (TreeTransition transition : children) { + if (!transition.isValidBranch()) { + return false; + } } - - /** - * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified - * and justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is valid, - * false otherwise - */ - @Override - public boolean isValidBranch() { - for (TreeTransition transition : children) { - if (!transition.isValidBranch()) { - return false; - } + return true; + } + + /** + * Gets all of the ancestors of this node + * + * @return list of all of the ancestors for this node + */ + public List getAncestors() { + List ancestors = new ArrayList<>(); + Queue it = new LinkedList<>(); + it.add(this); + + while (!it.isEmpty()) { + TreeNode next = it.poll(); + if (next.getParent() != null) { + for (TreeNode treeNode : next.getParent().getParents()) { + if (!it.contains(treeNode)) { + it.add(treeNode); + } } - return true; - } + } - /** - * Gets all of the ancestors of this node - * - * @return list of all of the ancestors for this node - */ - public List getAncestors() { - List ancestors = new ArrayList<>(); - Queue it = new LinkedList<>(); - it.add(this); - - while (!it.isEmpty()) { - TreeNode next = it.poll(); - if (next.getParent() != null) { - for (TreeNode treeNode : next.getParent().getParents()) { - if (!it.contains(treeNode)) { - it.add(treeNode); - } - } - } - - if (!ancestors.contains(next)) { - ancestors.add(next); - } - } - return ancestors; + if (!ancestors.contains(next)) { + ancestors.add(next); + } } - - /** - * Gets a list of the descendants of this node - * - * @return list of all the descendants for this node - */ - public List getDescendants() { - List descendants = new ArrayList<>(); - Queue it = new LinkedList<>(); - it.add(this); - - while (!it.isEmpty()) { - TreeElement next = it.poll(); - - if (next.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) next; - for (TreeTransition transition : node.getChildren()) { - if (!descendants.contains(transition)) { - descendants.add(transition); - it.add(transition); - } - } - } - else { - TreeTransition trans = (TreeTransition) next; - TreeNode childNode = trans.getChildNode(); - if (childNode != null && !descendants.contains(childNode)) { - descendants.add(childNode); - it.add(childNode); - } - } + return ancestors; + } + + /** + * Gets a list of the descendants of this node + * + * @return list of all the descendants for this node + */ + public List getDescendants() { + List descendants = new ArrayList<>(); + Queue it = new LinkedList<>(); + it.add(this); + + while (!it.isEmpty()) { + TreeElement next = it.poll(); + + if (next.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) next; + for (TreeTransition transition : node.getChildren()) { + if (!descendants.contains(transition)) { + descendants.add(transition); + it.add(transition); + } + } + } else { + TreeTransition trans = (TreeTransition) next; + TreeNode childNode = trans.getChildNode(); + if (childNode != null && !descendants.contains(childNode)) { + descendants.add(childNode); + it.add(childNode); } - return descendants; + } } - - /** - * Gets a DisjointSets containing the children of this node such that the sets contained within the DisjointSets - * are such that elements in the same set are branches of this tree node that will eventually merge. This could - * mean that multiple merges take place before this happens. - * - * @return DisjointSets of tree transitions containing unique non-merging branches - */ - public DisjointSets findMergingBranches() { - DisjointSets branches = new DisjointSets<>(); - children.forEach(branches::createSet); - - for (TreeTransition tran : children) { - branches.createSet(tran); - - TreeNode child = tran.getChildNode(); - if (child != null) { - List nodes = new ArrayList<>(); - nodes.add(child); - while (!nodes.isEmpty()) { - TreeElement element = nodes.get(0); - branches.createSet(element); - branches.union(tran, element); - - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - nodes.addAll(node.getChildren()); - } - else { - TreeTransition childTran = (TreeTransition) element; - if (childTran.getChildNode() != null) { - nodes.add(childTran.getChildNode()); - } - } - nodes.remove(element); - } + return descendants; + } + + /** + * Gets a DisjointSets containing the children of this node such that the sets contained within + * the DisjointSets are such that elements in the same set are branches of this tree node that + * will eventually merge. This could mean that multiple merges take place before this happens. + * + * @return DisjointSets of tree transitions containing unique non-merging branches + */ + public DisjointSets findMergingBranches() { + DisjointSets branches = new DisjointSets<>(); + children.forEach(branches::createSet); + + for (TreeTransition tran : children) { + branches.createSet(tran); + + TreeNode child = tran.getChildNode(); + if (child != null) { + List nodes = new ArrayList<>(); + nodes.add(child); + while (!nodes.isEmpty()) { + TreeElement element = nodes.get(0); + branches.createSet(element); + branches.union(tran, element); + + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + nodes.addAll(node.getChildren()); + } else { + TreeTransition childTran = (TreeTransition) element; + if (childTran.getChildNode() != null) { + nodes.add(childTran.getChildNode()); } + } + nodes.remove(element); } + } + } - DisjointSets mergingBranches = new DisjointSets<>(); - children.forEach(mergingBranches::createSet); + DisjointSets mergingBranches = new DisjointSets<>(); + children.forEach(mergingBranches::createSet); - for (TreeTransition tran : children) { - for (TreeTransition tran1 : children) { - if (branches.find(tran) == branches.find(tran1)) { - mergingBranches.union(tran, tran1); - } - } + for (TreeTransition tran : children) { + for (TreeTransition tran1 : children) { + if (branches.find(tran) == branches.find(tran1)) { + mergingBranches.union(tran, tran1); } - return mergingBranches; + } } - - /** - * Finds the point at which the set of tree elements passed in will merge. This must be a set gotten from - * findMergingBranches method DisjointSets - * - * @param branches tree elements to find the merging point - * @return tree transition of the merging point or null if no such point exists - */ - @SuppressWarnings("unchecked") - public static TreeTransition findMergingPoint(Set branches) { - DisjointSets mergeSet = new DisjointSets<>(); - Set branchesCopy = new HashSet<>(branches); - TreeElement headBranch = branchesCopy.iterator().next(); - branchesCopy.remove(headBranch); - - for (TreeElement element : branchesCopy) { - mergeSet.createSet(element); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getDescendants().forEach((TreeElement e) -> { - if (!mergeSet.contains(e)) { - mergeSet.createSet(e); - } - mergeSet.union(element, e); + return mergingBranches; + } + + /** + * Finds the point at which the set of tree elements passed in will merge. This must be a set + * gotten from findMergingBranches method DisjointSets + * + * @param branches tree elements to find the merging point + * @return tree transition of the merging point or null if no such point exists + */ + @SuppressWarnings("unchecked") + public static TreeTransition findMergingPoint(Set branches) { + DisjointSets mergeSet = new DisjointSets<>(); + Set branchesCopy = new HashSet<>(branches); + TreeElement headBranch = branchesCopy.iterator().next(); + branchesCopy.remove(headBranch); + + for (TreeElement element : branchesCopy) { + mergeSet.createSet(element); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getDescendants() + .forEach( + (TreeElement e) -> { + if (!mergeSet.contains(e)) { + mergeSet.createSet(e); + } + mergeSet.union(element, e); }); + } else { + TreeTransition transition = (TreeTransition) element; + TreeNode childNode = transition.getChildNode(); + if (childNode != null) { + List des = childNode.getDescendants(); + for (TreeElement e : des) { + if (!mergeSet.contains(e)) { + mergeSet.createSet(e); } - else { - TreeTransition transition = (TreeTransition) element; - TreeNode childNode = transition.getChildNode(); - if (childNode != null) { - List des = childNode.getDescendants(); - for (TreeElement e : des) { - if (!mergeSet.contains(e)) { - mergeSet.createSet(e); - } - mergeSet.union(element, e); - } - } - } + mergeSet.union(element, e); + } } + } + } - Queue next = new LinkedList<>(); - next.add(headBranch); - - while (!next.isEmpty()) { - TreeElement element = next.poll(); - if (!mergeSet.contains(element)) { - mergeSet.createSet(element); - } - mergeSet.union(headBranch, element); + Queue next = new LinkedList<>(); + next.add(headBranch); - if (mergeSet.setCount() == 1) { - if (element.getType() == TreeElementType.TRANSITION) { - return (TreeTransition) element; - } - return null; - } + while (!next.isEmpty()) { + TreeElement element = next.poll(); + if (!mergeSet.contains(element)) { + mergeSet.createSet(element); + } + mergeSet.union(headBranch, element); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - next.addAll(node.getChildren()); - } - else { - TreeTransition tran = (TreeTransition) element; - next.add(tran.getChildNode()); - } + if (mergeSet.setCount() == 1) { + if (element.getType() == TreeElementType.TRANSITION) { + return (TreeTransition) element; } return null; + } + + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + next.addAll(node.getChildren()); + } else { + TreeTransition tran = (TreeTransition) element; + next.add(tran.getChildNode()); + } } - - /** - * Determines if the specified tree transition is a parent of this node - * - * @param parent tree transition that could be a parent - * @return true if the specified tree transition is a parent of this node, false otherwise - */ - public boolean isParent(TreeTransition parent) { - return this.parent == parent; - } - - /** - * Adds a child to this tree node - * - * @param child child to add - */ - public void addChild(TreeTransition child) { - children.add(child); - } - - /** - * Removes a child to this tree node - * - * @param child child to remove - */ - public void removeChild(TreeTransition child) { - children.remove(child); - } - - /** - * Determines if the specified tree node is a child of this node - * - * @param child tree node that could be a child - * @return true if the specified tree node is a child of this node, false otherwise - */ - public boolean isChild(TreeNode child) { - return children.contains(child); - } - - /** - * Gets the TreeNode's parent - * - * @return the TreeNode's parent - */ - public TreeTransition getParent() { - return parent; - } - - /** - * Sets the TreeNode's parent - * - * @param parent the TreeNode's parent - */ - public void setParent(TreeTransition parent) { - this.parent = parent; - } - - /** - * Gets the TreeNode's children - * - * @return the TreeNode's children - */ - public List getChildren() { - return children; - } - - /** - * Sets the TreeNode's children - * - * @param children the TreeNode's children - */ - public void setChildren(List children) { - this.children = children; - } - - /** - * Is this node the root of the tree - * - * @return true if this node is the root of the tree, false otherwise - */ - public boolean isRoot() { - return isRoot; - } - - /** - * Sets the root of the tree - * - * @param isRoot true if this node is the root of the tree, false otherwise - */ - public void setRoot(boolean isRoot) { - this.isRoot = isRoot; - } - - public void clearChildren() { - this.children.clear(); - } - -} \ No newline at end of file + return null; + } + + /** + * Determines if the specified tree transition is a parent of this node + * + * @param parent tree transition that could be a parent + * @return true if the specified tree transition is a parent of this node, false otherwise + */ + public boolean isParent(TreeTransition parent) { + return this.parent == parent; + } + + /** + * Adds a child to this tree node + * + * @param child child to add + */ + public void addChild(TreeTransition child) { + children.add(child); + } + + /** + * Removes a child to this tree node + * + * @param child child to remove + */ + public void removeChild(TreeTransition child) { + children.remove(child); + } + + /** + * Determines if the specified tree node is a child of this node + * + * @param child tree node that could be a child + * @return true if the specified tree node is a child of this node, false otherwise + */ + public boolean isChild(TreeNode child) { + return children.contains(child); + } + + /** + * Gets the TreeNode's parent + * + * @return the TreeNode's parent + */ + public TreeTransition getParent() { + return parent; + } + + /** + * Sets the TreeNode's parent + * + * @param parent the TreeNode's parent + */ + public void setParent(TreeTransition parent) { + this.parent = parent; + } + + /** + * Gets the TreeNode's children + * + * @return the TreeNode's children + */ + public List getChildren() { + return children; + } + + /** + * Sets the TreeNode's children + * + * @param children the TreeNode's children + */ + public void setChildren(List children) { + this.children = children; + } + + /** + * Is this node the root of the tree + * + * @return true if this node is the root of the tree, false otherwise + */ + public boolean isRoot() { + return isRoot; + } + + /** + * Sets the root of the tree + * + * @param isRoot true if this node is the root of the tree, false otherwise + */ + public void setRoot(boolean isRoot) { + this.isRoot = isRoot; + } + + public void clearChildren() { + this.children.clear(); + } +} diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java b/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java index 72572ac72..e20ba8b6a 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java @@ -5,425 +5,417 @@ import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.rules.Rule; import edu.rpi.legup.model.rules.RuleType; - import java.util.ArrayList; import java.util.List; public class TreeTransition extends TreeElement { - private ArrayList parents; - private TreeNode childNode; - private Rule rule; - - private PuzzleElement selection; - private boolean isCorrect; - private boolean isVerified; - - /** - * TreeTransition Constructor create a transition from one node to another - * - * @param board board state of the transition - */ - public TreeTransition(Board board) { - super(TreeElementType.TRANSITION); - this.parents = new ArrayList<>(); - this.childNode = null; - this.board = board; - this.rule = null; - this.selection = null; - this.isCorrect = false; - this.isVerified = false; - } - - /** - * TreeTransition Constructor - create a transition from one node to another - * - * @param parent parent tree node associated with the transition - * @param board board state of the transition - */ - public TreeTransition(TreeNode parent, Board board) { - this(board); - this.parents.add(parent); - } - - /** - * Recursively propagates the change of puzzleElement down the tree - * - * @param element puzzleElement of the change made - */ - @SuppressWarnings("unchecked") - public void propagateChange(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyChange(element); - changed = true; - } - else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyChange(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyChange(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - PuzzleElement copy = element.copy(); - copy.setModifiable(false); - child.propagateChange(copy); - } - } - } - } - else { - // Overwrite previous modifications to this element - board.removeModifiedData(board.getPuzzleElement(element)); - - // apply changes to tranistion + private ArrayList parents; + private TreeNode childNode; + private Rule rule; + + private PuzzleElement selection; + private boolean isCorrect; + private boolean isVerified; + + /** + * TreeTransition Constructor create a transition from one node to another + * + * @param board board state of the transition + */ + public TreeTransition(Board board) { + super(TreeElementType.TRANSITION); + this.parents = new ArrayList<>(); + this.childNode = null; + this.board = board; + this.rule = null; + this.selection = null; + this.isCorrect = false; + this.isVerified = false; + } + + /** + * TreeTransition Constructor - create a transition from one node to another + * + * @param parent parent tree node associated with the transition + * @param board board state of the transition + */ + public TreeTransition(TreeNode parent, Board board) { + this(board); + this.parents.add(parent); + } + + /** + * Recursively propagates the change of puzzleElement down the tree + * + * @param element puzzleElement of the change made + */ + @SuppressWarnings("unchecked") + public void propagateChange(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyChange(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); board.notifyChange(element); - - // mark first transition as modified - if (!board.getPuzzleElement(element).equalsData(parents.get(0).getBoard().getPuzzleElement(element))) { - board.addModifiedData(element); - } - - // propagate to children - if (childNode != null) { - - // find starting board - TreeNode head = childNode; - while (head.getParent() != null) { - head = head.getParent().getParents().get(0); - } - Board headBoard = head.getBoard(); - - PuzzleElement copy = element.copy(); - // Set as modifiable if reverted to starting value (and started modifiable) - if (headBoard.getPuzzleElement(element).equalsData(element)) { - copy.setModifiable(headBoard.getPuzzleElement(element).isModifiable()); - } - else{ - copy.setModifiable(false); - } - - // apply changes to result node - childNode.getBoard().notifyChange(copy); - - // apply to all child transitions - for (TreeTransition child : childNode.getChildren()) { - child.propagateChange(copy.copy()); - } - } + changed = true; + } } - reverify(); - } - - /** - * Recursively propagates the addition of puzzleElement down the tree - * - * @param element puzzleElement of the addition made - */ - @SuppressWarnings("unchecked") - public void propagateAddition(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyDeletion(element); - changed = true; - } - else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyAddition(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyAddition(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateAddition(element.copy()); - } - } - } + if (changed && childNode != null) { + childNode.getBoard().notifyChange(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + PuzzleElement copy = element.copy(); + copy.setModifiable(false); + child.propagateChange(copy); + } } - else { - if (childNode != null) { - board.notifyAddition(element); - childNode.getBoard().notifyAddition(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateAddition(element.copy()); - } - } + } + } else { + // Overwrite previous modifications to this element + board.removeModifiedData(board.getPuzzleElement(element)); + + // apply changes to tranistion + board.notifyChange(element); + + // mark first transition as modified + if (!board + .getPuzzleElement(element) + .equalsData(parents.get(0).getBoard().getPuzzleElement(element))) { + board.addModifiedData(element); + } + + // propagate to children + if (childNode != null) { + + // find starting board + TreeNode head = childNode; + while (head.getParent() != null) { + head = head.getParent().getParents().get(0); } - reverify(); - } - - /** - * Recursively propagates the change of puzzleElement down the tree - * - * @param element puzzleElement of the change made - */ - @SuppressWarnings("unchecked") - public void propagateDeletion(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyDeletion(element); - changed = true; - } - else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyAddition(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyDeletion(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateDeletion(element.copy()); - } - } - } + Board headBoard = head.getBoard(); + + PuzzleElement copy = element.copy(); + // Set as modifiable if reverted to starting value (and started modifiable) + if (headBoard.getPuzzleElement(element).equalsData(element)) { + copy.setModifiable(headBoard.getPuzzleElement(element).isModifiable()); + } else { + copy.setModifiable(false); } - else { - if (childNode != null) { - board.notifyDeletion(element); - childNode.getBoard().notifyDeletion(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateDeletion(element.copy()); - } - } + + // apply changes to result node + childNode.getBoard().notifyChange(copy); + + // apply to all child transitions + for (TreeTransition child : childNode.getChildren()) { + child.propagateChange(copy.copy()); } - reverify(); + } } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node - * must lead to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - @Override - public boolean isContradictoryBranch() { - if (isJustified() && isCorrect() && rule.getRuleType() == RuleType.CONTRADICTION) { - return true; + reverify(); + } + + /** + * Recursively propagates the addition of puzzleElement down the tree + * + * @param element puzzleElement of the addition made + */ + @SuppressWarnings("unchecked") + public void propagateAddition(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyDeletion(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyAddition(element); + changed = true; + } } - else { - if (childNode == null) { - return false; - } - else { - return childNode.isContradictoryBranch() && isJustified() && isCorrect(); - } + if (changed && childNode != null) { + childNode.getBoard().notifyAddition(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateAddition(element.copy()); + } } - } - - /** - * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified - * and justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is valid, - * false otherwise - */ - @Override - public boolean isValidBranch() { - return isJustified() && isCorrect() && childNode != null && childNode.isValidBranch(); - } - - /** - * Gets the parent tree nodes of this transition - * - * @return parent tree nodes of this tree transition - */ - public ArrayList getParents() { - return parents; - } - - /** - * Sets the parent tree nodes of this transition - * - * @param parents parents tree nodes of this tree transition - */ - public void setParents(ArrayList parents) { - this.parents = parents; - } - - /** - * Adds a parent tree node to this tree transition - * - * @param parent parent tree node to add - */ - public void addParent(TreeNode parent) { - parents.add(parent); - } - - /** - * Removes a parent tree node to this tree transition - * - * @param parent parent tree node to remove - */ - public void removeParent(TreeNode parent) { - parents.remove(parent); - } - - /** - * Determines if the specified tree node is a parent of this transition - * - * @param parent tree node that could be a parent - * @return true if the specified tree node is a parent of this transition, false otherwise - */ - public boolean isParent(TreeNode parent) { - return parents.contains(parent); - } - - /** - * Gets the childNode tree node of this transition - * - * @return childNode tree node - */ - public TreeNode getChildNode() { - return childNode; - } - - /** - * Sets the childNode tree node of this transition - * - * @param childNode childNode tree node - */ - public void setChildNode(TreeNode childNode) { - this.childNode = childNode; - } - - /** - * Gets the rule associated with this transition - * - * @return rule of this transition - */ - public Rule getRule() { - return rule; - } - - /** - * Sets the rule associated with this transition - * - * @param rule rule of this transition - */ - public void setRule(Rule rule) { - this.rule = rule; - isVerified = false; - } - - /** - * Gets he selected element associated with this transition - * - * @return If this is a case rule, the selected element for that rule, null otherwise - */ - public PuzzleElement getSelection() { - if (this.rule instanceof CaseRule) { - return selection; + } + } else { + if (childNode != null) { + board.notifyAddition(element); + childNode.getBoard().notifyAddition(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateAddition(element.copy()); } - return null; - } - - /** - * Sets the selected element associated with this transition - * - * @param selection selected element for this transition - */ - public void setSelection(PuzzleElement selection) { - this.selection = selection; + } } - - /** - * Gets whether this transition is correctly justified - * - * @return true if this transition is correctly justified, false otherwise - */ - public boolean isCorrect() { - if (isJustified() && !isVerified) { - isCorrect = rule.checkRule(this) == null; - isVerified = true; + reverify(); + } + + /** + * Recursively propagates the change of puzzleElement down the tree + * + * @param element puzzleElement of the change made + */ + @SuppressWarnings("unchecked") + public void propagateDeletion(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyDeletion(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyAddition(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyDeletion(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateDeletion(element.copy()); + } } - return isJustified() && isCorrect; + } + } else { + if (childNode != null) { + board.notifyDeletion(element); + childNode.getBoard().notifyDeletion(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateDeletion(element.copy()); + } + } } - - /** - * Sets whether this transition is correctly justified - * - * @param isCorrect true if this transition is correctly justified, false otherwise - */ - public void setCorrect(boolean isCorrect) { - this.isCorrect = isCorrect; - this.isVerified = true; + reverify(); + } + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must lead + * to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + @Override + public boolean isContradictoryBranch() { + if (isJustified() && isCorrect() && rule.getRuleType() == RuleType.CONTRADICTION) { + return true; + } else { + if (childNode == null) { + return false; + } else { + return childNode.isContradictoryBranch() && isJustified() && isCorrect(); + } } - - /** - * Forces check of rule on this transition regardless if it has been cached already - * - * @return true if this transition is correctly justified, false otherwise - */ - public boolean reverify() { - isVerified = false; - return isCorrect(); + } + + /** + * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and + * justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + @Override + public boolean isValidBranch() { + return isJustified() && isCorrect() && childNode != null && childNode.isValidBranch(); + } + + /** + * Gets the parent tree nodes of this transition + * + * @return parent tree nodes of this tree transition + */ + public ArrayList getParents() { + return parents; + } + + /** + * Sets the parent tree nodes of this transition + * + * @param parents parents tree nodes of this tree transition + */ + public void setParents(ArrayList parents) { + this.parents = parents; + } + + /** + * Adds a parent tree node to this tree transition + * + * @param parent parent tree node to add + */ + public void addParent(TreeNode parent) { + parents.add(parent); + } + + /** + * Removes a parent tree node to this tree transition + * + * @param parent parent tree node to remove + */ + public void removeParent(TreeNode parent) { + parents.remove(parent); + } + + /** + * Determines if the specified tree node is a parent of this transition + * + * @param parent tree node that could be a parent + * @return true if the specified tree node is a parent of this transition, false otherwise + */ + public boolean isParent(TreeNode parent) { + return parents.contains(parent); + } + + /** + * Gets the childNode tree node of this transition + * + * @return childNode tree node + */ + public TreeNode getChildNode() { + return childNode; + } + + /** + * Sets the childNode tree node of this transition + * + * @param childNode childNode tree node + */ + public void setChildNode(TreeNode childNode) { + this.childNode = childNode; + } + + /** + * Gets the rule associated with this transition + * + * @return rule of this transition + */ + public Rule getRule() { + return rule; + } + + /** + * Sets the rule associated with this transition + * + * @param rule rule of this transition + */ + public void setRule(Rule rule) { + this.rule = rule; + isVerified = false; + } + + /** + * Gets he selected element associated with this transition + * + * @return If this is a case rule, the selected element for that rule, null otherwise + */ + public PuzzleElement getSelection() { + if (this.rule instanceof CaseRule) { + return selection; } - - /** - * Gets whether this transition is justified - * - * @return true if this transition is justified, false otherwise - */ - public boolean isJustified() { - return rule != null; + return null; + } + + /** + * Sets the selected element associated with this transition + * + * @param selection selected element for this transition + */ + public void setSelection(PuzzleElement selection) { + this.selection = selection; + } + + /** + * Gets whether this transition is correctly justified + * + * @return true if this transition is correctly justified, false otherwise + */ + public boolean isCorrect() { + if (isJustified() && !isVerified) { + isCorrect = rule.checkRule(this) == null; + isVerified = true; } - - /*public int modifiedData_size(){ - return board.getModifiedData().size(); - }*/ + return isJustified() && isCorrect; + } + + /** + * Sets whether this transition is correctly justified + * + * @param isCorrect true if this transition is correctly justified, false otherwise + */ + public void setCorrect(boolean isCorrect) { + this.isCorrect = isCorrect; + this.isVerified = true; + } + + /** + * Forces check of rule on this transition regardless if it has been cached already + * + * @return true if this transition is correctly justified, false otherwise + */ + public boolean reverify() { + isVerified = false; + return isCorrect(); + } + + /** + * Gets whether this transition is justified + * + * @return true if this transition is justified, false otherwise + */ + public boolean isJustified() { + return rule != null; + } + + /*public int modifiedData_size(){ + return board.getModifiedData().size(); + }*/ } diff --git a/src/main/java/edu/rpi/legup/puzzle/PuzzleElementTypes.java b/src/main/java/edu/rpi/legup/puzzle/PuzzleElementTypes.java index f2ddb056c..f0dd5a6e9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/PuzzleElementTypes.java +++ b/src/main/java/edu/rpi/legup/puzzle/PuzzleElementTypes.java @@ -1,4 +1,3 @@ package edu.rpi.legup.puzzle; -public enum PuzzleElementTypes { -} +public enum PuzzleElementTypes {} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java b/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java index 22a980251..fcfa70cd4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java @@ -6,152 +6,164 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Battleship extends Puzzle { - public Battleship() { - super(); + public Battleship() { + super(); - this.name = "Battleship"; + this.name = "Battleship"; - this.importer = new BattleshipImporter(this); - this.exporter = new BattleshipExporter(this); + this.importer = new BattleshipImporter(this); + this.exporter = new BattleshipExporter(this); - this.factory = new BattleshipCellFactory(); - } + this.factory = new BattleshipCellFactory(); + } - /** - * Initializes the game board. Called by the invoker of the class - */ - @Override - public void initializeView() { - boardView = new BattleshipView((BattleshipBoard) currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new BattleshipView((BattleshipBoard) currentBoard); + addBoardListener(boardView); + } - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Battleship - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Battleship, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for Battleship + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Battleship, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - BattleshipBoard battleShipBoard = (BattleshipBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + BattleshipBoard battleShipBoard = (BattleshipBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(battleShipBoard) == null) { - return false; - } - } - for (PuzzleElement data : battleShipBoard.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) data; - if (cell.getType() == BattleshipType.UNKNOWN) { - return false; - } - } - return true; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(battleShipBoard) == null) { + return false; + } } + for (PuzzleElement data : battleShipBoard.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) data; + if (cell.getType() == BattleshipType.UNKNOWN) { + return false; + } + } + return true; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} - } -// -// @Override -// public void onTreeSelectionChange(ArrayList newSelection) -// { -// -// } + // + // @Override + // public void onTreeSelectionChange(ArrayList newSelection) + // { + // + // } - @Override - public void importPuzzle(String fileName) { -// if(fileName != null) -// { -// InputStream inputStream = new FileInputStream(fileName); -// DocumentBuilder builder = null;//factory.newDocumentBuilder(); -// Document document = builder.parse(inputStream); -// -// BattleShipBoard battleShipBoard; -// -// PuzzleElement rootNode = document.getDocumentElement(); -// PuzzleElement puzzleElement = (PuzzleElement) rootNode.getElementsByTagName("edu.rpi.legup.puzzle").item(0); -// PuzzleElement boardElement = (PuzzleElement) puzzleElement.getElementsByTagName("board").item(0); -// PuzzleElement axesElement = (PuzzleElement) boardElement.getElementsByTagName("axes").item(0); -// PuzzleElement shipElement = (PuzzleElement) boardElement.getElementsByTagName("ships").item(0); -// PuzzleElement cellElement = (PuzzleElement) boardElement.getElementsByTagName("cells").item(0); -// PuzzleElement rightElement = (PuzzleElement) axesElement.getElementsByTagName("right").item(0); -// PuzzleElement bottomElement = (PuzzleElement) axesElement.getElementsByTagName("bottom").item(0); -// NodeList rightClueList = rightElement.getElementsByTagName("clue"); -// NodeList bottomClueList = bottomElement.getElementsByTagName("clue"); -// NodeList shipList = shipElement.getElementsByTagName("ship"); -// NodeList cells = cellElement.getElementsByTagName("cell"); -// -// int size = Integer.valueOf(boardElement.getAttribute("size")); -// battleShipBoard = new BattleShipBoard(size); -// -// ArrayList battleShipData = new ArrayList<>(); -// for(int i = 0; i < size * size; i++) -// { -// battleShipData.add(null); -// } -// -// for (int i = 0; i < rightClueList.getLength(); i++) { -// battleShipBoard.getRight()[i] = Integer.valueOf(rightClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); -// } -// -// for (int i = 0; i < bottomClueList.getLength(); i++) { -// battleShipBoard.getBottom()[i] = Integer.valueOf(bottomClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); -// } -// -// for (int i = 0; i < shipList.getLength(); i++) { -// int length = Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("length").getNodeValue()); -// int count = Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("count").getNodeValue()); -// battleShipBoard.getShips().add(new Ship(length, count)); -// } -// -// for (int i = 0; i < cells.getLength(); i++) { -// int x = Integer.valueOf(cells.item(i).getAttributes().getNamedItem("x").getNodeValue()); -// int y = Integer.valueOf(cells.item(i).getAttributes().getNamedItem("y").getNodeValue()); -// String value = cells.item(i).getAttributes().getNamedItem("value").getNodeValue().toUpperCase(); -// -// BattleShipCell cell = new BattleShipCell(BattleShipType.valueOf(value).ordinal(), new Point(x, y)); -// battleShipBoard.setCell(x, y, cell); -// cell.setModifiable(false); -// cell.setGiven(true); -// } -// -// for (int x = 0; x < size; x++) { -// for (int y = 0; y < size; y++) { -// if (battleShipBoard.getCell(x, y) == null) { -// BattleShipCell cell = new BattleShipCell(9, new Point(x, y)); -// cell.setModifiable(true); -// battleShipBoard.setCell(x, y, cell); -// } -// } -// } -// this.currentBoard = battleShipBoard; -// this.tree = new Tree(currentBoard); -// } - } -} \ No newline at end of file + @Override + public void importPuzzle(String fileName) { + // if(fileName != null) + // { + // InputStream inputStream = new FileInputStream(fileName); + // DocumentBuilder builder = null;//factory.newDocumentBuilder(); + // Document document = builder.parse(inputStream); + // + // BattleShipBoard battleShipBoard; + // + // PuzzleElement rootNode = document.getDocumentElement(); + // PuzzleElement puzzleElement = (PuzzleElement) + // rootNode.getElementsByTagName("edu.rpi.legup.puzzle").item(0); + // PuzzleElement boardElement = (PuzzleElement) + // puzzleElement.getElementsByTagName("board").item(0); + // PuzzleElement axesElement = (PuzzleElement) + // boardElement.getElementsByTagName("axes").item(0); + // PuzzleElement shipElement = (PuzzleElement) + // boardElement.getElementsByTagName("ships").item(0); + // PuzzleElement cellElement = (PuzzleElement) + // boardElement.getElementsByTagName("cells").item(0); + // PuzzleElement rightElement = (PuzzleElement) + // axesElement.getElementsByTagName("right").item(0); + // PuzzleElement bottomElement = (PuzzleElement) + // axesElement.getElementsByTagName("bottom").item(0); + // NodeList rightClueList = rightElement.getElementsByTagName("clue"); + // NodeList bottomClueList = bottomElement.getElementsByTagName("clue"); + // NodeList shipList = shipElement.getElementsByTagName("ship"); + // NodeList cells = cellElement.getElementsByTagName("cell"); + // + // int size = Integer.valueOf(boardElement.getAttribute("size")); + // battleShipBoard = new BattleShipBoard(size); + // + // ArrayList battleShipData = new ArrayList<>(); + // for(int i = 0; i < size * size; i++) + // { + // battleShipData.add(null); + // } + // + // for (int i = 0; i < rightClueList.getLength(); i++) { + // battleShipBoard.getRight()[i] = + // Integer.valueOf(rightClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); + // } + // + // for (int i = 0; i < bottomClueList.getLength(); i++) { + // battleShipBoard.getBottom()[i] = + // Integer.valueOf(bottomClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); + // } + // + // for (int i = 0; i < shipList.getLength(); i++) { + // int length = + // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("length").getNodeValue()); + // int count = + // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("count").getNodeValue()); + // battleShipBoard.getShips().add(new Ship(length, count)); + // } + // + // for (int i = 0; i < cells.getLength(); i++) { + // int x = + // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("x").getNodeValue()); + // int y = + // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("y").getNodeValue()); + // String value = + // cells.item(i).getAttributes().getNamedItem("value").getNodeValue().toUpperCase(); + // + // BattleShipCell cell = new + // BattleShipCell(BattleShipType.valueOf(value).ordinal(), new Point(x, y)); + // battleShipBoard.setCell(x, y, cell); + // cell.setModifiable(false); + // cell.setGiven(true); + // } + // + // for (int x = 0; x < size; x++) { + // for (int y = 0; y < size; y++) { + // if (battleShipBoard.getCell(x, y) == null) { + // BattleShipCell cell = new BattleShipCell(9, new Point(x, y)); + // cell.setModifiable(true); + // battleShipBoard.setCell(x, y, cell); + // } + // } + // } + // this.currentBoard = battleShipBoard; + // this.tree = new Tree(currentBoard); + // } + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java index 5965f7055..cbf7ffbcd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java @@ -2,157 +2,154 @@ import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.*; import java.util.ArrayList; import java.util.List; public class BattleshipBoard extends GridBoard { - private List east; - private List south; - - /** - * Constructor for creating a rectangular battleship board. - * - * @param width width of the board - * @param height height of the board - */ - public BattleshipBoard(int width, int height) { - super(width, height); - - this.east = new ArrayList<>(); - this.south = new ArrayList<>(); - - for (int i = 0; i < height; i++) { - east.add(null); - } - for (int i = 0; i < width; i++) { - south.add(null); - } - } - - /** - * Constructor for creating a square-sized battleship board. - * - * @param size size of the board - */ - public BattleshipBoard(int size) { - this(size, size); - } + private List east; + private List south; - /** - * Gets the east {@link BattleshipClue} - * - * @return List of BattleShipClue objects on the east - * side of the board - */ - public List getEast() { - return east; - } + /** + * Constructor for creating a rectangular battleship board. + * + * @param width width of the board + * @param height height of the board + */ + public BattleshipBoard(int width, int height) { + super(width, height); - /** - * Gets the east {@link BattleshipClue} - * - * @return east battle ship clues - */ - public List getSouth() { - return south; - } + this.east = new ArrayList<>(); + this.south = new ArrayList<>(); - @Override - public BattleshipCell getCell(int x, int y) { - return (BattleshipCell) super.getCell(x, y); + for (int i = 0; i < height; i++) { + east.add(null); } - - @Override - /** - * Creates a copy of the current board - * - * @return the copy of the board - */ - public BattleshipBoard copy() { - BattleshipBoard copy = new BattleshipBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.east = this.east; - copy.south = this.south; - return copy; + for (int i = 0; i < width; i++) { + south.add(null); } - - /** - * Get a list of all orthogonally adjacent cells. - * - * @param cell The cell to get adjacent cells from. - * @return List of adjacent cells in clockwise order: - * { up, right, down, left } - */ - public List getAdjOrthogonals(BattleshipCell cell) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - BattleshipCell up = getCell(loc.x, loc.y - 1); - BattleshipCell right = getCell(loc.x + 1, loc.y); - BattleshipCell down = getCell(loc.x, loc.y + 1); - BattleshipCell left = getCell(loc.x - 1, loc.y); - adj.add(up); - adj.add(right); - adj.add(down); - adj.add(left); - return adj; + } + + /** + * Constructor for creating a square-sized battleship board. + * + * @param size size of the board + */ + public BattleshipBoard(int size) { + this(size, size); + } + + /** + * Gets the east {@link BattleshipClue} + * + * @return List of BattleShipClue objects on the east side of the board + */ + public List getEast() { + return east; + } + + /** + * Gets the east {@link BattleshipClue} + * + * @return east battle ship clues + */ + public List getSouth() { + return south; + } + + @Override + public BattleshipCell getCell(int x, int y) { + return (BattleshipCell) super.getCell(x, y); + } + + @Override + /** + * Creates a copy of the current board + * + * @return the copy of the board + */ + public BattleshipBoard copy() { + BattleshipBoard copy = new BattleshipBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } - - /** - * Get a list of all diagonally adjacent cells. - * - * @param cell The cell to get diagonally adjacent cells from. - * @return List of diagonally adjacent cells in clockwise order: - * { upRight, downRight, downLeft, upLeft } - */ - public List getAdjDiagonals(BattleshipCell cell) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - BattleshipCell upRight = getCell(loc.x + 1, loc.y - 1); - BattleshipCell downRight = getCell(loc.x + 1, loc.y + 1); - BattleshipCell downLeft = getCell(loc.x - 1, loc.y + 1); - BattleshipCell upLeft = getCell(loc.x - 1, loc.y - 1); - dia.add(upRight); - dia.add(downRight); - dia.add(downLeft); - dia.add(upLeft); - return dia; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } - - /** - * Get a list of cells in a row. - * - * @param y The y-coordinate of the row. - * @return List of cells in the row in increasing x-coordinate order. - */ - public List getRow(int y) { - List row = new ArrayList<>(); - for (int x = 0; x < dimension.width; x++) { - row.add(getCell(x, y)); - } - return row; + copy.east = this.east; + copy.south = this.south; + return copy; + } + + /** + * Get a list of all orthogonally adjacent cells. + * + * @param cell The cell to get adjacent cells from. + * @return List of adjacent cells in clockwise order: { up, right, down, left } + */ + public List getAdjOrthogonals(BattleshipCell cell) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + BattleshipCell up = getCell(loc.x, loc.y - 1); + BattleshipCell right = getCell(loc.x + 1, loc.y); + BattleshipCell down = getCell(loc.x, loc.y + 1); + BattleshipCell left = getCell(loc.x - 1, loc.y); + adj.add(up); + adj.add(right); + adj.add(down); + adj.add(left); + return adj; + } + + /** + * Get a list of all diagonally adjacent cells. + * + * @param cell The cell to get diagonally adjacent cells from. + * @return List of diagonally adjacent cells in clockwise order: + * { upRight, downRight, downLeft, upLeft } + */ + public List getAdjDiagonals(BattleshipCell cell) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + BattleshipCell upRight = getCell(loc.x + 1, loc.y - 1); + BattleshipCell downRight = getCell(loc.x + 1, loc.y + 1); + BattleshipCell downLeft = getCell(loc.x - 1, loc.y + 1); + BattleshipCell upLeft = getCell(loc.x - 1, loc.y - 1); + dia.add(upRight); + dia.add(downRight); + dia.add(downLeft); + dia.add(upLeft); + return dia; + } + + /** + * Get a list of cells in a row. + * + * @param y The y-coordinate of the row. + * @return List of cells in the row in increasing x-coordinate order. + */ + public List getRow(int y) { + List row = new ArrayList<>(); + for (int x = 0; x < dimension.width; x++) { + row.add(getCell(x, y)); } - - /** - * Get a list of cells in a column. - * - * @param x The x-coordinate of the column. - * @return List of cells in the column in increasing y-coordinate order. - */ - public List getColumn(int x) { - List column = new ArrayList<>(); - for (int y = 0; y < dimension.height; y++) { - column.add(getCell(x, y)); - } - return column; + return row; + } + + /** + * Get a list of cells in a column. + * + * @param x The x-coordinate of the column. + * @return List of cells in the column in increasing y-coordinate order. + */ + public List getColumn(int x) { + List column = new ArrayList<>(); + for (int y = 0; y < dimension.height; y++) { + column.add(getCell(x, y)); } -} \ No newline at end of file + return column; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java index 5f2c5b975..1e902633e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java @@ -1,40 +1,39 @@ package edu.rpi.legup.puzzle.battleship; import edu.rpi.legup.model.gameboard.GridCell; - import java.awt.*; public class BattleshipCell extends GridCell { - /** - * BattleShipCell Constructor - creates a BattleShipCell from the specified value and location - * - * @param value value of the BattleShipCell - * @param location position of the BattleShipCell - */ - public BattleshipCell(BattleshipType value, Point location) { - super(value, location); - } + /** + * BattleShipCell Constructor - creates a BattleShipCell from the specified value and location + * + * @param value value of the BattleShipCell + * @param location position of the BattleShipCell + */ + public BattleshipCell(BattleshipType value, Point location) { + super(value, location); + } - /** - * Gets the type of this BattleShipCell - * - * @return type of BattleShipCell - */ - public BattleshipType getType() { - return data; - } + /** + * Gets the type of this BattleShipCell + * + * @return type of BattleShipCell + */ + public BattleshipType getType() { + return data; + } - /** - * Performs a deep copy on the BattleShipCell - * - * @return a new copy of the BattleShipCell that is independent of this one - */ - public BattleshipCell copy() { - BattleshipCell copy = new BattleshipCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the BattleShipCell + * + * @return a new copy of the BattleShipCell that is independent of this one + */ + public BattleshipCell copy() { + BattleshipCell copy = new BattleshipCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java index 89b5fa19a..d97a44034 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java @@ -2,42 +2,42 @@ import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.event.MouseEvent; public class BattleshipCellController extends ElementController { - /** - * Controller class for the Battleship puzzle - - * receives user mouse input and changes what's shown on the GUI - * - * @param data the PuzzleElement to be changed - * @param e the user mouse input - */ - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - BattleshipCell cell = (BattleshipCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView.getSelectionPopupMenu().show(boardView, this.boardView.getCanvas().getX() + e.getX(), this.boardView.getCanvas().getY() + e.getY()); - } - else { - if (cell.getData() == BattleshipType.SHIP_MIDDLE) { - cell.setData(BattleshipType.UNKNOWN); - } - else { - cell.setData(BattleshipType.getType(cell.getData().value + 1)); - } - } + /** + * Controller class for the Battleship puzzle - receives user mouse input and changes what's shown + * on the GUI + * + * @param data the PuzzleElement to be changed + * @param e the user mouse input + */ + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + BattleshipCell cell = (BattleshipCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == BattleshipType.SHIP_MIDDLE) { + cell.setData(BattleshipType.UNKNOWN); + } else { + cell.setData(BattleshipType.getType(cell.getData().value + 1)); } - else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == BattleshipType.UNKNOWN) { - cell.setData(BattleshipType.SHIP_MIDDLE); - } - else { - cell.setData(BattleshipType.getType(cell.getData().value - 1)); - } - } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == BattleshipType.UNKNOWN) { + cell.setData(BattleshipType.SHIP_MIDDLE); + } else { + cell.setData(BattleshipType.getType(cell.getData().value - 1)); } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java index 81629c360..f967a677e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java @@ -4,73 +4,72 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class BattleshipCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - BattleshipBoard battleShipBoard = (BattleshipBoard) board; - int width = battleShipBoard.getWidth(); - int height = battleShipBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - if (node.getNodeName().equalsIgnoreCase("cell")) { - - int value = Integer.parseInt(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.parseInt(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.parseInt(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("BattleShip Factory: cell location out of bounds"); - } - if (value < 0 || value > 3) { - throw new InvalidFileFormatException("BattleShip Factory: cell unknown value"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) + throws InvalidFileFormatException { + try { + BattleshipBoard battleShipBoard = (BattleshipBoard) board; + int width = battleShipBoard.getWidth(); + int height = battleShipBoard.getHeight(); + NamedNodeMap attributeList = node.getAttributes(); + if (node.getNodeName().equalsIgnoreCase("cell")) { - BattleshipCell cell = new BattleshipCell(BattleshipType.getType(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } - else { - throw new InvalidFileFormatException("BattleShip Factory: unknown puzzleElement puzzleElement"); - } + int value = Integer.parseInt(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.parseInt(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.parseInt(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("BattleShip Factory: cell location out of bounds"); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("BattleShip Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("BattleShip Factory: could not find attribute(s)"); + if (value < 0 || value > 3) { + throw new InvalidFileFormatException("BattleShip Factory: cell unknown value"); } + + BattleshipCell cell = new BattleshipCell(BattleshipType.getType(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } else { + throw new InvalidFileFormatException( + "BattleShip Factory: unknown puzzleElement puzzleElement"); + } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "BattleShip Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("BattleShip Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - BattleshipCell cell = (BattleshipCell) puzzleElement; - Point loc = cell.getLocation(); + BattleshipCell cell = (BattleshipCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java index 6b5856639..1ed0face1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java @@ -4,75 +4,75 @@ public class BattleshipClue extends PuzzleElement { - private BattleshipType type; + private BattleshipType type; - public BattleshipClue(int value, int index, BattleshipType type) { - super(value); - this.index = index; - this.type = type; - } + public BattleshipClue(int value, int index, BattleshipType type) { + super(value); + this.index = index; + this.type = type; + } - /** - * Returns the column number as a string - * - * @param col the column number that is to be converted and returned - * @return int value - */ - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; - } - return sb.reverse().toString(); + /** + * Returns the column number as a string + * + * @param col the column number that is to be converted and returned + * @return int value + */ + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; } + return sb.reverse().toString(); + } - /** - * Returns the column string as an integer - * - * @param col the column number as a string that is to be converted and returned - * @return string value - */ - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; - } - return result; + /** + * Returns the column string as an integer + * + * @param col the column number as a string that is to be converted and returned + * @return string value + */ + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; } + return result; + } - /** - * Gets the int value that represents this puzzleElement - * - * @return int value - */ - @Override - public Integer getData() { - return (Integer) super.getData(); - } + /** + * Gets the int value that represents this puzzleElement + * + * @return int value + */ + @Override + public Integer getData() { + return (Integer) super.getData(); + } - /** - * Returns the type of the battleship object (ship or clue) - * - * @return BattleshipType type - */ - public BattleshipType getType() { - return type; - } + /** + * Returns the type of the battleship object (ship or clue) + * + * @return BattleshipType type + */ + public BattleshipType getType() { + return type; + } - /** - * Sets the type of the battleship object (ship or clue) to the given type - * - * @param type given Battleship type - */ - public void setType(BattleshipType type) { - this.type = type; - } + /** + * Sets the type of the battleship object (ship or clue) to the given type + * + * @param type given Battleship type + */ + public void setType(BattleshipType type) { + this.type = type; + } - public BattleshipClue copy() { - return null; - } + public BattleshipClue copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java index 6a29eb7a3..e2ad8b863 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java @@ -1,59 +1,59 @@ package edu.rpi.legup.puzzle.battleship; import edu.rpi.legup.ui.boardview.ElementView; - import java.awt.*; public class BattleshipClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public BattleshipClueView(BattleshipClue clue) { - super(clue); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public BattleshipClueView(BattleshipClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public BattleshipClue getPuzzleElement() { + return (BattleshipClue) super.getPuzzleElement(); + } + + @Override + /** + * Draws the clue from the PuzzleElement associated with this view on the given frame + * + * @param graphics2D the frame the clue is to be drawn on + */ + public void draw(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + BattleshipClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + value = String.valueOf(clue.getData() + 1); + break; + case CLUE_EAST: + value = String.valueOf(clue.getData()); + break; + case CLUE_SOUTH: + value = String.valueOf(clue.getData()); + break; + case CLUE_WEST: + value = BattleshipClue.colNumToString(clue.getData() + 1); + break; + default: + value = ""; } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public BattleshipClue getPuzzleElement() { - return (BattleshipClue) super.getPuzzleElement(); - } - - @Override - /** - * Draws the clue from the PuzzleElement associated with this view on the given frame - * @param graphics2D the frame the clue is to be drawn on - */ - public void draw(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - BattleshipClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - value = String.valueOf(clue.getData() + 1); - break; - case CLUE_EAST: - value = String.valueOf(clue.getData()); - break; - case CLUE_SOUTH: - value = String.valueOf(clue.getData()); - break; - case CLUE_WEST: - value = BattleshipClue.colNumToString(clue.getData() + 1); - break; - default: - value = ""; - } - - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java index d66f159d7..fed0afaf3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java @@ -1,87 +1,97 @@ package edu.rpi.legup.puzzle.battleship; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; public class BattleshipElementView extends GridElementView { - private static final Stroke OUTLINE_STROKE = new BasicStroke(1); - private static final Color OUTLINE_COLOR = new Color(0x212121); - - private static final Color UNKNOWN_COLOR = new Color(0xE0E0E0); - private static final Color WATER_COLOR = new Color(0x1565C0); - private static final Color SHIP_COLOR = new Color(0x757575); + private static final Stroke OUTLINE_STROKE = new BasicStroke(1); + private static final Color OUTLINE_COLOR = new Color(0x212121); - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 10); - private static final Color FONT_COLOR = new Color(0xFFEB3B); + private static final Color UNKNOWN_COLOR = new Color(0xE0E0E0); + private static final Color WATER_COLOR = new Color(0x1565C0); + private static final Color SHIP_COLOR = new Color(0x757575); - public BattleshipElementView(BattleshipCell cell) { - super(cell); - } + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 10); + private static final Color FONT_COLOR = new Color(0xFFEB3B); - @Override - /** - * Draws on the given frame based on the type of the cell of the current puzzleElement - * @param graphics2D the frame to be drawn on - */ - public void drawElement(Graphics2D graphics2D) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - BattleshipType type = cell.getType(); + public BattleshipElementView(BattleshipCell cell) { + super(cell); + } - switch (type) { - case UNKNOWN: - graphics2D.setColor(UNKNOWN_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - case WATER: - graphics2D.setColor(WATER_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - case SHIP_UNKNOWN: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillRect(location.x + 3 * size.width / 8, location.y + 3 * size.height / 8, - size.width / 4, size.height / 4); + @Override + /** + * Draws on the given frame based on the type of the cell of the current puzzleElement + * + * @param graphics2D the frame to be drawn on + */ + public void drawElement(Graphics2D graphics2D) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + BattleshipType type = cell.getType(); - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = "?"; - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - break; - case SUBMARINE: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillOval(location.x + size.width / 4, location.y + size.width / 4, - size.width / 2, size.height / 2); - break; - case SHIP_TOP: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc(location.x, location.y - size.height / 2, size.width, size.height, 180, 180); - break; - case SHIP_RIGHT: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc(location.x + size.height / 2, location.y, size.width, size.height, 90, 180); - break; - case SHIP_BOTTOM: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc(location.x, location.y + size.height / 2, size.width, size.height, 0, 180); - break; - case SHIP_LEFT: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc(location.x - size.height / 2, location.y, size.width, size.height, 270, 180); - break; - case SHIP_MIDDLE: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - default: - graphics2D.setColor(new Color(0xE040FB)); - break; - } + switch (type) { + case UNKNOWN: + graphics2D.setColor(UNKNOWN_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + case WATER: + graphics2D.setColor(WATER_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + case SHIP_UNKNOWN: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillRect( + location.x + 3 * size.width / 8, + location.y + 3 * size.height / 8, + size.width / 4, + size.height / 4); - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.setStroke(OUTLINE_STROKE); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = "?"; + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + break; + case SUBMARINE: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillOval( + location.x + size.width / 4, + location.y + size.width / 4, + size.width / 2, + size.height / 2); + break; + case SHIP_TOP: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x, location.y - size.height / 2, size.width, size.height, 180, 180); + break; + case SHIP_RIGHT: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x + size.height / 2, location.y, size.width, size.height, 90, 180); + break; + case SHIP_BOTTOM: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x, location.y + size.height / 2, size.width, size.height, 0, 180); + break; + case SHIP_LEFT: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x - size.height / 2, location.y, size.width, size.height, 270, 180); + break; + case SHIP_MIDDLE: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + default: + graphics2D.setColor(new Color(0xE040FB)); + break; } -} \ No newline at end of file + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.setStroke(OUTLINE_STROKE); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java index 4205d0125..d9ec97a58 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java @@ -2,65 +2,64 @@ import edu.rpi.legup.model.PuzzleExporter; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import org.w3c.dom.Document; public class BattleshipExporter extends PuzzleExporter { - public BattleshipExporter(Battleship battleShip) { - super(battleShip); - } - - /** - * Creates and returns a new board element in the XML document specified - * - * @param newDocument the XML document to append to - * @return the new board element - */ - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - BattleshipBoard board; - if (puzzle.getTree() != null) { - board = (BattleshipBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (BattleshipBoard) puzzle.getBoardView().getBoard(); - } + public BattleshipExporter(Battleship battleShip) { + super(battleShip); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + /** + * Creates and returns a new board element in the XML document specified + * + * @param newDocument the XML document to append to + * @return the new board element + */ + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + BattleshipBoard board; + if (puzzle.getTree() != null) { + board = (BattleshipBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (BattleshipBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - if (cell.getData() != BattleshipType.getType(0)) { - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (BattleshipClue clue : board.getEast()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", BattleshipClue.colNumToString(clue.getIndex())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + if (cell.getData() != BattleshipType.getType(0)) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (BattleshipClue clue : board.getEast()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", String.valueOf(clue.getIndex())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (BattleshipClue clue : board.getEast()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", BattleshipClue.colNumToString(clue.getIndex())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); - return boardElement; + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (BattleshipClue clue : board.getEast()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", String.valueOf(clue.getIndex())); + axisSouth.appendChild(clueElement); } + boardElement.appendChild(axisSouth); + + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java index 749ceaaa9..012bf9b5c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java @@ -2,194 +2,182 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.awt.*; - public class BattleshipImporter extends PuzzleImporter { - public BattleshipImporter(Battleship battleShip) { - super(battleShip); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } - - @Override - public boolean acceptsTextInput() { - return false; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - - } + public BattleshipImporter(Battleship battleShip) { + super(battleShip); + } + + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } + + @Override + public boolean acceptsTextInput() { + return false; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + BattleshipBoard battleShipBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + battleShipBoard = new BattleshipBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + battleShipBoard = new BattleshipBoard(width, height); + } + } + + if (battleShipBoard == null) { + throw new InvalidFileFormatException("BattleShip Importer: " + "invalid board dimensions"); + } + + int width = battleShipBoard.getWidth(); + int height = battleShipBoard.getHeight(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + BattleshipCell cell = + (BattleshipCell) + puzzle.getFactory().importCell(elementDataList.item(i), battleShipBoard); + Point loc = cell.getLocation(); + if (cell.getData() != BattleshipType.getType(0)) { + cell.setModifiable(false); + cell.setGiven(true); + } + battleShipBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (battleShipBoard.getCell(x, y) == null) { + BattleshipCell cell = new BattleshipCell(BattleshipType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + battleShipBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("BattleShip Importer: " + "cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis2.hasAttribute("side")) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != battleShipBoard.getHeight() + || southClues.getLength() != battleShipBoard.getWidth()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + + "there must be same number of clues as the dimension " + + "of the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = BattleshipClue.colStringToColNum(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > battleShipBoard.getHeight()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "clue index out of bounds"); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName( - "cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - BattleshipBoard battleShipBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute( - "size")); - battleShipBoard = new BattleshipBoard(size); - } - else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute( - "width")); - int height = Integer.valueOf(boardElement.getAttribute( - "height")); - battleShipBoard = new BattleshipBoard(width, height); - } - } - - if (battleShipBoard == null) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "invalid board dimensions"); - } - - int width = battleShipBoard.getWidth(); - int height = battleShipBoard.getHeight(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - BattleshipCell cell = (BattleshipCell) puzzle.getFactory() - .importCell(elementDataList.item(i), battleShipBoard); - Point loc = cell.getLocation(); - if (cell.getData() != BattleshipType.getType(0)) { - cell.setModifiable(false); - cell.setGiven(true); - } - battleShipBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (battleShipBoard.getCell(x, y) == null) { - BattleshipCell cell = new BattleshipCell( - BattleshipType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - battleShipBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis2.hasAttribute( - "side")) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") - || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") - || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "axes must be different and be {east | south}"); - } - NodeList eastClues = side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") : - axis2.getElementsByTagName("clue"); - NodeList southClues = side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") : - axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != battleShipBoard.getHeight() - || southClues.getLength() != battleShipBoard.getWidth()) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "there must be same number of clues as the dimension " + - "of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = BattleshipClue.colStringToColNum( - clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > battleShipBoard.getHeight()) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "clue index out of bounds"); - } - - if (battleShipBoard.getEast().get(index - 1) != null) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "duplicate clue index"); - } - battleShipBoard.getEast().set(index - 1, new BattleshipClue( - value, index, BattleshipType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > battleShipBoard.getWidth()) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "clue index out of bounds"); - } - - if (battleShipBoard.getSouth().get(index - 1) != null) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "duplicate clue index"); - } - battleShipBoard.getSouth().set(index - 1, new BattleshipClue( - value, index, BattleshipType.CLUE_SOUTH)); - } - - puzzle.setCurrentBoard(battleShipBoard); + if (battleShipBoard.getEast().get(index - 1) != null) { + throw new InvalidFileFormatException("BattleShip Importer: " + "duplicate clue index"); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("BattleShip Importer: " + - "unknown value where integer expected"); + battleShipBoard + .getEast() + .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > battleShipBoard.getWidth()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "clue index out of bounds"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Battleship cannot accept text input"); + if (battleShipBoard.getSouth().get(index - 1) != null) { + throw new InvalidFileFormatException("BattleShip Importer: " + "duplicate clue index"); + } + battleShipBoard + .getSouth() + .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_SOUTH)); + } + + puzzle.setCurrentBoard(battleShipBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "unknown value where integer expected"); } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Battleship cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java index 6994222e3..2cee10469 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java @@ -1,37 +1,52 @@ package edu.rpi.legup.puzzle.battleship; public enum BattleshipType { - UNKNOWN, WATER, SUBMARINE, SHIP_UNKNOWN, - SHIP_TOP, SHIP_RIGHT, SHIP_BOTTOM, SHIP_LEFT, SHIP_MIDDLE, - CLUE_NORTH, CLUE_EAST, CLUE_SOUTH, CLUE_WEST; + UNKNOWN, + WATER, + SUBMARINE, + SHIP_UNKNOWN, + SHIP_TOP, + SHIP_RIGHT, + SHIP_BOTTOM, + SHIP_LEFT, + SHIP_MIDDLE, + CLUE_NORTH, + CLUE_EAST, + CLUE_SOUTH, + CLUE_WEST; - public int value; + public int value; - BattleshipType() { - this.value = this.ordinal(); - } + BattleshipType() { + this.value = this.ordinal(); + } - /** - * Gets the enum of this BattleShipType - * @param value the integer value input - * @return enum equivalent BattleShipType of integer value - */ - public static BattleshipType getType(int value) { - BattleshipType[] vals = values(); - if (value >= 0 && value < vals.length) { - return vals[value]; - } - return null; + /** + * Gets the enum of this BattleShipType + * + * @param value the integer value input + * @return enum equivalent BattleShipType of integer value + */ + public static BattleshipType getType(int value) { + BattleshipType[] vals = values(); + if (value >= 0 && value < vals.length) { + return vals[value]; } + return null; + } - /** - * Checks if the type is a ship. - * - * @param type the {@link BattleshipType} to check - * @return true if the type is a ship, false otherwise - */ - public static boolean isShip(BattleshipType type) { - return type == SHIP_UNKNOWN || type == SHIP_TOP || type == SHIP_RIGHT - || type == SHIP_BOTTOM || type == SHIP_LEFT || type == SHIP_MIDDLE; - } + /** + * Checks if the type is a ship. + * + * @param type the {@link BattleshipType} to check + * @return true if the type is a ship, false otherwise + */ + public static boolean isShip(BattleshipType type) { + return type == SHIP_UNKNOWN + || type == SHIP_TOP + || type == SHIP_RIGHT + || type == SHIP_BOTTOM + || type == SHIP_LEFT + || type == SHIP_MIDDLE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java index fbae2fa99..b82828fb8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java @@ -3,27 +3,26 @@ import edu.rpi.legup.controller.BoardController; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.ui.boardview.GridBoardView; - import java.awt.*; public class BattleshipView extends GridBoardView { - public BattleshipView(BattleshipBoard board) { - super(new BoardController(), new BattleshipCellController(), board.getDimension()); + public BattleshipView(BattleshipBoard board) { + super(new BoardController(), new BattleshipCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - Point loc = cell.getLocation(); - BattleshipElementView elementView = new BattleshipElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + Point loc = cell.getLocation(); + BattleshipElementView elementView = new BattleshipElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); - } -} \ No newline at end of file + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java index 49bee101a..41abeabe1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java @@ -6,85 +6,83 @@ import edu.rpi.legup.puzzle.battleship.BattleshipBoard; import edu.rpi.legup.puzzle.battleship.BattleshipCell; import edu.rpi.legup.puzzle.battleship.BattleshipType; - import java.util.List; public class AdjacentShipsContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE - = "No instance of the contradiction " + this.ruleName + " here"; - - public AdjacentShipsContradictionRule() { - super("BTSP-CONT-0001", - "Adjacent Ships", - "Cells next to the battleship must be water.", - "edu/rpi/legup/images/battleship/contradictions" + - "/AdjacentShips.png"); + private final String NO_CONTRADICTION_MESSAGE = + "No instance of the contradiction " + this.ruleName + " here"; + + public AdjacentShipsContradictionRule() { + super( + "BTSP-CONT-0001", + "Adjacent Ships", + "Cells next to the battleship must be water.", + "edu/rpi/legup/images/battleship/contradictions" + "/AdjacentShips.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule. + * + * @param board board to check contradiction + * @param puzzleElement equivalent {@link PuzzleElement} + * @return null if the transition contains a contradiction at the specified {@link + * PuzzleElement}, otherwise return a no contradiction message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + BattleshipBoard bsBoard = (BattleshipBoard) board; + BattleshipCell cell = (BattleshipCell) bsBoard.getPuzzleElement(puzzleElement); + + // rule only applies to battleship cells + if (!BattleshipType.isShip(cell.getType())) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; } - /** - * Checks whether the transition has a contradiction at the specific - * {@link PuzzleElement} index using this rule. - * - * @param board board to check contradiction - * @param puzzleElement equivalent {@link PuzzleElement} - * @return null if the transition contains a - * contradiction at the specified {@link PuzzleElement}, - * otherwise return a no contradiction message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - BattleshipBoard bsBoard = (BattleshipBoard) board; - BattleshipCell cell = (BattleshipCell) bsBoard.getPuzzleElement(puzzleElement); - - // rule only applies to battleship cells - if (!BattleshipType.isShip(cell.getType())) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - - // check orthogonally adjacent cells - List orthoAdjCells - = bsBoard.getAdjOrthogonals(cell); - - BattleshipCell up = orthoAdjCells.get(0); - BattleshipCell right = orthoAdjCells.get(1); - BattleshipCell down = orthoAdjCells.get(2); - BattleshipCell left = orthoAdjCells.get(3); + // check orthogonally adjacent cells + List orthoAdjCells = bsBoard.getAdjOrthogonals(cell); - boolean isVertical = (up != null && BattleshipType.isShip(up.getData())) - || (down != null && BattleshipType.isShip(down.getData())); + BattleshipCell up = orthoAdjCells.get(0); + BattleshipCell right = orthoAdjCells.get(1); + BattleshipCell down = orthoAdjCells.get(2); + BattleshipCell left = orthoAdjCells.get(3); - boolean isHorizontal = (left != null && BattleshipType.isShip(left.getData())) - || (right != null && BattleshipType.isShip(right.getData())); + boolean isVertical = + (up != null && BattleshipType.isShip(up.getData())) + || (down != null && BattleshipType.isShip(down.getData())); - // ships cannot be both vertical and horizontal - if (isVertical && isHorizontal) { - return null; - } + boolean isHorizontal = + (left != null && BattleshipType.isShip(left.getData())) + || (right != null && BattleshipType.isShip(right.getData())); - // check diagonally adjacent cells - List diagAdjCells - = bsBoard.getAdjDiagonals(cell); + // ships cannot be both vertical and horizontal + if (isVertical && isHorizontal) { + return null; + } - BattleshipCell upRight = diagAdjCells.get(0); - BattleshipCell downRight = diagAdjCells.get(1); - BattleshipCell downLeft = diagAdjCells.get(2); - BattleshipCell upLeft = diagAdjCells.get(3); + // check diagonally adjacent cells + List diagAdjCells = bsBoard.getAdjDiagonals(cell); - // diagonally adjacent cells must be water - if (upRight != null && BattleshipType.isShip(upRight.getData())) { - return null; - } - if (downRight != null && BattleshipType.isShip(downRight.getData())) { - return null; - } - if (downLeft != null && BattleshipType.isShip(downLeft.getData())) { - return null; - } - if (upLeft != null && BattleshipType.isShip(upLeft.getData())) { - return null; - } + BattleshipCell upRight = diagAdjCells.get(0); + BattleshipCell downRight = diagAdjCells.get(1); + BattleshipCell downLeft = diagAdjCells.get(2); + BattleshipCell upLeft = diagAdjCells.get(3); - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + // diagonally adjacent cells must be water + if (upRight != null && BattleshipType.isShip(upRight.getData())) { + return null; + } + if (downRight != null && BattleshipType.isShip(downRight.getData())) { + return null; + } + if (downLeft != null && BattleshipType.isShip(downLeft.getData())) { + return null; } + if (upLeft != null && BattleshipType.isShip(upLeft.getData())) { + return null; + } + + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java index 8b343f5a7..ab9a88525 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java @@ -8,36 +8,37 @@ public class ContinueShipDirectRule extends DirectRule { - public ContinueShipDirectRule() { - super("BTSP-BASC-0001", - "Continue Ship", - "", - "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); - } + public ContinueShipDirectRule() { + super( + "BTSP-BASC-0001", + "Continue Ship", + "", + "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should be overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should be overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java index c2fa6f84a..c4f4432d7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java @@ -9,108 +9,99 @@ import edu.rpi.legup.puzzle.battleship.BattleshipCell; import edu.rpi.legup.puzzle.battleship.BattleshipClue; import edu.rpi.legup.puzzle.battleship.BattleshipType; - import java.awt.*; import java.util.List; public class FinishWithShipsDirectRule extends DirectRule { - public FinishWithShipsDirectRule() { - super("BTSP-BASC-0002", - "Finish with Ships", - "The number of undetermined squares is equal to the number " + - "of segments remaining for each clue.", - "edu/rpi/legup/images/battleship/rules/finishShip.png"); - } + public FinishWithShipsDirectRule() { + super( + "BTSP-BASC-0002", + "Finish with Ships", + "The number of undetermined squares is equal to the number " + + "of segments remaining for each clue.", + "edu/rpi/legup/images/battleship/rules/finishShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should be overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node - * at the specified puzzleElement, otherwise error message. - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, - PuzzleElement puzzleElement) { - BattleshipBoard initBoard = (BattleshipBoard) transition.getParents() - .get(0).getBoard(); - BattleshipCell initCell = (BattleshipCell) initBoard - .getPuzzleElement(puzzleElement); - BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); - BattleshipCell finalCell = (BattleshipCell) finalBoard - .getPuzzleElement(puzzleElement); - if (!(initCell.getType() == BattleshipType.UNKNOWN - && BattleshipType.isShip(finalCell.getType()))) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should be overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message. + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + BattleshipBoard initBoard = (BattleshipBoard) transition.getParents().get(0).getBoard(); + BattleshipCell initCell = (BattleshipCell) initBoard.getPuzzleElement(puzzleElement); + BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); + BattleshipCell finalCell = (BattleshipCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == BattleshipType.UNKNOWN + && BattleshipType.isShip(finalCell.getType()))) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; + } - if (isForced(initBoard, initCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to" + - "be a ship segment."; - } + if (isForced(initBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This cell is not forced to" + + "be a ship segment."; } + } - private boolean isForced(BattleshipBoard board, BattleshipCell cell) { - Point loc = cell.getLocation(); + private boolean isForced(BattleshipBoard board, BattleshipCell cell) { + Point loc = cell.getLocation(); - // count the number of ship segments and unknowns in the row - List row = board.getRow(loc.y); - int rowCount = 0; - for (BattleshipCell c : row) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN - || BattleshipType.isShip(c.getType())) { - rowCount++; - } - } + // count the number of ship segments and unknowns in the row + List row = board.getRow(loc.y); + int rowCount = 0; + for (BattleshipCell c : row) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { + rowCount++; + } + } - // count the number of ship segments and unknowns in the column - List col = board.getColumn(loc.x); - int colCount = 0; - for (BattleshipCell c : col) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN - || BattleshipType.isShip(c.getType())) { - colCount++; - } - } + // count the number of ship segments and unknowns in the column + List col = board.getColumn(loc.x); + int colCount = 0; + for (BattleshipCell c : col) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { + colCount++; + } + } - // compare the counts with the clues - BattleshipClue east = board.getEast().get(loc.y); - BattleshipClue south = board.getSouth().get(loc.x); + // compare the counts with the clues + BattleshipClue east = board.getEast().get(loc.y); + BattleshipClue south = board.getSouth().get(loc.x); - return rowCount <= east.getData() && colCount <= south.getData(); - } + return rowCount <= east.getData() && colCount <= south.getData(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the - * {@link TreeNode}. - * - * @param node tree node used to create default transition board. - * @return default board or null if this rule cannot be applied to this tree - * node. - */ - @Override - public Board getDefaultBoard(TreeNode node) { - BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); - for (PuzzleElement element : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) element; - if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { - cell.setData(BattleshipType.SHIP_UNKNOWN); - board.addModifiedData(cell); - } - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board. + * @return default board or null if this rule cannot be applied to this tree node. + */ + @Override + public Board getDefaultBoard(TreeNode node) { + BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); + for (PuzzleElement element : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) element; + if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { + cell.setData(BattleshipType.SHIP_UNKNOWN); + board.addModifiedData(cell); + } + } - if (board.getModifiedData().isEmpty()) { - return null; - } - else { - return board; - } + if (board.getModifiedData().isEmpty()) { + return null; + } else { + return board; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java index 803548f34..6f32b35a6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java @@ -8,36 +8,37 @@ public class FinishWithWaterDirectRule extends DirectRule { - public FinishWithWaterDirectRule() { - super("BTSP-BASC-0003", - "Finish with Water", - "", - "edu/rpi/legup/images/battleship/rules/finishWater.png"); - } + public FinishWithWaterDirectRule() { + super( + "BTSP-BASC-0003", + "Finish with Water", + "", + "edu/rpi/legup/images/battleship/rules/finishWater.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java index 4a6cb3d15..05ed95fbd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java @@ -6,23 +6,25 @@ public class IncompleteShipContradictionRule extends ContradictionRule { - public IncompleteShipContradictionRule() { - super("BTSP-CONT-0002", - "Incomplete Ship", - "", - "edu/rpi/legup/images/battleship/contradictions/IncompleteShip.png"); - } + public IncompleteShipContradictionRule() { + super( + "BTSP-CONT-0002", + "Incomplete Ship", + "", + "edu/rpi/legup/images/battleship/contradictions/IncompleteShip.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java index 3850ee39f..afc4f8fc0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java @@ -5,63 +5,66 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.List; public class SegmentTypeCaseRule extends CaseRule { - public SegmentTypeCaseRule() { - super("BTSP-CASE-0001", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/cases/SegmentType.png"); - } + public SegmentTypeCaseRule() { + super( + "BTSP-CASE-0001", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/cases/SegmentType.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java index 42b16bb23..f95625e5e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java @@ -8,36 +8,37 @@ public class SegmentTypeDirectRule extends DirectRule { - public SegmentTypeDirectRule() { - super("BTSP-BASC-0004", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); - } + public SegmentTypeDirectRule() { + super( + "BTSP-BASC-0004", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java index f21488cca..3033bafbd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java @@ -5,64 +5,67 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.List; public class ShipLocationCaseRule extends CaseRule { - public ShipLocationCaseRule() { - super("BTSP-CASE-0002", - "Ship Location", - "", - "edu/rpi/legup/images/battleship/cases/ShipLocations.png"); - } + public ShipLocationCaseRule() { + super( + "BTSP-CASE-0002", + "Ship Location", + "", + "edu/rpi/legup/images/battleship/cases/ShipLocations.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java index a419b831f..3696049eb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java @@ -5,64 +5,67 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.List; public class ShipOrWaterCaseRule extends CaseRule { - public ShipOrWaterCaseRule() { - super("BTSP-CASE-0003", - "Ship or Water", - "", - "edu/rpi/legup/images/battleship/cases/ShipOrWater.png"); - } + public ShipOrWaterCaseRule() { + super( + "BTSP-CASE-0003", + "Ship or Water", + "", + "edu/rpi/legup/images/battleship/cases/ShipOrWater.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java index eb7ae1b9a..5a1821be0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java @@ -8,36 +8,37 @@ public class SurroundShipDirectRule extends DirectRule { - public SurroundShipDirectRule() { - super("BTSP-BASC-0005", - "Surround Ship", - "", - "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); - } + public SurroundShipDirectRule() { + super( + "BTSP-BASC-0005", + "Surround Ship", + "", + "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java index 5a4eb187e..a3dbba9c4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java @@ -6,23 +6,25 @@ public class TooFewInFleetContradictionRule extends ContradictionRule { - public TooFewInFleetContradictionRule() { - super("BTSP-CONT-0003", - "Too Few in Fleet", - "", - "edu/rpi/legup/images/battleship/contradictions/too_few_in_fleet.png"); - } + public TooFewInFleetContradictionRule() { + super( + "BTSP-CONT-0003", + "Too Few in Fleet", + "", + "edu/rpi/legup/images/battleship/contradictions/too_few_in_fleet.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java index 7c2fa7819..b4814796d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java @@ -6,23 +6,25 @@ public class TooFewRowColContradictionRule extends ContradictionRule { - public TooFewRowColContradictionRule() { - super("BTSP-CONT-0004", - "Too few in row/col", - "", - "edu/rpi/legup/images/battleship/contradictions/too_few_segments.png"); - } + public TooFewRowColContradictionRule() { + super( + "BTSP-CONT-0004", + "Too few in row/col", + "", + "edu/rpi/legup/images/battleship/contradictions/too_few_segments.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java index 3aad88613..a375b63e2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java @@ -6,23 +6,25 @@ public class TooManyInFleetContradictionRule extends ContradictionRule { - public TooManyInFleetContradictionRule() { - super("BTSP-CONT-0005", - "Too Many in Fleet", - "", - "edu/rpi/legup/images/battleship/contradictions/too_many_in_fleet.png"); - } + public TooManyInFleetContradictionRule() { + super( + "BTSP-CONT-0005", + "Too Many in Fleet", + "", + "edu/rpi/legup/images/battleship/contradictions/too_many_in_fleet.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java index 0970c9c69..abb72b5ca 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java @@ -6,23 +6,25 @@ public class TooManyRowColContradiction extends ContradictionRule { - public TooManyRowColContradiction() { - super("BTSP-CONT-0006", - "Too Many row/col", - "", - "edu/rpi/legup/images/battleship/contradictions/too_many_segments.png"); - } + public TooManyRowColContradiction() { + super( + "BTSP-CONT-0006", + "Too Many row/col", + "", + "edu/rpi/legup/images/battleship/contradictions/too_many_segments.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java index ef78f66aa..28d2a2790 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java @@ -6,66 +6,60 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Fillapix extends Puzzle { - /** - * Fillapix Constructor - */ - public Fillapix() { - super(); + /** Fillapix Constructor */ + public Fillapix() { + super(); - this.name = "Fillapix"; + this.name = "Fillapix"; - this.importer = new FillapixImporter(this); - this.exporter = new FillapixExporter(this); + this.importer = new FillapixImporter(this); + this.exporter = new FillapixExporter(this); - this.factory = new FillapixCellFactory(); - } + this.factory = new FillapixCellFactory(); + } - /** - * Initializes the game board - */ - @Override - public void initializeView() { - boardView = new FillapixView((FillapixBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board */ + @Override + public void initializeView() { + boardView = new FillapixView((FillapixBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Fillapix - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Fillapix, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return super.isValidDimensions(rows, columns); - } + @Override + /** + * Determines if the given dimensions are valid for Fillapix + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Fillapix, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return super.isValidDimensions(rows, columns); + } - @Override - public boolean isBoardComplete(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(fillapixBoard) == null) { - return false; - } - } - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN) { - return false; - } - } - return true; + @Override + public boolean isBoardComplete(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(fillapixBoard) == null) { + return false; + } } - - @Override - public void onBoardChange(Board board) { - + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN) { + return false; + } } -} \ No newline at end of file + return true; + } + + @Override + public void onBoardChange(Board board) {} +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java index 67987a6fd..eaf408fcd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java @@ -2,67 +2,66 @@ import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.*; import java.util.logging.Logger; public class FillapixBoard extends GridBoard { - private final static Logger LOGGER = Logger.getLogger(FillapixBoard.class.getName()); + private static final Logger LOGGER = Logger.getLogger(FillapixBoard.class.getName()); - public FillapixBoard(int width, int height) { - super(width, height); - } + public FillapixBoard(int width, int height) { + super(width, height); + } - public FillapixBoard(int size) { - this(size, size); - } + public FillapixBoard(int size) { + this(size, size); + } - public FillapixCell getCell(int x, int y) { - return (FillapixCell) super.getCell(x, y); - } + public FillapixCell getCell(int x, int y) { + return (FillapixCell) super.getCell(x, y); + } - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - @Override - public FillapixBoard copy() { - FillapixBoard copy = new FillapixBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + @Override + public FillapixBoard copy() { + FillapixBoard copy = new FillapixBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } - /** - * Finds the number of cells that match the specified type around and on a particular cell - * - * @param cell the cell we're looking around - * @param type the CellState whether it's black, white, or unknown - * @return integer number of cells that match specified type - */ - public int getNumCells(FillapixCell cell, FillapixCellType type) { - Point loc = cell.getLocation(); + /** + * Finds the number of cells that match the specified type around and on a particular cell + * + * @param cell the cell we're looking around + * @param type the CellState whether it's black, white, or unknown + * @return integer number of cells that match specified type + */ + public int getNumCells(FillapixCell cell, FillapixCellType type) { + Point loc = cell.getLocation(); - int numCells = 0; - for (int i = -1; i < 2; i++) { - for (int j = -1; j < 2; j++) { - if (loc.x + i > dimension.width || loc.y + j > dimension.height) { - continue; - } - FillapixCell c = getCell(loc.x + i, loc.y + j); - if (c != null && c.getType() == type) { - numCells++; - } - } + int numCells = 0; + for (int i = -1; i < 2; i++) { + for (int j = -1; j < 2; j++) { + if (loc.x + i > dimension.width || loc.y + j > dimension.height) { + continue; } - - return numCells; + FillapixCell c = getCell(loc.x + i, loc.y + j); + if (c != null && c.getType() == type) { + numCells++; + } + } } + + return numCells; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java index 5e6d4b9ed..5051eecdf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java @@ -2,103 +2,103 @@ import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.GridCell; - import java.awt.*; import java.awt.event.MouseEvent; import java.util.Objects; public class FillapixCell extends GridCell implements Comparable { - public static final int DEFAULT_VALUE = 10; + public static final int DEFAULT_VALUE = 10; - public FillapixCell(int value, Point location) { - super(value, location); - } + public FillapixCell(int value, Point location) { + super(value, location); + } - public int getNumber() { - int temp = (data % 100); - return temp == 10 ? -1 : temp; - } + public int getNumber() { + int temp = (data % 100); + return temp == 10 ? -1 : temp; + } - public void setNumber(int number) { - int temp = number == -1 ? 10 : number; - data = (data / 100) * 100 + temp; - } + public void setNumber(int number) { + int temp = number == -1 ? 10 : number; + data = (data / 100) * 100 + temp; + } - public FillapixCellType getType() { - switch (data / 100) { - case 0: - return FillapixCellType.UNKNOWN; - case 1: - return FillapixCellType.BLACK; - default: - return FillapixCellType.WHITE; - } + public FillapixCellType getType() { + switch (data / 100) { + case 0: + return FillapixCellType.UNKNOWN; + case 1: + return FillapixCellType.BLACK; + default: + return FillapixCellType.WHITE; } + } - public void setCellType(FillapixCellType type) { - data = type.value * 100 + (data % 100); - } + public void setCellType(FillapixCellType type) { + data = type.value * 100 + (data % 100); + } - @Override - public void setType(Element e, MouseEvent m) { - switch(e.getElementID()) { - case "FPIX-PLAC-0001": - this.setCellType(FillapixCellType.BLACK); - break; - case "FPIX-PLAC-0002": - this.setCellType(FillapixCellType.WHITE); - break; - case "FPIX-UNPL-0001": - int n = this.getNumber(); - switch (m.getButton()) { - case MouseEvent.BUTTON1: - n++; - break; - case MouseEvent.BUTTON3: - n--; - break; - } - if (n > 9) { - n = 0; - } - if (n < 0) { - n = 9; - } - this.setNumber(n); - break; - default: - this.setCellType(FillapixCellType.UNKNOWN); - this.data = -1; - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "FPIX-PLAC-0001": + this.setCellType(FillapixCellType.BLACK); + break; + case "FPIX-PLAC-0002": + this.setCellType(FillapixCellType.WHITE); + break; + case "FPIX-UNPL-0001": + int n = this.getNumber(); + switch (m.getButton()) { + case MouseEvent.BUTTON1: + n++; + break; + case MouseEvent.BUTTON3: + n--; + break; } + if (n > 9) { + n = 0; + } + if (n < 0) { + n = 9; + } + this.setNumber(n); + break; + default: + this.setCellType(FillapixCellType.UNKNOWN); + this.data = -1; + break; } + } - /** - * Performs a deep copy on the FillapixCell - * - * @return a new copy of the FillapixCell that is independent of this one - */ - @Override - public FillapixCell copy() { - FillapixCell cell = new FillapixCell(data, (Point) location.clone()); - cell.setIndex(index); - cell.setModifiable(isModifiable); - return cell; - } + /** + * Performs a deep copy on the FillapixCell + * + * @return a new copy of the FillapixCell that is independent of this one + */ + @Override + public FillapixCell copy() { + FillapixCell cell = new FillapixCell(data, (Point) location.clone()); + cell.setIndex(index); + cell.setModifiable(isModifiable); + return cell; + } - public boolean equals(FillapixCell otherCell) { -// return this.location.equals(otherCell.location) && this.index == otherCell.index && this.data == otherCell.data; - //return this.index == otherCell.index && this.data == otherCell.data; - //return this.index == otherCell.index; - return this.location.x == otherCell.location.x && this.location.y == otherCell.location.y; - } + public boolean equals(FillapixCell otherCell) { + // return this.location.equals(otherCell.location) && this.index == otherCell.index && + // this.data == otherCell.data; + // return this.index == otherCell.index && this.data == otherCell.data; + // return this.index == otherCell.index; + return this.location.x == otherCell.location.x && this.location.y == otherCell.location.y; + } - public int compareTo(FillapixCell otherCell) { - return this.index - otherCell.index; - } + public int compareTo(FillapixCell otherCell) { + return this.index - otherCell.index; + } - public int hashCode() { - return Objects.hash(this.index); - } -} \ No newline at end of file + public int hashCode() { + return Objects.hash(this.index); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java index df3bba403..45182c88f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java @@ -2,49 +2,47 @@ import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.event.MouseEvent; public class FillapixCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement puzzleElement) { - FillapixCell cell = (FillapixCell) puzzleElement; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView.getSelectionPopupMenu().show(boardView, this.boardView.getCanvas().getX() + e.getX(), this.boardView.getCanvas().getY() + e.getY()); - } - else { - if (cell.getType() == FillapixCellType.UNKNOWN) { - cell.setCellType(FillapixCellType.BLACK); - } - else { - if (cell.getType() == FillapixCellType.BLACK) { - cell.setCellType(FillapixCellType.WHITE); - } - else { - if (cell.getType() == FillapixCellType.WHITE) { - cell.setCellType(FillapixCellType.UNKNOWN); - } - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement puzzleElement) { + FillapixCell cell = (FillapixCell) puzzleElement; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getType() == FillapixCellType.UNKNOWN) { + cell.setCellType(FillapixCellType.BLACK); + } else { + if (cell.getType() == FillapixCellType.BLACK) { + cell.setCellType(FillapixCellType.WHITE); + } else { + if (cell.getType() == FillapixCellType.WHITE) { + cell.setCellType(FillapixCellType.UNKNOWN); } + } } - else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getType() == FillapixCellType.UNKNOWN) { - cell.setCellType(FillapixCellType.WHITE); - } - else { - if (cell.getType() == FillapixCellType.BLACK) { - cell.setCellType(FillapixCellType.UNKNOWN); - } - else { - if (cell.getType() == FillapixCellType.WHITE) { - cell.setCellType(FillapixCellType.BLACK); - } - } - } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getType() == FillapixCellType.UNKNOWN) { + cell.setCellType(FillapixCellType.WHITE); + } else { + if (cell.getType() == FillapixCellType.BLACK) { + cell.setCellType(FillapixCellType.UNKNOWN); + } else { + if (cell.getType() == FillapixCellType.WHITE) { + cell.setCellType(FillapixCellType.BLACK); } + } } + } } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java index fcc48bccd..37b4130b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java @@ -4,72 +4,71 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class FillapixCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public FillapixCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Fillapix Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public FillapixCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Fillapix Factory: unknown puzzleElement puzzleElement"); + } - FillapixBoard fillapixBoard = (FillapixBoard) board; - int width = fillapixBoard.getWidth(); - int height = fillapixBoard.getHeight(); + FillapixBoard fillapixBoard = (FillapixBoard) board; + int width = fillapixBoard.getWidth(); + int height = fillapixBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Fillapix Factory: cell location out of bounds"); - } - if (value / 100 > 2 || value % 100 > 10) { - throw new InvalidFileFormatException("Fillapix Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("Fillapix Factory: cell location out of bounds"); + } + if (value / 100 > 2 || value % 100 > 10) { + throw new InvalidFileFormatException("Fillapix Factory: cell unknown value"); + } - FillapixCell cell = new FillapixCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Fillapix Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("Fillapix Factory: could not find attribute(s)"); - } + FillapixCell cell = new FillapixCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Fillapix Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Fillapix Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - FillapixCell cell = (FillapixCell) puzzleElement; - Point loc = cell.getLocation(); + FillapixCell cell = (FillapixCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java index 3789fe339..659cebb1b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java @@ -1,15 +1,17 @@ package edu.rpi.legup.puzzle.fillapix; public enum FillapixCellType { - UNKNOWN(0), BLACK(1), WHITE(2); + UNKNOWN(0), + BLACK(1), + WHITE(2); - public int value; + public int value; - FillapixCellType(int value) { - this.value = value; - } + FillapixCellType(int value) { + this.value = value; + } - public String toString() { - return super.toString().toLowerCase(); - } + public String toString() { + return super.toString().toLowerCase(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java index 93fa0d451..97b864bc9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java @@ -1,62 +1,61 @@ package edu.rpi.legup.puzzle.fillapix; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; public class FillapixElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); - public FillapixElementView(FillapixCell cell) { - super(cell); - } + public FillapixElementView(FillapixCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public FillapixCell getPuzzleElement() { - return (FillapixCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public FillapixCell getPuzzleElement() { + return (FillapixCell) super.getPuzzleElement(); + } - /** - * Draws the fillapix puzzleElement to the screen - * - * @param graphics2D graphics object - */ - @Override - public void drawElement(Graphics2D graphics2D) { - FillapixCell cell = (FillapixCell) puzzleElement; - FillapixCellType type = cell.getType(); - graphics2D.setStroke(new BasicStroke(1)); - switch (type) { - case UNKNOWN: - graphics2D.setColor(GRAY_COLOR); - break; - case BLACK: - graphics2D.setColor(BLACK_COLOR); - break; - default: - graphics2D.setColor(WHITE_COLOR); - break; - } - graphics2D.fillRect(location.x, location.y, size.width, size.height); - if (cell.getNumber() >= 0 && cell.getNumber() < 10) { - graphics2D.setColor(type == FillapixCellType.WHITE ? BLACK_COLOR : WHITE_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getNumber()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + /** + * Draws the fillapix puzzleElement to the screen + * + * @param graphics2D graphics object + */ + @Override + public void drawElement(Graphics2D graphics2D) { + FillapixCell cell = (FillapixCell) puzzleElement; + FillapixCellType type = cell.getType(); + graphics2D.setStroke(new BasicStroke(1)); + switch (type) { + case UNKNOWN: + graphics2D.setColor(GRAY_COLOR); + break; + case BLACK: graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + break; + default: + graphics2D.setColor(WHITE_COLOR); + break; + } + graphics2D.fillRect(location.x, location.y, size.width, size.height); + if (cell.getNumber() >= 0 && cell.getNumber() < 10) { + graphics2D.setColor(type == FillapixCellType.WHITE ? BLACK_COLOR : WHITE_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getNumber()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); } -} \ No newline at end of file + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java index 757d14cd8..1df8157cf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java @@ -2,39 +2,38 @@ import edu.rpi.legup.model.PuzzleExporter; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import org.w3c.dom.Document; public class FillapixExporter extends PuzzleExporter { - public FillapixExporter(Fillapix fillapix) { - super(fillapix); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - FillapixBoard board; - if (puzzle.getTree() != null) { - board = (FillapixBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (FillapixBoard) puzzle.getBoardView().getBoard(); - } + public FillapixExporter(Fillapix fillapix) { + super(fillapix); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + FillapixBoard board; + if (puzzle.getTree() != null) { + board = (FillapixBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (FillapixBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) puzzleElement; - if (cell.getNumber() != -1 || cell.getType() != FillapixCellType.UNKNOWN) { - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) puzzleElement; + if (cell.getNumber() != -1 || cell.getType() != FillapixCellType.UNKNOWN) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java index 5213e7139..5877fd25b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java @@ -2,116 +2,116 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.awt.*; - public class FillapixImporter extends PuzzleImporter { - public FillapixImporter(Fillapix fillapix) { - super(fillapix); - } + public FillapixImporter(Fillapix fillapix) { + super(fillapix); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be made - */ - @Override - public void initializeBoard(int rows, int columns) { - FillapixBoard fillapixBoard = new FillapixBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be made + */ + @Override + public void initializeBoard(int rows, int columns) { + FillapixBoard fillapixBoard = new FillapixBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - FillapixCell cell = new FillapixCell(FillapixCellType.UNKNOWN.value, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setNumber(FillapixCell.DEFAULT_VALUE); - cell.setModifiable(true); - fillapixBoard.setCell(x, y, cell); - } - } - puzzle.setCurrentBoard(fillapixBoard); + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + FillapixCell cell = new FillapixCell(FillapixCellType.UNKNOWN.value, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setNumber(FillapixCell.DEFAULT_VALUE); + cell.setModifiable(true); + fillapixBoard.setCell(x, y, cell); + } } + puzzle.setCurrentBoard(fillapixBoard); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Fillapix Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Fillapix Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("Fillapix Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("Fillapix Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - FillapixBoard fillapixBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - fillapixBoard = new FillapixBoard(size); - } - else { - if (!boardElement.getAttribute("width").isEmpty() && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - fillapixBoard = new FillapixBoard(width, height); - } - } + FillapixBoard fillapixBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + fillapixBoard = new FillapixBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + fillapixBoard = new FillapixBoard(width, height); + } + } - if (fillapixBoard == null) { - throw new InvalidFileFormatException("Fillapix Importer: invalid board dimensions"); - } + if (fillapixBoard == null) { + throw new InvalidFileFormatException("Fillapix Importer: invalid board dimensions"); + } - int width = fillapixBoard.getWidth(); - int height = fillapixBoard.getHeight(); + int width = fillapixBoard.getWidth(); + int height = fillapixBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - FillapixCell cell = (FillapixCell) puzzle.getFactory().importCell(elementDataList.item(i), fillapixBoard); - Point loc = cell.getLocation(); - cell.setModifiable(true); - cell.setGiven(true); - fillapixBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + FillapixCell cell = + (FillapixCell) puzzle.getFactory().importCell(elementDataList.item(i), fillapixBoard); + Point loc = cell.getLocation(); + cell.setModifiable(true); + cell.setGiven(true); + fillapixBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (fillapixBoard.getCell(x, y) == null) { - FillapixCell cell = new FillapixCell(FillapixCell.DEFAULT_VALUE, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - fillapixBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(fillapixBoard); - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Fillapix Importer: unknown value where integer expected"); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (fillapixBoard.getCell(x, y) == null) { + FillapixCell cell = new FillapixCell(FillapixCell.DEFAULT_VALUE, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + fillapixBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(fillapixBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Fillapix Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Fillapix cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Fillapix cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java index a7feac91d..6eeb4bd25 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java @@ -3,204 +3,236 @@ import edu.rpi.legup.model.rules.ContradictionRule; import edu.rpi.legup.puzzle.fillapix.rules.TooFewBlackCellsContradictionRule; import edu.rpi.legup.puzzle.fillapix.rules.TooManyBlackCellsContradictionRule; - import java.awt.*; import java.util.ArrayList; public class FillapixUtilities { - public static boolean isForcedBlack(FillapixBoard board, FillapixCell cell) { - TooFewBlackCellsContradictionRule tooManyBlackCells = new TooFewBlackCellsContradictionRule(); - FillapixBoard whiteCaseBoard = board.copy(); - FillapixCell whiteCell = (FillapixCell) whiteCaseBoard.getPuzzleElement(cell); - whiteCell.setCellType(FillapixCellType.WHITE); - ArrayList adjCells = getAdjacentCells(whiteCaseBoard, whiteCell); - for (FillapixCell adjCell : adjCells) { - if (tooManyBlackCells.checkContradictionAt(whiteCaseBoard, adjCell) == null) { - return true; - } - } - return false; + public static boolean isForcedBlack(FillapixBoard board, FillapixCell cell) { + TooFewBlackCellsContradictionRule tooManyBlackCells = new TooFewBlackCellsContradictionRule(); + FillapixBoard whiteCaseBoard = board.copy(); + FillapixCell whiteCell = (FillapixCell) whiteCaseBoard.getPuzzleElement(cell); + whiteCell.setCellType(FillapixCellType.WHITE); + ArrayList adjCells = getAdjacentCells(whiteCaseBoard, whiteCell); + for (FillapixCell adjCell : adjCells) { + if (tooManyBlackCells.checkContradictionAt(whiteCaseBoard, adjCell) == null) { + return true; + } } + return false; + } - public static boolean isForcedWhite(FillapixBoard board, FillapixCell cell) { - TooManyBlackCellsContradictionRule tooManyBlackCells = new TooManyBlackCellsContradictionRule(); - FillapixBoard blackCaseBoard = board.copy(); - FillapixCell blackCell = (FillapixCell) blackCaseBoard.getPuzzleElement(cell); - blackCell.setCellType(FillapixCellType.BLACK); - ArrayList adjCells = getAdjacentCells(blackCaseBoard, blackCell); - for (FillapixCell adjCell : adjCells) { - if (tooManyBlackCells.checkContradictionAt(blackCaseBoard, adjCell) == null) { - return true; - } - } - return false; + public static boolean isForcedWhite(FillapixBoard board, FillapixCell cell) { + TooManyBlackCellsContradictionRule tooManyBlackCells = new TooManyBlackCellsContradictionRule(); + FillapixBoard blackCaseBoard = board.copy(); + FillapixCell blackCell = (FillapixCell) blackCaseBoard.getPuzzleElement(cell); + blackCell.setCellType(FillapixCellType.BLACK); + ArrayList adjCells = getAdjacentCells(blackCaseBoard, blackCell); + for (FillapixCell adjCell : adjCells) { + if (tooManyBlackCells.checkContradictionAt(blackCaseBoard, adjCell) == null) { + return true; + } } + return false; + } - public static boolean isComplete(FillapixBoard board, FillapixCell cell) { - int cellNum = cell.getNumber(); - int cellTouchBlack = 0; - ArrayList adjCells = getAdjacentCells(board, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - cellTouchBlack++; - } - } - return cellNum == cellTouchBlack; + public static boolean isComplete(FillapixBoard board, FillapixCell cell) { + int cellNum = cell.getNumber(); + int cellTouchBlack = 0; + ArrayList adjCells = getAdjacentCells(board, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + cellTouchBlack++; + } } + return cellNum == cellTouchBlack; + } - public static boolean hasEmptyAdjacent(FillapixBoard board, FillapixCell cell) { - ArrayList adjCells = getAdjacentCells(board, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - return true; - } - } - return false; + public static boolean hasEmptyAdjacent(FillapixBoard board, FillapixCell cell) { + ArrayList adjCells = getAdjacentCells(board, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + return true; + } } + return false; + } - /** - * Gets all cells adjacent to a specific cell. The cell itself will be included. - */ - public static ArrayList getAdjacentCells(FillapixBoard board, FillapixCell cell) { - ArrayList adjCells = new ArrayList(); - Point cellLoc = cell.getLocation(); - for (int i=-1; i <= 1; i++) { - for (int j=-1; j <= 1; j++) { - if (cellLoc.getX() + i < 0 || cellLoc.y + j < 0 || cellLoc.x + i >= board.getWidth() || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } + /** Gets all cells adjacent to a specific cell. The cell itself will be included. */ + public static ArrayList getAdjacentCells(FillapixBoard board, FillapixCell cell) { + ArrayList adjCells = new ArrayList(); + Point cellLoc = cell.getLocation(); + for (int i = -1; i <= 1; i++) { + for (int j = -1; j <= 1; j++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; } - return adjCells; + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } } + return adjCells; + } - /** - * Gets all cells that are contained in the square defined as having 'distance' - * cells between the center and the outer wall. For example, distance = 1:

- * |X|X|X|X|X|

- * |X| | | |X|

- * |X| |O| |X|

- * |X| | | |X|

- * |X|X|X|X|X|

- * O is 'cell', and all 'X' will be returned in the ArrayList - */ - public static ArrayList getCellsAtDistance(FillapixBoard board, FillapixCell cell, int distance) { - ArrayList adjCells = new ArrayList(); - Point cellLoc = cell.getLocation(); - int i = 0, j = 0; - // top line - for (i = cellLoc.x - (distance), j = cellLoc.y - (distance+1); i <= cellLoc.x + (distance+1); i++) { - if (cellLoc.getX() + i < 0 || cellLoc.y + j < 0 || cellLoc.x + i >= board.getWidth() || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // right line - for (i = cellLoc.x + (distance+1), j = cellLoc.y - (distance); j <= cellLoc.y + (distance+1); j++) { - if (cellLoc.getX() + i < 0 || cellLoc.y + j < 0 || cellLoc.x + i >= board.getWidth() || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // bottom line - for (i = cellLoc.x + (distance), j = cellLoc.y + (distance+1); i <= cellLoc.x - (distance+1); i--) { - if (cellLoc.getX() + i < 0 || cellLoc.y + j < 0 || cellLoc.x + i >= board.getWidth() || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // left line - for (i = cellLoc.x - (distance+1), j = cellLoc.y + (distance); j <= cellLoc.y - (distance+1); j--) { - if (cellLoc.getX() + i < 0 || cellLoc.y + j < 0 || cellLoc.x + i >= board.getWidth() || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } + /** + * Gets all cells that are contained in the square defined as having 'distance' cells between the + * center and the outer wall. For example, distance = 1: + * + *

|X|X|X|X|X| + * + *

|X| | | |X| + * + *

|X| |O| |X| + * + *

|X| | | |X| + * + *

|X|X|X|X|X| + * + *

O is 'cell', and all 'X' will be returned in the ArrayList + */ + public static ArrayList getCellsAtDistance( + FillapixBoard board, FillapixCell cell, int distance) { + ArrayList adjCells = new ArrayList(); + Point cellLoc = cell.getLocation(); + int i = 0, j = 0; + // top line + for (i = cellLoc.x - (distance), j = cellLoc.y - (distance + 1); + i <= cellLoc.x + (distance + 1); + i++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // right line + for (i = cellLoc.x + (distance + 1), j = cellLoc.y - (distance); + j <= cellLoc.y + (distance + 1); + j++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // bottom line + for (i = cellLoc.x + (distance), j = cellLoc.y + (distance + 1); + i <= cellLoc.x - (distance + 1); + i--) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // left line + for (i = cellLoc.x - (distance + 1), j = cellLoc.y + (distance); + j <= cellLoc.y - (distance + 1); + j--) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } - return adjCells; - } + return adjCells; + } - /** - * Finds all possible combinations of chosenNumObj items can be - * chosen from totalNumObj total items. - * For example, if 1 item is chosen from 2 possible items, the combinations - * are: - *

[ [true,false], [false,true] ]
- * - * @param totalNumItems the total number of items that can possibly be chosen - * @param chosenNumItems the number of items to be chosen - * - * @return an ArrayList of Boolean arrays. Each index in the ArrayList represents - * a distinct combination. Each Boolean array will be totalNumItems - * long and each index will be true if the corresponding item is - * included in that combination, and false otherwise. - */ - public static ArrayList getCombinations(int chosenNumItems, int totalNumItems) { - ArrayList combinations = new ArrayList(); + /** + * Finds all possible combinations of chosenNumObj items can be chosen from + * totalNumObj total items. For example, if 1 item is chosen from 2 possible items, the + * combinations are: + * + *
[ [true,false], [false,true] ]
+ * + * @param totalNumItems the total number of items that can possibly be chosen + * @param chosenNumItems the number of items to be chosen + * @return an ArrayList of Boolean arrays. Each index in the ArrayList represents a distinct + * combination. Each Boolean array will be totalNumItems long and each index will + * be true if the corresponding item is included in that combination, and + * false otherwise. + */ + public static ArrayList getCombinations(int chosenNumItems, int totalNumItems) { + ArrayList combinations = new ArrayList(); - // calculate all combinations - boolean[] array = new boolean[totalNumItems]; - recurseCombinations(combinations, 0, chosenNumItems, 0, totalNumItems, array); + // calculate all combinations + boolean[] array = new boolean[totalNumItems]; + recurseCombinations(combinations, 0, chosenNumItems, 0, totalNumItems, array); - return combinations; - } + return combinations; + } - private static void recurseCombinations(ArrayList result, int curIndex, int maxBlack, int numBlack, int len, boolean[] workingArray) { - if (curIndex == len) { - // complete, but not valid solution - if (numBlack != maxBlack) { - return; - } - // complete and valid solution - result.add(workingArray.clone()); - return; - } - // there is no chance of completing the required number of solutions, so quit - if (len - curIndex < maxBlack - numBlack) { - return; - } + private static void recurseCombinations( + ArrayList result, + int curIndex, + int maxBlack, + int numBlack, + int len, + boolean[] workingArray) { + if (curIndex == len) { + // complete, but not valid solution + if (numBlack != maxBlack) { + return; + } + // complete and valid solution + result.add(workingArray.clone()); + return; + } + // there is no chance of completing the required number of solutions, so quit + if (len - curIndex < maxBlack - numBlack) { + return; + } - if (numBlack < maxBlack) { - workingArray[curIndex] = true; - recurseCombinations(result, curIndex+1, maxBlack, numBlack+1, len, workingArray); - } - workingArray[curIndex] = false; - recurseCombinations(result, curIndex+1, maxBlack, numBlack, len, workingArray); + if (numBlack < maxBlack) { + workingArray[curIndex] = true; + recurseCombinations(result, curIndex + 1, maxBlack, numBlack + 1, len, workingArray); } - - public static boolean checkBoardForContradiction(FillapixBoard board) { - ContradictionRule tooManyBlack = new TooManyBlackCellsContradictionRule(); - ContradictionRule tooManyWhite = new TooFewBlackCellsContradictionRule(); - for (int i= 0; i < board.getWidth(); i++) { - for (int j=0; j < board.getHeight(); j++) { - if (tooManyBlack.checkContradictionAt(board, board.getCell(i, j)) == null || - tooManyWhite.checkContradictionAt(board, board.getCell(i, j)) == null) { - return true; - } - } + workingArray[curIndex] = false; + recurseCombinations(result, curIndex + 1, maxBlack, numBlack, len, workingArray); + } + + public static boolean checkBoardForContradiction(FillapixBoard board) { + ContradictionRule tooManyBlack = new TooManyBlackCellsContradictionRule(); + ContradictionRule tooManyWhite = new TooFewBlackCellsContradictionRule(); + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + if (tooManyBlack.checkContradictionAt(board, board.getCell(i, j)) == null + || tooManyWhite.checkContradictionAt(board, board.getCell(i, j)) == null) { + return true; } - return false; + } } + return false; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java index 7e6453f58..eea7c7a4d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java @@ -3,21 +3,20 @@ import edu.rpi.legup.controller.BoardController; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.ui.boardview.GridBoardView; - import java.awt.*; public class FillapixView extends GridBoardView { - public FillapixView(FillapixBoard board) { - super(new BoardController(), new FillapixCellController(), board.getDimension()); + public FillapixView(FillapixBoard board) { + super(new BoardController(), new FillapixCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) puzzleElement; - Point loc = cell.getLocation(); - FillapixElementView elementView = new FillapixElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) puzzleElement; + Point loc = cell.getLocation(); + FillapixElementView elementView = new FillapixElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java index 7e43fc6b4..ce4ba520c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BlackTile extends PlaceableElement { - public BlackTile() { - super("FPIX-PLAC-0001", "Black Tile", "The black tile", "edu/rpi/legup/images/fillapix/tiles/BlackTile.png"); - } + public BlackTile() { + super( + "FPIX-PLAC-0001", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/fillapix/tiles/BlackTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java index beee70e21..0b76b1b57 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java @@ -3,25 +3,28 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super("FPIX-UNPL-0001", "Number Tile", "A numbered tile", "edu/rpi/legup/images/fillapix/tiles/NumberTile.png"); - object_num = 0; - } + public NumberTile() { + super( + "FPIX-UNPL-0001", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/fillapix/tiles/NumberTile.png"); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } - - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java index ef754782f..25104eb60 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super("FPIX-UNPL-0002", "Unknown Tile", "A blank tile", "edu/rpi/legup/images/fillapix/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "FPIX-UNPL-0002", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/fillapix/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java index dd27d2834..935c9bc1b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class WhiteTile extends PlaceableElement { - public WhiteTile() { - super("FPIX-PLAC-0002", "White Tile", "The white tile", "edu/rpi/legup/images/fillapix/tiles/WhiteTile.png"); - } + public WhiteTile() { + super( + "FPIX-PLAC-0002", + "White Tile", + "The white tile", + "edu/rpi/legup/images/fillapix/tiles/WhiteTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java index 1e5151c48..02699327e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java @@ -8,81 +8,85 @@ import edu.rpi.legup.puzzle.fillapix.FillapixBoard; import edu.rpi.legup.puzzle.fillapix.FillapixCell; import edu.rpi.legup.puzzle.fillapix.FillapixCellType; - import java.util.ArrayList; import java.util.List; public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super("FPIX-CASE-0001", - "Black or White", - "Each cell is either black or white.", - "edu/rpi/legup/images/fillapix/cases/BlackOrWhite.png"); - } + public BlackOrWhiteCaseRule() { + super( + "FPIX-CASE-0001", + "Black or White", + "Each cell is either black or white.", + "edu/rpi/legup/images/fillapix/cases/BlackOrWhite.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); - fillapixBoard.setModifiable(false); - for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) data; - if (cell.getType() == FillapixCellType.UNKNOWN) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); + fillapixBoard.setModifiable(false); + for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) data; + if (cell.getType() == FillapixCellType.UNKNOWN) { + caseBoard.addPickableElement(data); + } } + return caseBoard; + } - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - - Board case1 = board.copy(); - FillapixCell cell1 = (FillapixCell) case1.getPuzzleElement(puzzleElement); - cell1.setCellType(FillapixCellType.BLACK); - case1.addModifiedData(cell1); - cases.add(case1); + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); - Board case2 = board.copy(); - FillapixCell cell2 = (FillapixCell) case2.getPuzzleElement(puzzleElement); - cell2.setCellType(FillapixCellType.WHITE); - case2.addModifiedData(cell2); - cases.add(case2); - - return cases; - } + Board case1 = board.copy(); + FillapixCell cell1 = (FillapixCell) case1.getPuzzleElement(puzzleElement); + cell1.setCellType(FillapixCellType.BLACK); + case1.addModifiedData(cell1); + cases.add(case1); - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; - } + Board case2 = board.copy(); + FillapixCell cell2 = (FillapixCell) case2.getPuzzleElement(puzzleElement); + cell2.setCellType(FillapixCellType.WHITE); + case2.addModifiedData(cell2); + cases.add(case2); - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 || - case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 1 modified cell for each case."; - } + return cases; + } - FillapixCell mod1 = (FillapixCell) case1.getBoard().getModifiedData().iterator().next(); - FillapixCell mod2 = (FillapixCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must modify the same cell for each case."; - } + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - if (!((mod1.getType() == FillapixCellType.BLACK && mod2.getType() == FillapixCellType.WHITE) - || (mod2.getType() == FillapixCellType.BLACK && mod1.getType() == FillapixCellType.WHITE))) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must an empty cell and a lit cell."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - return null; + FillapixCell mod1 = (FillapixCell) case1.getBoard().getModifiedData().iterator().next(); + FillapixCell mod2 = (FillapixCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; + if (!((mod1.getType() == FillapixCellType.BLACK && mod2.getType() == FillapixCellType.WHITE) + || (mod2.getType() == FillapixCellType.BLACK + && mod1.getType() == FillapixCellType.WHITE))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty cell and a lit cell."; } -} \ No newline at end of file + + return null; + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java index c9f26befd..da0ccb057 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java @@ -11,53 +11,55 @@ import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; public class FinishWithBlackDirectRule extends DirectRule { - public FinishWithBlackDirectRule() { - super("FPIX-BASC-0001", - "Finish with Black", - "The remaining unknowns around and on a cell must be black to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); - } + public FinishWithBlackDirectRule() { + super( + "FPIX-BASC-0001", + "Finish with Black", + "The remaining unknowns around and on a cell must be black to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == FillapixCellType.UNKNOWN && cell.getType() == FillapixCellType.BLACK)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be black to be applicable with this rule."; - } + if (!(parentCell.getType() == FillapixCellType.UNKNOWN + && cell.getType() == FillapixCellType.BLACK)) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must be black to be applicable with this rule."; + } - if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; - } + if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.BLACK); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return fillapixBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN + && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.BLACK); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } else { + return fillapixBoard; } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java index 13f0e4aa0..0d8423c0c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java @@ -11,53 +11,55 @@ import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; public class FinishWithWhiteDirectRule extends DirectRule { - public FinishWithWhiteDirectRule() { - super("FPIX-BASC-0002", - "Finish with White", - "The remaining unknowns around and on a cell must be white to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); - } + public FinishWithWhiteDirectRule() { + super( + "FPIX-BASC-0002", + "Finish with White", + "The remaining unknowns around and on a cell must be white to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == FillapixCellType.UNKNOWN && cell.getType() == FillapixCellType.WHITE)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be white to be applicable with this rule"; - } + if (!(parentCell.getType() == FillapixCellType.UNKNOWN + && cell.getType() == FillapixCellType.WHITE)) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must be white to be applicable with this rule"; + } - if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; - } + if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.WHITE); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return fillapixBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN + && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.WHITE); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } else { + return fillapixBoard; } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java index a9e6f85ae..f38c8179e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java @@ -1,9 +1,5 @@ package edu.rpi.legup.puzzle.fillapix.rules; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; @@ -14,90 +10,93 @@ import edu.rpi.legup.puzzle.fillapix.FillapixCell; import edu.rpi.legup.puzzle.fillapix.FillapixCellType; import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; public class MirrorDirectRule extends DirectRule { - public MirrorDirectRule() { - super("FPIX-BASC-0003", - "Mirror", - "Two adjacent clues with the same value must have the same number of black squares in their unshared regions", - "edu/rpi/legup/images/fillapix/rules/Mirror.png"); - } + public MirrorDirectRule() { + super( + "FPIX-BASC-0003", + "Mirror", + "Two adjacent clues with the same value must have the same number of black squares in their unshared regions", + "edu/rpi/legup/images/fillapix/rules/Mirror.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // find all cells adjacent to cell that are numbered - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - ArrayList adjNums = new ArrayList(); - for (int i=0; i < adjCells.size(); i++) { - if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { - adjNums.add(adjCells.get(i)); - } - } - // the numbered cells must be next to another numbered cell of the same value - Iterator itr = adjNums.iterator(); - while (itr.hasNext()) { - FillapixCell adjNum = itr.next(); - adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); - boolean found = false; - for (FillapixCell adjCell : adjCells) { - if (adjCell.getNumber() == adjNum.getNumber() && adjCell.getIndex() != adjNum.getIndex()) { - found = true; - } - } - if (!found) { - itr.remove(); - } + // find all cells adjacent to cell that are numbered + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + ArrayList adjNums = new ArrayList(); + for (int i = 0; i < adjCells.size(); i++) { + if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { + adjNums.add(adjCells.get(i)); + } + } + // the numbered cells must be next to another numbered cell of the same value + Iterator itr = adjNums.iterator(); + while (itr.hasNext()) { + FillapixCell adjNum = itr.next(); + adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); + boolean found = false; + for (FillapixCell adjCell : adjCells) { + if (adjCell.getNumber() == adjNum.getNumber() && adjCell.getIndex() != adjNum.getIndex()) { + found = true; } + } + if (!found) { + itr.remove(); + } + } - // change the color of the parentCell, and check if there exists a valid board - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } - else { - parentCell.setCellType(FillapixCellType.BLACK); - } - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjNum : adjNums) { - caseBoards = completeClue.getCases(parentBoard, adjNum); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } + // change the color of the parentCell, and check if there exists a valid board + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjNum : adjNums) { + caseBoards = completeClue.getCases(parentBoard, adjNum); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; } - - return super.getInvalidUseOfRuleMessage(); + } + if (found) { + return null; + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} \ No newline at end of file + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java index df6b5b76d..09930825e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java @@ -1,9 +1,5 @@ package edu.rpi.legup.puzzle.fillapix.rules; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; @@ -14,86 +10,90 @@ import edu.rpi.legup.puzzle.fillapix.FillapixCell; import edu.rpi.legup.puzzle.fillapix.FillapixCellType; import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; public class NonTouchingSharedDirectRule extends DirectRule { - public NonTouchingSharedDirectRule() { - super("FPIX-BASC-0005", - "NonTouching Shared", - "Clues with shared cells have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } + public NonTouchingSharedDirectRule() { + super( + "FPIX-BASC-0005", + "NonTouching Shared", + "Clues with shared cells have the same difference in black cells in their unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell not - * touching, but sharing cells */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - ArrayList sharingCells = FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); - boolean found = false; - for (FillapixCell sharingCell : sharingCells) { - if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { - found = true; - } - } - if (!found) { - itr.remove(); - } + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell not + * touching, but sharing cells */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + ArrayList sharingCells = + FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); + boolean found = false; + for (FillapixCell sharingCell : sharingCells) { + if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { + found = true; } + } + if (!found) { + itr.remove(); + } + } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } - else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; } - - return super.getInvalidUseOfRuleMessage(); + } + if (found) { + return null; + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } -} \ No newline at end of file + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java index 4520add31..fdfe2e765 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java @@ -1,12 +1,5 @@ package edu.rpi.legup.puzzle.fillapix.rules; -import java.awt.Point; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.CaseBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; @@ -17,218 +10,223 @@ import edu.rpi.legup.puzzle.fillapix.FillapixCell; import edu.rpi.legup.puzzle.fillapix.FillapixCellType; import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; +import java.awt.Point; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; public class SatisfyClueCaseRule extends CaseRule { - public SatisfyClueCaseRule() { - super("FPIX-CASE-0002", + public SatisfyClueCaseRule() { + super( + "FPIX-CASE-0002", "Satisfy Clue", "Each clue must touch that number of squares.", "edu/rpi/legup/images/fillapix/cases/SatisfyClue.png"); + } + + @Override + public CaseBoard getCaseBoard(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); + fillapixBoard.setModifiable(false); + for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) data; + if (cell.getNumber() >= 0 + && cell.getNumber() <= 9 + && FillapixUtilities.hasEmptyAdjacent(fillapixBoard, cell)) { + caseBoard.addPickableElement(data); + } } - - @Override - public CaseBoard getCaseBoard(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); - fillapixBoard.setModifiable(false); - for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) data; - if (cell.getNumber() >= 0 && cell.getNumber() <= 9 && FillapixUtilities.hasEmptyAdjacent(fillapixBoard, cell)) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; + return caseBoard; + } + + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + + // get value of cell + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + int cellMaxBlack = cell.getNumber(); + if (cellMaxBlack < 0 || cellMaxBlack > 9) { // cell is not valid cell + return null; } - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); + // find number of black & empty squares + int cellNumBlack = 0; + int cellNumEmpty = 0; + ArrayList emptyCells = new ArrayList(); + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + cellNumBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + cellNumEmpty++; + emptyCells.add(adjCell); + } + } + // no cases if no empty or if too many black already + if (cellNumBlack > cellMaxBlack || cellNumEmpty == 0) { + return cases; + } - // get value of cell - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellMaxBlack = cell.getNumber(); - if (cellMaxBlack < 0 || cellMaxBlack > 9) { // cell is not valid cell - return null; + // generate all cases as boolean expressions + ArrayList combinations; + combinations = FillapixUtilities.getCombinations(cellMaxBlack - cellNumBlack, cellNumEmpty); + + for (int i = 0; i < combinations.size(); i++) { + Board case_ = board.copy(); + for (int j = 0; j < combinations.get(i).length; j++) { + cell = (FillapixCell) case_.getPuzzleElement(emptyCells.get(j)); + if (combinations.get(i)[j]) { + cell.setCellType(FillapixCellType.BLACK); + } else { + cell.setCellType(FillapixCellType.WHITE); } + case_.addModifiedData(cell); + } + cases.add(case_); + } - // find number of black & empty squares - int cellNumBlack = 0; - int cellNumEmpty = 0; - ArrayList emptyCells = new ArrayList(); - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - cellNumBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - cellNumEmpty++; - emptyCells.add(adjCell); - } - } - // no cases if no empty or if too many black already - if (cellNumBlack > cellMaxBlack || cellNumEmpty == 0) { - return cases; - } - - // generate all cases as boolean expressions - ArrayList combinations; - combinations = FillapixUtilities.getCombinations(cellMaxBlack - cellNumBlack, cellNumEmpty); - - for (int i=0; i < combinations.size(); i++) { - Board case_ = board.copy(); - for (int j=0; j < combinations.get(i).length; j++) { - cell = (FillapixCell) case_.getPuzzleElement(emptyCells.get(j)); - if (combinations.get(i)[j]) { - cell.setCellType(FillapixCellType.BLACK); - } - else { - cell.setCellType(FillapixCellType.WHITE); - } - case_.addModifiedData(cell); - } - cases.add(case_); - } - - return cases; + return cases; + } + + @Override + public String checkRuleRaw(TreeTransition transition) { + TreeNode parent = transition.getParents().get(0); + List childTransitions = parent.getChildren(); + + /* + * In order for the transition to be valid, it can only be applied to + * one cell, thus: + * * there must be modified cells + * * all modified cells must share at least one common adjacent + * cell + * * all modified cells must fit within a 3X3 square + * * the center of one of the possible squaress must be a cell + * with a number + * * that cells possible combinations must match the transitions + * If all the above is verified, then the transition is valid + */ + + /* ensure there are modified cells */ + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() <= 0) { + return super.getInvalidUseOfRuleMessage(); } - @Override - public String checkRuleRaw(TreeTransition transition) { - TreeNode parent = transition.getParents().get(0); - List childTransitions = parent.getChildren(); - - /* - * In order for the transition to be valid, it can only be applied to - * one cell, thus: - * * there must be modified cells - * * all modified cells must share at least one common adjacent - * cell - * * all modified cells must fit within a 3X3 square - * * the center of one of the possible squaress must be a cell - * with a number - * * that cells possible combinations must match the transitions - * If all the above is verified, then the transition is valid - */ - - - /* ensure there are modified cells */ - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() <= 0) { - return super.getInvalidUseOfRuleMessage(); - } + /* ensure modified cells occur within a 3X3 square */ + int minVertLoc = Integer.MAX_VALUE, maxVertLoc = Integer.MIN_VALUE; + int minHorzLoc = Integer.MAX_VALUE, maxHorzLoc = Integer.MIN_VALUE; + for (PuzzleElement modCell : modCells) { + Point loc = ((FillapixCell) modCell).getLocation(); + if (loc.x < minHorzLoc) { + minHorzLoc = loc.x; + } + if (loc.x > maxHorzLoc) { + maxHorzLoc = loc.x; + } + if (loc.y < minVertLoc) { + minVertLoc = loc.y; + } + if (loc.y > maxVertLoc) { + maxVertLoc = loc.y; + } + } + if (maxVertLoc - minVertLoc > 3 || maxHorzLoc - minHorzLoc > 3) { + return super.getInvalidUseOfRuleMessage(); + } + /* get the center of all possible 3X3 squares, + * and collect all that have numbers */ + FillapixBoard board = (FillapixBoard) transition.getParents().get(0).getBoard(); + Set possibleCenters = new TreeSet(); + possibleCenters.addAll( + FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCells.iterator().next())); + for (PuzzleElement modCell : modCells) { + possibleCenters.retainAll( + (FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCell))); + } + // removing all elements without a valid number + possibleCenters.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + if (possibleCenters.isEmpty()) { + return super.getInvalidUseOfRuleMessage(); + } - /* ensure modified cells occur within a 3X3 square */ - int minVertLoc = Integer.MAX_VALUE, maxVertLoc = Integer.MIN_VALUE; - int minHorzLoc = Integer.MAX_VALUE, maxHorzLoc = Integer.MIN_VALUE; - for (PuzzleElement modCell : modCells) { - Point loc = ((FillapixCell) modCell).getLocation(); - if (loc.x < minHorzLoc) { - minHorzLoc = loc.x; - } - if (loc.x > maxHorzLoc) { - maxHorzLoc = loc.x; - } - if (loc.y < minVertLoc) { - minVertLoc = loc.y; - } - if (loc.y > maxVertLoc) { - maxVertLoc = loc.y; - } + /* Now go through the remaining centers, and check if their combinations + * match the transitions */ + for (FillapixCell possibleCenter : possibleCenters) { + int numBlack = 0; + int numEmpty = 0; + int maxBlack = possibleCenter.getNumber(); + for (FillapixCell adjCell : FillapixUtilities.getAdjacentCells(board, possibleCenter)) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; } - if (maxVertLoc - minVertLoc > 3 || maxHorzLoc - minHorzLoc > 3) { - return super.getInvalidUseOfRuleMessage(); + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + numEmpty++; } - - - /* get the center of all possible 3X3 squares, - * and collect all that have numbers */ - FillapixBoard board = (FillapixBoard) transition.getParents().get(0).getBoard(); - Set possibleCenters = new TreeSet(); - possibleCenters.addAll(FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCells.iterator().next())); + } + if (numEmpty <= 0 || numBlack > maxBlack) { + // this cell has no cases (no empty) or is already broken (too many black) + continue; + } + + ArrayList combinations = + FillapixUtilities.getCombinations(maxBlack - numBlack, numEmpty); + if (combinations.size() != childTransitions.size()) { + // not this center because combinations do not match transitions + continue; + } + boolean quitEarly = false; + for (TreeTransition trans : childTransitions) { + /* convert the transition board into boolean format, so that it + * can be compared to the combinations */ + FillapixBoard transBoard = (FillapixBoard) trans.getBoard(); + ArrayList transModCells = new ArrayList(); for (PuzzleElement modCell : modCells) { - possibleCenters.retainAll((FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCell))); - } - // removing all elements without a valid number - possibleCenters.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - if (possibleCenters.isEmpty()) { - return super.getInvalidUseOfRuleMessage(); + transModCells.add((FillapixCell) transBoard.getPuzzleElement(modCell)); } + boolean[] translatedModCells = new boolean[transModCells.size()]; + for (int i = 0; i < transModCells.size(); i++) { + if (transModCells.get(i).getType() == FillapixCellType.BLACK) { + translatedModCells[i] = true; + } else { + translatedModCells[i] = false; + } + } - /* Now go through the remaining centers, and check if their combinations - * match the transitions */ - for (FillapixCell possibleCenter : possibleCenters) { - int numBlack = 0; - int numEmpty = 0; - int maxBlack = possibleCenter.getNumber(); - for (FillapixCell adjCell : FillapixUtilities.getAdjacentCells(board, possibleCenter)) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - numEmpty++; - } - } - if (numEmpty <= 0 || numBlack > maxBlack) { - // this cell has no cases (no empty) or is already broken (too many black) - continue; - } - - ArrayList combinations = FillapixUtilities.getCombinations(maxBlack - numBlack, numEmpty); - if (combinations.size() != childTransitions.size()) { - // not this center because combinations do not match transitions - continue; - } - boolean quitEarly = false; - for (TreeTransition trans : childTransitions) { - /* convert the transition board into boolean format, so that it - * can be compared to the combinations */ - FillapixBoard transBoard = (FillapixBoard) trans.getBoard(); - ArrayList transModCells = new ArrayList(); - for (PuzzleElement modCell : modCells) { - transModCells.add((FillapixCell) transBoard.getPuzzleElement(modCell)); - } - - boolean[] translatedModCells = new boolean[transModCells.size()]; - for (int i=0; i < transModCells.size(); i++) { - if (transModCells.get(i).getType() == FillapixCellType.BLACK) { - translatedModCells[i] = true; - } - else { - translatedModCells[i] = false; - } - } - - // try to find the above state in the combinations, remove if found - boolean removed = false; - for (boolean[] combination : combinations) { - if (Arrays.equals(combination, translatedModCells)) { - combinations.remove(combination); - removed = true; - break; - } - } - // if combination not found, no need to check further, just quit - if (!removed) { - quitEarly = true; - break; - } - } - - /* we found a center that is valid */ - if (combinations.isEmpty() && !quitEarly) { - return null; - } + // try to find the above state in the combinations, remove if found + boolean removed = false; + for (boolean[] combination : combinations) { + if (Arrays.equals(combination, translatedModCells)) { + combinations.remove(combination); + removed = true; + break; + } } + // if combination not found, no need to check further, just quit + if (!removed) { + quitEarly = true; + break; + } + } - return super.getInvalidUseOfRuleMessage(); + /* we found a center that is valid */ + if (combinations.isEmpty() && !quitEarly) { + return null; + } } + return super.getInvalidUseOfRuleMessage(); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } -} \ No newline at end of file + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java index c37050978..09d031421 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java @@ -7,49 +7,50 @@ import edu.rpi.legup.puzzle.fillapix.FillapixCell; import edu.rpi.legup.puzzle.fillapix.FillapixCellType; import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; - import java.util.ArrayList; public class TooFewBlackCellsContradictionRule extends ContradictionRule { - public TooFewBlackCellsContradictionRule() { - super("FPIX-CONT-0001", - "Too Few Black Cells", - "There may not be fewer black cells than the number.", - "edu/rpi/legup/images/fillapix/contradictions/TooFewBlackCells.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + public TooFewBlackCellsContradictionRule() { + super( + "FPIX-CONT-0001", + "Too Few Black Cells", + "There may not be fewer black cells than the number.", + "edu/rpi/legup/images/fillapix/contradictions/TooFewBlackCells.png"); + } - int cellNum = cell.getNumber(); - if (cellNum < 0 || cellNum >= 10) { - return super.getNoContradictionMessage(); - } - int numBlack = 0, numEmpty = 0; - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - numEmpty++; - } - } - if (numBlack + numEmpty < cellNum) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - return super.getNoContradictionMessage(); + int cellNum = cell.getNumber(); + if (cellNum < 0 || cellNum >= 10) { + return super.getNoContradictionMessage(); } + int numBlack = 0, numEmpty = 0; + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + numEmpty++; + } + } + if (numBlack + numEmpty < cellNum) { + return null; + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java index 68395ce7f..9184212bb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java @@ -7,46 +7,47 @@ import edu.rpi.legup.puzzle.fillapix.FillapixCell; import edu.rpi.legup.puzzle.fillapix.FillapixCellType; import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; - import java.util.ArrayList; public class TooManyBlackCellsContradictionRule extends ContradictionRule { - public TooManyBlackCellsContradictionRule() { - super("FPIX-CONT-0002", - "Too Many Black Cells", - "There may not be more black cells than the number", - "edu/rpi/legup/images/fillapix/contradictions/TooManyBlackCells.png"); - } + public TooManyBlackCellsContradictionRule() { + super( + "FPIX-CONT-0002", + "Too Many Black Cells", + "There may not be more black cells than the number", + "edu/rpi/legup/images/fillapix/contradictions/TooManyBlackCells.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellNum = cell.getNumber(); - if (cellNum < 0 || cellNum >= 10) { - return super.getNoContradictionMessage(); - } - int numBlack = 0; - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - } - if (numBlack > cellNum) { - return null; - } - - return super.getNoContradictionMessage(); + int cellNum = cell.getNumber(); + if (cellNum < 0 || cellNum >= 10) { + return super.getNoContradictionMessage(); + } + int numBlack = 0; + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } } + if (numBlack > cellNum) { + return null; + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java index f0c8bb00d..34051f06f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java @@ -1,9 +1,5 @@ package edu.rpi.legup.puzzle.fillapix.rules; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; @@ -14,95 +10,100 @@ import edu.rpi.legup.puzzle.fillapix.FillapixCell; import edu.rpi.legup.puzzle.fillapix.FillapixCellType; import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; public class TouchingCornersDirectRule extends DirectRule { - public TouchingCornersDirectRule() { - super("FPIX-BASC-0005", - "Touching Corners", - "Clues with touching corners have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); - } + public TouchingCornersDirectRule() { + super( + "FPIX-BASC-0005", + "Touching Corners", + "Clues with touching corners have the same difference in black cells in their unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } - - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell diagonally - * adjacent to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - FillapixCell adjCell = itr.next(); + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - boolean found = false; - ArrayList adjAdjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjCell); - for (FillapixCell adjAdjCell : adjAdjCells) { - if (adjAdjCell.getLocation().x != adjCell.getLocation().x && - adjAdjCell.getLocation().y != adjCell.getLocation().y && - adjAdjCell.getNumber() >= 0 && adjAdjCell.getNumber() < 10 && - adjAdjCell.getIndex() != parentCell.getIndex()) { - // adjAdjCell is diagonally adjacent to adjCell && it has a - // number && it is not parentCell - found = true; - } - } + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell diagonally + * adjacent to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + FillapixCell adjCell = itr.next(); - // does not qualify for this rule - if (!found) { - itr.remove(); - } - } - - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } - else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } + boolean found = false; + ArrayList adjAdjCells = + FillapixUtilities.getAdjacentCells(parentBoard, adjCell); + for (FillapixCell adjAdjCell : adjAdjCells) { + if (adjAdjCell.getLocation().x != adjCell.getLocation().x + && adjAdjCell.getLocation().y != adjCell.getLocation().y + && adjAdjCell.getNumber() >= 0 + && adjAdjCell.getNumber() < 10 + && adjAdjCell.getIndex() != parentCell.getIndex()) { + // adjAdjCell is diagonally adjacent to adjCell && it has a + // number && it is not parentCell + found = true; } + } - return super.getInvalidUseOfRuleMessage(); + // does not qualify for this rule + if (!found) { + itr.remove(); + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } } -} \ No newline at end of file + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java index 5e60ab174..ea6b84c69 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java @@ -1,9 +1,5 @@ package edu.rpi.legup.puzzle.fillapix.rules; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; @@ -14,102 +10,113 @@ import edu.rpi.legup.puzzle.fillapix.FillapixCell; import edu.rpi.legup.puzzle.fillapix.FillapixCellType; import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; public class TouchingSidesDirectRule extends DirectRule { - public TouchingSidesDirectRule() { - super("FPIX-BASC-0004", - "Touching Sides", - "Clues with touching sides have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + public TouchingSidesDirectRule() { + super( + "FPIX-BASC-0004", + "Touching Sides", + "Clues with touching sides have the same difference in black cells in their unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell adjacent - * to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - // calculate x and y offset of adjCell from cell - FillapixCell adjCell = itr.next(); - int xOffset = adjCell.getLocation().x - cell.getLocation().x; - int yOffset = adjCell.getLocation().y - cell.getLocation().y; + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - boolean found = false; - // check vertically for numbered cell in opposite direction of cell - if (adjCell.getLocation().x + xOffset >= 0 && adjCell.getLocation().x < parentBoard.getWidth()) { - int adjNum = parentBoard.getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y).getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; - } - } - // check horizontally for numbered cell in opposite direction of cell - if (adjCell.getLocation().y + yOffset >= 0 && adjCell.getLocation().y < parentBoard.getHeight()) { - int adjNum = parentBoard.getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset).getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; - } - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, - // then adjCell is not valid, so should be removed - if (!found) { - itr.remove(); - } - } + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell adjacent + * to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + // calculate x and y offset of adjCell from cell + FillapixCell adjCell = itr.next(); + int xOffset = adjCell.getLocation().x - cell.getLocation().x; + int yOffset = adjCell.getLocation().y - cell.getLocation().y; - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); + boolean found = false; + // check vertically for numbered cell in opposite direction of cell + if (adjCell.getLocation().x + xOffset >= 0 + && adjCell.getLocation().x < parentBoard.getWidth()) { + int adjNum = + parentBoard + .getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y) + .getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; } - else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } + } + // check horizontally for numbered cell in opposite direction of cell + if (adjCell.getLocation().y + yOffset >= 0 + && adjCell.getLocation().y < parentBoard.getHeight()) { + int adjNum = + parentBoard + .getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset) + .getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; } + } - return super.getInvalidUseOfRuleMessage(); + // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, + // then adjCell is not valid, so should be removed + if (!found) { + itr.remove(); + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } } -} \ No newline at end of file + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java index fc52a6fff..119362a88 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java @@ -5,67 +5,63 @@ public class Heyawake extends Puzzle { - public Heyawake() { - super(); + public Heyawake() { + super(); - this.name = "Heyawake"; + this.name = "Heyawake"; - this.factory = new HeyawakeFactory(); + this.factory = new HeyawakeFactory(); - this.exporter = new HeyawakeExporter(this); - this.importer = new HeyawakeImporter(this); - } + this.exporter = new HeyawakeExporter(this); + this.importer = new HeyawakeImporter(this); + } - /** - * Initializes the view. Called by the invoker of the class - */ - @Override - public void initializeView() { - boardView = new HeyawakeView((HeyawakeBoard) currentBoard); - } + /** Initializes the view. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new HeyawakeView((HeyawakeBoard) currentBoard); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for HeyAwake - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for HeyAwake, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for HeyAwake + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for HeyAwake, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { - - } + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java index 2f15213ec..2dfe35138 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java @@ -2,7 +2,6 @@ import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.*; import java.util.ArrayList; import java.util.HashMap; @@ -11,46 +10,46 @@ public class HeyawakeBoard extends GridBoard { - private Map> regions; - - public HeyawakeBoard(int width, int height) { - super(width, height); - this.regions = new HashMap<>(); - } - - public HeyawakeBoard(int size) { - this(size, size); - } - - @Override - public HeyawakeCell getCell(int x, int y) { - return (HeyawakeCell) super.getCell(x, y); + private Map> regions; + + public HeyawakeBoard(int width, int height) { + super(width, height); + this.regions = new HashMap<>(); + } + + public HeyawakeBoard(int size) { + this(size, size); + } + + @Override + public HeyawakeCell getCell(int x, int y) { + return (HeyawakeCell) super.getCell(x, y); + } + + public List getRegion(int regionIndex) { + return this.regions.get(regionIndex); + } + + public Map> getRegions() { + return this.regions; + } + + @Override + public HeyawakeBoard copy() { + HeyawakeBoard copy = new HeyawakeBoard(dimension.width, dimension.height); + for (List region : regions.values()) { + List newCpy = new ArrayList<>(); + for (HeyawakeCell cell : region) { + Point point = cell.getLocation(); + HeyawakeCell cellCpy = cell.copy(); + copy.setCell(point.x, point.y, cellCpy); + newCpy.add(cellCpy); + } + copy.regions.put(region.get(0).getRegionIndex(), newCpy); } - - public List getRegion(int regionIndex) { - return this.regions.get(regionIndex); - } - - public Map> getRegions() { - return this.regions; - } - - @Override - public HeyawakeBoard copy() { - HeyawakeBoard copy = new HeyawakeBoard(dimension.width, dimension.height); - for (List region : regions.values()) { - List newCpy = new ArrayList<>(); - for (HeyawakeCell cell : region) { - Point point = cell.getLocation(); - HeyawakeCell cellCpy = cell.copy(); - copy.setCell(point.x, point.y, cellCpy); - newCpy.add(cellCpy); - } - copy.regions.put(region.get(0).getRegionIndex(), newCpy); - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java index ce8c73424..e75271355 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java @@ -1,28 +1,27 @@ package edu.rpi.legup.puzzle.heyawake; import edu.rpi.legup.model.gameboard.GridCell; - import java.awt.*; public class HeyawakeCell extends GridCell { - private int regionIndex; + private int regionIndex; - public HeyawakeCell(int valueInt, Point location, int regionIndex) { - super(valueInt, location); - this.regionIndex = regionIndex; - } + public HeyawakeCell(int valueInt, Point location, int regionIndex) { + super(valueInt, location); + this.regionIndex = regionIndex; + } - public int getRegionIndex() { - return this.regionIndex; - } + public int getRegionIndex() { + return this.regionIndex; + } - @Override - public HeyawakeCell copy() { - HeyawakeCell copy = new HeyawakeCell(data, (Point) location.clone(), regionIndex); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public HeyawakeCell copy() { + HeyawakeCell copy = new HeyawakeCell(data, (Point) location.clone(), regionIndex); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeController.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeController.java index 2bad91933..2d081d7da 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeController.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeController.java @@ -2,5 +2,4 @@ import edu.rpi.legup.controller.ElementController; -public class HeyawakeController extends ElementController { -} +public class HeyawakeController extends ElementController {} diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java index 5efec44ff..f1ca1c79e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java @@ -1,46 +1,45 @@ package edu.rpi.legup.puzzle.heyawake; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; public class HeyawakeElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); - - public HeyawakeElementView(HeyawakeCell cell) { - super(cell); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public HeyawakeCell getPuzzleElement() { - return (HeyawakeCell) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - - if (cell.getData() >= 0) { - graphics2D.setColor(BLACK_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); + + public HeyawakeElementView(HeyawakeCell cell) { + super(cell); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public HeyawakeCell getPuzzleElement() { + return (HeyawakeCell) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + + if (cell.getData() >= 0) { + graphics2D.setColor(BLACK_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java index 344a0be92..0856bf0de 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java @@ -2,39 +2,38 @@ import edu.rpi.legup.model.PuzzleExporter; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import org.w3c.dom.Document; public class HeyawakeExporter extends PuzzleExporter { - public HeyawakeExporter(Heyawake heyawake) { - super(heyawake); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - HeyawakeBoard board; - if (puzzle.getTree() != null) { - board = (HeyawakeBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (HeyawakeBoard) puzzle.getBoardView().getBoard(); - } + public HeyawakeExporter(Heyawake heyawake) { + super(heyawake); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + HeyawakeBoard board; + if (puzzle.getTree() != null) { + board = (HeyawakeBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (HeyawakeBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java index 96fc20e6f..f6853d75f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java @@ -4,75 +4,74 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class HeyawakeFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public HeyawakeCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Heyawake Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public HeyawakeCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Heyawake Factory: unknown puzzleElement puzzleElement"); + } - HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; - int width = heyawakeBoard.getWidth(); - int height = heyawakeBoard.getHeight(); + HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; + int width = heyawakeBoard.getWidth(); + int height = heyawakeBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - int regionIndex = Integer.valueOf(attributeList.getNamedItem("region").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Heyawake Factory: cell location out of bounds"); - } - if (value < -4 || value > 4) { - throw new InvalidFileFormatException("Heyawake Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + int regionIndex = Integer.valueOf(attributeList.getNamedItem("region").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("Heyawake Factory: cell location out of bounds"); + } + if (value < -4 || value > 4) { + throw new InvalidFileFormatException("Heyawake Factory: cell unknown value"); + } - HeyawakeCell cell = new HeyawakeCell(value, new Point(x, y), regionIndex); - cell.setIndex(y * height + x); - heyawakeBoard.getRegions(); - return cell; - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Heyawake Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("Heyawake Factory: could not find attribute(s)"); - } + HeyawakeCell cell = new HeyawakeCell(value, new Point(x, y), regionIndex); + cell.setIndex(y * height + x); + heyawakeBoard.getRegions(); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Heyawake Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Heyawake Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - Point loc = cell.getLocation(); + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); - cellElement.setAttribute("region", String.valueOf(cell.getRegionIndex())); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("region", String.valueOf(cell.getRegionIndex())); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java index 7527c717f..f85a0b46d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java @@ -2,108 +2,106 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.awt.*; - public class HeyawakeImporter extends PuzzleImporter { - public HeyawakeImporter(Heyawake heyawake) { - super(heyawake); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } - - @Override - public boolean acceptsTextInput() { - return false; - } + public HeyawakeImporter(Heyawake heyawake) { + super(heyawake); + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Heyawake Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Heyawake Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} - HeyawakeBoard heyawakeBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - heyawakeBoard = new HeyawakeBoard(size); - } - else { - if (!boardElement.getAttribute("width").isEmpty() && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - heyawakeBoard = new HeyawakeBoard(width, height); - } - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("Heyawake Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("Heyawake Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - if (heyawakeBoard == null) { - throw new InvalidFileFormatException("Heyawake Importer: invalid board dimensions"); - } + HeyawakeBoard heyawakeBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + heyawakeBoard = new HeyawakeBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + heyawakeBoard = new HeyawakeBoard(width, height); + } + } - int width = heyawakeBoard.getWidth(); - int height = heyawakeBoard.getHeight(); + if (heyawakeBoard == null) { + throw new InvalidFileFormatException("Heyawake Importer: invalid board dimensions"); + } - for (int i = 0; i < elementDataList.getLength(); i++) { - HeyawakeCell cell = (HeyawakeCell) puzzle.getFactory().importCell(elementDataList.item(i), heyawakeBoard); - Point loc = cell.getLocation(); - if (cell.getData() != -2) { - cell.setModifiable(false); - cell.setGiven(true); - } - heyawakeBoard.setCell(loc.x, loc.y, cell); - } + int width = heyawakeBoard.getWidth(); + int height = heyawakeBoard.getHeight(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (heyawakeBoard.getCell(x, y) == null) { - HeyawakeCell cell = new HeyawakeCell(0, new Point(x, y), -1); - cell.setIndex(y * height + x); - cell.setModifiable(false); - heyawakeBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(heyawakeBoard); + for (int i = 0; i < elementDataList.getLength(); i++) { + HeyawakeCell cell = + (HeyawakeCell) puzzle.getFactory().importCell(elementDataList.item(i), heyawakeBoard); + Point loc = cell.getLocation(); + if (cell.getData() != -2) { + cell.setModifiable(false); + cell.setGiven(true); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Heyawake Importer: unknown value where integer expected"); + heyawakeBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (heyawakeBoard.getCell(x, y) == null) { + HeyawakeCell cell = new HeyawakeCell(0, new Point(x, y), -1); + cell.setIndex(y * height + x); + cell.setModifiable(false); + heyawakeBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(heyawakeBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Heyawake Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Hey Awake cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Hey Awake cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java index 00506df0f..0c349ca87 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java @@ -4,7 +4,6 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.ui.boardview.ElementView; import edu.rpi.legup.ui.boardview.GridBoardView; - import java.awt.*; import java.awt.geom.Area; import java.util.HashMap; @@ -12,44 +11,43 @@ public class HeyawakeView extends GridBoardView { - private Map regionsBoundaries; - - public HeyawakeView(HeyawakeBoard board) { - super(new BoardController(), new HeyawakeController(), board.getDimension()); - - this.regionsBoundaries = new HashMap<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - Point loc = cell.getLocation(); - HeyawakeElementView elementView = new HeyawakeElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - - int regionIndex = cell.getRegionIndex(); - if (regionsBoundaries.get(regionIndex) == null) { - regionsBoundaries.put(regionIndex, new Area(elementView.getBounds())); - } - else { - regionsBoundaries.get(regionIndex).add(new Area(elementView.getBounds())); - } - } + private Map regionsBoundaries; + + public HeyawakeView(HeyawakeBoard board) { + super(new BoardController(), new HeyawakeController(), board.getDimension()); + + this.regionsBoundaries = new HashMap<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + Point loc = cell.getLocation(); + HeyawakeElementView elementView = new HeyawakeElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + + int regionIndex = cell.getRegionIndex(); + if (regionsBoundaries.get(regionIndex) == null) { + regionsBoundaries.put(regionIndex, new Area(elementView.getBounds())); + } else { + regionsBoundaries.get(regionIndex).add(new Area(elementView.getBounds())); + } } + } - @Override - public void drawBoard(Graphics2D graphics2D) { - HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; + @Override + public void drawBoard(Graphics2D graphics2D) { + HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; - for (ElementView elementView : elementViews) { - elementView.draw(graphics2D); - } + for (ElementView elementView : elementViews) { + elementView.draw(graphics2D); + } - graphics2D.setColor(Color.BLACK); - graphics2D.setStroke(new BasicStroke(3)); - for (Area s : regionsBoundaries.values()) { - graphics2D.draw(s); - } + graphics2D.setColor(Color.BLACK); + graphics2D.setStroke(new BasicStroke(3)); + for (Area s : regionsBoundaries.values()) { + graphics2D.draw(s); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java index d2eceb7a1..1a46e5265 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java @@ -6,22 +6,25 @@ public class AdjacentBlacksContradictionRule extends ContradictionRule { - public AdjacentBlacksContradictionRule() { - super("HEYA-CONT-0001", "Adjacent Blacks", - "", - "edu/rpi/legup/images/heyawake/contradictions/adjacentBlacks.png"); - } + public AdjacentBlacksContradictionRule() { + super( + "HEYA-CONT-0001", + "Adjacent Blacks", + "", + "edu/rpi/legup/images/heyawake/contradictions/adjacentBlacks.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java index 0e7552dd2..882372372 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java @@ -5,64 +5,67 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.List; public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super("HEYA-CASE-0001", - "Black or White", - "", - "edu/rpi/legup/images/heyawake/cases/BlackOrWhite.png"); - } + public BlackOrWhiteCaseRule() { + super( + "HEYA-CASE-0001", + "Black or White", + "", + "edu/rpi/legup/images/heyawake/cases/BlackOrWhite.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java index 1fc3d0776..d687569ff 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class BlackPathDirectRule { - public BlackPathDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public BlackPathDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java index 41d950378..033bce643 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class BottleNeckDirectRule { - public BottleNeckDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public BottleNeckDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java index 255678e02..8fe0f66e5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java @@ -8,36 +8,37 @@ public class FillRoomBlackDirectRule extends DirectRule { - public FillRoomBlackDirectRule() { - super("HEYA-BASC-0003", - "Fill Room Black", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); - } + public FillRoomBlackDirectRule() { + super( + "HEYA-BASC-0003", + "Fill Room Black", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java index 1dee36ecc..95473aa9c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java @@ -8,36 +8,37 @@ public class FillRoomWhiteDirectRule extends DirectRule { - public FillRoomWhiteDirectRule() { - super("HEYA-BASC-0004", - "Fill Room White", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); - } + public FillRoomWhiteDirectRule() { + super( + "HEYA-BASC-0004", + "Fill Room White", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java index 8b6f21564..233136061 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class OneRowDirectRule { - public OneRowDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public OneRowDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java index f5d4e78b7..14b3ef0a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class PreventWhiteLineDirectRule { - public PreventWhiteLineDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public PreventWhiteLineDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java index 0e0beaeb2..af2448b13 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java @@ -6,23 +6,25 @@ public class RoomTooEmptyContradictionRule extends ContradictionRule { - public RoomTooEmptyContradictionRule() { - super("HEYA-CONT-0002", - "Room too Empty", - "", - "edu/rpi/legup/images/heyawake/contradictions/RoomTooEmpty.png"); - } + public RoomTooEmptyContradictionRule() { + super( + "HEYA-CONT-0002", + "Room too Empty", + "", + "edu/rpi/legup/images/heyawake/contradictions/RoomTooEmpty.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java index 1de746cb2..d46ae27a0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java @@ -6,23 +6,25 @@ public class RoomTooFullContradictionRule extends ContradictionRule { - public RoomTooFullContradictionRule() { - super("HEYA-CONT-0003", - "Room too Full", - "", - "edu/rpi/legup/images/heyawake/contradictions/RoomTooFull.png"); - } + public RoomTooFullContradictionRule() { + super( + "HEYA-CONT-0003", + "Room too Full", + "", + "edu/rpi/legup/images/heyawake/contradictions/RoomTooFull.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java index cf2c241e3..b6782e380 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ThreeByThreeDirectRule { - public ThreeByThreeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ThreeByThreeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java index 83f1ca72f..0af7fbc15 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class TwoInCornerDirectRule { - public TwoInCornerDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public TwoInCornerDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java index a287d9c78..377ba5911 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java @@ -6,23 +6,25 @@ public class WhiteAreaContradictionRule extends ContradictionRule { - public WhiteAreaContradictionRule() { - super("HEYA-CONT-0004", - "White Area", - "", - "edu/rpi/legup/images/heyawake/contradictions/WhiteArea.png"); - } + public WhiteAreaContradictionRule() { + super( + "HEYA-CONT-0004", + "White Area", + "", + "edu/rpi/legup/images/heyawake/contradictions/WhiteArea.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java index e0f17a0ed..c6c7b7d6b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java @@ -8,36 +8,37 @@ public class WhiteAroundBlackDirectRule extends DirectRule { - public WhiteAroundBlackDirectRule() { - super("HEYA-BASC-0009", - "White Around Black", - "", - "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); - } + public WhiteAroundBlackDirectRule() { + super( + "HEYA-BASC-0009", + "White Around Black", + "", + "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java index f151ec12a..d4d547677 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class WhiteEscapeDirectRule { - public WhiteEscapeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public WhiteEscapeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java index 835bce98c..813dd45ed 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java @@ -6,24 +6,25 @@ public class WhiteLineContradictionRule extends ContradictionRule { - public WhiteLineContradictionRule() { - super("HEYA-CONT-0005", - "White Line", - "", - "edu/rpi/legup/images/heyawake/contradictions/WhiteLine.png"); + public WhiteLineContradictionRule() { + super( + "HEYA-CONT-0005", + "White Line", + "", + "edu/rpi/legup/images/heyawake/contradictions/WhiteLine.png"); + } - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java index d44491a6e..9f9212861 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ZigZagCaseRule { - public ZigZagCaseRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ZigZagCaseRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java index 9df735b0b..531cf030e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ZigZagWhiteDirectRule { - public ZigZagWhiteDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ZigZagWhiteDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java index 6a67d28ca..73878706f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java @@ -9,82 +9,79 @@ @RegisterPuzzle public class LightUp extends Puzzle { - public LightUp() { - super(); - this.name = "LightUp"; + public LightUp() { + super(); + this.name = "LightUp"; - this.importer = new LightUpImporter(this); - this.exporter = new LightUpExporter(this); + this.importer = new LightUpImporter(this); + this.exporter = new LightUpExporter(this); - this.factory = new LightUpCellFactory(); - } + this.factory = new LightUpCellFactory(); + } - /** - * Initializes the game board. Called by the invoker of the class - */ - @Override - public void initializeView() { - boardView = new LightUpView((LightUpBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new LightUpView((LightUpBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Light Up - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Light Up, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows > 0 && columns > 0; - } + @Override + /** + * Determines if the given dimensions are valid for Light Up + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Light Up, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows > 0 && columns > 0; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - lightUpBoard.fillWithLight(); + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + lightUpBoard.fillWithLight(); - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(lightUpBoard) == null) { - System.out.println(rule.getRuleName()); - return false; - } - } - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) data; - if ((cell.getType() == LightUpCellType.UNKNOWN || cell.getType() == LightUpCellType.EMPTY) && !cell.isLite()) { - return false; - } - } - return true; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(lightUpBoard) == null) { + System.out.println(rule.getRuleName()); + return false; + } } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { - + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) data; + if ((cell.getType() == LightUpCellType.UNKNOWN || cell.getType() == LightUpCellType.EMPTY) + && !cell.isLite()) { + return false; + } } + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java index b15f49919..5d0d66648 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java @@ -2,173 +2,173 @@ import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.*; import java.util.HashSet; import java.util.Set; public class LightUpBoard extends GridBoard { - public LightUpBoard(int width, int height) { - super(width, height); - } + public LightUpBoard(int width, int height) { + super(width, height); + } - public LightUpBoard(int size) { - super(size, size); + public LightUpBoard(int size) { + super(size, size); + } + + /** + * Sets cells in board to lite depending on whether there is a bulb cell in the current row or + * column + */ + public void fillWithLight() { + for (int y = 0; y < this.dimension.height; y++) { + for (int x = 0; x < this.dimension.width; x++) { + getCell(x, y).setLite(false); + } } - /** - * Sets cells in board to lite depending on whether there is a bulb cell in the current row or column - */ - public void fillWithLight() { - for (int y = 0; y < this.dimension.height; y++) { - for (int x = 0; x < this.dimension.width; x++) { - getCell(x, y).setLite(false); + for (int y = 0; y < this.dimension.height; y++) { + for (int x = 0; x < this.dimension.width; x++) { + LightUpCell cell = getCell(x, y); + if (cell.getType() == LightUpCellType.BULB) { + cell.setLite(true); + for (int i = x + 1; i < this.dimension.width; i++) { + LightUpCell c = getCell(i, y); + if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { + break; } - } - - for (int y = 0; y < this.dimension.height; y++) { - for (int x = 0; x < this.dimension.width; x++) { - LightUpCell cell = getCell(x, y); - if (cell.getType() == LightUpCellType.BULB) { - cell.setLite(true); - for (int i = x + 1; i < this.dimension.width; i++) { - LightUpCell c = getCell(i, y); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = x - 1; i >= 0; i--) { - LightUpCell c = getCell(i, y); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = y + 1; i < this.dimension.height; i++) { - LightUpCell c = getCell(x, i); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = y - 1; i >= 0; i--) { - LightUpCell c = getCell(x, i); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - } + c.setLite(true); + } + for (int i = x - 1; i >= 0; i--) { + LightUpCell c = getCell(i, y); + if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = y + 1; i < this.dimension.height; i++) { + LightUpCell c = getCell(x, i); + if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = y - 1; i >= 0; i--) { + LightUpCell c = getCell(x, i); + if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { + break; } + c.setLite(true); + } } + } } + } - /** - * Gets adjancent cells to the specified cell - * - * @param cell LightUpCell - * @return Set of adjacent LightUpCells - */ - public Set getAdj(LightUpCell cell) { - Set adjCells = new HashSet<>(); - cell = (LightUpCell) getPuzzleElement(cell); + /** + * Gets adjancent cells to the specified cell + * + * @param cell LightUpCell + * @return Set of adjacent LightUpCells + */ + public Set getAdj(LightUpCell cell) { + Set adjCells = new HashSet<>(); + cell = (LightUpCell) getPuzzleElement(cell); - Point loc = cell.getLocation(); - LightUpCell up = getCell(loc.x, loc.y + 1); - if (up != null) { - adjCells.add(up); - } - LightUpCell down = getCell(loc.x, loc.y - 1); - if (down != null) { - adjCells.add(down); - } - LightUpCell right = getCell(loc.x + 1, loc.y); - if (right != null) { - adjCells.add(right); - } - LightUpCell left = getCell(loc.x - 1, loc.y); - if (left != null) { - adjCells.add(left); - } - return adjCells; + Point loc = cell.getLocation(); + LightUpCell up = getCell(loc.x, loc.y + 1); + if (up != null) { + adjCells.add(up); } - - /** - * Gets the number of adjacent cells of the specified type - * - * @param cell base cell - * @param type specified type - * @return the number of adjacent cells - */ - public int getNumAdj(LightUpCell cell, LightUpCellType type) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.getType() == type) { - num++; - } - } - return num; + LightUpCell down = getCell(loc.x, loc.y - 1); + if (down != null) { + adjCells.add(down); } - - /** - * Gets the number of adjacent cells - * - * @param cell LightUpCell - * @return number of adjacent cells - */ - public int getNumAdjLite(LightUpCell cell) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.isLite()) { - num++; - } - } - return num; + LightUpCell right = getCell(loc.x + 1, loc.y); + if (right != null) { + adjCells.add(right); } + LightUpCell left = getCell(loc.x - 1, loc.y); + if (left != null) { + adjCells.add(left); + } + return adjCells; + } - /** - * Gets the number of adjacent cells that are placable - * - * @param cell specified cell - * @return number of adjacent cells that are placable - */ - public int getNumPlacble(LightUpCell cell) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - num++; - } - } - return num; + /** + * Gets the number of adjacent cells of the specified type + * + * @param cell base cell + * @param type specified type + * @return the number of adjacent cells + */ + public int getNumAdj(LightUpCell cell, LightUpCellType type) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.getType() == type) { + num++; + } } + return num; + } - @Override - public LightUpCell getCell(int x, int y) { - return (LightUpCell) super.getCell(x, y); + /** + * Gets the number of adjacent cells + * + * @param cell LightUpCell + * @return number of adjacent cells + */ + public int getNumAdjLite(LightUpCell cell) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.isLite()) { + num++; + } } + return num; + } - @Override - public void notifyChange(PuzzleElement puzzleElement) { - super.notifyChange(puzzleElement); - fillWithLight(); + /** + * Gets the number of adjacent cells that are placable + * + * @param cell specified cell + * @return number of adjacent cells that are placable + */ + public int getNumPlacble(LightUpCell cell) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + num++; + } } + return num; + } - @Override - public LightUpBoard copy() { - LightUpBoard copy = new LightUpBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.fillWithLight(); - return copy; + @Override + public LightUpCell getCell(int x, int y) { + return (LightUpCell) super.getCell(x, y); + } + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + super.notifyChange(puzzleElement); + fillWithLight(); + } + + @Override + public LightUpBoard copy() { + LightUpBoard copy = new LightUpBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + copy.fillWithLight(); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java index 36e5a5088..f21f42fd6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java @@ -2,85 +2,82 @@ import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.GridCell; - import java.awt.*; import java.awt.event.MouseEvent; public class LightUpCell extends GridCell { - private boolean isLite; + private boolean isLite; - public LightUpCell(int valueInt, Point location) { - super(valueInt, location); - this.isLite = false; - } + public LightUpCell(int valueInt, Point location) { + super(valueInt, location); + this.isLite = false; + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "LTUP-PLAC-0001": - this.data = -4; - break; - case "LTUP-UNPL-0002": - this.data = -1; - break; - case "LTUP-UNPL-0003": - this.data = -2; - break; - case "LTUP-UNPL-0001": - switch (m.getButton()){ - case MouseEvent.BUTTON1: - if (this.data < 0 || this.data > 3) { - this.data = 0; - } - else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 0) { - this.data = this.data - 1; - } - else { - this.data = 4; - } - break; - } - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "LTUP-PLAC-0001": + this.data = -4; + break; + case "LTUP-UNPL-0002": + this.data = -1; + break; + case "LTUP-UNPL-0003": + this.data = -2; + break; + case "LTUP-UNPL-0001": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data < 0 || this.data > 3) { + this.data = 0; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 0) { + this.data = this.data - 1; + } else { + this.data = 4; + } + break; } + break; } + } - public LightUpCellType getType() { - switch (data) { - case -4: - return LightUpCellType.BULB; - case -3: - return LightUpCellType.EMPTY; - case -2: - return LightUpCellType.UNKNOWN; - case -1: - return LightUpCellType.BLACK; - default: - if (data >= 0) { - return LightUpCellType.NUMBER; - } + public LightUpCellType getType() { + switch (data) { + case -4: + return LightUpCellType.BULB; + case -3: + return LightUpCellType.EMPTY; + case -2: + return LightUpCellType.UNKNOWN; + case -1: + return LightUpCellType.BLACK; + default: + if (data >= 0) { + return LightUpCellType.NUMBER; } - return null; } + return null; + } - public boolean isLite() { - return isLite; - } + public boolean isLite() { + return isLite; + } - public void setLite(boolean isLite) { - this.isLite = isLite; - } + public void setLite(boolean isLite) { + this.isLite = isLite; + } - @Override - public LightUpCell copy() { - LightUpCell copy = new LightUpCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public LightUpCell copy() { + LightUpCell copy = new LightUpCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java index 9c94b24f7..07217869e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java @@ -2,45 +2,43 @@ import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.event.MouseEvent; public class LightUpCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - LightUpCell cell = (LightUpCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView.getSelectionPopupMenu().show(boardView, this.boardView.getCanvas().getX() + e.getX(), this.boardView.getCanvas().getY() + e.getY()); - } - else { - if (cell.getData() == -2) { - data.setData(-4); - } - else { - if (cell.getData() == -4) { - data.setData(-3); - } - else { - data.setData(-2); - } - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + LightUpCell cell = (LightUpCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == -2) { + data.setData(-4); + } else { + if (cell.getData() == -4) { + data.setData(-3); + } else { + data.setData(-2); + } } - else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == -4) { - data.setData(-2); - } - else { - if (cell.getData() == -2) { - data.setData(-3); - } - else { - data.setData(-4); - } - } - } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == -4) { + data.setData(-2); + } else { + if (cell.getData() == -2) { + data.setData(-3); + } else { + data.setData(-4); + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java index 4914facfa..10a44ca85 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java @@ -4,72 +4,70 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class LightUpCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public LightUpCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("lightup Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public LightUpCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "lightup Factory: unknown puzzleElement puzzleElement"); + } - LightUpBoard lightUpBoard = (LightUpBoard) board; - int width = lightUpBoard.getWidth(); - int height = lightUpBoard.getHeight(); + LightUpBoard lightUpBoard = (LightUpBoard) board; + int width = lightUpBoard.getWidth(); + int height = lightUpBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("lightup Factory: cell location out of bounds"); - } - if (value < -4 || value > 4) { - throw new InvalidFileFormatException("lightup Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("lightup Factory: cell location out of bounds"); + } + if (value < -4 || value > 4) { + throw new InvalidFileFormatException("lightup Factory: cell unknown value"); + } - LightUpCell cell = new LightUpCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("lightup Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("lightup Factory: could not find attribute(s)"); - } + LightUpCell cell = new LightUpCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("lightup Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("lightup Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java index b0825910d..3d28a0604 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java @@ -1,11 +1,15 @@ package edu.rpi.legup.puzzle.lightup; public enum LightUpCellType { - BULB(-4), EMPTY(-3), UNKNOWN(-2), BLACK(-1), NUMBER(0); + BULB(-4), + EMPTY(-3), + UNKNOWN(-2), + BLACK(-1), + NUMBER(0); - public int value; + public int value; - LightUpCellType(int value) { - this.value = value; - } + LightUpCellType(int value) { + this.value = value; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java index 7f35d46a6..6805d9d29 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java @@ -1,82 +1,88 @@ package edu.rpi.legup.puzzle.lightup; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; public class LightUpElementView extends GridElementView { - private static final Color LITE = new Color(0xFFF176); - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color LITE = new Color(0xFFF176); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); - public LightUpElementView(LightUpCell cell) { - super(cell); - } + public LightUpElementView(LightUpCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public LightUpCell getPuzzleElement() { - return (LightUpCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public LightUpCell getPuzzleElement() { + return (LightUpCell) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + LightUpCell cell = (LightUpCell) puzzleElement; + LightUpCellType type = cell.getType(); + if (type == LightUpCellType.NUMBER) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); - @Override - public void drawElement(Graphics2D graphics2D) { - LightUpCell cell = (LightUpCell) puzzleElement; - LightUpCellType type = cell.getType(); - if (type == LightUpCellType.NUMBER) { + graphics2D.setColor(WHITE_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } else { + if (type == LightUpCellType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.EMPTY) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(cell.isLite() ? LITE : WHITE_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect( + location.x + size.width * 7 / 16, + location.y + size.height * 7 / 16, + size.width / 8, + size.height / 8); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.UNKNOWN) { graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); + graphics2D.setColor(cell.isLite() ? LITE : Color.LIGHT_GRAY); graphics2D.fillRect(location.x, location.y, size.width, size.height); - - graphics2D.setColor(WHITE_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } - else { - if (type == LightUpCellType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } - else { - if (type == LightUpCellType.EMPTY) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(cell.isLite() ? LITE : WHITE_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect(location.x + size.width * 7 / 16, location.y + size.height * 7 / 16, size.width / 8, size.height / 8); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - else { - if (type == LightUpCellType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(cell.isLite() ? LITE : Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - else { - if (type == LightUpCellType.BULB) { - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.drawImage(LightUpView.lightImage, location.x, location.y, size.width, size.height, LITE, null); - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - } - } + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.BULB) { + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.drawImage( + LightUpView.lightImage, + location.x, + location.y, + size.width, + size.height, + LITE, + null); + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); } + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java index 89024ad6c..d632879d5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java @@ -2,39 +2,38 @@ import edu.rpi.legup.model.PuzzleExporter; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import org.w3c.dom.Document; public class LightUpExporter extends PuzzleExporter { - public LightUpExporter(LightUp lightUp) { - super(lightUp); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - LightUpBoard board; - if (puzzle.getTree() != null) { - board = (LightUpBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (LightUpBoard) puzzle.getBoardView().getBoard(); - } + public LightUpExporter(LightUp lightUp) { + super(lightUp); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + LightUpBoard board; + if (puzzle.getTree() != null) { + board = (LightUpBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (LightUpBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java index 7ef24ca69..bce9f10ee 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java @@ -2,119 +2,119 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.awt.*; - public class LightUpImporter extends PuzzleImporter { - public LightUpImporter(LightUp lightUp) { - super(lightUp); - } + public LightUpImporter(LightUp lightUp) { + super(lightUp); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - LightUpBoard lightUpBoard = new LightUpBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + LightUpBoard lightUpBoard = new LightUpBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - if (lightUpBoard.getCell(x, y) == null) { - LightUpCell cell = new LightUpCell(-2, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - lightUpBoard.setCell(x, y, cell); - } - } + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + if (lightUpBoard.getCell(x, y) == null) { + LightUpCell cell = new LightUpCell(-2, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + lightUpBoard.setCell(x, y, cell); } - puzzle.setCurrentBoard(lightUpBoard); + } } + puzzle.setCurrentBoard(lightUpBoard); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("lightup Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("lightup Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - LightUpBoard lightUpBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - lightUpBoard = new LightUpBoard(size); - } - else { - if (!boardElement.getAttribute("width").isEmpty() && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - lightUpBoard = new LightUpBoard(width, height); - } - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("lightup Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("lightup Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - if (lightUpBoard == null) { - throw new InvalidFileFormatException("lightup Importer: invalid board dimensions"); - } + LightUpBoard lightUpBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + lightUpBoard = new LightUpBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + lightUpBoard = new LightUpBoard(width, height); + } + } - int width = lightUpBoard.getWidth(); - int height = lightUpBoard.getHeight(); + if (lightUpBoard == null) { + throw new InvalidFileFormatException("lightup Importer: invalid board dimensions"); + } - for (int i = 0; i < elementDataList.getLength(); i++) { - LightUpCell cell = (LightUpCell) puzzle.getFactory().importCell(elementDataList.item(i), lightUpBoard); - Point loc = cell.getLocation(); - if (cell.getData() != -2) { - cell.setModifiable(false); - cell.setGiven(true); - } - lightUpBoard.setCell(loc.x, loc.y, cell); - } + int width = lightUpBoard.getWidth(); + int height = lightUpBoard.getHeight(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (lightUpBoard.getCell(x, y) == null) { - LightUpCell cell = new LightUpCell(-2, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - lightUpBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(lightUpBoard); + for (int i = 0; i < elementDataList.getLength(); i++) { + LightUpCell cell = + (LightUpCell) puzzle.getFactory().importCell(elementDataList.item(i), lightUpBoard); + Point loc = cell.getLocation(); + if (cell.getData() != -2) { + cell.setModifiable(false); + cell.setGiven(true); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("lightup Importer: unknown value where integer expected"); + lightUpBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (lightUpBoard.getCell(x, y) == null) { + LightUpCell cell = new LightUpCell(-2, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + lightUpBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(lightUpBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "lightup Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Light Up cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Light Up cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java index 0fd57e705..b8122ffff 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java @@ -7,89 +7,94 @@ import edu.rpi.legup.ui.boardview.DataSelectionView; import edu.rpi.legup.ui.boardview.GridBoardView; import edu.rpi.legup.ui.boardview.SelectionItemView; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.imageio.ImageIO; -import javax.swing.*; import java.awt.*; import java.io.IOException; +import javax.imageio.ImageIO; +import javax.swing.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class LightUpView extends GridBoardView { - private final static Logger LOGGER = LogManager.getLogger(LightUpView.class.getName()); - static Image lightImage; + private static final Logger LOGGER = LogManager.getLogger(LightUpView.class.getName()); + static Image lightImage; - static { - try { - lightImage = ImageIO.read(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/lightup/light.png")); - } - catch (IOException e) { - LOGGER.error("Failed to open TreeTent images"); - } + static { + try { + lightImage = + ImageIO.read( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/lightup/light.png")); + } catch (IOException e) { + LOGGER.error("Failed to open TreeTent images"); } + } - public LightUpView(LightUpBoard board) { - super(new BoardController(), new LightUpCellController(), board.getDimension()); + public LightUpView(LightUpBoard board) { + super(new BoardController(), new LightUpCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); - LightUpElementView elementView = new LightUpElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); + LightUpElementView elementView = new LightUpElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - super.onTreeElementChanged(treeElement); - LightUpBoard lightUpBoard = board instanceof CaseBoard ? (LightUpBoard) ((CaseBoard) board).getBaseBoard() : (LightUpBoard) board; - lightUpBoard.fillWithLight(); - repaint(); - } + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + super.onTreeElementChanged(treeElement); + LightUpBoard lightUpBoard = + board instanceof CaseBoard + ? (LightUpBoard) ((CaseBoard) board).getBaseBoard() + : (LightUpBoard) board; + lightUpBoard.fillWithLight(); + repaint(); + } - /** - * Returns a DataSelectionView popup menu - */ - public DataSelectionView getSelectionPopupMenu() { - DataSelectionView selectionView = new DataSelectionView(elementController); - GridLayout layout = new GridLayout(3, 1); - selectionView.setLayout(layout); + /** Returns a DataSelectionView popup menu */ + public DataSelectionView getSelectionPopupMenu() { + DataSelectionView selectionView = new DataSelectionView(elementController); + GridLayout layout = new GridLayout(3, 1); + selectionView.setLayout(layout); - Dimension iconSize = new Dimension(32, 32); - Point loc = new Point(0, 0); + Dimension iconSize = new Dimension(32, 32); + Point loc = new Point(0, 0); - LightUpElementView element1 = new LightUpElementView(new LightUpCell(-2, null)); - element1.setSize(iconSize); - element1.setLocation(loc); - SelectionItemView item1 = new SelectionItemView(element1.getPuzzleElement(), new ImageIcon(element1.getImage())); - item1.addActionListener(elementController); - item1.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item1); + LightUpElementView element1 = new LightUpElementView(new LightUpCell(-2, null)); + element1.setSize(iconSize); + element1.setLocation(loc); + SelectionItemView item1 = + new SelectionItemView(element1.getPuzzleElement(), new ImageIcon(element1.getImage())); + item1.addActionListener(elementController); + item1.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item1); - LightUpElementView element2 = new LightUpElementView(new LightUpCell(-4, null)); - element2.setSize(iconSize); - element2.setLocation(loc); - SelectionItemView item2 = new SelectionItemView(element2.getPuzzleElement(), new ImageIcon(element2.getImage())); - item2.addActionListener(elementController); - item2.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item2); + LightUpElementView element2 = new LightUpElementView(new LightUpCell(-4, null)); + element2.setSize(iconSize); + element2.setLocation(loc); + SelectionItemView item2 = + new SelectionItemView(element2.getPuzzleElement(), new ImageIcon(element2.getImage())); + item2.addActionListener(elementController); + item2.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item2); - LightUpElementView element3 = new LightUpElementView(new LightUpCell(-3, null)); - element3.setSize(iconSize); - element3.setLocation(loc); - SelectionItemView item3 = new SelectionItemView(element3.getPuzzleElement(), new ImageIcon(element3.getImage())); - item3.addActionListener(elementController); - item3.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item3); + LightUpElementView element3 = new LightUpElementView(new LightUpCell(-3, null)); + element3.setSize(iconSize); + element3.setLocation(loc); + SelectionItemView item3 = + new SelectionItemView(element3.getPuzzleElement(), new ImageIcon(element3.getImage())); + item3.addActionListener(elementController); + item3.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item3); - return selectionView; - } + return selectionView; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java index d3e8cf506..bac5aa4ba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java @@ -3,7 +3,8 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class BlackTile extends NonPlaceableElement { - public BlackTile() { - super("LTUP-UNPL-0002", "Black Tile", "The black tile", "edu/rpi/legup/images/lightup/black.gif"); - } + public BlackTile() { + super( + "LTUP-UNPL-0002", "Black Tile", "The black tile", "edu/rpi/legup/images/lightup/black.gif"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java index 5fc4a334f..ce0629fbe 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java @@ -3,7 +3,7 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BulbTile extends PlaceableElement { - public BulbTile() { - super("LTUP-PLAC-0001", "Bulb Tile", "The bulb tile", "edu/rpi/legup/images/lightup/light.png"); - } + public BulbTile() { + super("LTUP-PLAC-0001", "Bulb Tile", "The bulb tile", "edu/rpi/legup/images/lightup/light.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java index e96a969e5..9a2fba5c7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java @@ -4,16 +4,20 @@ public class NumberTile extends NonPlaceableElement { - int object_number; + int object_number; - // Follow the default format and resolves the NoSuchMethod error - public NumberTile() { - super("LTUP-UNPL-0001", "Number Tile", "The number tile", "edu/rpi/legup/images/lightup/1.gif"); - } + // Follow the default format and resolves the NoSuchMethod error + public NumberTile() { + super("LTUP-UNPL-0001", "Number Tile", "The number tile", "edu/rpi/legup/images/lightup/1.gif"); + } - public NumberTile(int num) { - super("LTUP-UNPL-0001", "Number Tile", "The number tile", "edu/rpi/legup/images/lightup/" + num + ".gif"); - if (num > 3 || num < 1) num = 1; - object_number = num; - } + public NumberTile(int num) { + super( + "LTUP-UNPL-0001", + "Number Tile", + "The number tile", + "edu/rpi/legup/images/lightup/" + num + ".gif"); + if (num > 3 || num < 1) num = 1; + object_number = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java index 6839e70de..4e17c6b37 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super("LTUP-UNPL-0003", "Unknown Tile", "A blank tile", "edu/rpi/legup/images/lightup/UnknownTile.png"); - } + public UnknownTile() { + super( + "LTUP-UNPL-0003", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/lightup/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java index 2804e6eab..1adf449d0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java @@ -6,78 +6,76 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.awt.*; public class BulbsInPathContradictionRule extends ContradictionRule { - public BulbsInPathContradictionRule() { - super("LTUP-CONT-0001", "Bulbs In Path", - "A bulb cannot be placed in another bulb's path.", - "edu/rpi/legup/images/lightup/contradictions/BulbsInPath.png"); - } + public BulbsInPathContradictionRule() { + super( + "LTUP-CONT-0001", + "Bulbs In Path", + "A bulb cannot be placed in another bulb's path.", + "edu/rpi/legup/images/lightup/contradictions/BulbsInPath.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.BULB) { - return super.getNoContradictionMessage(); - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.BULB) { + return super.getNoContradictionMessage(); + } - Point location = cell.getLocation(); - for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.BULB) { - return null; - } - } + Point location = cell.getLocation(); + for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; } - for (int i = location.x - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.BULB) { - return null; - } - } + } + } + for (int i = location.x - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; } - for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.BULB) { - return null; - } - } + } + } + for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; } - for (int i = location.y - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.BULB) { - return null; - } - } + } + } + for (int i = location.y - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; } - return super.getNoContradictionMessage(); + } } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java index 011bf1c0a..b9b93620a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java @@ -6,86 +6,84 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.awt.*; public class CannotLightACellContradictionRule extends ContradictionRule { - public CannotLightACellContradictionRule() { - super("LTUP-CONT-0002", "Cannot Light A Cell", - "All cells must be able to be lit.", - "edu/rpi/legup/images/lightup/contradictions/CannotLightACell.png"); - } + public CannotLightACellContradictionRule() { + super( + "LTUP-CONT-0002", + "Cannot Light A Cell", + "All cells must be able to be lit.", + "edu/rpi/legup/images/lightup/contradictions/CannotLightACell.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - /*if (cell.getType() == LightUpCellType.BLACK || cell.getType() == LightUpCellType.NUMBER || cell.isLite()) { - return "This cell does not contain a contradiction"; - }*/ - if (cell.getType() != LightUpCellType.EMPTY || cell.isLite()) { - return super.getNoContradictionMessage(); - } - Point location = cell.getLocation(); - int ver_count = 0; - int hor_count = 0; - for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - hor_count += 1; - } - } - } - for (int i = location.x - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - hor_count += 1; - } - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + /*if (cell.getType() == LightUpCellType.BLACK || cell.getType() == LightUpCellType.NUMBER || cell.isLite()) { + return "This cell does not contain a contradiction"; + }*/ + if (cell.getType() != LightUpCellType.EMPTY || cell.isLite()) { + return super.getNoContradictionMessage(); + } + Point location = cell.getLocation(); + int ver_count = 0; + int hor_count = 0; + for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + hor_count += 1; } - for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - ver_count += 1; - } - } + } + } + for (int i = location.x - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + hor_count += 1; } - for (int i = location.y - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - ver_count += 1; - } - } + } + } + for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + ver_count += 1; } - System.out.printf("%d, %d, %d, %d\n", location.x, location.y, hor_count, ver_count); - if (hor_count == 0 && ver_count == 0) { - return null; + } + } + for (int i = location.y - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + ver_count += 1; } - return super.getNoContradictionMessage(); + } + } + System.out.printf("%d, %d, %d, %d\n", location.x, location.y, hor_count, ver_count); + if (hor_count == 0 && ver_count == 0) { + return null; } -} \ No newline at end of file + return super.getNoContradictionMessage(); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java index 290671cb8..857d2333d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java @@ -11,54 +11,57 @@ public class EmptyCellinLightDirectRule extends DirectRule { - public EmptyCellinLightDirectRule() { - super("LTUP-BASC-0002", "Empty Cells in Light", - "Cells in light must be empty.", - "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); - } + public EmptyCellinLightDirectRule() { + super( + "LTUP-BASC-0002", + "Empty Cells in Light", + "Cells in light must be empty.", + "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - initialBoard.fillWithLight(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); - if (finalCell.getType() == LightUpCellType.EMPTY && initCell.getType() == LightUpCellType.UNKNOWN && initCell.isLite()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + initialBoard.fillWithLight(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); + if (finalCell.getType() == LightUpCellType.EMPTY + && initCell.getType() == LightUpCellType.UNKNOWN + && initCell.isLite()) { + return null; } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java index 173c15fd2..e0e22b5f4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java @@ -8,108 +8,107 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.awt.*; import java.util.ArrayList; import java.util.List; public class EmptyCornersDirectRule extends DirectRule { - public EmptyCornersDirectRule() { - super("LTUP-BASC-0003", "Empty Corners", - "Cells on the corners of a number must be empty if placing bulbs would prevent the number from being satisfied.", - "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); - } + public EmptyCornersDirectRule() { + super( + "LTUP-BASC-0003", + "Empty Corners", + "Cells on the corners of a number must be empty if placing bulbs would prevent the number from being satisfied.", + "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(cell.getType() == LightUpCellType.UNKNOWN && finalCell.getType() == LightUpCellType.EMPTY)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; - } + if (!(cell.getType() == LightUpCellType.UNKNOWN + && finalCell.getType() == LightUpCellType.EMPTY)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; + } - Point loc = finalCell.getLocation(); - List numberedCells = new ArrayList<>(); - LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); - if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperRight); - } - LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); - if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperLeft); - } - LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); - if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerRight); - } - LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); - if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerLeft); - } - if (numberedCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() + ": This cell must diagonal to a numbered cell"; - } + Point loc = finalCell.getLocation(); + List numberedCells = new ArrayList<>(); + LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); + if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperRight); + } + LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); + if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperLeft); + } + LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); + if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerRight); + } + LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); + if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerLeft); + } + if (numberedCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + ": This cell must diagonal to a numbered cell"; + } - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - LightUpBoard bulbCaseBoard = finalBoard.copy(); - LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); - bulbCaseCell.setData(LightUpCellType.BULB.value); - bulbCaseBoard.fillWithLight(); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + LightUpBoard bulbCaseBoard = finalBoard.copy(); + LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); + bulbCaseCell.setData(LightUpCellType.BULB.value); + bulbCaseBoard.fillWithLight(); - boolean createsContra = false; - for (LightUpCell c : numberedCells) { - createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; - } - if (createsContra) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; - } + boolean createsContra = false; + for (LightUpCell c : numberedCells) { + createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; } + if (createsContra) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; + } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); - TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); - for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - int temp = cell.getData(); - cell.setData(LightUpCellType.EMPTY.value); - if (checkRuleRawAt(transition, cell) == null) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(modCell); - } - else { - cell.setData(temp); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); + TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); + for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + int temp = cell.getData(); + cell.setData(LightUpCellType.EMPTY.value); + if (checkRuleRawAt(transition, cell) == null) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(modCell); + } else { + cell.setData(temp); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java index 632a3e4dd..b2ae63788 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java @@ -8,100 +8,101 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.util.Set; public class FinishWithBulbsDirectRule extends DirectRule { - public FinishWithBulbsDirectRule() { - super("LTUP-BASC-0004", "Finish with Bulbs", - "The remaining unknowns around a block must be bulbs to satisfy the number.", - "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); - } + public FinishWithBulbsDirectRule() { + super( + "LTUP-BASC-0004", + "Finish with Bulbs", + "The remaining unknowns around a block must be bulbs to satisfy the number.", + "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == LightUpCellType.UNKNOWN && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == LightUpCellType.UNKNOWN + && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } - Set adjCells = finalBoard.getAdj(finalCell); - adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() + ": This cell is not adjacent to a numbered cell"; - } + Set adjCells = finalBoard.getAdj(finalCell); + adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + ": This cell is not adjacent to a numbered cell"; + } - LightUpBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return null; - } - } - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; + LightUpBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return null; + } } + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; + } - /** - * Determines whether the specified cell is forced to be a bulb or not - * - * @param board the entire board - * @param cell specified cell - * @return whether cell is forced to be a bulb or not - */ - private boolean isForced(LightUpBoard board, LightUpCell cell) { - Set adjCells = board.getAdj(cell); - adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return false; - } + /** + * Determines whether the specified cell is forced to be a bulb or not + * + * @param board the entire board + * @param cell specified cell + * @return whether cell is forced to be a bulb or not + */ + private boolean isForced(LightUpBoard board, LightUpCell cell) { + Set adjCells = board.getAdj(cell); + adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return false; + } - LightUpBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return true; - } - } - return false; + LightUpBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return true; + } } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { - cell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { + cell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java index ca90d4e0a..dc2647eb9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java @@ -8,111 +8,112 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.awt.*; public class FinishWithEmptyDirectRule extends DirectRule { - public FinishWithEmptyDirectRule() { - super("LTUP-BASC-0005", "Finish with Empty", - "The remaining unknowns around a block must be empty if the number is satisfied.", - "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.EMPTY) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; - } + public FinishWithEmptyDirectRule() { + super( + "LTUP-BASC-0005", + "Finish with Empty", + "The remaining unknowns around a block must be empty if the number is satisfied.", + "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); + } - if (isForced(initialBoard, cell.getLocation())) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.EMPTY) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; } - /** - * Checks whether a certain cell is forced to not be a bulb - * - * @param board specified board - * @param location location of cell to check - * @return boolean value based on whether a certain cell has an adjacent cell that has the required amount of adjacent bulbs - */ - private boolean isForced(LightUpBoard board, Point location) { - return isForcedEmpty(board, new Point(location.x + 1, location.y)) || - isForcedEmpty(board, new Point(location.x, location.y + 1)) || - isForcedEmpty(board, new Point(location.x - 1, location.y)) || - isForcedEmpty(board, new Point(location.x, location.y - 1)); + if (isForced(initialBoard, cell.getLocation())) { + return null; } + return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; + } - /** - * Checks whether a certain cell has the required amount of adjacent bulbs - * - * @param board specified board - * @param loc location of cell to check - * @return boolean value based on whether a certain cell has the required amount of adjacent bulbs - */ - private boolean isForcedEmpty(LightUpBoard board, Point loc) { - LightUpCell cell = board.getCell(loc.x, loc.y); - if (cell == null || cell.getType() != LightUpCellType.NUMBER) { - return false; - } + /** + * Checks whether a certain cell is forced to not be a bulb + * + * @param board specified board + * @param location location of cell to check + * @return boolean value based on whether a certain cell has an adjacent cell that has the + * required amount of adjacent bulbs + */ + private boolean isForced(LightUpBoard board, Point location) { + return isForcedEmpty(board, new Point(location.x + 1, location.y)) + || isForcedEmpty(board, new Point(location.x, location.y + 1)) + || isForcedEmpty(board, new Point(location.x - 1, location.y)) + || isForcedEmpty(board, new Point(location.x, location.y - 1)); + } - int bulbs = 0; - int bulbsNeeded = cell.getData(); - cell = board.getCell(loc.x + 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y + 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x - 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y - 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - return bulbs == bulbsNeeded; + /** + * Checks whether a certain cell has the required amount of adjacent bulbs + * + * @param board specified board + * @param loc location of cell to check + * @return boolean value based on whether a certain cell has the required amount of adjacent bulbs + */ + private boolean isForcedEmpty(LightUpBoard board, Point loc) { + LightUpCell cell = board.getCell(loc.x, loc.y); + if (cell == null || cell.getType() != LightUpCellType.NUMBER) { + return false; } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell.getLocation())) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } + int bulbs = 0; + int bulbsNeeded = cell.getData(); + cell = board.getCell(loc.x + 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y + 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x - 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y - 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + return bulbs == bulbsNeeded; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell.getLocation())) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java index 410c30e9c..39ad146a7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java @@ -8,101 +8,105 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.util.ArrayList; import java.util.List; public class LightOrEmptyCaseRule extends CaseRule { - public LightOrEmptyCaseRule() { - super("LTUP-CASE-0001", "Light or Empty", - "Each blank cell is either a light or empty.", - "edu/rpi/legup/images/lightup/cases/LightOrEmpty.png"); - } + public LightOrEmptyCaseRule() { + super( + "LTUP-CASE-0001", + "Light or Empty", + "Each blank cell is either a light or empty.", + "edu/rpi/legup/images/lightup/cases/LightOrEmpty.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); - lightUpBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((LightUpCell) data).getType() == LightUpCellType.UNKNOWN) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); + lightUpBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((LightUpCell) data).getType() == LightUpCellType.UNKNOWN) { + caseBoard.addPickableElement(data); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(-4); - case1.addModifiedData(data1); - cases.add(case1); - - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(-3); - case2.addModifiedData(data2); - cases.add(case2); - - return cases; - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(-4); + case1.addModifiedData(data1); + cases.add(case1); - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children"; - } + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(-3); + case2.addModifiedData(data2); + cases.add(case2); - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 || - case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 1 modified cell for each case"; - } + return cases; + } - LightUpCell mod1 = (LightUpCell) case1.getBoard().getModifiedData().iterator().next(); - LightUpCell mod2 = (LightUpCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must modify the same cell for each case"; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children"; + } - if (!((mod1.getType() == LightUpCellType.EMPTY && mod2.getType() == LightUpCellType.BULB) || - (mod2.getType() == LightUpCellType.EMPTY && mod1.getType() == LightUpCellType.BULB))) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must an empty cell and a bulb cell"; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; + } - return null; + LightUpCell mod1 = (LightUpCell) case1.getBoard().getModifiedData().iterator().next(); + LightUpCell mod2 = (LightUpCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case"; } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + if (!((mod1.getType() == LightUpCellType.EMPTY && mod2.getType() == LightUpCellType.BULB) + || (mod2.getType() == LightUpCellType.EMPTY && mod1.getType() == LightUpCellType.BULB))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty cell and a bulb cell"; } + + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java index 6b44fc0b7..272450959 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java @@ -8,142 +8,145 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.awt.*; public class MustLightDirectRule extends DirectRule { - public MustLightDirectRule() { - super("LTUP-BASC-0006", "Must Light", - "A cell must be a bulb if it is the only cell to be able to light another.", - "edu/rpi/legup/images/lightup/rules/MustLight.png"); - } + public MustLightDirectRule() { + super( + "LTUP-BASC-0006", + "Must Light", + "A cell must be a bulb if it is the only cell to be able to light another.", + "edu/rpi/legup/images/lightup/rules/MustLight.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == LightUpCellType.UNKNOWN && !parentCell.isLite() && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(parentCell.getType() == LightUpCellType.UNKNOWN + && !parentCell.isLite() + && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } - finalBoard.fillWithLight(); - boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); - finalCell.setData(LightUpCellType.BULB.value); - finalBoard.fillWithLight(); + finalBoard.fillWithLight(); + boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); + finalCell.setData(LightUpCellType.BULB.value); + finalBoard.fillWithLight(); - if (isForced) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; - } + if (isForced) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; } + } - private boolean isForcedBulb(LightUpBoard board, Point loc) { - CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); - LightUpBoard modifiedBoard = board.copy(); - LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); - modifiedCell.setData(LightUpCellType.EMPTY.value); - //Check if this cell itself (the one with the bulb) has no other lighting option - if ((modifiedCell.getType() == LightUpCellType.EMPTY || modifiedCell.getType() == LightUpCellType.UNKNOWN) && - !modifiedCell.isLite() && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { - return true; - } - //Look right - for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.EMPTY && - !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } + private boolean isForcedBulb(LightUpBoard board, Point loc) { + CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); + LightUpBoard modifiedBoard = board.copy(); + LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); + modifiedCell.setData(LightUpCellType.EMPTY.value); + // Check if this cell itself (the one with the bulb) has no other lighting option + if ((modifiedCell.getType() == LightUpCellType.EMPTY + || modifiedCell.getType() == LightUpCellType.UNKNOWN) + && !modifiedCell.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { + return true; + } + // Look right + for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; } - //Look left - for (int i = loc.x - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.EMPTY && - !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } + } + } + // Look left + for (int i = loc.x - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; } - //Look down - for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.EMPTY && - !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } + } + } + // Look down + for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; } - //Look up - for (int i = loc.y - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else { - if (c.getType() == LightUpCellType.EMPTY && - !c.isLite() && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } + } + } + // Look up + for (int i = loc.y - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; } - return false; + } } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : tempBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - if (isForcedBulb(initialBoard, cell.getLocation())) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(modCell); - } - cell.setData(LightUpCellType.UNKNOWN.value); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : tempBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + if (isForcedBulb(initialBoard, cell.getLocation())) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(modCell); } + cell.setData(LightUpCellType.UNKNOWN.value); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java index cf7b70ccd..7e9f258a3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java @@ -9,7 +9,6 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.awt.*; import java.util.ArrayList; import java.util.Iterator; @@ -18,336 +17,337 @@ public class SatisfyNumberCaseRule extends CaseRule { - public SatisfyNumberCaseRule() { - super("LTUP-CASE-0002", "Satisfy Number", - "The different ways a blocks number can be satisfied.", - "edu/rpi/legup/images/lightup/cases/SatisfyNumber.png"); + public SatisfyNumberCaseRule() { + super( + "LTUP-CASE-0002", + "Satisfy Number", + "The different ways a blocks number can be satisfied.", + "edu/rpi/legup/images/lightup/cases/SatisfyNumber.png"); + } + + @Override + public CaseBoard getCaseBoard(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + lightUpBoard.setModifiable(false); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((LightUpCell) data).getType() == LightUpCellType.NUMBER) { + caseBoard.addPickableElement(data); + } } - - @Override - public CaseBoard getCaseBoard(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - lightUpBoard.setModifiable(false); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((LightUpCell) data).getType() == LightUpCellType.NUMBER) { - caseBoard.addPickableElement(data); - } + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); + + List openSpots = new ArrayList<>(); + + int numNeeded = cell.getData(); + + LightUpCell checkCell = lightUpBoard.getCell(loc.x + 1, loc.y); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; } - return caseBoard; + } } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); - - List openSpots = new ArrayList<>(); - - int numNeeded = cell.getData(); - - LightUpCell checkCell = lightUpBoard.getCell(loc.x + 1, loc.y); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } - else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; - } - } + checkCell = lightUpBoard.getCell(loc.x, loc.y + 1); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; } - checkCell = lightUpBoard.getCell(loc.x, loc.y + 1); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } - else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; - } - } - } - checkCell = lightUpBoard.getCell(loc.x - 1, loc.y); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } - else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; - } - } + } + } + checkCell = lightUpBoard.getCell(loc.x - 1, loc.y); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; } - checkCell = lightUpBoard.getCell(loc.x, loc.y - 1); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } - else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; - } - } + } + } + checkCell = lightUpBoard.getCell(loc.x, loc.y - 1); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; } + } + } - ArrayList cases = new ArrayList<>(); - if (numNeeded == 0) { - return cases; - } + ArrayList cases = new ArrayList<>(); + if (numNeeded == 0) { + return cases; + } - generateCases(lightUpBoard, numNeeded, openSpots, cases); + generateCases(lightUpBoard, numNeeded, openSpots, cases); - return cases; - } + return cases; + } - private void generateCases(final LightUpBoard board, final int num, List openSpots, List cases) { - if (num > openSpots.size()) { - return; - } + private void generateCases( + final LightUpBoard board, final int num, List openSpots, List cases) { + if (num > openSpots.size()) { + return; + } - for (int i = 0; i < openSpots.size(); i++) { - LightUpCell c = openSpots.get(i); - LightUpBoard newCase = board.copy(); - LightUpCell newCell = c.copy(); - Point loc = c.getLocation(); + for (int i = 0; i < openSpots.size(); i++) { + LightUpCell c = openSpots.get(i); + LightUpBoard newCase = board.copy(); + LightUpCell newCell = c.copy(); + Point loc = c.getLocation(); - newCell.setData(-4); - newCase.setCell(loc.x, loc.y, newCell); - newCase.addModifiedData(newCell); + newCell.setData(-4); + newCase.setCell(loc.x, loc.y, newCell); + newCase.addModifiedData(newCell); - generateCases(board, num, openSpots, cases, newCase, i); - } + generateCases(board, num, openSpots, cases, newCase, i); + } + } + + private void generateCases( + final LightUpBoard board, + final int num, + List openSpots, + List cases, + LightUpBoard curBoard, + int index) { + if (num <= curBoard.getModifiedData().size()) { + cases.add(curBoard); + return; } - private void generateCases(final LightUpBoard board, final int num, List openSpots, List cases, LightUpBoard curBoard, int index) { - if (num <= curBoard.getModifiedData().size()) { - cases.add(curBoard); - return; - } - - for (int i = index + 1; i < openSpots.size(); i++) { - LightUpCell c = openSpots.get(i); - Point loc = c.getLocation(); - LightUpCell cc = curBoard.getCell(loc.x, loc.y); - if (!curBoard.getModifiedData().contains(cc)) { - LightUpBoard newCase = board.copy(); - LightUpCell newCell = c.copy(); + for (int i = index + 1; i < openSpots.size(); i++) { + LightUpCell c = openSpots.get(i); + Point loc = c.getLocation(); + LightUpCell cc = curBoard.getCell(loc.x, loc.y); + if (!curBoard.getModifiedData().contains(cc)) { + LightUpBoard newCase = board.copy(); + LightUpCell newCell = c.copy(); - for (PuzzleElement mod : curBoard.getModifiedData()) { - LightUpCell modCell = (LightUpCell) mod.copy(); - Point modLoc = modCell.getLocation(); + for (PuzzleElement mod : curBoard.getModifiedData()) { + LightUpCell modCell = (LightUpCell) mod.copy(); + Point modLoc = modCell.getLocation(); - modCell.setData(-4); + modCell.setData(-4); - newCase.setCell(modLoc.x, modLoc.y, modCell); - newCase.addModifiedData(modCell); - } + newCase.setCell(modLoc.x, modLoc.y, modCell); + newCase.addModifiedData(modCell); + } - newCell.setData(-4); + newCell.setData(-4); - newCase.setCell(loc.x, loc.y, newCell); - newCase.addModifiedData(newCell); + newCase.setCell(loc.x, loc.y, newCell); + newCase.addModifiedData(newCell); - generateCases(board, num, openSpots, cases, newCase, i); - } - } + generateCases(board, num, openSpots, cases, newCase, i); + } + } + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + TreeNode parent = transition.getParents().get(0); + List childTransitions = parent.getChildren(); + + List spots = getPossibleSpots(transition); + if (spots == null) { + return super.getInvalidUseOfRuleMessage(); } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - TreeNode parent = transition.getParents().get(0); - List childTransitions = parent.getChildren(); - - List spots = getPossibleSpots(transition); - if (spots == null) { - return super.getInvalidUseOfRuleMessage(); - } - - for (LightUpCell c : spots) { - ArrayList cases = getCases(parent.getBoard(), c); - - // We will allow case rules to have only one option - if (cases.size() == childTransitions.size() && cases.size() >= 1) { - boolean foundSpot = true; - for (TreeTransition childTrans : childTransitions) { - LightUpBoard actCase = (LightUpBoard) childTrans.getBoard(); - boolean foundBoard = false; - for (Board b : cases) { - LightUpBoard posCase = (LightUpBoard) b; - boolean foundAllCells = false; - if (posCase.getModifiedData().size() == actCase.getModifiedData().size()) { - foundAllCells = true; - for (PuzzleElement actEle : actCase.getModifiedData()) { - LightUpCell actCell = (LightUpCell) actEle; - boolean foundCell = false; - for (PuzzleElement posEle : posCase.getModifiedData()) { - LightUpCell posCell = (LightUpCell) posEle; - if (actCell.getType() == posCell.getType() && - actCell.getLocation().equals(posCell.getLocation())) { - foundCell = true; - break; - } - } - if (!foundCell) { - foundAllCells = false; - break; - } - } - } - if (foundAllCells) { - foundBoard = true; - break; - } - } - if (!foundBoard) { - foundSpot = false; - break; - } + for (LightUpCell c : spots) { + ArrayList cases = getCases(parent.getBoard(), c); + + // We will allow case rules to have only one option + if (cases.size() == childTransitions.size() && cases.size() >= 1) { + boolean foundSpot = true; + for (TreeTransition childTrans : childTransitions) { + LightUpBoard actCase = (LightUpBoard) childTrans.getBoard(); + boolean foundBoard = false; + for (Board b : cases) { + LightUpBoard posCase = (LightUpBoard) b; + boolean foundAllCells = false; + if (posCase.getModifiedData().size() == actCase.getModifiedData().size()) { + foundAllCells = true; + for (PuzzleElement actEle : actCase.getModifiedData()) { + LightUpCell actCell = (LightUpCell) actEle; + boolean foundCell = false; + for (PuzzleElement posEle : posCase.getModifiedData()) { + LightUpCell posCell = (LightUpCell) posEle; + if (actCell.getType() == posCell.getType() + && actCell.getLocation().equals(posCell.getLocation())) { + foundCell = true; + break; + } } - if (foundSpot) { - return null; + if (!foundCell) { + foundAllCells = false; + break; } + } } + if (foundAllCells) { + foundBoard = true; + break; + } + } + if (!foundBoard) { + foundSpot = false; + break; + } + } + if (foundSpot) { + return null; } - return super.getInvalidUseOfRuleMessage(); + } } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Gets all cells in the TreeTransition board that are adjacent to all modified cells + * + * @param transition TreeTransition object + * @return list of cells that are adjacent to all modified cells, returns null if the number of + * modified cells is =0 || >4 + */ + private List getPossibleSpots(TreeTransition transition) { + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Set modCells = transition.getBoard().getModifiedData(); + + int size = modCells.size(); + if (size == 0 || size > 4) { + return null; + } else { + Iterator it = modCells.iterator(); + List spots = getAdjacentCells(board, (LightUpCell) it.next()); + + while (it.hasNext()) { + spots.retainAll(getAdjacentCells(board, (LightUpCell) it.next())); + } + return spots; } - - /** - * Gets all cells in the TreeTransition board that are adjacent to all modified cells - * - * @param transition TreeTransition object - * @return list of cells that are adjacent to all modified cells, returns null if the number of modified cells is =0 || >4 - */ - private List getPossibleSpots(TreeTransition transition) { - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Set modCells = transition.getBoard().getModifiedData(); - - int size = modCells.size(); - if (size == 0 || size > 4) { - return null; - } - else { - Iterator it = modCells.iterator(); - List spots = getAdjacentCells(board, (LightUpCell) it.next()); - - while (it.hasNext()) { - spots.retainAll(getAdjacentCells(board, (LightUpCell) it.next())); - } - return spots; - } + } + + private List getAdjacentCells(LightUpBoard board, LightUpCell cell) { + List cells = new ArrayList<>(); + Point point = cell.getLocation(); + LightUpCell right = board.getCell(point.x + 1, point.y); + if (right != null) { + cells.add(right); } - - private List getAdjacentCells(LightUpBoard board, LightUpCell cell) { - List cells = new ArrayList<>(); - Point point = cell.getLocation(); - LightUpCell right = board.getCell(point.x + 1, point.y); - if (right != null) { - cells.add(right); + LightUpCell down = board.getCell(point.x, point.y + 1); + if (down != null) { + cells.add(down); + } + LightUpCell left = board.getCell(point.x - 1, point.y); + if (left != null) { + cells.add(left); + } + LightUpCell up = board.getCell(point.x, point.y - 1); + if (up != null) { + cells.add(up); + } + return cells; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + LightUpBoard puzzleBoard = (LightUpBoard) board; + LightUpCell point = (LightUpCell) puzzleBoard.getPuzzleElement(puzzleElement); + + List cells = getAdjacentCells(puzzleBoard, point); + + for (LightUpCell cell : cells) { + // add cells that can light adjacents from any direction + Point location = cell.getLocation(); + for (int i = location.x; i < puzzleBoard.getWidth(); i++) { + System.out.println(i); + LightUpCell c = puzzleBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); } - LightUpCell down = board.getCell(point.x, point.y + 1); - if (down != null) { - cells.add(down); + } + for (int i = location.x; i >= 0; i--) { + LightUpCell c = puzzleBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); } - LightUpCell left = board.getCell(point.x - 1, point.y); - if (left != null) { - cells.add(left); + } + for (int i = location.y; i < puzzleBoard.getHeight(); i++) { + LightUpCell c = puzzleBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); } - LightUpCell up = board.getCell(point.x, point.y - 1); - if (up != null) { - cells.add(up); + } + for (int i = location.y; i >= 0; i--) { + LightUpCell c = puzzleBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); } - return cells; + } } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be valid - * Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends upon. - * Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - LightUpBoard puzzleBoard = (LightUpBoard) board; - LightUpCell point = (LightUpCell)puzzleBoard.getPuzzleElement(puzzleElement); - - List cells = getAdjacentCells(puzzleBoard,point); - - for (LightUpCell cell : cells) { - //add cells that can light adjacents from any direction - Point location = cell.getLocation(); - for (int i = location.x; i < puzzleBoard.getWidth(); i++) { - System.out.println(i); - LightUpCell c = puzzleBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); - } - } - for (int i = location.x; i >= 0; i--) { - LightUpCell c = puzzleBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); - } - } - for (int i = location.y; i < puzzleBoard.getHeight(); i++) { - LightUpCell c = puzzleBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); - } - } - for (int i = location.y; i >= 0; i--) { - LightUpCell c = puzzleBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } - else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); - } - } - } - - return elements; - } + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java index f36c4ca57..8b00e537e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java @@ -6,39 +6,41 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.awt.*; public class TooFewBulbsContradictionRule extends ContradictionRule { - public TooFewBulbsContradictionRule() { - super("LTUP-CONT-0003", "Too Few Bulbs", - "There cannot be less bulbs around a block than its number states.", - "edu/rpi/legup/images/lightup/contradictions/TooFewBulbs.png"); - } + public TooFewBulbsContradictionRule() { + super( + "LTUP-CONT-0003", + "Too Few Bulbs", + "There cannot be less bulbs around a block than its number states.", + "edu/rpi/legup/images/lightup/contradictions/TooFewBulbs.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.NUMBER) { - return super.getNoContradictionMessage(); - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.NUMBER) { + return super.getNoContradictionMessage(); + } - int bulbs = lightUpBoard.getNumAdj(cell, LightUpCellType.BULB); - int placeable = lightUpBoard.getNumPlacble(cell); + int bulbs = lightUpBoard.getNumAdj(cell, LightUpCellType.BULB); + int placeable = lightUpBoard.getNumPlacble(cell); - if (bulbs + placeable < cell.getData()) { - return null; - } - return super.getNoContradictionMessage(); + if (bulbs + placeable < cell.getData()) { + return null; } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java index ffe7ca4d1..8d1403663 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java @@ -6,57 +6,59 @@ import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; - import java.awt.*; public class TooManyBulbsContradictionRule extends ContradictionRule { - public TooManyBulbsContradictionRule() { - super("LTUP-CONT-0004", "Too Many Bulbs", - "There cannot be more bulbs around a block than its number states.", - "edu/rpi/legup/images/lightup/contradictions/TooManyBulbs.png"); + public TooManyBulbsContradictionRule() { + super( + "LTUP-CONT-0004", + "Too Many Bulbs", + "There cannot be more bulbs around a block than its number states.", + "edu/rpi/legup/images/lightup/contradictions/TooManyBulbs.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.NUMBER) { + return super.getNoContradictionMessage(); + } + + Point location = cell.getLocation(); + + int bulbs = 0; + + LightUpCell up = lightUpBoard.getCell(location.x, location.y + 1); + if (up != null && up.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell down = lightUpBoard.getCell(location.x, location.y - 1); + if (down != null && down.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell right = lightUpBoard.getCell(location.x + 1, location.y); + if (right != null && right.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell left = lightUpBoard.getCell(location.x - 1, location.y); + if (left != null && left.getType() == LightUpCellType.BULB) { + bulbs++; } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.NUMBER) { - return super.getNoContradictionMessage(); - } - - Point location = cell.getLocation(); - - int bulbs = 0; - - LightUpCell up = lightUpBoard.getCell(location.x, location.y + 1); - if (up != null && up.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell down = lightUpBoard.getCell(location.x, location.y - 1); - if (down != null && down.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell right = lightUpBoard.getCell(location.x + 1, location.y); - if (right != null && right.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell left = lightUpBoard.getCell(location.x - 1, location.y); - if (left != null && left.getType() == LightUpCellType.BULB) { - bulbs++; - } - - if (bulbs > cell.getData()) { - return null; - } - return super.getNoContradictionMessage(); + if (bulbs > cell.getData()) { + return null; } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java b/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java index 827be37ff..98e22173e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java @@ -1,5 +1,7 @@ package edu.rpi.legup.puzzle.masyu; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.history.PuzzleCommand; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.gameboard.Board; @@ -12,163 +14,157 @@ import edu.rpi.legup.ui.boardview.BoardView; import edu.rpi.legup.ui.boardview.ElementView; import edu.rpi.legup.ui.proofeditorui.treeview.*; - import java.awt.event.MouseEvent; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class EditLineCommand extends PuzzleCommand { - private TreeTransition transition; - private PuzzleElement oldData; - private PuzzleElement newData; - - private ElementView elementView; - private TreeElementView selectedView; - private TreeElementView newSelectedView; - private MouseEvent event; - - private TreeTransitionView transitionView; - - public EditLineCommand(ElementView elementView, TreeElementView selectedView, MouseEvent event, MasyuLine line) { - this.elementView = elementView; - this.selectedView = selectedView; - this.event = event; - this.newData = line; - this.oldData = newData.copy(); - this.transition = null; + private TreeTransition transition; + private PuzzleElement oldData; + private PuzzleElement newData; + + private ElementView elementView; + private TreeElementView selectedView; + private TreeElementView newSelectedView; + private MouseEvent event; + + private TreeTransitionView transitionView; + + public EditLineCommand( + ElementView elementView, TreeElementView selectedView, MouseEvent event, MasyuLine line) { + this.elementView = elementView; + this.selectedView = selectedView; + this.event = event; + this.newData = line; + this.oldData = newData.copy(); + this.transition = null; + } + + /** Executes a command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + Puzzle puzzle = getInstance().getPuzzleModule(); + + MasyuBoard board = (MasyuBoard) selectedView.getTreeElement().getBoard(); + int index = elementView.getIndex(); + + if (selectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); + + if (transition == null) { + transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + } + + treeNode.getChildren().add(transition); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeElementAdded(transition)); + transitionView = (TreeTransitionView) treeView.getElementView(transition); + + selection.newSelection(transitionView); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeSelectionChanged(selection)); + + getInstance().getLegupUI().repaintTree(); + board = (MasyuBoard) transition.getBoard(); + getInstance().getPuzzleModule().setCurrentBoard(board); + oldData = newData.copy(); + } else { + transitionView = (TreeTransitionView) selectedView; + transition = transitionView.getTreeElement(); } - - /** - * Executes a command - */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - Puzzle puzzle = getInstance().getPuzzleModule(); - - MasyuBoard board = (MasyuBoard) selectedView.getTreeElement().getBoard(); - int index = elementView.getIndex(); - - if (selectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); - - if (transition == null) { - transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - } - - treeNode.getChildren().add(transition); - puzzle.notifyTreeListeners((ITreeListener listener) -> listener.onTreeElementAdded(transition)); - transitionView = (TreeTransitionView) treeView.getElementView(transition); - - selection.newSelection(transitionView); - puzzle.notifyTreeListeners((ITreeListener listener) -> listener.onTreeSelectionChanged(selection)); - - getInstance().getLegupUI().repaintTree(); - board = (MasyuBoard) transition.getBoard(); - getInstance().getPuzzleModule().setCurrentBoard(board); - oldData = newData.copy(); - } - else { - transitionView = (TreeTransitionView) selectedView; - transition = transitionView.getTreeElement(); - } - newSelectedView = transitionView; - PuzzleElement dup_line = null; - boolean mod_contains = false; - boolean contains = false; - final MasyuBoard editBoard = board; - System.out.println("Size: " + board.getModifiedData().size()); - for (PuzzleElement puzzleElement : board.getModifiedData()) { - if (puzzleElement instanceof MasyuLine) { - if (((MasyuLine) newData).compare((MasyuLine) puzzleElement)) { - System.out.println("contains"); - dup_line = puzzleElement; - mod_contains = true; - } - } - } - for (int i = 0; i < board.getLines().size(); i++) { - if (board.getLines().get(i).compare((MasyuLine) newData)) { - contains = true; - } - } - if (contains || mod_contains) { - System.out.println("delete"); - board.getModifiedData().remove(dup_line); - board.getLines().remove(dup_line); -// puzzle.notifyBoardListeners((IBoardListener listener) -> listener.onTreeElementChanged(editBoard)); + newSelectedView = transitionView; + PuzzleElement dup_line = null; + boolean mod_contains = false; + boolean contains = false; + final MasyuBoard editBoard = board; + System.out.println("Size: " + board.getModifiedData().size()); + for (PuzzleElement puzzleElement : board.getModifiedData()) { + if (puzzleElement instanceof MasyuLine) { + if (((MasyuLine) newData).compare((MasyuLine) puzzleElement)) { + System.out.println("contains"); + dup_line = puzzleElement; + mod_contains = true; } - else { - System.out.println("adding"); - board.getModifiedData().add(newData); - board.getLines().add((MasyuLine) newData); -// puzzle.notifyBoardListeners((IBoardListener listener) -> listener.onTreeElementChanged(editBoard)); - } - - transition.propagateChange(newData); + } + } + for (int i = 0; i < board.getLines().size(); i++) { + if (board.getLines().get(i).compare((MasyuLine) newData)) { + contains = true; + } + } + if (contains || mod_contains) { + System.out.println("delete"); + board.getModifiedData().remove(dup_line); + board.getLines().remove(dup_line); + // puzzle.notifyBoardListeners((IBoardListener listener) -> + // listener.onTreeElementChanged(editBoard)); + } else { + System.out.println("adding"); + board.getModifiedData().add(newData); + board.getLines().add((MasyuLine) newData); + // puzzle.notifyBoardListeners((IBoardListener listener) -> + // listener.onTreeElementChanged(editBoard)); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - Board board = selectedView.getTreeElement().getBoard(); - if (!board.isModifiable()) { - return "Board is not modifiable"; - } - else { - if (!board.getPuzzleElement(elementView.getPuzzleElement()).isModifiable()) { - return "Data is not modifiable"; - } - } - return null; + transition.propagateChange(newData); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + Board board = selectedView.getTreeElement().getBoard(); + if (!board.isModifiable()) { + return "Board is not modifiable"; + } else { + if (!board.getPuzzleElement(elementView.getPuzzleElement()).isModifiable()) { + return "Data is not modifiable"; + } } + return null; + } - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); - Board board = transition.getBoard(); + Board board = transition.getBoard(); - if (selectedView.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); + if (selectedView.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); - tree.removeTreeElement(transition); - treeView.removeTreeElement(newSelectedView); + tree.removeTreeElement(transition); + treeView.removeTreeElement(newSelectedView); - selection.newSelection(selectedView); + selection.newSelection(selectedView); - getInstance().getLegupUI().repaintTree(); - getInstance().getPuzzleModule().setCurrentBoard(treeNode.getBoard()); - } + getInstance().getLegupUI().repaintTree(); + getInstance().getPuzzleModule().setCurrentBoard(treeNode.getBoard()); + } - Board prevBoard = null;// transition.getParentNode().getBoard(); + Board prevBoard = null; // transition.getParentNode().getBoard(); - newData.setData(oldData.getData()); - board.notifyChange(newData); + newData.setData(oldData.getData()); + board.notifyChange(newData); - //System.err.println(newData.getData() + " : " + oldData.getData()); + // System.err.println(newData.getData() + " : " + oldData.getData()); - if (prevBoard.getPuzzleElement(elementView.getPuzzleElement()).equalsData(newData)) { - board.removeModifiedData(newData); - } - else { - board.addModifiedData(newData); - } - transition.propagateChange(newData); + if (prevBoard.getPuzzleElement(elementView.getPuzzleElement()).equalsData(newData)) { + board.removeModifiedData(newData); + } else { + board.addModifiedData(newData); } + transition.propagateChange(newData); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java b/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java index b339630e9..1c5d19e08 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java @@ -5,68 +5,63 @@ public class Masyu extends Puzzle { - public Masyu() { - super(); + public Masyu() { + super(); - this.name = "Masyu"; + this.name = "Masyu"; - this.importer = new MasyuImporter(this); - this.exporter = new MasyuExporter(this); + this.importer = new MasyuImporter(this); + this.exporter = new MasyuExporter(this); - this.factory = new MasyuCellFactory(); + this.factory = new MasyuCellFactory(); + } - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new MasyuView((MasyuBoard) currentBoard); + } - /** - * Initializes the game board. Called by the invoker of the class - */ - @Override - public void initializeView() { - boardView = new MasyuView((MasyuBoard) currentBoard); - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + @Override + /** + * Determines if the given dimensions are valid for Masyu + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Masyu, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - @Override - /** - * Determines if the given dimensions are valid for Masyu - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Masyu, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { - - } + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java index 96183bcfe..554408dd3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java @@ -2,60 +2,58 @@ import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.util.ArrayList; import java.util.List; public class MasyuBoard extends GridBoard { - private List lines; + private List lines; - public MasyuBoard(int width, int height) { - super(width, height); - this.lines = new ArrayList<>(); - } + public MasyuBoard(int width, int height) { + super(width, height); + this.lines = new ArrayList<>(); + } - public MasyuBoard(int size) { - this(size, size); - } + public MasyuBoard(int size) { + this(size, size); + } - @Override - public MasyuCell getCell(int x, int y) { - return (MasyuCell) super.getCell(x, y); - } + @Override + public MasyuCell getCell(int x, int y) { + return (MasyuCell) super.getCell(x, y); + } - public List getLines() { - return lines; - } + public List getLines() { + return lines; + } - public void setLines(List lines) { - this.lines = lines; - } + public void setLines(List lines) { + this.lines = lines; + } - @Override - public void notifyChange(PuzzleElement puzzleElement) { - if (puzzleElement instanceof MasyuLine) { - lines.add((MasyuLine) puzzleElement); - } - else { - super.notifyChange(puzzleElement); - } + @Override + public void notifyChange(PuzzleElement puzzleElement) { + if (puzzleElement instanceof MasyuLine) { + lines.add((MasyuLine) puzzleElement); + } else { + super.notifyChange(puzzleElement); } - - @Override - public MasyuBoard copy() { - MasyuBoard copy = new MasyuBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (MasyuLine line : lines) { - copy.lines.add(line.copy()); - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + } + + @Override + public MasyuBoard copy() { + MasyuBoard copy = new MasyuBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (MasyuLine line : lines) { + copy.lines.add(line.copy()); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java index af32dbfb6..7d23cdf37 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java @@ -1,25 +1,24 @@ package edu.rpi.legup.puzzle.masyu; import edu.rpi.legup.model.gameboard.GridCell; - import java.awt.*; public class MasyuCell extends GridCell { - public MasyuCell(MasyuType value, Point location) { - super(value, location); - } + public MasyuCell(MasyuType value, Point location) { + super(value, location); + } - public MasyuType getType() { - return data; - } + public MasyuType getType() { + return data; + } - @Override - public MasyuCell copy() { - MasyuCell copy = new MasyuCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public MasyuCell copy() { + MasyuCell copy = new MasyuCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java index 5278e0036..803edfbea 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java @@ -4,72 +4,69 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class MasyuCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public MasyuCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Masyu Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public MasyuCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException("Masyu Factory: unknown puzzleElement puzzleElement"); + } - MasyuBoard masyuBoard = (MasyuBoard) board; - int width = masyuBoard.getWidth(); - int height = masyuBoard.getHeight(); + MasyuBoard masyuBoard = (MasyuBoard) board; + int width = masyuBoard.getWidth(); + int height = masyuBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Masyu Factory: cell location out of bounds"); - } - if (value < 0 || value > 2) { - throw new InvalidFileFormatException("Masyu Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("Masyu Factory: cell location out of bounds"); + } + if (value < 0 || value > 2) { + throw new InvalidFileFormatException("Masyu Factory: cell unknown value"); + } - MasyuCell cell = new MasyuCell(MasyuType.convertToMasyuType(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Masyu Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("Masyu Factory: could not find attribute(s)"); - } + MasyuCell cell = new MasyuCell(MasyuType.convertToMasyuType(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("Masyu Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Masyu Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - MasyuCell cell = (MasyuCell) puzzleElement; - Point loc = cell.getLocation(); + MasyuCell cell = (MasyuCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java index 02328c691..1644e4d11 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java @@ -1,102 +1,102 @@ package edu.rpi.legup.puzzle.masyu; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.ui.boardview.BoardView; - import java.awt.*; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class MasyuController extends ElementController { - private MasyuElementView mousePressedCell; - private MasyuElementView mouseDraggedCell; - private List masyuLine; + private MasyuElementView mousePressedCell; + private MasyuElementView mouseDraggedCell; + private List masyuLine; - public MasyuController() { - super(); - this.mousePressedCell = null; - this.mouseDraggedCell = null; - this.masyuLine = new ArrayList<>(); - } + public MasyuController() { + super(); + this.mousePressedCell = null; + this.mouseDraggedCell = null; + this.masyuLine = new ArrayList<>(); + } - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e the event to be processed - */ - @Override - public void mousePressed(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - this.masyuLine.clear(); - mousePressedCell = (MasyuElementView) boardView.getElement(e.getPoint()); - masyuLine.add(mousePressedCell); - } + /** + * Invoked when a mouse button has been pressed on a component. + * + * @param e the event to be processed + */ + @Override + public void mousePressed(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + this.masyuLine.clear(); + mousePressedCell = (MasyuElementView) boardView.getElement(e.getPoint()); + masyuLine.add(mousePressedCell); + } - @Override - public void mouseDragged(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - MasyuElementView elementView = (MasyuElementView) boardView.getElement(e.getPoint()); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (mousePressedCell != null && elementView != null) { - if (mouseDraggedCell == null) { - mouseDraggedCell = elementView; - Point p1 = mousePressedCell.getPuzzleElement().getLocation(); - Point p2 = mouseDraggedCell.getPuzzleElement().getLocation(); + @Override + public void mouseDragged(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + MasyuElementView elementView = (MasyuElementView) boardView.getElement(e.getPoint()); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (mousePressedCell != null && elementView != null) { + if (mouseDraggedCell == null) { + mouseDraggedCell = elementView; + Point p1 = mousePressedCell.getPuzzleElement().getLocation(); + Point p2 = mouseDraggedCell.getPuzzleElement().getLocation(); - if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { - masyuLine.add(elementView); - MasyuLine newLine = new MasyuLine(mousePressedCell.getPuzzleElement(), mouseDraggedCell.getPuzzleElement()); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); - } - } - else { - if (mouseDraggedCell != elementView) { - Point p1 = mouseDraggedCell.getPuzzleElement().getLocation(); - Point p2 = elementView.getPuzzleElement().getLocation(); + if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { + masyuLine.add(elementView); + MasyuLine newLine = + new MasyuLine( + mousePressedCell.getPuzzleElement(), mouseDraggedCell.getPuzzleElement()); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); + } + } else { + if (mouseDraggedCell != elementView) { + Point p1 = mouseDraggedCell.getPuzzleElement().getLocation(); + Point p2 = elementView.getPuzzleElement().getLocation(); - if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { - masyuLine.add(elementView); - MasyuLine newLine = new MasyuLine(mouseDraggedCell.getPuzzleElement(), elementView.getPuzzleElement()); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); - } - mouseDraggedCell = elementView; - } - } + if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { + masyuLine.add(elementView); + MasyuLine newLine = + new MasyuLine(mouseDraggedCell.getPuzzleElement(), elementView.getPuzzleElement()); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); + } + mouseDraggedCell = elementView; } + } } + } - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - mousePressedCell = null; - mouseDraggedCell = null; - masyuLine.clear(); - } + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + mousePressedCell = null; + mouseDraggedCell = null; + masyuLine.clear(); + } - /** - * Alters the cells as they are being dragged over or clicked - * - * @param e Mouse event being used - * @param data Data of selected cell - */ - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - MasyuCell cell = (MasyuCell) data; - if (cell.getData() == MasyuType.BLACK || cell.getData() == MasyuType.WHITE) { - return; - } - if (cell.getData() == MasyuType.UNKNOWN) { - data.setData(3); - } - else { - data.setData(0); - } + /** + * Alters the cells as they are being dragged over or clicked + * + * @param e Mouse event being used + * @param data Data of selected cell + */ + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + MasyuCell cell = (MasyuCell) data; + if (cell.getData() == MasyuType.BLACK || cell.getData() == MasyuType.WHITE) { + return; + } + if (cell.getData() == MasyuType.UNKNOWN) { + data.setData(3); + } else { + data.setData(0); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java index b2f1f8902..d01e74033 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java @@ -1,54 +1,51 @@ package edu.rpi.legup.puzzle.masyu; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; public class MasyuElementView extends GridElementView { - public MasyuElementView(MasyuCell masyuCell) { - super(masyuCell); - } + public MasyuElementView(MasyuCell masyuCell) { + super(masyuCell); + } - @Override - public MasyuCell getPuzzleElement() { - return (MasyuCell) super.getPuzzleElement(); - } + @Override + public MasyuCell getPuzzleElement() { + return (MasyuCell) super.getPuzzleElement(); + } - @Override - public void drawElement(Graphics2D graphics2D) { - MasyuCell cell = (MasyuCell) puzzleElement; - MasyuType type = cell.getType(); - if (type == MasyuType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - else { - if (type == MasyuType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - else { - if (type == MasyuType.WHITE) { - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.WHITE); - graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); - graphics2D.setColor(Color.BLACK); - graphics2D.drawOval(location.x + 6, location.y + 6, 18, 18); - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - } + @Override + public void drawElement(Graphics2D graphics2D) { + MasyuCell cell = (MasyuCell) puzzleElement; + MasyuType type = cell.getType(); + if (type == MasyuType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == MasyuType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == MasyuType.WHITE) { + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.WHITE); + graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); + graphics2D.setColor(Color.BLACK); + graphics2D.drawOval(location.x + 6, location.y + 6, 18, 18); + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java index e5fb071b4..0f8555ce0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java @@ -2,37 +2,35 @@ import edu.rpi.legup.model.PuzzleExporter; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import org.w3c.dom.Document; public class MasyuExporter extends PuzzleExporter { - public MasyuExporter(Masyu masyu) { - super(masyu); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - MasyuBoard board; - if (puzzle.getTree() != null) { - board = (MasyuBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (MasyuBoard) puzzle.getBoardView().getBoard(); - } + public MasyuExporter(Masyu masyu) { + super(masyu); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + MasyuBoard board; + if (puzzle.getTree() != null) { + board = (MasyuBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (MasyuBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - MasyuCell cell = (MasyuCell) puzzleElement; - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + MasyuCell cell = (MasyuCell) puzzleElement; + org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java index 3e0d328c4..b5db71234 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java @@ -2,107 +2,104 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.awt.*; - public class MasyuImporter extends PuzzleImporter { - public MasyuImporter(Masyu masyu) { - super(masyu); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + public MasyuImporter(Masyu masyu) { + super(masyu); + } - @Override - public boolean acceptsTextInput() { - return false; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Masyu Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Masyu Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} - MasyuBoard masyuBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - masyuBoard = new MasyuBoard(size); - } - else { - if (!boardElement.getAttribute("width").isEmpty() && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - masyuBoard = new MasyuBoard(width, height); - } - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("Masyu Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("Masyu Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - if (masyuBoard == null) { - throw new InvalidFileFormatException("Masyu Importer: invalid board dimensions"); - } + MasyuBoard masyuBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + masyuBoard = new MasyuBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + masyuBoard = new MasyuBoard(width, height); + } + } - int width = masyuBoard.getWidth(); - int height = masyuBoard.getHeight(); + if (masyuBoard == null) { + throw new InvalidFileFormatException("Masyu Importer: invalid board dimensions"); + } - for (int i = 0; i < elementDataList.getLength(); i++) { - MasyuCell cell = (MasyuCell) puzzle.getFactory().importCell(elementDataList.item(i), masyuBoard); - Point loc = cell.getLocation(); - if (cell.getData() != MasyuType.UNKNOWN) { - cell.setModifiable(false); - cell.setGiven(true); - } - masyuBoard.setCell(loc.x, loc.y, cell); - } + int width = masyuBoard.getWidth(); + int height = masyuBoard.getHeight(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (masyuBoard.getCell(x, y) == null) { - MasyuCell cell = new MasyuCell(MasyuType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - masyuBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(masyuBoard); + for (int i = 0; i < elementDataList.getLength(); i++) { + MasyuCell cell = + (MasyuCell) puzzle.getFactory().importCell(elementDataList.item(i), masyuBoard); + Point loc = cell.getLocation(); + if (cell.getData() != MasyuType.UNKNOWN) { + cell.setModifiable(false); + cell.setGiven(true); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Masyu Importer: unknown value where integer expected"); + masyuBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (masyuBoard.getCell(x, y) == null) { + MasyuCell cell = new MasyuCell(MasyuType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + masyuBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(masyuBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("Masyu Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Masyu cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Masyu cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java index d8c3240c7..30924ea57 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java @@ -4,38 +4,40 @@ import edu.rpi.legup.utility.Entry; public class MasyuLine extends PuzzleElement> { - public MasyuLine(MasyuCell c1, MasyuCell c2) { - this.data = new Entry<>(c1, c2); - } - - public MasyuCell getC1() { - return data.getKey(); - } - - public void setC1(MasyuCell c1) { - this.data.setKey(c1); - } - - public MasyuCell getC2() { - return data.getValue(); - } - - public void setC2(MasyuCell c2) { - this.data.setValue(c2); - } - - public boolean compare(MasyuLine line) { - return ((line.getC1().getLocation().equals(data.getKey().getLocation()) && line.getC2().getLocation().equals(data.getValue().getLocation())) || - (line.getC1().getLocation().equals(data.getValue().getLocation()) && line.getC2().getLocation().equals(data.getKey().getLocation()))); - } - - /** - * Copies this elements puzzleElement to a new PuzzleElement object - * - * @return copied PuzzleElement object - */ - @Override - public MasyuLine copy() { - return new MasyuLine(data.getKey().copy(), data.getValue().copy()); - } + public MasyuLine(MasyuCell c1, MasyuCell c2) { + this.data = new Entry<>(c1, c2); + } + + public MasyuCell getC1() { + return data.getKey(); + } + + public void setC1(MasyuCell c1) { + this.data.setKey(c1); + } + + public MasyuCell getC2() { + return data.getValue(); + } + + public void setC2(MasyuCell c2) { + this.data.setValue(c2); + } + + public boolean compare(MasyuLine line) { + return ((line.getC1().getLocation().equals(data.getKey().getLocation()) + && line.getC2().getLocation().equals(data.getValue().getLocation())) + || (line.getC1().getLocation().equals(data.getValue().getLocation()) + && line.getC2().getLocation().equals(data.getKey().getLocation()))); + } + + /** + * Copies this elements puzzleElement to a new PuzzleElement object + * + * @return copied PuzzleElement object + */ + @Override + public MasyuLine copy() { + return new MasyuLine(data.getKey().copy(), data.getValue().copy()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java index d527ca414..54efc335f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java @@ -1,31 +1,30 @@ package edu.rpi.legup.puzzle.masyu; import edu.rpi.legup.ui.boardview.ElementView; - import java.awt.*; public class MasyuLineView extends ElementView { - private final Color LINE_COLOR = Color.GREEN; + private final Color LINE_COLOR = Color.GREEN; - private final Stroke LINE_STROKE = new BasicStroke(3); + private final Stroke LINE_STROKE = new BasicStroke(3); - public MasyuLineView(MasyuLine line) { - super(line); - } + public MasyuLineView(MasyuLine line) { + super(line); + } - @Override - public void draw(Graphics2D graphics2D) { - MasyuLine line = (MasyuLine) puzzleElement; - Point p1 = line.getC1().getLocation(); - Point p2 = line.getC2().getLocation(); - int x1 = p1.x * size.width + size.width / 2; - int y1 = p1.y * size.height + size.height / 2; + @Override + public void draw(Graphics2D graphics2D) { + MasyuLine line = (MasyuLine) puzzleElement; + Point p1 = line.getC1().getLocation(); + Point p2 = line.getC2().getLocation(); + int x1 = p1.x * size.width + size.width / 2; + int y1 = p1.y * size.height + size.height / 2; - int x2 = p2.x * size.width + size.width / 2; - int y2 = p2.y * size.height + size.height / 2; + int x2 = p2.x * size.width + size.width / 2; + int y2 = p2.y * size.height + size.height / 2; - graphics2D.setColor(line.isModified() ? Color.GREEN : Color.BLACK); - graphics2D.setStroke(LINE_STROKE); - graphics2D.drawLine(x1, y1, x2, y2); - } + graphics2D.setColor(line.isModified() ? Color.GREEN : Color.BLACK); + graphics2D.setStroke(LINE_STROKE); + graphics2D.drawLine(x1, y1, x2, y2); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java index 264350a95..114e4bf71 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java @@ -1,21 +1,21 @@ package edu.rpi.legup.puzzle.masyu; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - public enum MasyuType { - UNKNOWN, BLACK, WHITE, LINE; + UNKNOWN, + BLACK, + WHITE, + LINE; - public static MasyuType convertToMasyuType(int num) { - switch (num) { - case 1: - return BLACK; - case 2: - return WHITE; - case 3: - return LINE; - default: - return UNKNOWN; - } + public static MasyuType convertToMasyuType(int num) { + switch (num) { + case 1: + return BLACK; + case 2: + return WHITE; + case 3: + return LINE; + default: + return UNKNOWN; } + } } - diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java index ac60dbe66..dc81b24cd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java @@ -3,53 +3,52 @@ import edu.rpi.legup.controller.BoardController; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.ui.boardview.GridBoardView; - import java.awt.*; import java.util.ArrayList; import java.util.List; public class MasyuView extends GridBoardView { - private List lineViews; + private List lineViews; - public MasyuView(MasyuBoard board) { - super(new BoardController(), new MasyuController(), board.getDimension()); + public MasyuView(MasyuBoard board) { + super(new BoardController(), new MasyuController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - MasyuCell cell = (MasyuCell) puzzleElement; - Point loc = cell.getLocation(); - MasyuElementView elementView = new MasyuElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } - lineViews = new ArrayList<>(); - for (MasyuLine line : board.getLines()) { - MasyuLineView lineView = new MasyuLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + MasyuCell cell = (MasyuCell) puzzleElement; + Point loc = cell.getLocation(); + MasyuElementView elementView = new MasyuElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } - - @Override - public void drawBoard(Graphics2D graphics2D) { - graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - super.drawBoard(graphics2D); - lineViews.forEach(masyuLineView -> masyuLineView.draw(graphics2D)); + lineViews = new ArrayList<>(); + for (MasyuLine line : board.getLines()) { + MasyuLineView lineView = new MasyuLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); } + } + + @Override + public void drawBoard(Graphics2D graphics2D) { + graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + super.drawBoard(graphics2D); + lineViews.forEach(masyuLineView -> masyuLineView.draw(graphics2D)); + } - /** - * Called when the board puzzleElement changed - * - * @param puzzleElement puzzleElement of the puzzleElement that changed - */ - @Override - public void onBoardDataChanged(PuzzleElement puzzleElement) { - if (puzzleElement instanceof MasyuLine) { - MasyuLineView lineView = new MasyuLineView((MasyuLine) puzzleElement); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - repaint(); + /** + * Called when the board puzzleElement changed + * + * @param puzzleElement puzzleElement of the puzzleElement that changed + */ + @Override + public void onBoardDataChanged(PuzzleElement puzzleElement) { + if (puzzleElement instanceof MasyuLine) { + MasyuLineView lineView = new MasyuLineView((MasyuLine) puzzleElement); + lineView.setSize(elementSize); + lineViews.add(lineView); } + repaint(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java index 0da4dffe2..f4dd95268 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java @@ -6,22 +6,25 @@ public class BadLoopingContradictionRule extends ContradictionRule { - public BadLoopingContradictionRule() { - super("MASY-CONT-0001", "Bad Looping", - "", - "edu/rpi/legup/images/masyu/ContradictionBadLooping.png"); - } + public BadLoopingContradictionRule() { + super( + "MASY-CONT-0001", + "Bad Looping", + "", + "edu/rpi/legup/images/masyu/ContradictionBadLooping.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java index b4d32a46a..f4e95eb14 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java @@ -6,22 +6,21 @@ public class BlackContradictionRule extends ContradictionRule { - public BlackContradictionRule() { - super("MASY-CONT-0002", "Black", - "", - "edu/rpi/legup/images/masyu/ContradictionBlack.png"); - } + public BlackContradictionRule() { + super("MASY-CONT-0002", "Black", "", "edu/rpi/legup/images/masyu/ContradictionBlack.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java index f9f29be75..63b40d7f3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java @@ -8,35 +8,33 @@ public class BlackEdgeDirectRule extends DirectRule { - public BlackEdgeDirectRule() { - super("MASY-BASC-0001", "Black Edge", - "", - "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); - } + public BlackEdgeDirectRule() { + super("MASY-BASC-0001", "Black Edge", "", "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java index 3db89ef58..2b598321c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java @@ -5,63 +5,63 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.List; public class BlackSplitCaseRule extends CaseRule { - public BlackSplitCaseRule() { - super("MASY-CASE-0001", "Black Split", - "", - "edu/rpi/legup/images/masyu/CaseBlackSplit.png"); - } + public BlackSplitCaseRule() { + super("MASY-CASE-0001", "Black Split", "", "edu/rpi/legup/images/masyu/CaseBlackSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java index 6b191fee7..faa311450 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java @@ -8,35 +8,33 @@ public class BlockedBlackDirectRule extends DirectRule { - public BlockedBlackDirectRule() { - super("MASY-BASC-0002", "Blocked Black", - "", - "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); - } + public BlockedBlackDirectRule() { + super("MASY-BASC-0002", "Blocked Black", "", "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java index ad1e6a264..1a49b83a1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java @@ -8,35 +8,37 @@ public class ConnectedCellsDirectRule extends DirectRule { - public ConnectedCellsDirectRule() { - super("MASY-BASC-0003", "Connected Cells", - "", - "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); - } + public ConnectedCellsDirectRule() { + super( + "MASY-BASC-0003", + "Connected Cells", + "", + "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java index 9fe7f3fa7..f6c95050b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java @@ -8,35 +8,33 @@ public class FinishPathDirectRule extends DirectRule { - public FinishPathDirectRule() { - super("MASY-BASC-0004", "Finished Path", - "", - "edu/rpi/legup/images/masyu/RuleFinishPath.png"); - } + public FinishPathDirectRule() { + super("MASY-BASC-0004", "Finished Path", "", "edu/rpi/legup/images/masyu/RuleFinishPath.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java index e6ecd872b..67ed25d64 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java @@ -8,35 +8,33 @@ public class NearWhiteDirectRule extends DirectRule { - public NearWhiteDirectRule() { - super("MASY-BASC-0005", "Near White", - "", - "edu/rpi/legup/images/masyu/RuleNearWhite.png"); - } + public NearWhiteDirectRule() { + super("MASY-BASC-0005", "Near White", "", "edu/rpi/legup/images/masyu/RuleNearWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java index 19da790aa..f068c6503 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java @@ -6,22 +6,25 @@ public class NoOptionsContradictionRule extends ContradictionRule { - public NoOptionsContradictionRule() { - super("MASY-CONT-0003", "No Options", - "", - "edu/rpi/legup/images/masyu/ContradictionNoOptions.png"); - } + public NoOptionsContradictionRule() { + super( + "MASY-CONT-0003", + "No Options", + "", + "edu/rpi/legup/images/masyu/ContradictionNoOptions.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java index ab47adc1b..015a7dcf9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java @@ -5,63 +5,63 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.List; public class NormalSplitCaseRule extends CaseRule { - public NormalSplitCaseRule() { - super("MASY-CASE-0002", "Normal Split", - "", - "edu/rpi/legup/images/masyu/CaseNormalSplit.png"); - } + public NormalSplitCaseRule() { + super("MASY-CASE-0002", "Normal Split", "", "edu/rpi/legup/images/masyu/CaseNormalSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java index 017768867..b25ac8c09 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java @@ -8,35 +8,37 @@ public class OnlyOneChoiceDirectRule extends DirectRule { - public OnlyOneChoiceDirectRule() { - super("MASY-BASC-0006", "Only One Choice", - "", - "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); - } + public OnlyOneChoiceDirectRule() { + super( + "MASY-BASC-0006", + "Only One Choice", + "", + "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java index ab587a0ec..bda563b2e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java @@ -6,22 +6,21 @@ public class OnlyTwoContradictionRule extends ContradictionRule { - public OnlyTwoContradictionRule() { - super("MASY-CONT-0004", "Only Two", - "", - "edu/rpi/legup/images/masyu/ContradictionOnly2.png"); - } + public OnlyTwoContradictionRule() { + super("MASY-CONT-0004", "Only Two", "", "edu/rpi/legup/images/masyu/ContradictionOnly2.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java index 091c2b039..4ae418c36 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java @@ -6,22 +6,21 @@ public class WhiteContradictionRule extends ContradictionRule { - public WhiteContradictionRule() { - super("MASY-CONT-0005", "White", - "", - "edu/rpi/legup/images/masyu/ContradictionWhite.png"); - } + public WhiteContradictionRule() { + super("MASY-CONT-0005", "White", "", "edu/rpi/legup/images/masyu/ContradictionWhite.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java index 67488775e..e653c96b0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java @@ -7,35 +7,33 @@ import edu.rpi.legup.model.tree.TreeTransition; public class WhiteEdgeDirectRule extends DirectRule { - public WhiteEdgeDirectRule() { - super("MASY-BASC-0007", "White Edge", - "", - "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); - } + public WhiteEdgeDirectRule() { + super("MASY-BASC-0007", "White Edge", "", "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * This method is the one that should overridden in child classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java index e45fde0a1..e8eb97cd8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java @@ -5,63 +5,63 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - import java.util.List; public class WhiteSplitCaseRule extends CaseRule { - public WhiteSplitCaseRule() { - super("MASY-CASE-0003", "White Split", - "", - "edu/rpi/legup/images/masyu/CaseWhiteSplit.png"); - } + public WhiteSplitCaseRule() { + super("MASY-CASE-0003", "White Split", "", "edu/rpi/legup/images/masyu/CaseWhiteSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific puzzleElement index using - * this rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java index 2edbcb039..c8aa80012 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java @@ -6,81 +6,77 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Nurikabe extends Puzzle { - public Nurikabe() { - super(); + public Nurikabe() { + super(); - this.name = "Nurikabe"; + this.name = "Nurikabe"; - this.importer = new NurikabeImporter(this); - this.exporter = new NurikabeExporter(this); + this.importer = new NurikabeImporter(this); + this.exporter = new NurikabeExporter(this); - this.factory = new NurikabeCellFactory(); - } + this.factory = new NurikabeCellFactory(); + } - /** - * Initializes the game board. Called by the invoker of the class - */ - @Override - public void initializeView() { - boardView = new NurikabeView((NurikabeBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new NurikabeView((NurikabeBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Nurikabe - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Nurikabe, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows >= 2 && columns >= 2; - } + @Override + /** + * Determines if the given dimensions are valid for Nurikabe + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Nurikabe, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows >= 2 && columns >= 2; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(nurikabeBoard) == null) { - return false; - } - } - for (PuzzleElement data : nurikabeBoard.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.UNKNOWN) { - return false; - } - } - return true; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(nurikabeBoard) == null) { + return false; + } } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { - + for (PuzzleElement data : nurikabeBoard.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.UNKNOWN) { + return false; + } } + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java index d5b83d1e8..7be7813ac 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java @@ -1,54 +1,56 @@ package edu.rpi.legup.puzzle.nurikabe; -import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; public class NurikabeBoard extends GridBoard { - public NurikabeBoard(int width, int height) { - super(width, height); - } + public NurikabeBoard(int width, int height) { + super(width, height); + } - public NurikabeBoard(int size) { - super(size, size); - } + public NurikabeBoard(int size) { + super(size, size); + } - @Override - public NurikabeCell getCell(int x, int y) { - if (y * dimension.width + x >= puzzleElements.size() || x >= dimension.width || - y >= dimension.height || x < 0 || y < 0) { - return null; - } - return (NurikabeCell) super.getCell(x, y); + @Override + public NurikabeCell getCell(int x, int y) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return null; } + return (NurikabeCell) super.getCell(x, y); + } - /** - * Gets the cells as an int array - * - * @return int array of values - */ - public int[][] getIntArray() { - int[][] arr = new int[dimension.height][dimension.width]; - for (int i = 0; i < dimension.height; i++) { - for (int k = 0; k < dimension.width; k++) { - arr[i][k] = getCell(k, i).getData(); - } - } - return arr; + /** + * Gets the cells as an int array + * + * @return int array of values + */ + public int[][] getIntArray() { + int[][] arr = new int[dimension.height][dimension.width]; + for (int i = 0; i < dimension.height; i++) { + for (int k = 0; k < dimension.width; k++) { + arr[i][k] = getCell(k, i).getData(); + } } + return arr; + } - @Override - public NurikabeBoard copy() { - // System.out.println("NurikabeBoard copy()"); - NurikabeBoard copy = new NurikabeBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + @Override + public NurikabeBoard copy() { + // System.out.println("NurikabeBoard copy()"); + NurikabeBoard copy = new NurikabeBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java index f84a3c9f1..4f92c6227 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java @@ -1,95 +1,92 @@ package edu.rpi.legup.puzzle.nurikabe; -import edu.rpi.legup.model.gameboard.GridCell; import edu.rpi.legup.model.elements.Element; - +import edu.rpi.legup.model.gameboard.GridCell; import java.awt.*; import java.awt.event.MouseEvent; public class NurikabeCell extends GridCell { - /** - * NurikabeCell Constructor - creates a NurikabeCell from the specified value and location - * - * @param value value of the NurikabeCell - * @param location position of the NurikabeCell - */ - public NurikabeCell(int value, Point location) { - super(value, location); - } + /** + * NurikabeCell Constructor - creates a NurikabeCell from the specified value and location + * + * @param value value of the NurikabeCell + * @param location position of the NurikabeCell + */ + public NurikabeCell(int value, Point location) { + super(value, location); + } - /** - * Gets the type of this NurikabeCell - * - * @return type of NurikabeCell - */ - public NurikabeType getType() { - switch (data) { - case -2: - return NurikabeType.UNKNOWN; - case -1: - return NurikabeType.BLACK; - case 0: - return NurikabeType.WHITE; - default: - if (data > 0) { - return NurikabeType.NUMBER; - } + /** + * Gets the type of this NurikabeCell + * + * @return type of NurikabeCell + */ + public NurikabeType getType() { + switch (data) { + case -2: + return NurikabeType.UNKNOWN; + case -1: + return NurikabeType.BLACK; + case 0: + return NurikabeType.WHITE; + default: + if (data > 0) { + return NurikabeType.NUMBER; } - return null; } + return null; + } - /** - * Sets the type of this NurikabeCell - * - * @param e element to set the type of this nurikabe cell to - */ - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()){ - case "NURI-PLAC-0001": - this.data = -1; - break; - case "NURI-PLAC-0002": - this.data = 0; - break; - case "NURI-UNPL-0001": - switch (m.getButton()){ - case MouseEvent.BUTTON1: - if (this.data <= 0 || this.data > 8) { - this.data = 1; - } - else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 1) { - this.data = this.data - 1; - } - else { - this.data = 9; - } - break; - } - break; - default: - this.data = -2; - break; + /** + * Sets the type of this NurikabeCell + * + * @param e element to set the type of this nurikabe cell to + */ + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "NURI-PLAC-0001": + this.data = -1; + break; + case "NURI-PLAC-0002": + this.data = 0; + break; + case "NURI-UNPL-0001": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data <= 0 || this.data > 8) { + this.data = 1; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 1) { + this.data = this.data - 1; + } else { + this.data = 9; + } + break; } + break; + default: + this.data = -2; + break; } + } - /** - * Performs a deep copy on the NurikabeCell - * - * @return a new copy of the NurikabeCell that is independent of this one - */ - @Override - public NurikabeCell copy() { - NurikabeCell copy = new NurikabeCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } -} \ No newline at end of file + /** + * Performs a deep copy on the NurikabeCell + * + * @return a new copy of the NurikabeCell that is independent of this one + */ + @Override + public NurikabeCell copy() { + NurikabeCell copy = new NurikabeCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java index b754f3e46..298acfb7b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java @@ -4,72 +4,71 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class NurikabeCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public NurikabeCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("nurikabe Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public NurikabeCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown puzzleElement puzzleElement"); + } - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int width = nurikabeBoard.getWidth(); - int height = nurikabeBoard.getHeight(); + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("nurikabe Factory: cell location out of bounds"); - } - if (value < -2) { - throw new InvalidFileFormatException("nurikabe Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("nurikabe Factory: cell location out of bounds"); + } + if (value < -2) { + throw new InvalidFileFormatException("nurikabe Factory: cell unknown value"); + } - NurikabeCell cell = new NurikabeCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("nurikabe Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); - } + NurikabeCell cell = new NurikabeCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - NurikabeCell cell = (NurikabeCell) puzzleElement; - Point loc = cell.getLocation(); + NurikabeCell cell = (NurikabeCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java index c115498a8..e87f661eb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java @@ -2,46 +2,44 @@ import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.event.MouseEvent; public class NurikabeController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - NurikabeCell cell = (NurikabeCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView.getSelectionPopupMenu().show(boardView, this.boardView.getCanvas().getX() + e.getX(), this.boardView.getCanvas().getY() + e.getY()); - } - else { - if (cell.getData() == -2) { - data.setData(0); - } - else { - if (cell.getData() == 0) { - data.setData(-1); - } - else { - data.setData(-2); - } - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + NurikabeCell cell = (NurikabeCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == -2) { + data.setData(0); + } else { + if (cell.getData() == 0) { + data.setData(-1); + } else { + data.setData(-2); + } } - else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == -2) { - data.setData(-1); - } - else { - if (cell.getData() == 0) { - data.setData(-2); - } - else { - data.setData(0); - } - } - } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == -2) { + data.setData(-1); + } else { + if (cell.getData() == 0) { + data.setData(-2); + } else { + data.setData(0); + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java index f122a7a5b..6569cfaf7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java @@ -1,72 +1,68 @@ package edu.rpi.legup.puzzle.nurikabe; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; public class NurikabeElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; - public NurikabeElementView(NurikabeCell cell) { - super(cell); - } + public NurikabeElementView(NurikabeCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public NurikabeCell getPuzzleElement() { - return (NurikabeCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public NurikabeCell getPuzzleElement() { + return (NurikabeCell) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + NurikabeType type = cell.getType(); + if (type == NurikabeType.NUMBER) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.WHITE); + graphics2D.fillRect(location.x, location.y, size.width, size.height); - @Override - public void drawElement(Graphics2D graphics2D) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - NurikabeType type = cell.getType(); - if (type == NurikabeType.NUMBER) { + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } else { + if (type == NurikabeType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.BLACK); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } else { + if (type == NurikabeType.WHITE) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.WHITE); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == NurikabeType.UNKNOWN) { graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.WHITE); + graphics2D.setColor(Color.LIGHT_GRAY); graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); graphics2D.drawRect(location.x, location.y, size.width, size.height); - - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } - else { - if (type == NurikabeType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.BLACK); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } - else { - if (type == NurikabeType.WHITE) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.WHITE); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - else { - if (type == NurikabeType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - } - } + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java index 095642a6e..1a0f06bb2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java @@ -6,34 +6,34 @@ public class NurikabeExporter extends PuzzleExporter { - public NurikabeExporter(Nurikabe nurikabe) { - super(nurikabe); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - NurikabeBoard board; - if (puzzle.getTree() != null) { - board = (NurikabeBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (NurikabeBoard) puzzle.getBoardView().getBoard(); - } + public NurikabeExporter(Nurikabe nurikabe) { + super(nurikabe); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + NurikabeBoard board; + if (puzzle.getTree() != null) { + board = (NurikabeBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (NurikabeBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java index 2cbcc9ad0..2be1ba899 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java @@ -2,117 +2,117 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.awt.*; - public class NurikabeImporter extends PuzzleImporter { - public NurikabeImporter(Nurikabe nurikabe) { - super(nurikabe); - } + public NurikabeImporter(Nurikabe nurikabe) { + super(nurikabe); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - NurikabeBoard nurikabeBoard = new NurikabeBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + NurikabeBoard nurikabeBoard = new NurikabeBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - nurikabeBoard.setCell(x, y, cell); - } - } - puzzle.setCurrentBoard(nurikabeBoard); + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + nurikabeBoard.setCell(x, y, cell); + } } + puzzle.setCurrentBoard(nurikabeBoard); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("nurikabe Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("nurikabe Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - NurikabeBoard nurikabeBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - nurikabeBoard = new NurikabeBoard(size); - } - else { - if (!boardElement.getAttribute("width").isEmpty() && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - nurikabeBoard = new NurikabeBoard(width, height); - } - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("nurikabe Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("nurikabe Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - if (nurikabeBoard == null) { - throw new InvalidFileFormatException("nurikabe Importer: invalid board dimensions"); - } + NurikabeBoard nurikabeBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + nurikabeBoard = new NurikabeBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + nurikabeBoard = new NurikabeBoard(width, height); + } + } - int width = nurikabeBoard.getWidth(); - int height = nurikabeBoard.getHeight(); + if (nurikabeBoard == null) { + throw new InvalidFileFormatException("nurikabe Importer: invalid board dimensions"); + } - for (int i = 0; i < elementDataList.getLength(); i++) { - NurikabeCell cell = (NurikabeCell) puzzle.getFactory().importCell(elementDataList.item(i), nurikabeBoard); - Point loc = cell.getLocation(); - if (cell.getData() != NurikabeType.UNKNOWN.toValue()) { - cell.setModifiable(false); - cell.setGiven(true); - } - nurikabeBoard.setCell(loc.x, loc.y, cell); - } + int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (nurikabeBoard.getCell(x, y) == null) { - NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - nurikabeBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(nurikabeBoard); + for (int i = 0; i < elementDataList.getLength(); i++) { + NurikabeCell cell = + (NurikabeCell) puzzle.getFactory().importCell(elementDataList.item(i), nurikabeBoard); + Point loc = cell.getLocation(); + if (cell.getData() != NurikabeType.UNKNOWN.toValue()) { + cell.setModifiable(false); + cell.setGiven(true); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("nurikabe Importer: unknown value where integer expected"); + nurikabeBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (nurikabeBoard.getCell(x, y) == null) { + NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + nurikabeBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(nurikabeBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Nurikabe cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Nurikabe cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java index 1dbab645d..a692a27fe 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java @@ -1,9 +1,12 @@ package edu.rpi.legup.puzzle.nurikabe; public enum NurikabeType { - UNKNOWN, BLACK, WHITE, NUMBER; + UNKNOWN, + BLACK, + WHITE, + NUMBER; - public int toValue() { - return this.ordinal() - 2; - } + public int toValue() { + return this.ordinal() - 2; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java index 024cf6bb2..f6b1a02a4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java @@ -2,7 +2,6 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.utility.DisjointSets; - import java.awt.*; import java.util.HashMap; import java.util.HashSet; @@ -11,297 +10,303 @@ public class NurikabeUtilities { - /** - * Gets all of the numbered cells in the Nurikabe board - * - * @param board nurikabe board - * @return a list of all of the numbered cells - */ - public static Set getNurikabeNumberedCells(NurikabeBoard board) { - Set numberedCells = new HashSet<>(); + /** + * Gets all of the numbered cells in the Nurikabe board + * + * @param board nurikabe board + * @return a list of all of the numbered cells + */ + public static Set getNurikabeNumberedCells(NurikabeBoard board) { + Set numberedCells = new HashSet<>(); + + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.NUMBER) { + numberedCells.add(cell); + } + } + return numberedCells; + } + + /** + * Gets nurikabe regions of black, white, and unknown cells + * + * @param board nurikabe board + * @return a disjoint set of the regions + */ + public static DisjointSets getNurikabeRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); + + DisjointSets regions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + regions.createSet((NurikabeCell) data); + } - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.NUMBER) { - numberedCells.add(cell); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + + if (cell.getType() == NurikabeType.NUMBER || cell.getType() == NurikabeType.WHITE) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.NUMBER + || rightCell.getType() == NurikabeType.WHITE)) { + regions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.NUMBER + || downCell.getType() == NurikabeType.WHITE)) { + regions.union(cell, downCell); + } + } else { + if (cell.getType() == NurikabeType.BLACK) { + if (rightCell != null && rightCell.getType() == NurikabeType.BLACK) { + regions.union(cell, rightCell); } + if (downCell != null && downCell.getType() == NurikabeType.BLACK) { + regions.union(cell, downCell); + } + } else { + if (cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null && rightCell.getType() == NurikabeType.UNKNOWN) { + regions.union(cell, rightCell); + } + if (downCell != null && downCell.getType() == NurikabeType.UNKNOWN) { + regions.union(cell, downCell); + } + } + } } - return numberedCells; + } + } + return regions; + } + + /** + * Gets the disjoint set containing the possible black regions be interpreting all unknown cells + * as black cells + * + * @param board nurikabe board + * @return the disjoint set containing the possible black regions + */ + public static DisjointSets getPossibleBlackRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); + + DisjointSets blackRegions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { + blackRegions.createSet(cell); + } } - /** - * Gets nurikabe regions of black, white, and unknown cells - * - * @param board nurikabe board - * @return a disjoint set of the regions - */ - public static DisjointSets getNurikabeRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); - - DisjointSets regions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - regions.createSet((NurikabeCell) data); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.BLACK + || rightCell.getType() == NurikabeType.UNKNOWN)) { + blackRegions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.BLACK + || downCell.getType() == NurikabeType.UNKNOWN)) { + blackRegions.union(cell, downCell); + } } + } + } + return blackRegions; + } + + /** + * Gets the disjoint set containing the possible white regions be interpreting all unknown cells + * as white cells + * + * @param board nurikabe board + * @return the disjoint set containing the possible white regions + */ + public static DisjointSets getPossibleWhiteRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); + + DisjointSets whiteRegions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.WHITE + || cell.getType() == NurikabeType.NUMBER + || cell.getType() == NurikabeType.UNKNOWN) { + whiteRegions.createSet(cell); + } + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - - if (cell.getType() == NurikabeType.NUMBER || - cell.getType() == NurikabeType.WHITE) { - if (rightCell != null && (rightCell.getType() == NurikabeType.NUMBER || - rightCell.getType() == NurikabeType.WHITE)) { - regions.union(cell, rightCell); - } - if (downCell != null && (downCell.getType() == NurikabeType.NUMBER || - downCell.getType() == NurikabeType.WHITE)) { - regions.union(cell, downCell); - } - } - else { - if (cell.getType() == NurikabeType.BLACK) { - if (rightCell != null && rightCell.getType() == NurikabeType.BLACK) { - regions.union(cell, rightCell); - } - if (downCell != null && downCell.getType() == NurikabeType.BLACK) { - regions.union(cell, downCell); - } - } - else { - if (cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null && rightCell.getType() == NurikabeType.UNKNOWN) { - regions.union(cell, rightCell); - } - if (downCell != null && downCell.getType() == NurikabeType.UNKNOWN) { - regions.union(cell, downCell); - } - } - } - } - } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + if (cell.getType() == NurikabeType.WHITE + || cell.getType() == NurikabeType.NUMBER + || cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.WHITE + || rightCell.getType() == NurikabeType.NUMBER + || rightCell.getType() == NurikabeType.UNKNOWN)) { + whiteRegions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.WHITE + || downCell.getType() == NurikabeType.NUMBER + || downCell.getType() == NurikabeType.UNKNOWN)) { + whiteRegions.union(cell, downCell); + } } - return regions; + } } - - /** - * Gets the disjoint set containing the possible black regions be interpreting all unknown cells - * as black cells - * - * @param board nurikabe board - * @return the disjoint set containing the possible black regions - */ - public static DisjointSets getPossibleBlackRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); - - DisjointSets blackRegions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { - blackRegions.createSet(cell); - } + return whiteRegions; + } + + /** + * Makes a map where the keys are white/numbered cells and the values are the amount of cells that + * need to be added to the region + * + * @param board nurikabe board + * @return a map of cell keys to integer values + */ + public static HashMap getWhiteRegionMap(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); + + Set numberedCells = getNurikabeNumberedCells(board); + // Final mapping of cell to size + HashMap whiteRegionMap = new HashMap<>(); + for (NurikabeCell center : numberedCells) { + // BFS for each center to find the size of the region + int size = 1; + // Mark all the vertices as not visited(By default + // set as false) + HashMap visited = new HashMap<>(); + + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); + + // Mark the current node as visited and enqueue it + visited.put(center, true); + queue.add(center); + + // Set of cells in the current region + Set connected = new HashSet<>(); + + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + // s is the source node in the graph + NurikabeCell s = queue.poll(); + System.out.print(s + " "); + + // Make a linked list of all adjacent squares + Set adj = new HashSet<>(); + + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(board.getCell(loc.x - 1, loc.y)); } - - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null && (rightCell.getType() == NurikabeType.BLACK || - rightCell.getType() == NurikabeType.UNKNOWN)) { - blackRegions.union(cell, rightCell); - } - if (downCell != null && (downCell.getType() == NurikabeType.BLACK || - downCell.getType() == NurikabeType.UNKNOWN)) { - blackRegions.union(cell, downCell); - } - } - } + if (loc.x < width - 1) { + adj.add(board.getCell(loc.x + 1, loc.y)); } - return blackRegions; - } - - /** - * Gets the disjoint set containing the possible white regions be interpreting all unknown cells - * as white cells - * - * @param board nurikabe board - * @return the disjoint set containing the possible white regions - */ - public static DisjointSets getPossibleWhiteRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); - - DisjointSets whiteRegions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.WHITE || cell.getType() == NurikabeType.NUMBER || cell.getType() == NurikabeType.UNKNOWN) { - whiteRegions.createSet(cell); - } + if (loc.y >= 1) { + adj.add(board.getCell(loc.x, loc.y - 1)); } - - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.WHITE || cell.getType() == NurikabeType.NUMBER || - cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null && (rightCell.getType() == NurikabeType.WHITE || - rightCell.getType() == NurikabeType.NUMBER || rightCell.getType() == NurikabeType.UNKNOWN)) { - whiteRegions.union(cell, rightCell); - } - if (downCell != null && (downCell.getType() == NurikabeType.WHITE || - downCell.getType() == NurikabeType.NUMBER || downCell.getType() == NurikabeType.UNKNOWN)) { - whiteRegions.union(cell, downCell); - } - } - } + if (loc.y < height - 1) { + adj.add(board.getCell(loc.x, loc.y + 1)); } - return whiteRegions; - } - - /** - * Makes a map where the keys are white/numbered cells - * and the values are the amount of cells that need - * to be added to the region - * - * @param board nurikabe board - * @return a map of cell keys to integer values - */ - public static HashMap getWhiteRegionMap(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); - - Set numberedCells = getNurikabeNumberedCells(board); - // Final mapping of cell to size - HashMap whiteRegionMap = new HashMap<>(); - for (NurikabeCell center : numberedCells) { - //BFS for each center to find the size of the region - int size = 1; - // Mark all the vertices as not visited(By default - // set as false) - HashMap visited = new HashMap<>(); - - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); - - // Mark the current node as visited and enqueue it - visited.put(center, true); - queue.add(center); - - // Set of cells in the current region - Set connected = new HashSet<>(); - - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - // s is the source node in the graph - NurikabeCell s = queue.poll(); - System.out.print(s + " "); - - // Make a linked list of all adjacent squares - Set adj = new HashSet<>(); - - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(board.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(board.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(board.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(board.getCell(loc.x, loc.y + 1)); - } - // Get all adjacent vertices of the dequeued vertex s - // If a adjacent has not been visited, then mark it - // visited and enqueue it - for (NurikabeCell n : adj) { - if (!visited.getOrDefault(n, false) - && n.getType() == NurikabeType.WHITE) { - connected.add(n); - visited.put(n, true); - queue.add(n); - ++size; - } - } - } - // Map the cells to the center-size (including the center) - whiteRegionMap.put(center, center.getData() - size); - for (NurikabeCell member : connected) { - whiteRegionMap.put(member, center.getData() - size); - } + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (NurikabeCell n : adj) { + if (!visited.getOrDefault(n, false) && n.getType() == NurikabeType.WHITE) { + connected.add(n); + visited.put(n, true); + queue.add(n); + ++size; + } } - return whiteRegionMap; + } + // Map the cells to the center-size (including the center) + whiteRegionMap.put(center, center.getData() - size); + for (NurikabeCell member : connected) { + whiteRegionMap.put(member, center.getData() - size); + } } - - /** - * Gets all the non-black cells connected to the given cell - * - * @param board nurikabe board - * @param center nurikabe cell - * @return a set of all white/numbered cells in the region - */ - public static Set getSurroundedRegionOf(NurikabeBoard board, NurikabeCell center) { - int width = board.getWidth(); - int height = board.getHeight(); - - // Mark all the vertices as not visited(By default - // set as false) - Set visited = new HashSet<>(); - - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); - - // Mark the current node as visited and enqueue it - visited.add(center); - queue.add(center); - - // Set of cells in the current region - Set connected = new HashSet<>(); - - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - // s is the source node in the graph - NurikabeCell s = queue.poll(); - System.out.print(s + " "); - - // Make a set of all adjacent squares - Set adj = new HashSet<>(); - - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(board.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(board.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(board.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(board.getCell(loc.x, loc.y + 1)); - } - // Get all adjacent vertices of the dequeued vertex s - // If a adjacent has not been visited, then mark it - // visited and enqueue it - for (NurikabeCell n : adj) { - if (!visited.contains(n) && n.getType() != NurikabeType.BLACK) { - connected.add(n); - visited.add(n); - queue.add(n); - } - } + return whiteRegionMap; + } + + /** + * Gets all the non-black cells connected to the given cell + * + * @param board nurikabe board + * @param center nurikabe cell + * @return a set of all white/numbered cells in the region + */ + public static Set getSurroundedRegionOf(NurikabeBoard board, NurikabeCell center) { + int width = board.getWidth(); + int height = board.getHeight(); + + // Mark all the vertices as not visited(By default + // set as false) + Set visited = new HashSet<>(); + + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); + + // Mark the current node as visited and enqueue it + visited.add(center); + queue.add(center); + + // Set of cells in the current region + Set connected = new HashSet<>(); + + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + // s is the source node in the graph + NurikabeCell s = queue.poll(); + System.out.print(s + " "); + + // Make a set of all adjacent squares + Set adj = new HashSet<>(); + + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(board.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(board.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(board.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(board.getCell(loc.x, loc.y + 1)); + } + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (NurikabeCell n : adj) { + if (!visited.contains(n) && n.getType() != NurikabeType.BLACK) { + connected.add(n); + visited.add(n); + queue.add(n); } - - return connected; + } } + + return connected; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java index cef287b92..04e1910e4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java @@ -3,22 +3,21 @@ import edu.rpi.legup.controller.BoardController; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.ui.boardview.GridBoardView; - import java.awt.*; public class NurikabeView extends GridBoardView { - public NurikabeView(NurikabeBoard board) { - super(new BoardController(), new NurikabeController(), board.getDimension()); + public NurikabeView(NurikabeBoard board) { + super(new BoardController(), new NurikabeController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - Point loc = cell.getLocation(); - NurikabeElementView elementView = new NurikabeElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + Point loc = cell.getLocation(); + NurikabeElementView elementView = new NurikabeElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java index 1609fbf99..25f817ff2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BlackTile extends PlaceableElement { - public BlackTile() { - super("NURI-PLAC-0001", "Black Tile", "The black tile", "edu/rpi/legup/images/nurikabe/tiles/BlackTile.png"); - } + public BlackTile() { + super( + "NURI-PLAC-0001", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/nurikabe/tiles/BlackTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java index 0b1ee9656..9c0f3ff94 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java @@ -3,25 +3,28 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super("NURI-UNPL-0001", "Number Tile", "A numbered tile", "edu/rpi/legup/images/nurikabe/tiles/NumberTile.png"); - object_num = 0; - } + public NumberTile() { + super( + "NURI-UNPL-0001", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/nurikabe/tiles/NumberTile.png"); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } - - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java index 259e17e74..0b16d4a17 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super("NURI-UNPL-0002", "Unknown Tile", "A blank tile", "edu/rpi/legup/images/nurikabe/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "NURI-UNPL-0002", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/nurikabe/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java index 434e0663e..c086ce55c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class WhiteTile extends PlaceableElement { - public WhiteTile() { - super("NURI-PLAC-0002", "White Tile", "The white tile", "edu/rpi/legup/images/nurikabe/tiles/WhiteTile.png"); - } + public WhiteTile() { + super( + "NURI-PLAC-0002", + "White Tile", + "The white tile", + "edu/rpi/legup/images/nurikabe/tiles/WhiteTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java index 62d305048..f8fb66110 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java @@ -2,8 +2,8 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; @@ -11,102 +11,109 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; import edu.rpi.legup.utility.DisjointSets; - import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; public class BlackBetweenRegionsDirectRule extends DirectRule { - public BlackBetweenRegionsDirectRule() { - super("NURI-BASC-0001", - "Black Between Regions", - "Any unknowns between two regions must be black.", - "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); - } + public BlackBetweenRegionsDirectRule() { + super( + "NURI-BASC-0001", + "Black Between Regions", + "Any unknowns between two regions must be black.", + "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new MultipleNumbersContradictionRule()); - contras.add(new TooManySpacesContradictionRule()); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new MultipleNumbersContradictionRule()); + contras.add(new TooManySpacesContradictionRule()); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } - - int x = cell.getLocation().x; - int y = cell.getLocation().y; - - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adjacentWhiteRegions = new HashSet<>(); - NurikabeCell upCell = destBoardState.getCell(x, y - 1); - NurikabeCell rightCell = destBoardState.getCell(x + 1, y); - NurikabeCell downCell = destBoardState.getCell(x, y + 1); - NurikabeCell leftCell = destBoardState.getCell(x - 1, y); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; + } - if (upCell != null && (upCell.getType() == NurikabeType.WHITE || upCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(upCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (rightCell != null && (rightCell.getType() == NurikabeType.WHITE || rightCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(rightCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (downCell != null && (downCell.getType() == NurikabeType.WHITE || downCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(downCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (leftCell != null && (leftCell.getType() == NurikabeType.WHITE || leftCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(leftCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } + int x = cell.getLocation().x; + int y = cell.getLocation().y; - if (adjacentWhiteRegions.size() < 2) { - return "The new black cell must separate two white regions for this rule!"; - } + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adjacentWhiteRegions = new HashSet<>(); + NurikabeCell upCell = destBoardState.getCell(x, y - 1); + NurikabeCell rightCell = destBoardState.getCell(x + 1, y); + NurikabeCell downCell = destBoardState.getCell(x, y + 1); + NurikabeCell leftCell = destBoardState.getCell(x - 1, y); - NurikabeBoard modified = origBoardState.copy(); - modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); + if (upCell != null + && (upCell.getType() == NurikabeType.WHITE || upCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(upCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (rightCell != null + && (rightCell.getType() == NurikabeType.WHITE + || rightCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(rightCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (downCell != null + && (downCell.getType() == NurikabeType.WHITE + || downCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(downCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (leftCell != null + && (leftCell.getType() == NurikabeType.WHITE + || leftCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(leftCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } - for (ContradictionRule c : contras) { - if (c.checkContradiction(modified) == null) { - return null; - } - } - return "Does not follow from the rule"; + if (adjacentWhiteRegions.size() < 2) { + return "The new black cell must separate two white regions for this rule!"; } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + NurikabeBoard modified = origBoardState.copy(); + modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); + + for (ContradictionRule c : contras) { + if (c.checkContradiction(modified) == null) { return null; + } } + return "Does not follow from the rule"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java index 6eca91dbf..75035018b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java @@ -2,8 +2,8 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; @@ -12,54 +12,54 @@ public class BlackBottleNeckDirectRule extends DirectRule { - public BlackBottleNeckDirectRule() { - super("NURI-BASC-0002", - "Black Bottle Neck", - "If there is only one path for a black to escape, then those unknowns must be black.", - "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); - } + public BlackBottleNeckDirectRule() { + super( + "NURI-BASC-0002", + "Black Bottle Neck", + "If there is only one path for a black to escape, then those unknowns must be black.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new IsolateBlackContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new IsolateBlackContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); - - if (contraRule.checkContradiction(modified) == null) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This is not the only way for black to escape!"; - } + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + if (contraRule.checkContradiction(modified) == null) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This is not the only way for black to escape!"; } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java index 641b76322..9c6bf1a63 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java @@ -8,103 +8,106 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; import edu.rpi.legup.puzzle.nurikabe.NurikabeType; - import java.util.ArrayList; import java.util.List; public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super("NURI-CASE-0001", - "Black or White", - "Each blank cell is either black or white.", - "edu/rpi/legup/images/nurikabe/cases/BlackOrWhite.png"); - } - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this rule. This method is - * the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; - } + public BlackOrWhiteCaseRule() { + super( + "NURI-CASE-0001", + "Black or White", + "Each blank cell is either black or white.", + "edu/rpi/legup/images/nurikabe/cases/BlackOrWhite.png"); + } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 || - case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 1 modified cell for each case."; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - NurikabeCell mod1 = (NurikabeCell) case1.getBoard().getModifiedData().iterator().next(); - NurikabeCell mod2 = (NurikabeCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must modify the same cell for each case."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - if (!((mod1.getType() == NurikabeType.WHITE && mod2.getType() == NurikabeType.BLACK) || - (mod2.getType() == NurikabeType.WHITE && mod1.getType() == NurikabeType.BLACK))) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must an empty white and black cell."; - } + NurikabeCell mod1 = (NurikabeCell) case1.getBoard().getModifiedData().iterator().next(); + NurikabeCell mod2 = (NurikabeCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } - return null; + if (!((mod1.getType() == NurikabeType.WHITE && mod2.getType() == NurikabeType.BLACK) + || (mod2.getType() == NurikabeType.WHITE && mod1.getType() == NurikabeType.BLACK))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty white and black cell."; } - @Override - public CaseBoard getCaseBoard(Board board) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(nurikabeBoard, this); - nurikabeBoard.setModifiable(false); - for (PuzzleElement element : nurikabeBoard.getPuzzleElements()) { - if (((NurikabeCell) element).getType() == NurikabeType.UNKNOWN) { - caseBoard.addPickableElement(element); - } - } - return caseBoard; + return null; + } + + @Override + public CaseBoard getCaseBoard(Board board) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(nurikabeBoard, this); + nurikabeBoard.setModifiable(false); + for (PuzzleElement element : nurikabeBoard.getPuzzleElements()) { + if (((NurikabeCell) element).getType() == NurikabeType.UNKNOWN) { + caseBoard.addPickableElement(element); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(NurikabeType.WHITE.toValue()); - case1.addModifiedData(data1); - cases.add(case1); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(NurikabeType.WHITE.toValue()); + case1.addModifiedData(data1); + cases.add(case1); - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(NurikabeType.BLACK.toValue()); - case2.addModifiedData(data2); - cases.add(case2); + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(NurikabeType.BLACK.toValue()); + case2.addModifiedData(data2); + cases.add(case2); - return cases; - } + return cases; + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java index 2dfb817e2..bdc72d921 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java @@ -9,47 +9,52 @@ public class BlackSquareContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "No 2x2 square of black exists."; - private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - - public BlackSquareContradictionRule() { - super("NURI-CONT-0001", - "Black Square", - "There cannot be a 2x2 square of black.", - "edu/rpi/legup/images/nurikabe/contradictions/BlackSquare.png"); + private final String NO_CONTRADICTION_MESSAGE = "No 2x2 square of black exists."; + private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; + + public BlackSquareContradictionRule() { + super( + "NURI-CONT-0001", + "Black Square", + "There cannot be a 2x2 square of black.", + "edu/rpi/legup/images/nurikabe/contradictions/BlackSquare.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int height = nurikabeBoard.getHeight(); - int width = nurikabeBoard.getWidth(); - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } - - for (int x = cell.getLocation().x - 1; x >= 0 && x < cell.getLocation().x + 1 && x < width - 1; x++) { - for (int y = cell.getLocation().y - 1; y >= 0 && y < cell.getLocation().y + 1 && y < height - 1; y++) { - if (nurikabeBoard.getCell(x, y).getType() == NurikabeType.BLACK && - nurikabeBoard.getCell(x + 1, y).getType() == NurikabeType.BLACK && - nurikabeBoard.getCell(x, y + 1).getType() == NurikabeType.BLACK && - nurikabeBoard.getCell(x + 1, y + 1).getType() == NurikabeType.BLACK) { - return null; - } - } + for (int x = cell.getLocation().x - 1; + x >= 0 && x < cell.getLocation().x + 1 && x < width - 1; + x++) { + for (int y = cell.getLocation().y - 1; + y >= 0 && y < cell.getLocation().y + 1 && y < height - 1; + y++) { + if (nurikabeBoard.getCell(x, y).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x + 1, y).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x, y + 1).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x + 1, y + 1).getType() == NurikabeType.BLACK) { + return null; } - - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } + + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java index 4c8f37e05..0b699b7bd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java @@ -2,8 +2,8 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; @@ -11,51 +11,52 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; public class CannotReachCellDirectRule extends DirectRule { - public CannotReachCellDirectRule() { - super("NURI-BASC-0008", - "Can't Reach Cell", - "A cell must be black if it cannot be reached by any white region", - "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); - } + public CannotReachCellDirectRule() { + super( + "NURI-BASC-0008", + "Can't Reach Cell", + "A cell must be black if it cannot be reached by any white region", + "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; + } - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeBoard modified = origBoardState.copy(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modifiedCell.setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; + NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modifiedCell.setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { + return null; } + return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java index fe79d8919..bcb8edf0c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java @@ -2,107 +2,126 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.utility.ConnectedRegions; - import java.awt.*; import java.util.Set; public class CornerBlackDirectRule extends DirectRule { - public CornerBlackDirectRule() { - super("NURI-BASC-0003", - "Corners Black", - "If there is only one white square connected to unknowns and one more white is needed then the angles of that white square are black", - "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); + public CornerBlackDirectRule() { + super( + "NURI-BASC-0003", + "Corners Black", + "If there is only one white square connected to unknowns and one more white is needed then the angles of that white square are black", + "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; + ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); + Point cellLocation = cell.getLocation(); + // 1. Find the coordinates of the white space (should be a corner of cell) + for (int i = -1; i < 2; i += 2) { + for (int j = -1; j < 2; j += 2) { + // If the corner does not exist, skip the corner + if (!(cellLocation.x + i >= 0 + && cellLocation.x + i < board.getWidth() + && cellLocation.y + j >= 0 + && cellLocation.y + j < board.getHeight())) { + continue; } - ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); - Point cellLocation = cell.getLocation(); - // 1. Find the coordinates of the white space (should be a corner of cell) - for (int i = -1; i < 2; i += 2) { - for (int j = -1; j < 2; j += 2) { - // If the corner does not exist, skip the corner - if (!(cellLocation.x + i >= 0 && cellLocation.x + i < board.getWidth() && cellLocation.y + j >= 0 && cellLocation.y + j < board.getHeight())) { - continue; - } - - NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); - NurikabeType cornerType = corner.getType(); - if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { - Point cornerLocation = corner.getLocation(); - // 2. Check if the intersecting adjacent spaces of the white space and the black corner are empty - if (board.getCell(cornerLocation.x, cellLocation.y).getType() == NurikabeType.UNKNOWN && board.getCell(cellLocation.x, cornerLocation.y).getType() == NurikabeType.UNKNOWN) { - // System.out.println("Went inside if statement"); - NurikabeBoard modified = board.copy(); - modified.getCell(cornerLocation.x, cellLocation.y).setData(NurikabeType.BLACK.toValue()); - modified.getCell(cellLocation.x, cornerLocation.y).setData(NurikabeType.BLACK.toValue()); - boolean containsContradiction = tooFewContra.checkContradiction(modified) == null; - if (containsContradiction) { - // 3. Check if the connected region is 1 under what is needed - Set region = ConnectedRegions.getRegionAroundPoint(cornerLocation, NurikabeType.BLACK.toValue(), modified.getIntArray(), modified.getWidth(), modified.getHeight()); - int regionNumber = 0; - // System.out.println("Region set size: " + region.size()); - for (Point p : region) { - NurikabeCell pCell = modified.getCell(p.x, p.y); - if (pCell.getType() == NurikabeType.NUMBER) { - if (regionNumber == 0) { - regionNumber = pCell.getData(); - } - else { - return "There is a MultipleNumbers Contradiction on the board."; - } - } - } - // If the region size is 0, there is a possibility that there was only 1 cell in the white - // region, and that white cell was a NurikabeType.NUMBER cell - if (regionNumber == 0 && corner.getType() == NurikabeType.NUMBER && corner.getData() == 2) { - return null; - } - // If the region size is not 0, make sure the regionNumber and the region size match (need - // to add 1 to account for the cell that was surrounded - if (regionNumber != 0 && region.size() + 1 == regionNumber) { - return null; - } - } - } + NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); + NurikabeType cornerType = corner.getType(); + if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { + Point cornerLocation = corner.getLocation(); + // 2. Check if the intersecting adjacent spaces of the white space and the black corner + // are empty + if (board.getCell(cornerLocation.x, cellLocation.y).getType() == NurikabeType.UNKNOWN + && board.getCell(cellLocation.x, cornerLocation.y).getType() + == NurikabeType.UNKNOWN) { + // System.out.println("Went inside if statement"); + NurikabeBoard modified = board.copy(); + modified + .getCell(cornerLocation.x, cellLocation.y) + .setData(NurikabeType.BLACK.toValue()); + modified + .getCell(cellLocation.x, cornerLocation.y) + .setData(NurikabeType.BLACK.toValue()); + boolean containsContradiction = tooFewContra.checkContradiction(modified) == null; + if (containsContradiction) { + // 3. Check if the connected region is 1 under what is needed + Set region = + ConnectedRegions.getRegionAroundPoint( + cornerLocation, + NurikabeType.BLACK.toValue(), + modified.getIntArray(), + modified.getWidth(), + modified.getHeight()); + int regionNumber = 0; + // System.out.println("Region set size: " + region.size()); + for (Point p : region) { + NurikabeCell pCell = modified.getCell(p.x, p.y); + if (pCell.getType() == NurikabeType.NUMBER) { + if (regionNumber == 0) { + regionNumber = pCell.getData(); + } else { + return "There is a MultipleNumbers Contradiction on the board."; + } } + } + // If the region size is 0, there is a possibility that there was only 1 cell in the + // white + // region, and that white cell was a NurikabeType.NUMBER cell + if (regionNumber == 0 + && corner.getType() == NurikabeType.NUMBER + && corner.getData() == 2) { + return null; + } + // If the region size is not 0, make sure the regionNumber and the region size match + // (need + // to add 1 to account for the cell that was surrounded + if (regionNumber != 0 && region.size() + 1 == regionNumber) { + return null; + } } + } } - return "This is not a valid use of the corner black rule!"; + } } + return "This is not a valid use of the corner black rule!"; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java index 7e2568b58..3507d0a7f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java @@ -2,8 +2,8 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; @@ -12,49 +12,50 @@ public class FillinBlackDirectRule extends DirectRule { - public FillinBlackDirectRule() { - super("NURI-BASC-0004", - "Fill In Black", - "If there an unknown region surrounded by black, it must be black.", - "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); - } + public FillinBlackDirectRule() { + super( + "NURI-BASC-0004", + "Fill In Black", + "If there an unknown region surrounded by black, it must be black.", + "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new NoNumberContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new NoNumberContradictionRule(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "Black cells must be placed in a region of black cells!"; - } - return null; + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "Black cells must be placed in a region of black cells!"; } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java index e5a901158..30d5a3a51 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java @@ -2,8 +2,8 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; @@ -12,49 +12,50 @@ public class FillinWhiteDirectRule extends DirectRule { - public FillinWhiteDirectRule() { - super("NURI-BASC-0005", - "Fill In White", - "If there an unknown region surrounded by white, it must be white.", - "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); - } + public FillinWhiteDirectRule() { + super( + "NURI-BASC-0005", + "Fill In White", + "If there an unknown region surrounded by white, it must be white.", + "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new IsolateBlackContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new IsolateBlackContradictionRule(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "white cells must be placed in a region of white cells!"; - } - return null; + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "white cells must be placed in a region of white cells!"; } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java index c7331330b..831dd134b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java @@ -8,54 +8,54 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; import edu.rpi.legup.utility.DisjointSets; - import java.util.Set; public class IsolateBlackContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Contradiction applied incorrectly. No isolated Blacks."; - private final String INVALID_USE_MESSAGE = "Contradiction must be a black cell"; + private final String NO_CONTRADICTION_MESSAGE = + "Contradiction applied incorrectly. No isolated Blacks."; + private final String INVALID_USE_MESSAGE = "Contradiction must be a black cell"; - public IsolateBlackContradictionRule() { - super("NURI-CONT-0003", - "Isolated Black", - "There must still be a possibility to connect every Black cell", - "edu/rpi/legup/images/nurikabe/contradictions/BlackArea.png"); - } + public IsolateBlackContradictionRule() { + super( + "NURI-CONT-0003", + "Isolated Black", + "There must still be a possibility to connect every Black cell", + "edu/rpi/legup/images/nurikabe/contradictions/BlackArea.png"); + } - /** - * Checks whether the transition has a contradiction at the specific - * {@link PuzzleElement} index using this rule. - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a - * contradiction at the specified {@link PuzzleElement}, - * otherwise return a no contradiction message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule. + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified {@link + * PuzzleElement}, otherwise return a no contradiction message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - DisjointSets blackRegions = NurikabeUtilities.getPossibleBlackRegions(nurikabeBoard); - boolean oneRegion = false; - for (Set region : blackRegions.getAllSets()) { - for (NurikabeCell c : region) { - if (c.getType() == NurikabeType.BLACK) { - if (oneRegion) { - return null; - } - else { - oneRegion = true; - break; - } - } - } + DisjointSets blackRegions = + NurikabeUtilities.getPossibleBlackRegions(nurikabeBoard); + boolean oneRegion = false; + for (Set region : blackRegions.getAllSets()) { + for (NurikabeCell c : region) { + if (c.getType() == NurikabeType.BLACK) { + if (oneRegion) { + return null; + } else { + oneRegion = true; + break; + } } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java index e83204b99..d19cde25a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java @@ -8,44 +8,45 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; import edu.rpi.legup.utility.DisjointSets; - import java.util.Set; public class MultipleNumbersContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a numbered cell"; + private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a numbered cell"; - public MultipleNumbersContradictionRule() { - super("NURI-CONT-0004", - "Multiple Numbers", - "All white regions cannot have more than one number.", - "edu/rpi/legup/images/nurikabe/contradictions/MultipleNumbers.png"); - } + public MultipleNumbersContradictionRule() { + super( + "NURI-CONT-0004", + "Multiple Numbers", + "All white regions cannot have more than one number.", + "edu/rpi/legup/images/nurikabe/contradictions/MultipleNumbers.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + INVALID_USE_MESSAGE; - } - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); - Set numberedRegion = regions.getSet(cell); - for (NurikabeCell c : numberedRegion) { - if (c != cell && c.getType() == NurikabeType.NUMBER) { - return null; - } - } - return super.getNoContradictionMessage() + ": " + NO_CONTRADICTION_MESSAGE; + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + INVALID_USE_MESSAGE; + } + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); + Set numberedRegion = regions.getSet(cell); + for (NurikabeCell c : numberedRegion) { + if (c != cell && c.getType() == NurikabeType.NUMBER) { + return null; + } } + return super.getNoContradictionMessage() + ": " + NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java index c2752da7a..64d3383e1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java @@ -7,67 +7,66 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; -import edu.rpi.legup.utility.DisjointSets; - import java.util.Set; -import java.util.List; public class NoNumberContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white cell"; - private final String NOT_SURROUNDED_BY_BLACK_MESSAGE = "Must be surrounded by black cells"; + private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white cell"; + private final String NOT_SURROUNDED_BY_BLACK_MESSAGE = "Must be surrounded by black cells"; - public NoNumberContradictionRule() { - super("NURI-CONT-0005", - "No Number", - "All enclosed white regions must have a number.", - "edu/rpi/legup/images/nurikabe/contradictions/NoNumber.png"); - } + public NoNumberContradictionRule() { + super( + "NURI-CONT-0005", + "No Number", + "All enclosed white regions must have a number.", + "edu/rpi/legup/images/nurikabe/contradictions/NoNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - Set region = NurikabeUtilities.getSurroundedRegionOf(nurikabeBoard, cell); + Set region = NurikabeUtilities.getSurroundedRegionOf(nurikabeBoard, cell); - boolean numberExists = false; - for (NurikabeCell c : region) { - if (c.getType() == NurikabeType.NUMBER) { - numberExists = true; - break; - } - } - if (!numberExists) { - return null; - } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + boolean numberExists = false; + for (NurikabeCell c : region) { + if (c.getType() == NurikabeType.NUMBER) { + numberExists = true; + break; + } + } + if (!numberExists) { + return null; } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } - /** - * Checks whether a give NurikabeCell is empty. - * - * @param cell NurikabeCell to check if empty - * @return false if the NurikabeCell is not empty or null, true otherwise - */ - private boolean isEmptyCell(NurikabeCell cell) { - if (cell == null) { - return false; - } - NurikabeType cellType = cell.getType(); - return cellType != NurikabeType.BLACK && cellType != NurikabeType.WHITE; + /** + * Checks whether a give NurikabeCell is empty. + * + * @param cell NurikabeCell to check if empty + * @return false if the NurikabeCell is not empty or null, true otherwise + */ + private boolean isEmptyCell(NurikabeCell cell) { + if (cell == null) { + return false; } + NurikabeType cellType = cell.getType(); + return cellType != NurikabeType.BLACK && cellType != NurikabeType.WHITE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java index eff0c8e1f..a9ae5441f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java @@ -2,8 +2,8 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; @@ -12,55 +12,55 @@ public class PreventBlackSquareDirectRule extends DirectRule { - public PreventBlackSquareDirectRule() { - super("NURI-BASC-0006", - "Prevent Black Square", - "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", - "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); - } + public PreventBlackSquareDirectRule() { + super( + "NURI-BASC-0006", + "Prevent Black Square", + "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", + "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new BlackSquareContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new BlackSquareContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradiction(modified) == null) { - return null; - } - else { - return "Does not contain a contradiction at this index"; - } + if (contraRule.checkContradiction(modified) == null) { + return null; + } else { + return "Does not contain a contradiction at this index"; } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java index 9ee0ee245..e471de3b1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java @@ -10,86 +10,89 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; import edu.rpi.legup.utility.DisjointSets; - -import java.util.Arrays; +import java.awt.*; import java.util.ArrayList; -import java.util.List; +import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Set; -import java.awt.*; public class SurroundRegionDirectRule extends DirectRule { - public SurroundRegionDirectRule() { - super("NURI-BASC-0007", "Surround Region", - "Surround Region", - "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); - } + public SurroundRegionDirectRule() { + super( + "NURI-BASC-0007", + "Surround Region", + "Surround Region", + "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); - if(cell.getType() == NurikabeType.BLACK) { - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adj = new HashSet<>(); //set to hold adjacent cells - Point loc = cell.getLocation(); //position of placed cell - List directions = Arrays.asList(new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); - for(Point direction : directions) { - NurikabeCell curr = destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); - if(curr != null) { - if(curr.getType() == NurikabeType.WHITE || curr.getType() == NurikabeType.NUMBER) { - adj.add(curr); //adds cells to adj only if they are white or number blocks - } - } - } - List numberedCells = new ArrayList<>(); //number value of number cells - for (NurikabeCell c : adj) { //loops through adjacent cells - Set disRow = regions.getSet(c); //set of white spaces - for (NurikabeCell d : disRow) { //loops through white spaces - if (d.getType() == NurikabeType.NUMBER) { //if the white space is a number - numberedCells.add(d); //add that number to numberedCells - } - } - } - for (NurikabeCell number : numberedCells) { //loops through numberedCells - if (regions.getSet(number).size() == number.getData()) { //if that cells white area is the exact - return null; //size of the number of one of the number cells within that set - } - } + if (cell.getType() == NurikabeType.BLACK) { + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adj = new HashSet<>(); // set to hold adjacent cells + Point loc = cell.getLocation(); // position of placed cell + List directions = + Arrays.asList(new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); + for (Point direction : directions) { + NurikabeCell curr = destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); + if (curr != null) { + if (curr.getType() == NurikabeType.WHITE || curr.getType() == NurikabeType.NUMBER) { + adj.add(curr); // adds cells to adj only if they are white or number blocks + } } - return "Does not follow from this rule at this index"; + } + List numberedCells = new ArrayList<>(); // number value of number cells + for (NurikabeCell c : adj) { // loops through adjacent cells + Set disRow = regions.getSet(c); // set of white spaces + for (NurikabeCell d : disRow) { // loops through white spaces + if (d.getType() == NurikabeType.NUMBER) { // if the white space is a number + numberedCells.add(d); // add that number to numberedCells + } + } + } + for (NurikabeCell number : numberedCells) { // loops through numberedCells + if (regions.getSet(number).size() + == number.getData()) { // if that cells white area is the exact + return null; // size of the number of one of the number cells within that set + } + } } + return "Does not follow from this rule at this index"; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java index d01dd806c..c9ae05064 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java @@ -8,52 +8,54 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; import edu.rpi.legup.utility.DisjointSets; - import java.util.Set; public class TooFewSpacesContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; + private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; + + public TooFewSpacesContradictionRule() { + super( + "NURI-CONT-0006", + "Too Few Spaces", + "A region cannot contain less spaces than its number.", + "edu/rpi/legup/images/nurikabe/contradictions/TooFewSpaces.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - public TooFewSpacesContradictionRule() { - super("NURI-CONT-0006", - "Too Few Spaces", - "A region cannot contain less spaces than its number.", - "edu/rpi/legup/images/nurikabe/contradictions/TooFewSpaces.png"); + DisjointSets regions = NurikabeUtilities.getPossibleWhiteRegions(nurikabeBoard); + Set whiteRegion = regions.getSet(cell); + NurikabeCell numberedCell = null; + for (NurikabeCell c : whiteRegion) { + if (c.getType() == NurikabeType.NUMBER) { + numberedCell = c; + break; + } } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } - - DisjointSets regions = NurikabeUtilities.getPossibleWhiteRegions(nurikabeBoard); - Set whiteRegion = regions.getSet(cell); - NurikabeCell numberedCell = null; - for (NurikabeCell c : whiteRegion) { - if (c.getType() == NurikabeType.NUMBER) { - numberedCell = c; - break; - } - } - - if (numberedCell != null && whiteRegion.size() < numberedCell.getData()) { - // System.err.println("Cell Value: " + numberedCell.getData() + ", Loc: " + cell.getLocation() + ", region: " + whiteRegion.size()); - return null; - } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + if (numberedCell != null && whiteRegion.size() < numberedCell.getData()) { + // System.err.println("Cell Value: " + numberedCell.getData() + ", Loc: " + cell.getLocation() + // + ", region: " + whiteRegion.size()); + return null; } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java index e5aa9f18b..550c07f57 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java @@ -8,53 +8,54 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; import edu.rpi.legup.utility.DisjointSets; - import java.util.ArrayList; import java.util.Set; public class TooManySpacesContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; + private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; + + public TooManySpacesContradictionRule() { + super( + "NURI-CONT-0007", + "Too Many Spaces", + "A region cannot contain more spaces than its number.", + "edu/rpi/legup/images/nurikabe/contradictions/TooManySpaces.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - public TooManySpacesContradictionRule() { - super("NURI-CONT-0007", - "Too Many Spaces", - "A region cannot contain more spaces than its number.", - "edu/rpi/legup/images/nurikabe/contradictions/TooManySpaces.png"); + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); + Set whiteRegion = regions.getSet(cell); + ArrayList numberedCells = new ArrayList<>(); + for (NurikabeCell c : whiteRegion) { + if (c.getType() == NurikabeType.NUMBER) { + numberedCells.add(c); + } } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } - - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); - Set whiteRegion = regions.getSet(cell); - ArrayList numberedCells = new ArrayList<>(); - for (NurikabeCell c : whiteRegion) { - if (c.getType() == NurikabeType.NUMBER) { - numberedCells.add(c); - } - } - - for (NurikabeCell number : numberedCells) { - if (whiteRegion.size() > number.getData()) { - return null; - } - } - return super.getNoContradictionMessage() + ":" + this.NO_CONTRADICTION_MESSAGE; + for (NurikabeCell number : numberedCells) { + if (whiteRegion.size() > number.getData()) { + return null; + } } + return super.getNoContradictionMessage() + ":" + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java index ec16475f1..92b6f8d3e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java @@ -7,98 +7,99 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.NurikabeUtilities; - import java.awt.*; import java.util.*; public class UnreachableWhiteCellContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Cell at this index can be reached"; - private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - - public UnreachableWhiteCellContradictionRule() { - super("NURI-CONT-0002", - "Unreachable White Cell", - "A white cell must be able to reach a white region", - "edu/rpi/legup/images/nurikabe/contradictions/CantReach.png"); - } + private final String NO_CONTRADICTION_MESSAGE = "Cell at this index can be reached"; + private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + public UnreachableWhiteCellContradictionRule() { + super( + "NURI-CONT-0002", + "Unreachable White Cell", + "A white cell must be able to reach a white region", + "edu/rpi/legup/images/nurikabe/contradictions/CantReach.png"); + } - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int height = nurikabeBoard.getHeight(); - int width = nurikabeBoard.getWidth(); + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - // Get regions - HashMap whiteRegionMap = NurikabeUtilities.getWhiteRegionMap(nurikabeBoard); - if (whiteRegionMap.containsKey(cell)) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - // BFS to a region + int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Get regions + HashMap whiteRegionMap = + NurikabeUtilities.getWhiteRegionMap(nurikabeBoard); + if (whiteRegionMap.containsKey(cell)) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } + // BFS to a region - // Mark the current node as visited and enqueue it - HashMap visited = new HashMap<>(); - visited.put(cell, true); - queue.add(cell); - int pathLength = 1; - while (queue.size() != 0) { - // Set of adjacent squares - Set adj = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - NurikabeCell s = queue.poll(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(nurikabeBoard.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(nurikabeBoard.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(nurikabeBoard.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(nurikabeBoard.getCell(loc.x, loc.y + 1)); - } + // Mark the current node as visited and enqueue it + HashMap visited = new HashMap<>(); + visited.put(cell, true); + queue.add(cell); + int pathLength = 1; + while (queue.size() != 0) { + // Set of adjacent squares + Set adj = new HashSet<>(); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + NurikabeCell s = queue.poll(); - for (NurikabeCell n : adj) { - int regionNeed = whiteRegionMap.getOrDefault(n, -1); - if (pathLength <= regionNeed) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - } - } + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(nurikabeBoard.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(nurikabeBoard.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(nurikabeBoard.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(nurikabeBoard.getCell(loc.x, loc.y + 1)); + } - for (NurikabeCell n : adj) { - if (!visited.getOrDefault(n, false) - && (n.getType() == NurikabeType.UNKNOWN || - n.getType() == NurikabeType.WHITE)) { - visited.put(n, true); - queue.add(n); - } - } - ++pathLength; + for (NurikabeCell n : adj) { + int regionNeed = whiteRegionMap.getOrDefault(n, -1); + if (pathLength <= regionNeed) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } + } - return null; + for (NurikabeCell n : adj) { + if (!visited.getOrDefault(n, false) + && (n.getType() == NurikabeType.UNKNOWN || n.getType() == NurikabeType.WHITE)) { + visited.put(n, true); + queue.add(n); + } + } + ++pathLength; } + + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java index 7d10c36d0..ddc5e78b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java @@ -2,68 +2,69 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; import edu.rpi.legup.puzzle.nurikabe.NurikabeType; - import java.util.LinkedHashSet; import java.util.Set; public class WhiteBottleNeckDirectRule extends DirectRule { - public WhiteBottleNeckDirectRule() { - super("NURI-BASC-0009", - "White Bottle Neck", - "If a region needs more whites and there is only one path for the region to expand, then those unknowns must be white.", "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new NoNumberContradictionRule()); - contras.add(new TooFewSpacesContradictionRule()); + public WhiteBottleNeckDirectRule() { + super( + "NURI-BASC-0009", + "White Bottle Neck", + "If a region needs more whites and there is only one path for the region to expand, then those unknowns must be white.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); + } - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new NoNumberContradictionRule()); + contras.add(new TooFewSpacesContradictionRule()); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - for (ContradictionRule contraRule : contras) { - if (contraRule.checkContradiction(modified) == null) { - return null; - } - } - return "This is not the only way for white to escape!"; + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + for (ContradictionRule contraRule : contras) { + if (contraRule.checkContradiction(modified) == null) { return null; + } } + return "This is not the only way for white to escape!"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java index e8f9ffc0d..4e6f25cba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java @@ -7,109 +7,104 @@ public class ShortTruthTable extends Puzzle { - public ShortTruthTable() { - super(); - - this.name = "ShortTruthTable"; - - this.importer = new ShortTruthTableImporter(this); - this.exporter = new ShortTruthTableExporter(this); - - this.factory = new ShortTruthTableCellFactory(); + public ShortTruthTable() { + super(); + + this.name = "ShortTruthTable"; + + this.importer = new ShortTruthTableImporter(this); + this.exporter = new ShortTruthTableExporter(this); + + this.factory = new ShortTruthTableCellFactory(); + } + + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) currentBoard; + boardView = new ShortTruthTableView(sttBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } + + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } + + @Override + /** + * Determines if the given dimensions are valid for Short Truth Table + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Short Truth Table, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // Number of rows must be odd to allow for proper spacing between the statements + if (rows % 2 != 1) { + return false; } - /** - * Initializes the game board. Called by the invoker of the class - */ - @Override - public void initializeView() { - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) currentBoard; - boardView = new ShortTruthTableView(sttBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); + return true; + } + + /** + * Determines if the given statements are valid for Short Truth Table + * + * @param statements + * @return true if the statements are valid for Short Truth Table, false otherwise + */ + public boolean isValidTextInput(String[] statements) { + if (statements.length == 0) { + return false; } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; + ShortTruthTableImporter importer = (ShortTruthTableImporter) this.getImporter(); + for (String s : statements) { + if (!importer.validGrammar(s)) { + return false; + } } - - @Override - /** - * Determines if the given dimensions are valid for Short Truth Table - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Short Truth Table, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // Number of rows must be odd to allow for proper spacing between the statements - if (rows % 2 != 1) { - return false; - } - - return true; - } - - /** - * Determines if the given statements are valid for Short Truth Table - * - * @param statements - * @return true if the statements are valid for Short Truth Table, false otherwise - */ - public boolean isValidTextInput(String[] statements) { - if (statements.length == 0) { - return false; - } - - ShortTruthTableImporter importer = (ShortTruthTableImporter) this.getImporter(); - for (String s : statements) { - if (!importer.validGrammar(s)) { - return false; - } - } - return true; + return true; + } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + + ShortTruthTableBoard sttboard = (ShortTruthTableBoard) board; + + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(sttboard) == null) { + return false; + } } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - - ShortTruthTableBoard sttboard = (ShortTruthTableBoard) board; - - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(sttboard) == null) { - return false; - } - } - for (PuzzleElement data : sttboard.getPuzzleElements()) { - ShortTruthTableCell cell = (ShortTruthTableCell) data; - if (cell.getType() == ShortTruthTableCellType.UNKNOWN) { - return false; - } - } - return true; - - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { - + for (PuzzleElement data : sttboard.getPuzzleElements()) { + ShortTruthTableCell cell = (ShortTruthTableCell) data; + if (cell.getType() == ShortTruthTableCellType.UNKNOWN) { + return false; + } } -} \ No newline at end of file + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java index e5011182a..2876523f8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java @@ -1,133 +1,124 @@ package edu.rpi.legup.puzzle.shorttruthtable; -import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - -import edu.rpi.legup.puzzle.lightup.LightUpCell; -import edu.rpi.legup.puzzle.shorttruthtable.*; - import java.awt.*; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.HashSet; public class ShortTruthTableBoard extends GridBoard { - private ShortTruthTableStatement[] statements; + private ShortTruthTableStatement[] statements; - public ShortTruthTableBoard(int width, int height, ShortTruthTableStatement[] statements) { + public ShortTruthTableBoard(int width, int height, ShortTruthTableStatement[] statements) { - super(width, height); - - this.statements = statements; - - } + super(width, height); + this.statements = statements; + } - public Set getCellsWithSymbol(char symbol) { - Set cells = new HashSet(); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - ShortTruthTableCell cell = (ShortTruthTableCell) getCell(x, y); - if (cell.getSymbol() == symbol) { - cells.add(cell); - } - } + public Set getCellsWithSymbol(char symbol) { + Set cells = new HashSet(); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + ShortTruthTableCell cell = (ShortTruthTableCell) getCell(x, y); + if (cell.getSymbol() == symbol) { + cells.add(cell); } - return cells; + } } - - public ShortTruthTableCell getCellFromElement(PuzzleElement element) { - return (ShortTruthTableCell) getPuzzleElement(element); - } - - @Override - public ShortTruthTableCell getCell(int x, int y) { - return (ShortTruthTableCell) super.getCell(x, y); + return cells; + } + + public ShortTruthTableCell getCellFromElement(PuzzleElement element) { + return (ShortTruthTableCell) getPuzzleElement(element); + } + + @Override + public ShortTruthTableCell getCell(int x, int y) { + return (ShortTruthTableCell) super.getCell(x, y); + } + + @Override + public ShortTruthTableBoard copy() { + + // Copy the statements + ShortTruthTableStatement[] statementsCopy = + new ShortTruthTableStatement[this.statements.length]; + for (int i = 0; i < statements.length; i++) { + statementsCopy[i] = this.statements[i].copy(); } - - - @Override - public ShortTruthTableBoard copy() { - - //Copy the statements - ShortTruthTableStatement[] statementsCopy = new ShortTruthTableStatement[this.statements.length]; - for (int i = 0; i < statements.length; i++) { - statementsCopy[i] = this.statements[i].copy(); + // copy the board and set the cells + ShortTruthTableBoard boardCopy = + new ShortTruthTableBoard(getWidth(), getHeight(), statementsCopy); + for (int r = 0; r < this.dimension.height; r++) { + for (int c = 0; c < this.dimension.width; c++) { + if (r % 2 == 0 && c < statementsCopy[r / 2].getLength()) { + boardCopy.setCell(c, r, statementsCopy[r / 2].getCell(c)); + } else { + boardCopy.setCell(c, r, getCell(c, r).copy()); } - //copy the board and set the cells - ShortTruthTableBoard boardCopy = new ShortTruthTableBoard(getWidth(), getHeight(), statementsCopy); - for (int r = 0; r < this.dimension.height; r++) { - for (int c = 0; c < this.dimension.width; c++) { - if (r % 2 == 0 && c < statementsCopy[r / 2].getLength()) { - boardCopy.setCell(c, r, statementsCopy[r / 2].getCell(c)); - } - else { - boardCopy.setCell(c, r, getCell(c, r).copy()); - } - } - } - for (PuzzleElement e : modifiedData) { - boardCopy.getPuzzleElement(e).setModifiable(false); - } - System.out.println("Board.copy()"); - System.out.println("original:\n" + this); - System.out.println("copy:\n" + boardCopy); - return boardCopy; - + } } - - public ShortTruthTableStatement[] getStatements() { - return statements; + for (PuzzleElement e : modifiedData) { + boardCopy.getPuzzleElement(e).setModifiable(false); } - - public static List copyStatementList(List statements) { - List copy = new ArrayList(); - for (int i = 0; i < statements.size(); i++) { - copy.add(statements.get(i).copy()); - } - return copy; + System.out.println("Board.copy()"); + System.out.println("original:\n" + this); + System.out.println("copy:\n" + boardCopy); + return boardCopy; + } + + public ShortTruthTableStatement[] getStatements() { + return statements; + } + + public static List copyStatementList( + List statements) { + List copy = new ArrayList(); + for (int i = 0; i < statements.size(); i++) { + copy.add(statements.get(i).copy()); } - - -// @Override -// public void setPuzzleElement(int index, PuzzleElement element){ -// ShortTruthTableCell cellElement = (ShortTruthTableCell) element; -// ShortTruthTableCell cell = getCell(cellElement.getX(), cellElement.getY()); -// cell.setType(cellElement.getType()); -// } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - int r = cell.getY(); - int c = cell.getX(); - if (r % 2 == 0 && c < statements[r / 2].getLength()) { - statements[r / 2] = statements[r / 2].replace(c, cell); - setCell(c, r, statements[r / 2].getCell(c)); - } - super.notifyChange(cell); + return copy; + } + + // @Override + // public void setPuzzleElement(int index, PuzzleElement element){ + // ShortTruthTableCell cellElement = (ShortTruthTableCell) element; + // ShortTruthTableCell cell = getCell(cellElement.getX(), cellElement.getY()); + // cell.setType(cellElement.getType()); + // } + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + int r = cell.getY(); + int c = cell.getX(); + if (r % 2 == 0 && c < statements[r / 2].getLength()) { + statements[r / 2] = statements[r / 2].replace(c, cell); + setCell(c, r, statements[r / 2].getCell(c)); } - - @Override - public String toString() { - System.out.println("ShortTruthTableBoard toString() called"); - StringBuilder str = new StringBuilder(); - for (int i = 0; i < dimension.height; i += 2) { - for (int j = 0; j < dimension.width; j++) { - ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); - str.append(c.getSymbol()); - } - str.append(" "); - for (int j = 0; j < dimension.width; j++) { - ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); - str.append(ShortTruthTableCellType.toChar(c.getType())); - } - str.append('\n'); - } - return str.toString(); + super.notifyChange(cell); + } + + @Override + public String toString() { + System.out.println("ShortTruthTableBoard toString() called"); + StringBuilder str = new StringBuilder(); + for (int i = 0; i < dimension.height; i += 2) { + for (int j = 0; j < dimension.width; j++) { + ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); + str.append(c.getSymbol()); + } + str.append(" "); + for (int j = 0; j < dimension.width; j++) { + ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); + str.append(ShortTruthTableCellType.toChar(c.getType())); + } + str.append('\n'); } - + return str.toString(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java index 59b5f4272..a432fe5e4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java @@ -2,231 +2,215 @@ import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.GridCell; - -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableStatement; - import java.awt.Point; import java.awt.event.MouseEvent; public class ShortTruthTableCell extends GridCell { - //The symbol on the cell - private char symbol; - - //This is a reference to the statement that contains this cell - private ShortTruthTableStatement statement; - - //Constructors - - public ShortTruthTableCell(char symbol, ShortTruthTableCellType cellType, Point location) { - super(cellType, location); - this.symbol = symbol; - } - - - /** - * Constructs a new NOT_IN_PLAY Cell - * - * @param location the location of this cell on the board - */ - public ShortTruthTableCell(Point location) { - this(' ', ShortTruthTableCellType.NOT_IN_PLAY, location); - } - - - //Getters - - public ShortTruthTableStatement getStatementReference() { - return statement; - } - - public ShortTruthTableCellType getType() { - return data; - } - - public char getSymbol() { - return symbol; - } - - /** - * Returns true if this cell is a letter; false if it is an operation, paren, unused, etc - * - * @return true if cell is a variable; false otherwise - */ - public boolean isVariable() { - return Character.isLetter(symbol); - } - - public int getX() { - return (int) location.getX(); - } - - public int getY() { - return (int) location.getY(); - } - - - public boolean isAssigned() { - return getType() == ShortTruthTableCellType.TRUE || getType() == ShortTruthTableCellType.FALSE; - } - - //Setters - - void setStatementReference(ShortTruthTableStatement statement) { - this.statement = statement; - } - - public void setType(ShortTruthTableCellType type) { - data = type; - } - - public void setGiven(ShortTruthTableCellType type) { - setType(type); - setModifiable(false); - setGiven(true); - } - - //Modifiers - - public void cycleTypeForward() { - switch (data) { - case UNKNOWN: - data = ShortTruthTableCellType.TRUE; - break; - case TRUE: - data = ShortTruthTableCellType.FALSE; - break; - case FALSE: - data = ShortTruthTableCellType.UNKNOWN; - break; - default: - break; - } - } - - public void cycleTypeBackward() { - cycleTypeForward(); - cycleTypeForward(); - } - - - //TO STRING - - @Override - public String toString() { - return String.format("STTCell: %c %2d %-11s %s", symbol, index, data, location.toString()); - } - - - //Copy function - - @Override - public ShortTruthTableCell copy() { - ShortTruthTableCell copy = new ShortTruthTableCell(symbol, data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } - - /** - * Sets the type of this ShortTruthTableCell - * - * @param e element to set the type of this Short Truth Table cell to - */ - @Override - public void setType(Element e, MouseEvent m) { - // Do not allow odd rows to be modified since they are spacer rows - if (this.getLocation().getY() % 2 == 1) { - return; - } - - // Red Element - if (e.getElementID().equals("STTT-PLAC-0002")) { - this.data = ShortTruthTableCellType.FALSE; + // The symbol on the cell + private char symbol; + + // This is a reference to the statement that contains this cell + private ShortTruthTableStatement statement; + + // Constructors + + public ShortTruthTableCell(char symbol, ShortTruthTableCellType cellType, Point location) { + super(cellType, location); + this.symbol = symbol; + } + + /** + * Constructs a new NOT_IN_PLAY Cell + * + * @param location the location of this cell on the board + */ + public ShortTruthTableCell(Point location) { + this(' ', ShortTruthTableCellType.NOT_IN_PLAY, location); + } + + // Getters + + public ShortTruthTableStatement getStatementReference() { + return statement; + } + + public ShortTruthTableCellType getType() { + return data; + } + + public char getSymbol() { + return symbol; + } + + /** + * Returns true if this cell is a letter; false if it is an operation, paren, unused, etc + * + * @return true if cell is a variable; false otherwise + */ + public boolean isVariable() { + return Character.isLetter(symbol); + } + + public int getX() { + return (int) location.getX(); + } + + public int getY() { + return (int) location.getY(); + } + + public boolean isAssigned() { + return getType() == ShortTruthTableCellType.TRUE || getType() == ShortTruthTableCellType.FALSE; + } + + // Setters + + void setStatementReference(ShortTruthTableStatement statement) { + this.statement = statement; + } + + public void setType(ShortTruthTableCellType type) { + data = type; + } + + public void setGiven(ShortTruthTableCellType type) { + setType(type); + setModifiable(false); + setGiven(true); + } + + // Modifiers + + public void cycleTypeForward() { + switch (data) { + case UNKNOWN: + data = ShortTruthTableCellType.TRUE; + break; + case TRUE: + data = ShortTruthTableCellType.FALSE; + break; + case FALSE: + data = ShortTruthTableCellType.UNKNOWN; + break; + default: + break; + } + } + + public void cycleTypeBackward() { + cycleTypeForward(); + cycleTypeForward(); + } + + // TO STRING + + @Override + public String toString() { + return String.format("STTCell: %c %2d %-11s %s", symbol, index, data, location.toString()); + } + + // Copy function + + @Override + public ShortTruthTableCell copy() { + ShortTruthTableCell copy = new ShortTruthTableCell(symbol, data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } + + /** + * Sets the type of this ShortTruthTableCell + * + * @param e element to set the type of this Short Truth Table cell to + */ + @Override + public void setType(Element e, MouseEvent m) { + // Do not allow odd rows to be modified since they are spacer rows + if (this.getLocation().getY() % 2 == 1) { + return; + } + + // Red Element + if (e.getElementID().equals("STTT-PLAC-0002")) { + this.data = ShortTruthTableCellType.FALSE; + } + // Green Element + else { + if (e.getElementID().equals("STTT-PLAC-0001")) { + this.data = ShortTruthTableCellType.TRUE; + } + // Unknown Element + else { + if (e.getElementID().equals("STTT-PLAC-0003")) { + this.data = ShortTruthTableCellType.UNKNOWN; } - // Green Element + // Argument Element else { - if (e.getElementID().equals("STTT-PLAC-0001")) { - this.data = ShortTruthTableCellType.TRUE; + if (e.getElementID().equals("STTT-UNPL-0001")) { + // Prevents non-argument symbols from being changed + if (!(this.symbol >= 'A' && this.symbol <= 'Z')) { + return; } - // Unknown Element - else { - if (e.getElementID().equals("STTT-PLAC-0003")) { - this.data = ShortTruthTableCellType.UNKNOWN; - } - // Argument Element - else { - if (e.getElementID().equals("STTT-UNPL-0001")) { - // Prevents non-argument symbols from being changed - if (!(this.symbol >= 'A' && this.symbol <= 'Z')) { - return; - } - if (m.getButton() == MouseEvent.BUTTON1) { - this.symbol += 1; - if (this.symbol > 'Z') { - this.symbol = 'A'; - } - } - else { - if (m.getButton() == MouseEvent.BUTTON3) { - this.symbol -= 1; - if (this.symbol < 'A') { - this.symbol = 'Z'; - } - } - } + if (m.getButton() == MouseEvent.BUTTON1) { + this.symbol += 1; + if (this.symbol > 'Z') { + this.symbol = 'A'; + } + } else { + if (m.getButton() == MouseEvent.BUTTON3) { + this.symbol -= 1; + if (this.symbol < 'A') { + this.symbol = 'Z'; + } + } + } + } + // And/Or Element + else { + if (e.getElementID().equals("STTT-UNPL-0002")) { + if (m.getButton() == MouseEvent.BUTTON1) { + if (this.symbol == '^') { + this.symbol = '|'; + } else { + if (this.symbol == '|') { + this.symbol = '>'; + } else { + if (this.symbol == '>') { + this.symbol = '-'; + } else { + if (this.symbol == '-') { + this.symbol = '^'; + } } - // And/Or Element - else { - if (e.getElementID().equals("STTT-UNPL-0002")) { - if (m.getButton() == MouseEvent.BUTTON1) { - if (this.symbol == '^') { - this.symbol = '|'; - } - else { - if (this.symbol == '|') { - this.symbol = '>'; - } - else { - if (this.symbol == '>') { - this.symbol = '-'; - } - else { - if (this.symbol == '-') { - this.symbol = '^'; - } - } - } - } - } - else { - if (m.getButton() == MouseEvent.BUTTON3) { - if (this.symbol == '^') { - this.symbol = '-'; - } - else { - if (this.symbol == '|') { - this.symbol = '^'; - } - else { - if (this.symbol == '>') { - this.symbol = '|'; - } - else { - if (this.symbol == '-') { - this.symbol = '>'; - } - } - } - } - } - } + } + } + } else { + if (m.getButton() == MouseEvent.BUTTON3) { + if (this.symbol == '^') { + this.symbol = '-'; + } else { + if (this.symbol == '|') { + this.symbol = '^'; + } else { + if (this.symbol == '>') { + this.symbol = '|'; + } else { + if (this.symbol == '-') { + this.symbol = '>'; } + } } + } } + } } + } } + } } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java index 99d626447..288fd11f9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java @@ -4,69 +4,67 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class ShortTruthTableCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public ShortTruthTableCell importCell(Node node, Board board) throws InvalidFileFormatException { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public ShortTruthTableCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("ShortTruthTable Factory: unknown puzzleElement puzzleElement"); - } + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "ShortTruthTable Factory: unknown puzzleElement puzzleElement"); + } - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board; + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board; - //get the attributes for the cell - NamedNodeMap attributeList = node.getAttributes(); - int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); - int charIndex = Integer.valueOf(attributeList.getNamedItem("char_index").getNodeValue()); - String cellType = attributeList.getNamedItem("type").getNodeValue(); + // get the attributes for the cell + NamedNodeMap attributeList = node.getAttributes(); + int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); + int charIndex = Integer.valueOf(attributeList.getNamedItem("char_index").getNodeValue()); + String cellType = attributeList.getNamedItem("type").getNodeValue(); - //modify the appropriate cell - ShortTruthTableCell cell = (ShortTruthTableCell) sttBoard.getCell(charIndex, rowIndex * 2); - cell.setData(ShortTruthTableCellType.valueOf(cellType)); + // modify the appropriate cell + ShortTruthTableCell cell = (ShortTruthTableCell) sttBoard.getCell(charIndex, rowIndex * 2); + cell.setData(ShortTruthTableCellType.valueOf(cellType)); - return cell; - - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("nurikabe Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); - } + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - org.w3c.dom.Element cellElement = document.createElement("cell"); - cellElement.setAttribute("row_index", String.valueOf(cell.getY() / 2)); - cellElement.setAttribute("char_index", String.valueOf(cell.getX())); - cellElement.setAttribute("type", String.valueOf(cell.getType())); + org.w3c.dom.Element cellElement = document.createElement("cell"); + cellElement.setAttribute("row_index", String.valueOf(cell.getY() / 2)); + cellElement.setAttribute("char_index", String.valueOf(cell.getX())); + cellElement.setAttribute("type", String.valueOf(cell.getType())); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java index c997faf5f..fde55ee3c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java @@ -1,67 +1,67 @@ package edu.rpi.legup.puzzle.shorttruthtable; -import java.util.Map; import java.util.HashMap; +import java.util.Map; public enum ShortTruthTableCellType { + FALSE(0), + TRUE(1), + UNKNOWN(-1), + NOT_IN_PLAY(-2), + PARENTHESIS(-3); - FALSE(0), TRUE(1), UNKNOWN(-1), NOT_IN_PLAY(-2), PARENTHESIS(-3); - - public int value; - private static Map map = new HashMap<>(); + public int value; + private static Map map = new HashMap<>(); - ShortTruthTableCellType(int value) { - this.value = value; - } + ShortTruthTableCellType(int value) { + this.value = value; + } - static { - for (ShortTruthTableCellType cellType : ShortTruthTableCellType.values()) { - map.put(cellType.value, cellType); - } + static { + for (ShortTruthTableCellType cellType : ShortTruthTableCellType.values()) { + map.put(cellType.value, cellType); } + } - public static ShortTruthTableCellType valueOf(int cellType) { - return (ShortTruthTableCellType) map.get(cellType); - } + public static ShortTruthTableCellType valueOf(int cellType) { + return (ShortTruthTableCellType) map.get(cellType); + } - /** - * Gets the char value of a cell, Used for debugging - * - * @param type cell type input - * @return true if value is 1, false if value is 0, ? if value is -1, or blank otherwise - */ - public static char toChar(ShortTruthTableCellType type) { - if (type == TRUE) return 'T'; - if (type == FALSE) return 'F'; - if (type == UNKNOWN) return '?'; - return ' '; - } + /** + * Gets the char value of a cell, Used for debugging + * + * @param type cell type input + * @return true if value is 1, false if value is 0, ? if value is -1, or blank otherwise + */ + public static char toChar(ShortTruthTableCellType type) { + if (type == TRUE) return 'T'; + if (type == FALSE) return 'F'; + if (type == UNKNOWN) return '?'; + return ' '; + } + /** + * Returns true if this cell holds the value either TRUE or FALSE + * + * @return true if this cell holds the value either TRUE or FALSE + */ + public boolean isTrueOrFalse() { + return value == 0 || value == 1; + } - /** - * Returns true if this cell holds the value either TRUE or FALSE - * - * @return true if this cell holds the value either TRUE or FALSE - */ - public boolean isTrueOrFalse() { - return value == 0 || value == 1; - } - - - public ShortTruthTableCellType getNegation() { - switch (value) { - case 1: - return ShortTruthTableCellType.FALSE; - case 0: - return ShortTruthTableCellType.TRUE; - default: - throw new RuntimeException("Trying to negate a cell not assigned to true or false"); - } - } - - public static ShortTruthTableCellType getDefaultType(char c) { - if (c == '(' || c == ')') return PARENTHESIS; - return UNKNOWN; + public ShortTruthTableCellType getNegation() { + switch (value) { + case 1: + return ShortTruthTableCellType.FALSE; + case 0: + return ShortTruthTableCellType.TRUE; + default: + throw new RuntimeException("Trying to negate a cell not assigned to true or false"); } + } -} \ No newline at end of file + public static ShortTruthTableCellType getDefaultType(char c) { + if (c == '(' || c == ')') return PARENTHESIS; + return UNKNOWN; + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java index bddde44a5..e83c7b358 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java @@ -2,31 +2,33 @@ import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.event.MouseEvent; public class ShortTruthTableController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { - System.out.println("STTController: Cell change"); + System.out.println("STTController: Cell change"); - // cast the data to a short truth table cell - ShortTruthTableCell cell = (ShortTruthTableCell) data; + // cast the data to a short truth table cell + ShortTruthTableCell cell = (ShortTruthTableCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView.getSelectionPopupMenu().show(boardView, this.boardView.getCanvas().getX() + e.getX(), this.boardView.getCanvas().getY() + e.getY()); - } - else { - cell.cycleTypeForward(); - } - } - else { - if (e.getButton() == MouseEvent.BUTTON3) { - cell.cycleTypeBackward(); - } - } + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + cell.cycleTypeForward(); + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + cell.cycleTypeBackward(); + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java index b787921ad..af6e412ba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java @@ -1,82 +1,78 @@ package edu.rpi.legup.puzzle.shorttruthtable; -import edu.rpi.legup.ui.boardview.GridElementView; import edu.rpi.legup.app.LegupPreferences; - +import edu.rpi.legup.ui.boardview.GridElementView; import java.awt.*; public class ShortTruthTableElementView extends GridElementView { - //Font - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - //Square Colors - private static final Color TRUE_COLOR = new Color(0, 130, 0);//green - private static final Color TRUE_COLOR_COLORBLIND = new Color(0, 0, 255); - private static final Color FALSE_COLOR = new Color(200, 0, 0);//red - - private static final Color FALSE_COLOR_COLORBLIND = new Color(255, 0, 0); - private static final Color UNKNOWN_COLOR = Color.WHITE; - - public ShortTruthTableElementView(ShortTruthTableCell cell) { - super(cell); - } - - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public ShortTruthTableCell getPuzzleElement() { - return (ShortTruthTableCell) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - - //get information about the cell - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - ShortTruthTableCellType type = cell.getData(); - - //do not draw the cell if it is not in play - if (type == ShortTruthTableCellType.NOT_IN_PLAY) return; - - //fill in background color of the cell - graphics2D.setStroke(new BasicStroke(1)); - LegupPreferences prefs = LegupPreferences.getInstance(); - switch (type) { - case TRUE: - if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - graphics2D.setColor(TRUE_COLOR_COLORBLIND); - break; - } - graphics2D.setColor(TRUE_COLOR); - break; - case FALSE: - if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - graphics2D.setColor(FALSE_COLOR_COLORBLIND); - break; - } - graphics2D.setColor(FALSE_COLOR); - break; - default: - graphics2D.setColor(UNKNOWN_COLOR); - break; + // Font + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + // Square Colors + private static final Color TRUE_COLOR = new Color(0, 130, 0); // green + private static final Color TRUE_COLOR_COLORBLIND = new Color(0, 0, 255); + private static final Color FALSE_COLOR = new Color(200, 0, 0); // red + + private static final Color FALSE_COLOR_COLORBLIND = new Color(255, 0, 0); + private static final Color UNKNOWN_COLOR = Color.WHITE; + + public ShortTruthTableElementView(ShortTruthTableCell cell) { + super(cell); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public ShortTruthTableCell getPuzzleElement() { + return (ShortTruthTableCell) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + + // get information about the cell + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + ShortTruthTableCellType type = cell.getData(); + + // do not draw the cell if it is not in play + if (type == ShortTruthTableCellType.NOT_IN_PLAY) return; + + // fill in background color of the cell + graphics2D.setStroke(new BasicStroke(1)); + LegupPreferences prefs = LegupPreferences.getInstance(); + switch (type) { + case TRUE: + if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + graphics2D.setColor(TRUE_COLOR_COLORBLIND); + break; } - graphics2D.fillRect(location.x, location.y, size.width, size.height); - - //Draw the symbol on the cell - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getSymbol()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(ShortTruthTableOperation.getLogicSymbol(cell.getSymbol()), xText, yText); - - + graphics2D.setColor(TRUE_COLOR); + break; + case FALSE: + if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + graphics2D.setColor(FALSE_COLOR_COLORBLIND); + break; + } + graphics2D.setColor(FALSE_COLOR); + break; + default: + graphics2D.setColor(UNKNOWN_COLOR); + break; } + graphics2D.fillRect(location.x, location.y, size.width, size.height); + + // Draw the symbol on the cell + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getSymbol()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(ShortTruthTableOperation.getLogicSymbol(cell.getSymbol()), xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java index 9d6553c7c..a3c2c6918 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java @@ -2,47 +2,44 @@ import edu.rpi.legup.model.PuzzleExporter; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; import org.w3c.dom.Document; public class ShortTruthTableExporter extends PuzzleExporter { - public ShortTruthTableExporter(ShortTruthTable stt) { - super(stt); + public ShortTruthTableExporter(ShortTruthTable stt) { + super(stt); + } + + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + ShortTruthTableBoard board; + if (puzzle.getTree() != null) { + board = (ShortTruthTableBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (ShortTruthTableBoard) puzzle.getBoardView().getBoard(); } - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - ShortTruthTableBoard board; - if (puzzle.getTree() != null) { - board = (ShortTruthTableBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (ShortTruthTableBoard) puzzle.getBoardView().getBoard(); - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); - org.w3c.dom.Element boardElement = newDocument.createElement("board"); + org.w3c.dom.Element dataElement = newDocument.createElement("data"); - org.w3c.dom.Element dataElement = newDocument.createElement("data"); - - ShortTruthTableStatement[] statements = board.getStatements(); - for (int i = 0; i < statements.length; i++) { - org.w3c.dom.Element statementElement = newDocument.createElement("statement"); - statementElement.setAttribute("representation", statements[i].getStringRep()); - statementElement.setAttribute("row_index", String.valueOf(i)); - dataElement.appendChild(statementElement); - } - - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - ShortTruthTableCell cell = board.getCellFromElement(puzzleElement); - if (!cell.getType().isTrueOrFalse()) continue; + ShortTruthTableStatement[] statements = board.getStatements(); + for (int i = 0; i < statements.length; i++) { + org.w3c.dom.Element statementElement = newDocument.createElement("statement"); + statementElement.setAttribute("representation", statements[i].getStringRep()); + statementElement.setAttribute("row_index", String.valueOf(i)); + dataElement.appendChild(statementElement); + } - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - dataElement.appendChild(cellElement); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + ShortTruthTableCell cell = board.getCellFromElement(puzzleElement); + if (!cell.getType().isTrueOrFalse()) continue; - boardElement.appendChild(dataElement); - return boardElement; + org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); + dataElement.appendChild(cellElement); } + + boardElement.appendChild(dataElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java index 84d04fb45..c9cf388f1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java @@ -2,347 +2,346 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; +import javax.swing.*; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; class ShortTruthTableImporter extends PuzzleImporter { - public ShortTruthTableImporter(ShortTruthTable stt) { - super(stt); + public ShortTruthTableImporter(ShortTruthTable stt) { + super(stt); + } + + /** + * Parse a string into all the cells, the y position of the statement is passed so the y position + * can be set + * + * @param statement + * @param y + * @return + */ + private List getCells(String statement, int y) { + List cells = new ArrayList(); + // go through each char in the statement and make a cell for it + for (int i = 0; i < statement.length(); i++) { + char c = statement.charAt(i); + ShortTruthTableCell cell = + new ShortTruthTableCell(c, ShortTruthTableCellType.getDefaultType(c), new Point(i, y)); + // it is modifiable if the type is unknown + cell.setModifiable(cell.getType() == ShortTruthTableCellType.UNKNOWN); + cells.add(cell); } - - - /** - * Parse a string into all the cells, the y position of the statement is passed so the y position can be set - * - * @param statement - * @param y - * @return - */ - private List getCells(String statement, int y) { - List cells = new ArrayList(); - //go through each char in the statement and make a cell for it - for (int i = 0; i < statement.length(); i++) { - char c = statement.charAt(i); - ShortTruthTableCell cell = new ShortTruthTableCell(c, ShortTruthTableCellType.getDefaultType(c), new Point(i, y)); - //it is modifiable if the type is unknown - cell.setModifiable(cell.getType() == ShortTruthTableCellType.UNKNOWN); - cells.add(cell); - } - return cells; + return cells; + } + + /** + * Parses the statementData into all the cells (with symbols) and statements for the puzzle. All + * cells are set to UNKNWON, it their value is given, it will be set later in the import process. + * + *

Both allCells and statements act as returns, They should be passed as empty arrays + * + * @param statementData The data to be imported + * @param allCells returns all the cells as a jagged 2d array + * @param statements returns all the statements + * @return the length, in chars, of the longest statement + */ + private int parseAllStatementsAndCells( + final NodeList statementData, + List> allCells, + List statements) + throws InvalidFileFormatException { + + int maxStatementLength = 0; + + // get a 2D arraylist of all the cells + for (int i = 0; i < statementData.getLength(); i++) { + + // Get the atributes from the statement i in the file + NamedNodeMap attributeList = statementData.item(i).getAttributes(); + + String statementRep = attributeList.getNamedItem("representation").getNodeValue(); + System.out.println("STATEMENT REP: " + statementRep); + System.out.println("ROW INDEX: " + attributeList.getNamedItem("row_index").getNodeValue()); + // parser time (on statementRep) + // if (!validGrammar(statementRep)) throw some error + if (!validGrammar(statementRep)) { + JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); + throw new InvalidFileFormatException("shorttruthtable importer: invalid sentence syntax"); + } + int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); + + // get the cells for the statement + List rowOfCells = getCells(statementRep, rowIndex * 2); + allCells.add(rowOfCells); + statements.add(new ShortTruthTableStatement(statementRep, rowOfCells)); + + // keep track of the length of the longest statement + maxStatementLength = Math.max(maxStatementLength, statementRep.length()); } - - /** - * Parses the statementData into all the cells (with symbols) and statements for the - * puzzle. All cells are set to UNKNWON, it their value is given, it will be set later - * in the import process. - *

- * Both allCells and statements act as returns, They should be passed as empty arrays - * - * @param statementData The data to be imported - * @param allCells returns all the cells as a jagged 2d array - * @param statements returns all the statements - * @return the length, in chars, of the longest statement - */ - private int parseAllStatementsAndCells(final NodeList statementData, - List> allCells, - List statements) throws InvalidFileFormatException { - - int maxStatementLength = 0; - - //get a 2D arraylist of all the cells - for (int i = 0; i < statementData.getLength(); i++) { - - //Get the atributes from the statement i in the file - NamedNodeMap attributeList = statementData.item(i).getAttributes(); - - String statementRep = attributeList.getNamedItem("representation").getNodeValue(); - System.out.println("STATEMENT REP: " + statementRep); - System.out.println("ROW INDEX: " + attributeList.getNamedItem("row_index").getNodeValue()); - //parser time (on statementRep) - //if (!validGrammar(statementRep)) throw some error - if (!validGrammar(statementRep)) { - JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); - throw new InvalidFileFormatException("shorttruthtable importer: invalid sentence syntax"); - } - int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); - - //get the cells for the statement - List rowOfCells = getCells(statementRep, rowIndex * 2); - allCells.add(rowOfCells); - statements.add(new ShortTruthTableStatement(statementRep, rowOfCells)); - - //keep track of the length of the longest statement - maxStatementLength = Math.max(maxStatementLength, statementRep.length()); - - } - - return maxStatementLength; + return maxStatementLength; + } + + private int parseAllStatementsAndCells( + String[] statementData, + List> allCells, + List statements) + throws IllegalArgumentException { + int maxStatementLength = 0; + + for (int i = 0; i < statementData.length; i++) { + if (!validGrammar(statementData[i])) { + JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); + throw new IllegalArgumentException("shorttruthtable importer: invalid sentence syntax"); + } + + // get the cells for the statement + List rowOfCells = getCells(statementData[i], i * 2); + allCells.add(rowOfCells); + statements.add(new ShortTruthTableStatement(statementData[i], rowOfCells)); + + // keep track of the length of the longest statement + maxStatementLength = Math.max(maxStatementLength, statementData[i].length()); } - private int parseAllStatementsAndCells(String[] statementData, - List> allCells, - List statements) throws IllegalArgumentException { - int maxStatementLength = 0; - - for (int i = 0; i < statementData.length; i++) { - if (!validGrammar(statementData[i])) { - JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); - throw new IllegalArgumentException("shorttruthtable importer: invalid sentence syntax"); - } - - //get the cells for the statement - List rowOfCells = getCells(statementData[i], i * 2); - allCells.add(rowOfCells); - statements.add(new ShortTruthTableStatement(statementData[i], rowOfCells)); - - //keep track of the length of the longest statement - maxStatementLength = Math.max(maxStatementLength, statementData[i].length()); + return maxStatementLength; + } + + protected boolean validGrammar(String sentence) { + int open = 0; + int close = 0; + char[] valid_characters = new char[] {'^', 'v', '!', '>', '-', '&', '|', '~', '$', '%'}; + for (int i = 0; i < sentence.length(); i++) { + char s = sentence.charAt(i); + if (s == '(' || s == ')') { + switch (s) { + case ')': + close++; + break; + case '(': + open++; + break; } - - return maxStatementLength; - } - - protected boolean validGrammar(String sentence) { - int open = 0; - int close = 0; - char[] valid_characters = new char[]{'^', 'v', '!', '>', '-', '&', '|', '~', '$', '%'}; - for (int i = 0; i < sentence.length(); i++) { - char s = sentence.charAt(i); - if (s == '(' || s == ')') { - switch (s) { - case ')': - close++; - break; - case '(': - open++; - break; - } - continue; - } - if (!Character.isLetter(s)) { - boolean valid = false; - for (char c : valid_characters) { - if (c == s) { - valid = true; - break; - } - } - if (!valid) { - System.out.println("Invalid character"); - System.out.println(s); - return false; - } - if (i != sentence.length() - 1) { - char next = sentence.charAt(i + 1); - if (next != '!' && next != '~') { - for (char c : valid_characters) { - if (c == next) { - System.out.println("Invalid next character"); - System.out.println(s); - System.out.println(next); - return false; - } - } - } - } - } - else { - if (i != sentence.length() - 1) { - if (Character.isLetter(sentence.charAt(i + 1))) { - System.out.println("Invalid next character"); - System.out.println(s); - System.out.println(sentence.charAt(i + 1)); - return false; - } - } - } + continue; + } + if (!Character.isLetter(s)) { + boolean valid = false; + for (char c : valid_characters) { + if (c == s) { + valid = true; + break; + } } - return open == close; - } - - private ShortTruthTableBoard generateBoard(List> allCells, - List statements, - int width) { - - //calculate the height for the board - int height = statements.size() * 2 - 1; - - //instantiate the board with the correct width and height - ShortTruthTableBoard sttBoard = new ShortTruthTableBoard(width, height, - statements.toArray(new ShortTruthTableStatement[statements.size()])); - - //set the cells in the board. create not_in_play cells where needed - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - - //get the statement index for this row of the table - int statementIndex = y / 2; - - //get the cell at this location; or create a not_in_play one if necessary - ShortTruthTableCell cell = null; - - //for a cell to exist at (x, y), it must be a valid row and within the statement length - if (y % 2 == 0 && x < statements.get(statementIndex).getLength()) { - cell = allCells.get(statementIndex).get(x); - System.out.println("Importer: check cell statement ref: " + cell.getStatementReference()); - } - else { - //if it is not a valid cell space, add a NOT_IN_PLAY cell - cell = new ShortTruthTableCell(' ', ShortTruthTableCellType.NOT_IN_PLAY, new Point(x, y)); - cell.setModifiable(false); - } - - //add the cell to the table - cell.setIndex(y * width + x); - sttBoard.setCell(x, y, cell); - } + if (!valid) { + System.out.println("Invalid character"); + System.out.println(s); + return false; } - - return sttBoard; - - } - - - private void setGivenCells(ShortTruthTableBoard sttBoard, - Element dataElement, - NodeList cellData, - List statements) throws InvalidFileFormatException { - - - //if it is normal, set all predicates to true and the conclusion to false - if (dataElement.getAttribute("normal").equalsIgnoreCase("true")) { - //set all predicates to true (all but the last one) - for (int i = 0; i < statements.size() - 1; i++) { - statements.get(i).getCell().setGiven(ShortTruthTableCellType.TRUE); + if (i != sentence.length() - 1) { + char next = sentence.charAt(i + 1); + if (next != '!' && next != '~') { + for (char c : valid_characters) { + if (c == next) { + System.out.println("Invalid next character"); + System.out.println(s); + System.out.println(next); + return false; + } } - //set the conclusion to false (the last one) - statements.get(statements.size() - 1).getCell().setGiven(ShortTruthTableCellType.FALSE); + } } - - //set the given cell values - for (int i = 0; i < cellData.getLength(); i++) { - //set the value with the factory importer - ShortTruthTableCell cell = (ShortTruthTableCell) puzzle.getFactory().importCell(cellData.item(i), sttBoard); - //set the modifiable and given flags - cell.setModifiable(false); - cell.setGiven(true); + } else { + if (i != sentence.length() - 1) { + if (Character.isLetter(sentence.charAt(i + 1))) { + System.out.println("Invalid next character"); + System.out.println(s); + System.out.println(sentence.charAt(i + 1)); + return false; + } } - - + } } + return open == close; + } + + private ShortTruthTableBoard generateBoard( + List> allCells, + List statements, + int width) { + + // calculate the height for the board + int height = statements.size() * 2 - 1; + + // instantiate the board with the correct width and height + ShortTruthTableBoard sttBoard = + new ShortTruthTableBoard( + width, height, statements.toArray(new ShortTruthTableStatement[statements.size()])); + + // set the cells in the board. create not_in_play cells where needed + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + + // get the statement index for this row of the table + int statementIndex = y / 2; + + // get the cell at this location; or create a not_in_play one if necessary + ShortTruthTableCell cell = null; + + // for a cell to exist at (x, y), it must be a valid row and within the statement length + if (y % 2 == 0 && x < statements.get(statementIndex).getLength()) { + cell = allCells.get(statementIndex).get(x); + System.out.println("Importer: check cell statement ref: " + cell.getStatementReference()); + } else { + // if it is not a valid cell space, add a NOT_IN_PLAY cell + cell = new ShortTruthTableCell(' ', ShortTruthTableCellType.NOT_IN_PLAY, new Point(x, y)); + cell.setModifiable(false); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return false; + // add the cell to the table + cell.setIndex(y * width + x); + sttBoard.setCell(x, y, cell); + } } - @Override - public boolean acceptsTextInput() { - return true; + return sttBoard; + } + + private void setGivenCells( + ShortTruthTableBoard sttBoard, + Element dataElement, + NodeList cellData, + List statements) + throws InvalidFileFormatException { + + // if it is normal, set all predicates to true and the conclusion to false + if (dataElement.getAttribute("normal").equalsIgnoreCase("true")) { + // set all predicates to true (all but the last one) + for (int i = 0; i < statements.size() - 1; i++) { + statements.get(i).getCell().setGiven(ShortTruthTableCellType.TRUE); + } + // set the conclusion to false (the last one) + statements.get(statements.size() - 1).getCell().setGiven(ShortTruthTableCellType.FALSE); } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException - */ - @Override - public void initializeBoard(int rows, int columns) { - + // set the given cell values + for (int i = 0; i < cellData.getLength(); i++) { + // set the value with the factory importer + ShortTruthTableCell cell = + (ShortTruthTableCell) puzzle.getFactory().importCell(cellData.item(i), sttBoard); + // set the modifiable and given flags + cell.setModifiable(false); + cell.setGiven(true); } - - //STATEMENT IMPORTER - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - - try { - - //Check File formatting - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("short truth table Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("data").getLength() == 0) { - throw new InvalidFileFormatException("short truth table Importer: no statements found for board"); - } - - - //get all the cells in a 2D arraylist - List> allCells = new ArrayList>(); - //store the statement data structors - List statements = new ArrayList(); - - //get the elements from the file - Element dataElement = (Element) boardElement.getElementsByTagName("data").item(0); - NodeList statementData = dataElement.getElementsByTagName("statement"); - NodeList cellData = dataElement.getElementsByTagName("cell"); - - - //Parse the data - int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); - - //generate the board - ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); - - //set the given cell values - setGivenCells(sttBoard, dataElement, cellData, statements); - - puzzle.setCurrentBoard(sttBoard); - - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("short truth table Importer: unknown value where integer expected"); - } + } + + @Override + public boolean acceptsRowsAndColumnsInput() { + return false; + } + + @Override + public boolean acceptsTextInput() { + return true; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException + */ + @Override + public void initializeBoard(int rows, int columns) {} + + // STATEMENT IMPORTER + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + + try { + + // Check File formatting + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "short truth table Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("data").getLength() == 0) { + throw new InvalidFileFormatException( + "short truth table Importer: no statements found for board"); + } + + // get all the cells in a 2D arraylist + List> allCells = new ArrayList>(); + // store the statement data structors + List statements = new ArrayList(); + + // get the elements from the file + Element dataElement = (Element) boardElement.getElementsByTagName("data").item(0); + NodeList statementData = dataElement.getElementsByTagName("statement"); + NodeList cellData = dataElement.getElementsByTagName("cell"); + + // Parse the data + int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); + + // generate the board + ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); + + // set the given cell values + setGivenCells(sttBoard, dataElement, cellData, statements); + + puzzle.setCurrentBoard(sttBoard); + + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "short truth table Importer: unknown value where integer expected"); } + } + + /** + * Creates the board for building using statements + * + * @param statementInput + * @throws UnsupportedOperationException + * @throws IllegalArgumentException + */ + public void initializeBoard(String[] statementInput) + throws UnsupportedOperationException, IllegalArgumentException { + List statementsList = new LinkedList<>(); + for (String s : statementInput) { + if (s.strip().length() > 0) { + statementsList.add(s); + } + } + String[] statementData = statementsList.toArray(new String[statementsList.size()]); - /** - * Creates the board for building using statements - * - * @param statementInput - * @throws UnsupportedOperationException - * @throws IllegalArgumentException - */ - public void initializeBoard(String[] statementInput) throws UnsupportedOperationException, IllegalArgumentException { - List statementsList = new LinkedList<>(); - for (String s : statementInput) { - if (s.strip().length() > 0) { - statementsList.add(s); - } - } - String[] statementData = statementsList.toArray(new String[statementsList.size()]); - - if (statementData.length == 0) { - throw new IllegalArgumentException("short truth table Importer: no statements found for board"); - } + if (statementData.length == 0) { + throw new IllegalArgumentException( + "short truth table Importer: no statements found for board"); + } - // Store all cells and statements - List> allCells = new ArrayList<>(); - List statements = new ArrayList<>(); + // Store all cells and statements + List> allCells = new ArrayList<>(); + List statements = new ArrayList<>(); - // Parse the data - int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); + // Parse the data + int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); - // Generate and set the board - don't set given cell values since none are given - ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); - puzzle.setCurrentBoard(sttBoard); - } + // Generate and set the board - don't set given cell values since none are given + ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); + puzzle.setCurrentBoard(sttBoard); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java index 70011d5dd..1a5fd3a12 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java @@ -1,57 +1,48 @@ package edu.rpi.legup.puzzle.shorttruthtable; -import java.util.Collections; -import java.util.Map; -import java.util.TreeMap; - public class ShortTruthTableOperation { - public static final char AND = '^'; - public static final char OR = '|'; - public static final char NOT = '~'; - public static final char CONDITIONAL = '>'; - public static final char BICONDITIONAL = '-'; + public static final char AND = '^'; + public static final char OR = '|'; + public static final char NOT = '~'; + public static final char CONDITIONAL = '>'; + public static final char BICONDITIONAL = '-'; - private ShortTruthTableOperation() { - } + private ShortTruthTableOperation() {} - public static String getLogicSymbol(char c) { - switch (c) { - case AND: - return "\u2227"; - case OR: - return "\u2228"; - case NOT: - return "\u00AC"; - case CONDITIONAL: - return "\u2192"; - case BICONDITIONAL: - return "\u2194"; - } - return "" + c; + public static String getLogicSymbol(char c) { + switch (c) { + case AND: + return "\u2227"; + case OR: + return "\u2228"; + case NOT: + return "\u00AC"; + case CONDITIONAL: + return "\u2192"; + case BICONDITIONAL: + return "\u2194"; } + return "" + c; + } - public static String getRuleName(char operation) { - switch (operation) { - case AND: - return "And"; - case OR: - return "Or"; - case NOT: - return "Not"; - case CONDITIONAL: - return "Conditional"; - case BICONDITIONAL: - return "Biconditional"; - } - return null; + public static String getRuleName(char operation) { + switch (operation) { + case AND: + return "And"; + case OR: + return "Or"; + case NOT: + return "Not"; + case CONDITIONAL: + return "Conditional"; + case BICONDITIONAL: + return "Biconditional"; } + return null; + } - public static boolean isOperation(char c) { - return c == AND || - c == OR || - c == NOT || - c == CONDITIONAL || - c == BICONDITIONAL; - } + public static boolean isOperation(char c) { + return c == AND || c == OR || c == NOT || c == CONDITIONAL || c == BICONDITIONAL; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java index e40a10cf0..59073f8e3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java @@ -1,313 +1,298 @@ package edu.rpi.legup.puzzle.shorttruthtable; - import edu.rpi.legup.model.gameboard.PuzzleElement; - -import java.util.Set; -import java.util.HashSet; import java.awt.Point; -import java.util.List; import java.util.ArrayList; - +import java.util.HashSet; +import java.util.List; +import java.util.Set; public class ShortTruthTableStatement extends PuzzleElement { - //the cell that this statement holds - private final ShortTruthTableCell cell; + // the cell that this statement holds + private final ShortTruthTableCell cell; - //child nodes of the tree - private final ShortTruthTableStatement parentStatement; - private final ShortTruthTableStatement leftStatement; - private final ShortTruthTableStatement rightStatement; + // child nodes of the tree + private final ShortTruthTableStatement parentStatement; + private final ShortTruthTableStatement leftStatement; + private final ShortTruthTableStatement rightStatement; - //the representation string for this statement - private final String stringRep; - private final List cells; + // the representation string for this statement + private final String stringRep; + private final List cells; + // constructor for root statement, sets parent to null + public ShortTruthTableStatement(String statement, List cells) { + this(statement, null, cells); + } - //constructor for root statement, sets parent to null - public ShortTruthTableStatement(String statement, List cells) { - this(statement, null, cells); - } - - //recursive constructor; constructs child statement nodes if necessary - private ShortTruthTableStatement(String statement, ShortTruthTableStatement parent, List cells) { + // recursive constructor; constructs child statement nodes if necessary + private ShortTruthTableStatement( + String statement, ShortTruthTableStatement parent, List cells) { - this.parentStatement = parent; + this.parentStatement = parent; - //set the string rep to the statement (include parens in case this is a sub statement) - this.stringRep = statement; - this.cells = new ArrayList(cells); + // set the string rep to the statement (include parens in case this is a sub statement) + this.stringRep = statement; + this.cells = new ArrayList(cells); - //remove the parens for parsing the statement - statement = removeParens(statement); - removeParens(cells); + // remove the parens for parsing the statement + statement = removeParens(statement); + removeParens(cells); - //get the index of the char that this statement represents - int index = parse(statement); + // get the index of the char that this statement represents + int index = parse(statement); - //construct the cell for this node in the tree - cell = cells.get(index); - //give the cell a reference back to this statement - cell.setStatementReference(this); + // construct the cell for this node in the tree + cell = cells.get(index); + // give the cell a reference back to this statement + cell.setStatementReference(this); - //get the strings on either side of this char in the string rep - String left = statement.substring(0, index); - String right = statement.substring(index + 1); - - List leftCells = new ArrayList(cells.subList(0, index)); - List rightCells = new ArrayList(cells.subList(index + 1, cells.size())); - - //construct sub-statements if necessary - if (left.length() > 0) { - leftStatement = new ShortTruthTableStatement(left, this, leftCells); - } - else { - leftStatement = null; - } + // get the strings on either side of this char in the string rep + String left = statement.substring(0, index); + String right = statement.substring(index + 1); - if (right.length() > 0) { - rightStatement = new ShortTruthTableStatement(right, this, rightCells); - } - else { - rightStatement = null; - } + List leftCells = + new ArrayList(cells.subList(0, index)); + List rightCells = + new ArrayList(cells.subList(index + 1, cells.size())); + // construct sub-statements if necessary + if (left.length() > 0) { + leftStatement = new ShortTruthTableStatement(left, this, leftCells); + } else { + leftStatement = null; } - - //parsing for the constructor - static String removeParens(String statement) { - - if (statement.charAt(0) != '(') { - return statement; - } - - //if the statement does start with a paren, check that it matches with the last paren - int openParenCount = 1; - int i = 1; - while (i < statement.length() - 1) { - char c = statement.charAt(i); - if (c == '(') { - openParenCount++; - } - else { - if (c == ')') openParenCount--; - } - - //if the first paren has been closed, and it is not the end of the string, - //then there is no whole statement parens to remove - if (openParenCount == 0 && i != statement.length() - 1) { - return statement; - } - - i++; - } - //if the while loop made it through the entire statement, there are parens around the whole thing - return statement.substring(1, statement.length() - 1); - + if (right.length() > 0) { + rightStatement = new ShortTruthTableStatement(right, this, rightCells); + } else { + rightStatement = null; } + } - int parse(String statement) { - - - //Split by and, or, CONDITIONAL, or biconditional - //keep track of the parens, it must be equal to zero to split - int openParenCount = 0; - //index for stepping through the string - int i = 0; - //step through each char in the statement - while (i < statement.length()) { - //get the char - char c = statement.charAt(i); - //keep track of the open parens - if (c == '(') { - openParenCount++; - } - else { - if (c == ')') { - openParenCount--; - } - //if the char is an operator, and there are no open parens, split the statement here - else { - if (openParenCount == 0 && ShortTruthTableOperation.isOperation(c) && c != ShortTruthTableOperation.NOT) { - return i; - } - } - } - //increment the index - i++; - } - - //if it made it through the while loop: - //this is an atomic statement or a negation - //either way, the important char is the first character in the string - return 0; + // parsing for the constructor + static String removeParens(String statement) { + if (statement.charAt(0) != '(') { + return statement; } - static void removeParens(List cells) { - - if (cells.get(0).getSymbol() != '(') { - return; + // if the statement does start with a paren, check that it matches with the last paren + int openParenCount = 1; + int i = 1; + while (i < statement.length() - 1) { + char c = statement.charAt(i); + if (c == '(') { + openParenCount++; + } else { + if (c == ')') openParenCount--; + } + + // if the first paren has been closed, and it is not the end of the string, + // then there is no whole statement parens to remove + if (openParenCount == 0 && i != statement.length() - 1) { + return statement; + } + + i++; + } + // if the while loop made it through the entire statement, there are parens around the whole + // thing + return statement.substring(1, statement.length() - 1); + } + + int parse(String statement) { + + // Split by and, or, CONDITIONAL, or biconditional + // keep track of the parens, it must be equal to zero to split + int openParenCount = 0; + // index for stepping through the string + int i = 0; + // step through each char in the statement + while (i < statement.length()) { + // get the char + char c = statement.charAt(i); + // keep track of the open parens + if (c == '(') { + openParenCount++; + } else { + if (c == ')') { + openParenCount--; } - - //if the statement does start with a paren, check that it matches with the last paren - int openParenCount = 1; - int i = 1; - while (i < cells.size() - 1) { - char c = cells.get(i).getSymbol(); - if (c == '(') { - openParenCount++; - } - else { - if (c == ')') openParenCount--; - } - - //if the first paren has been closed, and it is not the end of the string, - //then there is no whole statement parens to remove - if (openParenCount == 0 && i != cells.size() - 1) { - return; - } - - i++; + // if the char is an operator, and there are no open parens, split the statement here + else { + if (openParenCount == 0 + && ShortTruthTableOperation.isOperation(c) + && c != ShortTruthTableOperation.NOT) { + return i; + } } - - //if the while loop made it through the entire statement, there are parens around the whole thing - cells.remove(cells.size() - 1); - cells.remove(0); - + } + // increment the index + i++; } + // if it made it through the while loop: + // this is an atomic statement or a negation + // either way, the important char is the first character in the string + return 0; + } - //Getters - + static void removeParens(List cells) { - public ShortTruthTableCell getCell() { - return cell; + if (cells.get(0).getSymbol() != '(') { + return; } - public ShortTruthTableStatement getLeftStatement() { - return leftStatement; + // if the statement does start with a paren, check that it matches with the last paren + int openParenCount = 1; + int i = 1; + while (i < cells.size() - 1) { + char c = cells.get(i).getSymbol(); + if (c == '(') { + openParenCount++; + } else { + if (c == ')') openParenCount--; + } + + // if the first paren has been closed, and it is not the end of the string, + // then there is no whole statement parens to remove + if (openParenCount == 0 && i != cells.size() - 1) { + return; + } + + i++; } - public ShortTruthTableStatement getRightStatement() { - return rightStatement; - } + // if the while loop made it through the entire statement, there are parens around the whole + // thing + cells.remove(cells.size() - 1); + cells.remove(0); + } - public ShortTruthTableStatement getParentStatement() { - return parentStatement; - } + // Getters - @Override - public String toString() { - if (this.parentStatement == null) { - return "SST_Statement: " + stringRep + " parent: null"; - } - return "SST_Statement: " + stringRep + " parent: " + parentStatement.stringRep; - } + public ShortTruthTableCell getCell() { + return cell; + } - public String getStringRep() { - return this.stringRep; - } + public ShortTruthTableStatement getLeftStatement() { + return leftStatement; + } - /** - * Returns the length of the statement in cells. This includes all cells used for parenthesis - * - * @return the number of cells contained in this statement - */ - public int getLength() { - return stringRep.length(); - } + public ShortTruthTableStatement getRightStatement() { + return rightStatement; + } + public ShortTruthTableStatement getParentStatement() { + return parentStatement; + } - public ShortTruthTableCell getCell(int i) { - return cells.get(i); + @Override + public String toString() { + if (this.parentStatement == null) { + return "SST_Statement: " + stringRep + " parent: null"; } - - - //Getters (recursive) - - //returns all cells in this statement with the symbol 'symbol'; runs recursively on both sides of the tree - public Set getCellsWithSymbol(char symbol) { - Set set = new HashSet(getLength()); - if (cell.getSymbol() == symbol) set.add(cell); - if (leftStatement != null) set.addAll(leftStatement.getCellsWithSymbol(symbol)); - if (rightStatement != null) set.addAll(rightStatement.getCellsWithSymbol(symbol)); - return set; + return "SST_Statement: " + stringRep + " parent: " + parentStatement.stringRep; + } + + public String getStringRep() { + return this.stringRep; + } + + /** + * Returns the length of the statement in cells. This includes all cells used for parenthesis + * + * @return the number of cells contained in this statement + */ + public int getLength() { + return stringRep.length(); + } + + public ShortTruthTableCell getCell(int i) { + return cells.get(i); + } + + // Getters (recursive) + + // returns all cells in this statement with the symbol 'symbol'; runs recursively on both sides of + // the tree + public Set getCellsWithSymbol(char symbol) { + Set set = new HashSet(getLength()); + if (cell.getSymbol() == symbol) set.add(cell); + if (leftStatement != null) set.addAll(leftStatement.getCellsWithSymbol(symbol)); + if (rightStatement != null) set.addAll(rightStatement.getCellsWithSymbol(symbol)); + return set; + } + + /** + * Returns an array of three elements where [0] is the left statement type, [1] is this statement + * type, and [2] is the right statement type. null means either the statement doesn't exist or is + * an unknown value. + * + * @return the assigned values to this statement and its sub-statements + */ + public ShortTruthTableCellType[] getCellTypePattern() { + // get this type and the right type, they will always be used + ShortTruthTableCellType type = this.cell.getType(); + System.out.println("Right statement: " + rightStatement.getCell()); + ShortTruthTableCellType rightType = this.rightStatement.getCell().getType(); + System.out.println("Right type: " + rightType); + // if this is a not statement, there is no left side + if (cell.getSymbol() == ShortTruthTableOperation.NOT) { + return new ShortTruthTableCellType[] {null, type, rightType}; } - - /** - * Returns an array of three elements where [0] is the left - * statement type, [1] is this statement type, and [2] is the - * right statement type. null means either the statement doesn't - * exist or is an unknown value. - * - * @return the assigned values to this statement and its sub-statements - */ - public ShortTruthTableCellType[] getCellTypePattern() { - //get this type and the right type, they will always be used - ShortTruthTableCellType type = this.cell.getType(); - System.out.println("Right statement: " + rightStatement.getCell()); - ShortTruthTableCellType rightType = this.rightStatement.getCell().getType(); - System.out.println("Right type: " + rightType); - //if this is a not statement, there is no left side - if (cell.getSymbol() == ShortTruthTableOperation.NOT) { - return new ShortTruthTableCellType[]{null, type, rightType}; - } - //if it is any other operation, get the left side too and return it - ShortTruthTableCellType leftType = this.leftStatement.getCell().getType(); - return new ShortTruthTableCellType[]{leftType, type, rightType}; + // if it is any other operation, get the left side too and return it + ShortTruthTableCellType leftType = this.leftStatement.getCell().getType(); + return new ShortTruthTableCellType[] {leftType, type, rightType}; + } + + // Setters + + private void setCellLocations(int rowIndex, int offset) { + // set the location of this cell + int xLoc = offset; + if (leftStatement != null) { + xLoc += leftStatement.getLength(); } - - //Setters - - private void setCellLocations(int rowIndex, int offset) { - //set the location of this cell - int xLoc = offset; - if (leftStatement != null) { - xLoc += leftStatement.getLength(); - } - cell.setLocation(new Point(xLoc, rowIndex)); - //recurse on both sides of the tree - if (leftStatement != null) { - leftStatement.setCellLocations(rowIndex, offset); - } - if (rightStatement != null) { - rightStatement.setCellLocations(rowIndex, xLoc + 1); - } + cell.setLocation(new Point(xLoc, rowIndex)); + // recurse on both sides of the tree + if (leftStatement != null) { + leftStatement.setCellLocations(rowIndex, offset); } - - public void setCellLocations(int rowIndex) { - setCellLocations(rowIndex, 0); + if (rightStatement != null) { + rightStatement.setCellLocations(rowIndex, xLoc + 1); } + } + public void setCellLocations(int rowIndex) { + setCellLocations(rowIndex, 0); + } - public ShortTruthTableStatement copy() { - //copy all the cells - List cellsCopy = new ArrayList<>(); - for (ShortTruthTableCell c : cells) { - cellsCopy.add(c.copy()); - } - //make a copy of the statement with all the copied cells - //return the new statement - return new ShortTruthTableStatement(stringRep, cellsCopy); + public ShortTruthTableStatement copy() { + // copy all the cells + List cellsCopy = new ArrayList<>(); + for (ShortTruthTableCell c : cells) { + cellsCopy.add(c.copy()); } - - public ShortTruthTableStatement replace(int column, ShortTruthTableCell cell) { - //copy all the cells (replacing one) - List cellsCopy = new ArrayList<>(); - for (ShortTruthTableCell c : cells) { - if (c.getX() == column) { - cellsCopy.add(cell); - } - else { - cellsCopy.add(c); - } - } - //make a copy of the statement with all the copied cells - //return the new statement - return new ShortTruthTableStatement(stringRep, cellsCopy); + // make a copy of the statement with all the copied cells + // return the new statement + return new ShortTruthTableStatement(stringRep, cellsCopy); + } + + public ShortTruthTableStatement replace(int column, ShortTruthTableCell cell) { + // copy all the cells (replacing one) + List cellsCopy = new ArrayList<>(); + for (ShortTruthTableCell c : cells) { + if (c.getX() == column) { + cellsCopy.add(cell); + } else { + cellsCopy.add(c); + } } - -} \ No newline at end of file + // make a copy of the statement with all the copied cells + // return the new statement + return new ShortTruthTableStatement(stringRep, cellsCopy); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java index 64e9fda75..e15f5b928 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java @@ -3,23 +3,22 @@ import edu.rpi.legup.controller.BoardController; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.ui.boardview.GridBoardView; - import java.awt.*; public class ShortTruthTableView extends GridBoardView { - public ShortTruthTableView(ShortTruthTableBoard board) { - super(new BoardController(), new ShortTruthTableController(), board.getDimension()); + public ShortTruthTableView(ShortTruthTableBoard board) { + super(new BoardController(), new ShortTruthTableController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; -// System.out.println("STTView :"+cell); - Point loc = cell.getLocation(); - ShortTruthTableElementView elementView = new ShortTruthTableElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + // System.out.println("STTView :"+cell); + Point loc = cell.getLocation(); + ShortTruthTableElementView elementView = new ShortTruthTableElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java index 9f238a9bf..ed53dc3bf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class ArgumentElement extends NonPlaceableElement { - public ArgumentElement() { - super("STTT-UNPL-0001", "Argument Element", "Argument of logic statement element", "edu/rpi/legup/images/shorttruthtable/tiles/LetterTile.png"); - } + public ArgumentElement() { + super( + "STTT-UNPL-0001", + "Argument Element", + "Argument of logic statement element", + "edu/rpi/legup/images/shorttruthtable/tiles/LetterTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java index 605f6a207..eb6b9996c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class GreenElement extends PlaceableElement { - public GreenElement() { - super("STTT-PLAC-0001", "Green Element", "A green tile to set certain tiles to true", "edu/rpi/legup/images/shorttruthtable/tiles/GreenTile.png"); - } + public GreenElement() { + super( + "STTT-PLAC-0001", + "Green Element", + "A green tile to set certain tiles to true", + "edu/rpi/legup/images/shorttruthtable/tiles/GreenTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java index b2adfddef..8336e0a41 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class LogicSymbolElement extends NonPlaceableElement { - public LogicSymbolElement() { - super("STTT-UNPL-0002", "Logic Symbol Element", "Logic symbol element", "edu/rpi/legup/images/shorttruthtable/tiles/ConditionalBiconditionalTile.png"); - } + public LogicSymbolElement() { + super( + "STTT-UNPL-0002", + "Logic Symbol Element", + "Logic symbol element", + "edu/rpi/legup/images/shorttruthtable/tiles/ConditionalBiconditionalTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java index ecc7d5a02..c9e0472ae 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class RedElement extends PlaceableElement { - public RedElement() { - super("STTT-PLAC-0002", "Red Element", "A red tile to set certain tiles to false", "edu/rpi/legup/images/shorttruthtable/tiles/RedTile.png"); - } + public RedElement() { + super( + "STTT-PLAC-0002", + "Red Element", + "A red tile to set certain tiles to false", + "edu/rpi/legup/images/shorttruthtable/tiles/RedTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java index 9a9ab8b84..87feed9ed 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class UnknownElement extends PlaceableElement { - public UnknownElement() { - super("STTT-PLAC-0003", "Unknown Element", "A blank tile", "edu/rpi/legup/images/shorttruthtable/tiles/UnknownTile.png"); - } + public UnknownElement() { + super( + "STTT-PLAC-0003", + "Unknown Element", + "A blank tile", + "edu/rpi/legup/images/shorttruthtable/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java index 4b40c833d..f8421da08 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java @@ -4,13 +4,13 @@ public class DirectRuleAtomic extends DirectRule_Generic { - public DirectRuleAtomic() { - super("STTT-BASC-0001", "Atomic Rule", - "All identical atoms have the same T/F value", - "Atomic", - new ContradictionRuleAtomic(), - false - ); - } - -} \ No newline at end of file + public DirectRuleAtomic() { + super( + "STTT-BASC-0001", + "Atomic Rule", + "All identical atoms have the same T/F value", + "Atomic", + new ContradictionRuleAtomic(), + false); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java index e1ac78b8c..106b34fd5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java @@ -2,72 +2,87 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; +import edu.rpi.legup.model.rules.ContradictionRule; import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; - import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; -import edu.rpi.legup.model.rules.ContradictionRule; public abstract class DirectRule_Generic extends DirectRule { - final ContradictionRule CORRESPONDING_CONTRADICTION_RULE; - final boolean ELIMINATION_RULE; - - public DirectRule_Generic(String ruleID, String ruleName, String description, String imageName, ContradictionRule contraRule, boolean eliminationRule) { - super(ruleID, ruleName, description, "edu/rpi/legup/images/shorttruthtable/ruleimages/basic/" + imageName + ".png"); - this.CORRESPONDING_CONTRADICTION_RULE = contraRule; - this.ELIMINATION_RULE = eliminationRule; + final ContradictionRule CORRESPONDING_CONTRADICTION_RULE; + final boolean ELIMINATION_RULE; + + public DirectRule_Generic( + String ruleID, + String ruleName, + String description, + String imageName, + ContradictionRule contraRule, + boolean eliminationRule) { + super( + ruleID, + ruleName, + description, + "edu/rpi/legup/images/shorttruthtable/ruleimages/basic/" + imageName + ".png"); + this.CORRESPONDING_CONTRADICTION_RULE = contraRule; + this.ELIMINATION_RULE = eliminationRule; + } + + public String checkRuleRawAt(TreeTransition transition, PuzzleElement element) { + // Rule must have cell to evaluate on + if (element == null) return super.getInvalidUseOfRuleMessage() + ": Must have painted cell"; + + // Check that the puzzle element is not unknown + ShortTruthTableBoard parentBoard = + (ShortTruthTableBoard) transition.getParents().get(0).getBoard(); + ShortTruthTableBoard finalBoard = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell parentCell = (ShortTruthTableCell) parentBoard.getPuzzleElement(element); + ShortTruthTableCell finalCell = (ShortTruthTableCell) finalBoard.getPuzzleElement(element); + + if (!finalCell.isAssigned()) { + return super.getInvalidUseOfRuleMessage() + + ": Only assigned cells are allowed for basic rules"; } - public String checkRuleRawAt(TreeTransition transition, PuzzleElement element) { - // Rule must have cell to evaluate on - if (element == null) return super.getInvalidUseOfRuleMessage() + ": Must have painted cell"; - - // Check that the puzzle element is not unknown - ShortTruthTableBoard parentBoard = (ShortTruthTableBoard) transition.getParents().get(0).getBoard(); - ShortTruthTableBoard finalBoard = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell parentCell = (ShortTruthTableCell) parentBoard.getPuzzleElement(element); - ShortTruthTableCell finalCell = (ShortTruthTableCell) finalBoard.getPuzzleElement(element); + // Strategy: Negate the modified cell and check if there is a contradiction. If there is one, + // then the + // original statement must be true. If there isn't one, then the original statement must be + // false. - if (!finalCell.isAssigned()) { - return super.getInvalidUseOfRuleMessage() + ": Only assigned cells are allowed for basic rules"; - } + ShortTruthTableBoard modifiedBoard = parentBoard.copy(); - // Strategy: Negate the modified cell and check if there is a contradiction. If there is one, then the - // original statement must be true. If there isn't one, then the original statement must be false. + PuzzleElement checkElement = + this.ELIMINATION_RULE + ? parentCell.getStatementReference().getParentStatement().getCell() + : element; - ShortTruthTableBoard modifiedBoard = parentBoard.copy(); + ShortTruthTableCell checkCell = + this.ELIMINATION_RULE + ? (ShortTruthTableCell) modifiedBoard.getCell(parentCell.getX(), parentCell.getY()) + : (ShortTruthTableCell) modifiedBoard.getPuzzleElement(element); - PuzzleElement checkElement = - this.ELIMINATION_RULE - ? parentCell.getStatementReference().getParentStatement().getCell() - : element; + checkCell.setType(finalCell.getType().getNegation()); - ShortTruthTableCell checkCell = - this.ELIMINATION_RULE - ? (ShortTruthTableCell) modifiedBoard.getCell(parentCell.getX(), parentCell.getY()) - : (ShortTruthTableCell) modifiedBoard.getPuzzleElement(element); - - checkCell.setType(finalCell.getType().getNegation()); - - String contradictionMessage = CORRESPONDING_CONTRADICTION_RULE.checkContradictionAt(modifiedBoard, checkElement); - if (contradictionMessage == null) { // A contradiction exists in the modified statement; this is good! - return null; - } - - return super.getInvalidUseOfRuleMessage(); + String contradictionMessage = + CORRESPONDING_CONTRADICTION_RULE.checkContradictionAt(modifiedBoard, checkElement); + if (contradictionMessage + == null) { // A contradiction exists in the modified statement; this is good! + return null; } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node short truth table board used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node short truth table board used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java index 3456d3aa0..b6e88fa65 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java @@ -4,8 +4,7 @@ public class DirectRuleAndElimination extends DirectRule_GenericElimination { - public DirectRuleAndElimination() { - super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); - } - -} \ No newline at end of file + public DirectRuleAndElimination() { + super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java index 4d53d05cf..8c12882a7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java @@ -4,8 +4,7 @@ public class DirectRuleBiconditionalElimination extends DirectRule_GenericElimination { - public DirectRuleBiconditionalElimination() { - super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); - } - -} \ No newline at end of file + public DirectRuleBiconditionalElimination() { + super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java index c1c1720af..a316b4566 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java @@ -4,8 +4,7 @@ public class DirectRuleConditionalElimination extends DirectRule_GenericElimination { - public DirectRuleConditionalElimination() { - super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); - } - -} \ No newline at end of file + public DirectRuleConditionalElimination() { + super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java index 576cef6ec..f15a4d2b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java @@ -4,8 +4,7 @@ public class DirectRuleNotElimination extends DirectRule_GenericElimination { - public DirectRuleNotElimination() { - super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); - } - -} \ No newline at end of file + public DirectRuleNotElimination() { + super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java index c57266d0d..77d507764 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java @@ -4,8 +4,7 @@ public class DirectRuleOrElimination extends DirectRule_GenericElimination { - public DirectRuleOrElimination() { - super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); - } - -} \ No newline at end of file + public DirectRuleOrElimination() { + super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java index e47c9d11c..b741f47b9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java @@ -1,18 +1,19 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.elimination; -import edu.rpi.legup.puzzle.shorttruthtable.rules.basic.DirectRule_Generic; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.puzzle.shorttruthtable.rules.basic.DirectRule_Generic; public abstract class DirectRule_GenericElimination extends DirectRule_Generic { - public DirectRule_GenericElimination(String ruleID, String ruleName, ContradictionRule contradictionRule) { - - super(ruleID, ruleName + " Elimination", - ruleName + " statements must have a valid pattern", - "elimination/" + ruleName, - contradictionRule, - true - ); - } + public DirectRule_GenericElimination( + String ruleID, String ruleName, ContradictionRule contradictionRule) { -} \ No newline at end of file + super( + ruleID, + ruleName + " Elimination", + ruleName + " statements must have a valid pattern", + "elimination/" + ruleName, + contradictionRule, + true); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java index 03db396ad..838f28e4c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java @@ -4,8 +4,7 @@ public class DirectRuleAndIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleAndIntroduction() { - super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); - } - -} \ No newline at end of file + public DirectRuleAndIntroduction() { + super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java index 74024c95d..5e332c355 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java @@ -4,8 +4,7 @@ public class DirectRuleBiconditionalIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleBiconditionalIntroduction() { - super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); - } - -} \ No newline at end of file + public DirectRuleBiconditionalIntroduction() { + super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java index 2782098f3..7b3843fde 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java @@ -4,8 +4,7 @@ public class DirectRuleConditionalIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleConditionalIntroduction() { - super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); - } - -} \ No newline at end of file + public DirectRuleConditionalIntroduction() { + super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java index ca98cdc21..be6926915 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java @@ -4,8 +4,7 @@ public class DirectRuleNotIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleNotIntroduction() { - super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); - } - -} \ No newline at end of file + public DirectRuleNotIntroduction() { + super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java index 3c82faaf9..887b1bff0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java @@ -4,8 +4,7 @@ public class DirectRuleOrIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleOrIntroduction() { - super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); - } - -} \ No newline at end of file + public DirectRuleOrIntroduction() { + super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java index 9d6c3f7d4..5b6803dc2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java @@ -1,18 +1,19 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.basic.introduction; -import edu.rpi.legup.puzzle.shorttruthtable.rules.basic.DirectRule_Generic; import edu.rpi.legup.model.rules.ContradictionRule; +import edu.rpi.legup.puzzle.shorttruthtable.rules.basic.DirectRule_Generic; public abstract class DirectRule_GenericIntroduction extends DirectRule_Generic { - protected DirectRule_GenericIntroduction(String ruleID, String ruleName, ContradictionRule contradictionRule) { - - super(ruleID, ruleName + " Introduction", - ruleName + " statements must have a valid pattern", - "introduction/" + ruleName, - contradictionRule, - false - ); - } + protected DirectRule_GenericIntroduction( + String ruleID, String ruleName, ContradictionRule contradictionRule) { -} \ No newline at end of file + super( + ruleID, + ruleName + " Introduction", + ruleName + " statements must have a valid pattern", + "introduction/" + ruleName, + contradictionRule, + false); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java index 2b8d39b22..60c9ab49e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java @@ -1,23 +1,17 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class CaseRuleAnd extends CaseRule_GenericStatement { - public CaseRuleAnd() { - super("STTT-CASE-0001", ShortTruthTableOperation.AND, - "And", - trueCases, - falseCases); - } - - private static final ShortTruthTableCellType[][] trueCases = { - {T, T} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {F, U}, - {U, F} - }; + public CaseRuleAnd() { + super("STTT-CASE-0001", ShortTruthTableOperation.AND, "And", trueCases, falseCases); + } + private static final ShortTruthTableCellType[][] trueCases = {{T, T}}; + private static final ShortTruthTableCellType[][] falseCases = { + {F, U}, + {U, F} + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java index f168499cc..46975b7df 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java @@ -3,68 +3,65 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.CaseBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; - - import java.util.ArrayList; -import java.util.List; public class CaseRuleAtomic extends CaseRule_Generic { - public CaseRuleAtomic() { - super("STTT-CASE-0002", "Atomic", - "True or False", - "Each unknown cell must either be true or false"); - } + public CaseRuleAtomic() { + super( + "STTT-CASE-0002", + "Atomic", + "True or False", + "Each unknown cell must either be true or false"); + } - // Adds all elements that can be selected for this case rule - @Override - public CaseBoard getCaseBoard(Board board) { - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); - sttBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(sttBoard, this); - for (PuzzleElement element : sttBoard.getPuzzleElements()) { - if (((ShortTruthTableCell) element).getType() == ShortTruthTableCellType.UNKNOWN) { - caseBoard.addPickableElement(element); - } - } - return caseBoard; + // Adds all elements that can be selected for this case rule + @Override + public CaseBoard getCaseBoard(Board board) { + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); + sttBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(sttBoard, this); + for (PuzzleElement element : sttBoard.getPuzzleElements()) { + if (((ShortTruthTableCell) element).getType() == ShortTruthTableCellType.UNKNOWN) { + caseBoard.addPickableElement(element); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(ShortTruthTableCellType.TRUE); - case1.addModifiedData(data1); - cases.add(case1); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(ShortTruthTableCellType.TRUE); + case1.addModifiedData(data1); + cases.add(case1); - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(ShortTruthTableCellType.FALSE); - case2.addModifiedData(data2); - cases.add(case2); + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(ShortTruthTableCellType.FALSE); + case2.addModifiedData(data2); + cases.add(case2); - return cases; - } + return cases; + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java index 85c6f5447..52058a6f5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java @@ -1,24 +1,25 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class CaseRuleBiconditional extends CaseRule_GenericStatement { - public CaseRuleBiconditional() { - super("STTT-CASE-0003", ShortTruthTableOperation.BICONDITIONAL, - "Biconditional", - trueCases, - falseCases); - } - - private static final ShortTruthTableCellType[][] trueCases = { - {T, T}, - {F, F} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - {F, T} - }; + public CaseRuleBiconditional() { + super( + "STTT-CASE-0003", + ShortTruthTableOperation.BICONDITIONAL, + "Biconditional", + trueCases, + falseCases); + } + private static final ShortTruthTableCellType[][] trueCases = { + {T, T}, + {F, F} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + {F, T} + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java index cb34bb6e0..ea1f78408 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java @@ -1,23 +1,24 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class CaseRuleConditional extends CaseRule_GenericStatement { - public CaseRuleConditional() { - super("STTT-CASE-0004", ShortTruthTableOperation.CONDITIONAL, - "Conditional", - trueCases, - falseCases); - } - - private static final ShortTruthTableCellType[][] trueCases = { - {U, T}, - {F, U} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - }; + public CaseRuleConditional() { + super( + "STTT-CASE-0004", + ShortTruthTableOperation.CONDITIONAL, + "Conditional", + trueCases, + falseCases); + } + private static final ShortTruthTableCellType[][] trueCases = { + {U, T}, + {F, U} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java index 2a155a41a..a9b2abb65 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java @@ -1,23 +1,19 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class CaseRuleOr extends CaseRule_GenericStatement { - public CaseRuleOr() { - super("STTT-CASE-0005", ShortTruthTableOperation.OR, - "Or", - trueCases, - falseCases); - } - - private static final ShortTruthTableCellType[][] trueCases = { - {T, U}, - {U, T} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {F, F}, - }; + public CaseRuleOr() { + super("STTT-CASE-0005", ShortTruthTableOperation.OR, "Or", trueCases, falseCases); + } + private static final ShortTruthTableCellType[][] trueCases = { + {T, U}, + {U, T} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {F, F}, + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java index 1d8f54d62..b4a6afee6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java @@ -1,71 +1,62 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.caserule; -import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.CaseBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; - -import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; -import edu.rpi.legup.puzzle.nurikabe.NurikabeType; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; - - -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import javax.swing.JOptionPane; - -import com.google.firebase.database.core.utilities.Tree; - public abstract class CaseRule_Generic extends CaseRule { - public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { - super(ruleID, title, description, "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); + public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { + super( + ruleID, + title, + description, + "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + // Validate that two children are generated + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "ERROR: This case rule must spawn at least 1 child."; } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - // Validate that two children are generated - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "ERROR: This case rule must spawn at least 1 child."; - } - - // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE - // List cases = Arrays.asList(childTransitions.get(0), childTransitions.get(1)); - // for (TreeTransition c : cases) { - // ShortTruthTableCell mod1 = (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // ShortTruthTableCell mod2 = (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && - // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { - // return "ERROR: This case rule must be an unknown, true, or false cell."; - // } - // } - return null; - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE + // List cases = Arrays.asList(childTransitions.get(0), childTransitions.get(1)); + // for (TreeTransition c : cases) { + // ShortTruthTableCell mod1 = + // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // ShortTruthTableCell mod2 = + // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == + // ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && + // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == + // ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { + // return "ERROR: This case rule must be an unknown, true, or false cell."; + // } + // } + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java index 0e25586a8..68dd33b16 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java @@ -3,135 +3,143 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.CaseBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableStatement; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; - -import java.util.List; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableStatement; import java.util.ArrayList; +import java.util.List; public abstract class CaseRule_GenericStatement extends CaseRule_Generic { - public CaseRule_GenericStatement(String ruleID, char operation, String title, - ShortTruthTableCellType[][] trueCases, - ShortTruthTableCellType[][] falseCases) { - super(ruleID, ShortTruthTableOperation.getRuleName(operation), - title + " case", - "A known " + title.toUpperCase() + " statement can have multiple forms"); - - this.operation = operation; - - this.trueCases = trueCases; - this.falseCases = falseCases; + public CaseRule_GenericStatement( + String ruleID, + char operation, + String title, + ShortTruthTableCellType[][] trueCases, + ShortTruthTableCellType[][] falseCases) { + super( + ruleID, + ShortTruthTableOperation.getRuleName(operation), + title + " case", + "A known " + title.toUpperCase() + " statement can have multiple forms"); + + this.operation = operation; + + this.trueCases = trueCases; + this.falseCases = falseCases; + } + + private final char operation; + + private final ShortTruthTableCellType[][] trueCases; + private final ShortTruthTableCellType[][] falseCases; + + protected static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; + protected static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; + protected static final ShortTruthTableCellType U = ShortTruthTableCellType.UNKNOWN; + + // Adds all elements that can be selected for this caserule + @Override + public CaseBoard getCaseBoard(Board board) { + // copy the board and add all elements that can be selected + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); + sttBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(sttBoard, this); + + // add all elements that can be selected for the case rule statement + for (PuzzleElement element : sttBoard.getPuzzleElements()) { + // get the cell object + ShortTruthTableCell cell = sttBoard.getCellFromElement(element); + // the cell must match the symbol + if (cell.getSymbol() != this.operation) continue; + // the statement must be assigned with unassigned sub-statements + if (!cell.getType().isTrueOrFalse()) continue; + if (cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) + continue; + if (this.operation != ShortTruthTableOperation.NOT + && cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) { + continue; + } + // if the element has passed all the checks, it can be selected + caseBoard.addPickableElement(element); } + return caseBoard; + } - private final char operation; - - private final ShortTruthTableCellType[][] trueCases; - private final ShortTruthTableCellType[][] falseCases; - - protected static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; - protected static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; - protected static final ShortTruthTableCellType U = ShortTruthTableCellType.UNKNOWN; - - // Adds all elements that can be selected for this caserule - @Override - public CaseBoard getCaseBoard(Board board) { - //copy the board and add all elements that can be selected - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); - sttBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(sttBoard, this); - - //add all elements that can be selected for the case rule statement - for (PuzzleElement element : sttBoard.getPuzzleElements()) { - //get the cell object - ShortTruthTableCell cell = sttBoard.getCellFromElement(element); - //the cell must match the symbol - if (cell.getSymbol() != this.operation) continue; - //the statement must be assigned with unassigned sub-statements - if (!cell.getType().isTrueOrFalse()) continue; - if (cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) continue; - if (this.operation != ShortTruthTableOperation.NOT && - cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) { - continue; - } - //if the element has passed all the checks, it can be selected - caseBoard.addPickableElement(element); - } - return caseBoard; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ShortTruthTableBoard sttBoard = ((ShortTruthTableBoard) board); + ShortTruthTableCell cell = sttBoard.getCellFromElement(puzzleElement); + + // If the statement is set to true, collect true cases. Otherwise, collect the false cases + if (cell.getType() == ShortTruthTableCellType.TRUE) { + return getCasesFromCell(sttBoard, puzzleElement, trueCases); } + return getCasesFromCell(sttBoard, puzzleElement, falseCases); + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ShortTruthTableBoard sttBoard = ((ShortTruthTableBoard) board); - ShortTruthTableCell cell = sttBoard.getCellFromElement(puzzleElement); - - // If the statement is set to true, collect true cases. Otherwise, collect the false cases - if (cell.getType() == ShortTruthTableCellType.TRUE) { - return getCasesFromCell(sttBoard, puzzleElement, trueCases); - } - return getCasesFromCell(sttBoard, puzzleElement, falseCases); + /** + * Collects a list of boards for each possible outcome of case-rule application + * + * @param board current board state + * @param puzzleElement case rule operator + * @param possibilities list of possibilities for operator state + * @return ArrayList of Boards + */ + private ArrayList getCasesFromCell( + ShortTruthTableBoard board, + PuzzleElement puzzleElement, + ShortTruthTableCellType[][] possibilities) { + // Create branch case for each possibility + ArrayList cases = new ArrayList<>(); + for (int i = 0; i < possibilities.length; i++) { + // Create a new board to modify and get statement of selected square + ShortTruthTableBoard b = board.copy(); + ShortTruthTableCell cell = b.getCellFromElement(puzzleElement); + ShortTruthTableStatement statement = cell.getStatementReference(); + + // Modify neighboring cells of case-rule application by the provided logical cases + if (possibilities[i][0] != ShortTruthTableCellType.UNKNOWN) { + ShortTruthTableCell leftCell = statement.getLeftStatement().getCell(); + leftCell.setData(possibilities[i][0]); + b.addModifiedData(leftCell); + } + if (possibilities[i][1] != ShortTruthTableCellType.UNKNOWN) { + ShortTruthTableCell rightCell = statement.getRightStatement().getCell(); + rightCell.setData(possibilities[i][1]); + b.addModifiedData(rightCell); + } + + cases.add(b); } + return cases; + } - /** - * Collects a list of boards for each possible outcome of case-rule application - * @param board current board state - * @param puzzleElement case rule operator - * @param possibilities list of possibilities for operator state - * @return ArrayList of Boards - */ - private ArrayList getCasesFromCell(ShortTruthTableBoard board, PuzzleElement puzzleElement, ShortTruthTableCellType[][] possibilities) { - // Create branch case for each possibility - ArrayList cases = new ArrayList<>(); - for (int i = 0; i < possibilities.length; i++) { - // Create a new board to modify and get statement of selected square - ShortTruthTableBoard b = board.copy(); - ShortTruthTableCell cell = b.getCellFromElement(puzzleElement); - ShortTruthTableStatement statement = cell.getStatementReference(); - - // Modify neighboring cells of case-rule application by the provided logical cases - if (possibilities[i][0] != ShortTruthTableCellType.UNKNOWN) { - ShortTruthTableCell leftCell = statement.getLeftStatement().getCell(); - leftCell.setData(possibilities[i][0]); - b.addModifiedData(leftCell); - } - if (possibilities[i][1] != ShortTruthTableCellType.UNKNOWN) { - ShortTruthTableCell rightCell = statement.getRightStatement().getCell(); - rightCell.setData(possibilities[i][1]); - b.addModifiedData(rightCell); - } - - cases.add(b); - } - return cases; - } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be valid - * Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends upon. - * Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = super.dependentElements(board,puzzleElement); - - elements.add(board.getPuzzleElement(puzzleElement)); - - return elements; - } + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = super.dependentElements(board, puzzleElement); + + elements.add(board.getPuzzleElement(puzzleElement)); + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java index aa0da52c3..0549b5f99 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java @@ -1,22 +1,22 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class ContradictionRuleAnd extends ContradictionRule_GenericStatement { - public ContradictionRuleAnd() { - super("STTT-CONT-0001", "Contradicting And", - "An AND statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/And.png", - ShortTruthTableOperation.AND, - new ShortTruthTableCellType[][]{ - {n, T, F}, - {F, T, n}, - // {F, T, F}, - {T, F, T}, - } - ); - } - -} \ No newline at end of file + public ContradictionRuleAnd() { + super( + "STTT-CONT-0001", + "Contradicting And", + "An AND statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/And.png", + ShortTruthTableOperation.AND, + new ShortTruthTableCellType[][] { + {n, T, F}, + {F, T, n}, + // {F, T, F}, + {T, F, T}, + }); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java index 2d1efb945..1c2342557 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java @@ -1,65 +1,58 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.ContradictionRule; - import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableStatement; - -import java.util.Set; import java.util.Iterator; - +import java.util.Set; public class ContradictionRuleAtomic extends ContradictionRule { + public ContradictionRuleAtomic() { + super( + "STTT-CONT-0002", + "Contradicting Variable", + "A single variable can not be both True and False", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Atomic.png"); + } - public ContradictionRuleAtomic() { - super("STTT-CONT-0002", "Contradicting Variable", - "A single variable can not be both True and False", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Atomic.png"); - } - - - @Override - public String checkContradictionAt(Board puzzleBoard, PuzzleElement puzzleElement) { - - //cast the board toa shortTruthTableBoard - ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - - //get the cell that contradicts another cell in the board - ShortTruthTableCell cell = (ShortTruthTableCell) board.getPuzzleElement(puzzleElement); + @Override + public String checkContradictionAt(Board puzzleBoard, PuzzleElement puzzleElement) { - if (!cell.isVariable()) { - System.out.println(" Not Var"); - return "Can not check for contradiction on a non-variable element"; - } + // cast the board toa shortTruthTableBoard + ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - ShortTruthTableCellType cellType = cell.getType(); - if (!cellType.isTrueOrFalse()) { - return "Can only check for a contradiction against a cell that is assigned a value of True or False"; - } + // get the cell that contradicts another cell in the board + ShortTruthTableCell cell = (ShortTruthTableCell) board.getPuzzleElement(puzzleElement); - //get all the cells with the same value - Set varCells = board.getCellsWithSymbol(cell.getSymbol()); - - //check if there are any contradictions - Iterator itr = varCells.iterator(); - while (itr.hasNext()) { - ShortTruthTableCell checkCell = itr.next(); - ShortTruthTableCellType checkCellType = checkCell.getType(); - //if there is an assigned contradiction, return null - if (checkCellType.isTrueOrFalse() && checkCellType != cellType) { - return null; - } - } + if (!cell.isVariable()) { + System.out.println(" Not Var"); + return "Can not check for contradiction on a non-variable element"; + } - //if it made it through the while loop, thene there is no contradiction - return "There is no contradiction for the variable " + cell.getSymbol(); + ShortTruthTableCellType cellType = cell.getType(); + if (!cellType.isTrueOrFalse()) { + return "Can only check for a contradiction against a cell that is assigned a value of True or False"; + } + // get all the cells with the same value + Set varCells = board.getCellsWithSymbol(cell.getSymbol()); + + // check if there are any contradictions + Iterator itr = varCells.iterator(); + while (itr.hasNext()) { + ShortTruthTableCell checkCell = itr.next(); + ShortTruthTableCellType checkCellType = checkCell.getType(); + // if there is an assigned contradiction, return null + if (checkCellType.isTrueOrFalse() && checkCellType != cellType) { + return null; + } } -} \ No newline at end of file + // if it made it through the while loop, thene there is no contradiction + return "There is no contradiction for the variable " + cell.getSymbol(); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java index bf215358a..2be92ffb1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java @@ -1,22 +1,22 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class ContradictionRuleBiconditional extends ContradictionRule_GenericStatement { - public ContradictionRuleBiconditional() { - super("STTT-CONT-0003", "Contradicting Biconditional", - "A Biconditional statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Biconditional.png", - ShortTruthTableOperation.BICONDITIONAL, - new ShortTruthTableCellType[][]{ - {T, T, F}, - {F, T, T}, - {T, F, T}, - {F, F, F} - } - ); - } - -} \ No newline at end of file + public ContradictionRuleBiconditional() { + super( + "STTT-CONT-0003", + "Contradicting Biconditional", + "A Biconditional statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Biconditional.png", + ShortTruthTableOperation.BICONDITIONAL, + new ShortTruthTableCellType[][] { + {T, T, F}, + {F, T, T}, + {T, F, T}, + {F, F, F} + }); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java index caa65afa4..b9ce9b74e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java @@ -1,21 +1,21 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class ContradictionRuleConditional extends ContradictionRule_GenericStatement { - public ContradictionRuleConditional() { - super("STTT-CONT-0004", "Contradicting Conditional", - "A Conditional statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Conditional.png", - ShortTruthTableOperation.CONDITIONAL, - new ShortTruthTableCellType[][]{ - {n, F, T}, - {F, F, n}, - {T, T, F} - } - ); - } - -} \ No newline at end of file + public ContradictionRuleConditional() { + super( + "STTT-CONT-0004", + "Contradicting Conditional", + "A Conditional statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Conditional.png", + ShortTruthTableOperation.CONDITIONAL, + new ShortTruthTableCellType[][] { + {n, F, T}, + {F, F, n}, + {T, T, F} + }); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java index 4be059a06..6c4bb40e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java @@ -1,20 +1,20 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class ContradictionRuleNot extends ContradictionRule_GenericStatement { - public ContradictionRuleNot() { - super("STTT-CONT-0005", "Contradicting Negation", - "A negation and its following statement can not have the same truth value", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Not.png", - ShortTruthTableOperation.NOT, - new ShortTruthTableCellType[][]{ - {n, T, T}, - {n, F, F} - } - ); - } - -} \ No newline at end of file + public ContradictionRuleNot() { + super( + "STTT-CONT-0005", + "Contradicting Negation", + "A negation and its following statement can not have the same truth value", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Not.png", + ShortTruthTableOperation.NOT, + new ShortTruthTableCellType[][] { + {n, T, T}, + {n, F, F} + }); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java index 46fee2a44..85f29ca3f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java @@ -1,21 +1,21 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction; -import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; +import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableOperation; public class ContradictionRuleOr extends ContradictionRule_GenericStatement { - public ContradictionRuleOr() { - super("STTT-CONT-0006", "Contradicting Or", - "An OR statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Or.png", - ShortTruthTableOperation.OR, - new ShortTruthTableCellType[][]{ - {n, F, T}, - {T, F, n}, - {F, T, F} - } - ); - } - -} \ No newline at end of file + public ContradictionRuleOr() { + super( + "STTT-CONT-0006", + "Contradicting Or", + "An OR statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Or.png", + ShortTruthTableOperation.OR, + new ShortTruthTableCellType[][] { + {n, F, T}, + {T, F, n}, + {F, T, F} + }); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java index 4554e5100..95f0f495a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java @@ -1,80 +1,85 @@ package edu.rpi.legup.puzzle.shorttruthtable.rules.contradiction; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.ContradictionRule; - import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableStatement; - public abstract class ContradictionRule_GenericStatement extends ContradictionRule { - private final char operationSymbol; + private final char operationSymbol; - private final ShortTruthTableCellType[][] contradictionPatterns; + private final ShortTruthTableCellType[][] contradictionPatterns; - final static ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; - final static ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; - final static ShortTruthTableCellType n = null; + static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; + static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; + static final ShortTruthTableCellType n = null; - private final String NOT_RIGHT_OPERATOR_ERROR_MESSAGE = "This cell does not contain the correct operation"; - private final String NOT_TRUE_FALSE_ERROR_MESSAGE = "Can only check for a contradiction on a cell that is assigned a value of True or False"; + private final String NOT_RIGHT_OPERATOR_ERROR_MESSAGE = + "This cell does not contain the correct operation"; + private final String NOT_TRUE_FALSE_ERROR_MESSAGE = + "Can only check for a contradiction on a cell that is assigned a value of True or False"; - public ContradictionRule_GenericStatement(String ruleID, String ruleName, String description, String imageName, - char operationSymbol, ShortTruthTableCellType[][] contradictionPatterns) { - super(ruleID, ruleName, description, imageName); - this.operationSymbol = operationSymbol; - this.contradictionPatterns = contradictionPatterns; - } + public ContradictionRule_GenericStatement( + String ruleID, + String ruleName, + String description, + String imageName, + char operationSymbol, + ShortTruthTableCellType[][] contradictionPatterns) { + super(ruleID, ruleName, description, imageName); + this.operationSymbol = operationSymbol; + this.contradictionPatterns = contradictionPatterns; + } - @Override - public String checkContradictionAt(Board puzzleBoard, PuzzleElement operatorPuzzleElement) { + @Override + public String checkContradictionAt(Board puzzleBoard, PuzzleElement operatorPuzzleElement) { - // cast the board to a shortTruthTableBoard - ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; + // cast the board to a shortTruthTableBoard + ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - // get the cell that contradicts another cell in the board - ShortTruthTableCell cell = board.getCellFromElement(operatorPuzzleElement); - ShortTruthTableStatement statement = cell.getStatementReference(); + // get the cell that contradicts another cell in the board + ShortTruthTableCell cell = board.getCellFromElement(operatorPuzzleElement); + ShortTruthTableStatement statement = cell.getStatementReference(); - if (cell.getSymbol() != this.operationSymbol) { - return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_RIGHT_OPERATOR_ERROR_MESSAGE; - } + if (cell.getSymbol() != this.operationSymbol) { + return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_RIGHT_OPERATOR_ERROR_MESSAGE; + } - // check that the initial statement is assigned - ShortTruthTableCellType cellType = cell.getType(); + // check that the initial statement is assigned + ShortTruthTableCellType cellType = cell.getType(); - if (!cellType.isTrueOrFalse()) { - return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_TRUE_FALSE_ERROR_MESSAGE; - } + if (!cellType.isTrueOrFalse()) { + return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_TRUE_FALSE_ERROR_MESSAGE; + } - // get the pattern for this sub-statement - ShortTruthTableCellType[] testPattern = statement.getCellTypePattern(); - - // if the board pattern matches any contradiction pattern, it is a valid contradiction - for (ShortTruthTableCellType[] pattern : contradictionPatterns) { - boolean matches = true; - for (int i = 0; i < 3; i++) { - // ull means that part does not affect the statement - if (pattern[i] == null) { - continue; - } - //if it is not null, it must match the test pattern - if (pattern[i] != testPattern[i]) { - matches = false; - break; - } - } - // if testPattern matches one of the valid contradiction patterns, the contradiction is correct - if (matches) { - return null; - } - } + // get the pattern for this sub-statement + ShortTruthTableCellType[] testPattern = statement.getCellTypePattern(); - return super.getNoContradictionMessage(); + // if the board pattern matches any contradiction pattern, it is a valid contradiction + for (ShortTruthTableCellType[] pattern : contradictionPatterns) { + boolean matches = true; + for (int i = 0; i < 3; i++) { + // ull means that part does not affect the statement + if (pattern[i] == null) { + continue; + } + // if it is not null, it must match the test pattern + if (pattern[i] != testPattern[i]) { + matches = false; + break; + } + } + // if testPattern matches one of the valid contradiction patterns, the contradiction is + // correct + if (matches) { + return null; + } } -} \ No newline at end of file + + return super.getNoContradictionMessage(); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java index f87462978..4dd2781e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java @@ -7,82 +7,78 @@ public class Skyscrapers extends Puzzle { - public Skyscrapers() { - super(); + public Skyscrapers() { + super(); - this.name = "Skyscrapers"; + this.name = "Skyscrapers"; - this.importer = new SkyscrapersImporter(this); - this.exporter = new SkyscrapersExporter(this); + this.importer = new SkyscrapersImporter(this); + this.exporter = new SkyscrapersExporter(this); - this.factory = new SkyscrapersCellFactory(); - } + this.factory = new SkyscrapersCellFactory(); + } - /** - * Initializes the game board. Called by the invoker of the class - */ - @Override - public void initializeView() { - boardView = new SkyscrapersView((SkyscrapersBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new SkyscrapersView((SkyscrapersBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Skyscrapers - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Skyscrapers, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows >= 4 && rows == columns; - } + @Override + /** + * Determines if the given dimensions are valid for Skyscrapers + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Skyscrapers, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows >= 4 && rows == columns; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - SkyscrapersBoard SkyscraperBoard = (SkyscrapersBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + SkyscrapersBoard SkyscraperBoard = (SkyscrapersBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(SkyscraperBoard) == null) { - System.out.println(rule.getRuleName()); - return false; - } - } - for (PuzzleElement data : SkyscraperBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) data; - if (cell.getType() == SkyscrapersType.UNKNOWN) { - return false; - } - } - return true; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(SkyscraperBoard) == null) { + System.out.println(rule.getRuleName()); + return false; + } } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { - + for (PuzzleElement data : SkyscraperBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) data; + if (cell.getType() == SkyscrapersType.UNKNOWN) { + return false; + } } + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java index 65f5eb561..7bc754cb4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java @@ -3,7 +3,6 @@ import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.*; import java.awt.event.MouseEvent; import java.util.ArrayList; @@ -11,281 +10,264 @@ public class SkyscrapersBoard extends GridBoard { - - private ArrayList eastClues; - //EAST clues - private ArrayList southClues; - //SOUTH clues - private ArrayList westClues; - //WEST clues - private ArrayList northClues; - //NORTH clues - - private boolean viewFlag = false; - private boolean dupeFlag = false; - - public SkyscrapersBoard(int size) { - super(size, size); - - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - this.northClues = new ArrayList<>(); - - for (int i = 0; i < size; i++) { - eastClues.add(null); - southClues.add(null); - westClues.add(null); - northClues.add(null); - } + private ArrayList eastClues; + // EAST clues + private ArrayList southClues; + // SOUTH clues + private ArrayList westClues; + // WEST clues + private ArrayList northClues; + // NORTH clues + + private boolean viewFlag = false; + private boolean dupeFlag = false; + + public SkyscrapersBoard(int size) { + super(size, size); + + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + this.northClues = new ArrayList<>(); + + for (int i = 0; i < size; i++) { + eastClues.add(null); + southClues.add(null); + westClues.add(null); + northClues.add(null); } - - - /** - * @return eastClues a list of the eastern clues ordered from loc.y = 0 to max - */ - public ArrayList getEastClues() { - return eastClues; + } + + /** + * @return eastClues a list of the eastern clues ordered from loc.y = 0 to max + */ + public ArrayList getEastClues() { + return eastClues; + } + + /** + * @return southClues a list of the southern clues ordered from loc.x = 0 to max + */ + public ArrayList getSouthClues() { + return southClues; + } + + /** + * @return westClues a list of the western clues ordered from loc.y = 0 to max + */ + public ArrayList getWestClues() { + return westClues; + } + + /** + * @return northClues a list of the northern clues ordered from loc.x = 0 to max + */ + public ArrayList getNorthClues() { + return northClues; + } + + public boolean getDupeFlag() { + return dupeFlag; + } + + public boolean getViewFlag() { + return viewFlag; + } + + public void setDupeFlag(boolean newFlag) { + dupeFlag = newFlag; + } + + public void setViewFlag(boolean newFlag) { + viewFlag = newFlag; + } + + @Override + public SkyscrapersCell getCell(int x, int y) { + return (SkyscrapersCell) super.getCell(x, y); + } + + public int getSize() { + return this.getWidth(); + } + + @Override + public PuzzleElement getPuzzleElement(PuzzleElement element) { + // If the element index is -2, it is a clue and should be returned separately + if (element.getIndex() == -2) { + return element; } - - /** - * @return southClues a list of the southern clues ordered from loc.x = 0 to max - */ - public ArrayList getSouthClues() { - return southClues; + return super.getPuzzleElement(element); + } + + /** + * Gets the cells of a certain type directly adjacent to a given cell + * + * @param cell at the center, + * @param type of cell to collect + * @return list of cells of the given type + */ + public List getAdjacent(SkyscrapersCell cell, SkyscrapersType type) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + SkyscrapersCell up = getCell(loc.x, loc.y - 1); + SkyscrapersCell right = getCell(loc.x + 1, loc.y); + SkyscrapersCell down = getCell(loc.x, loc.y + 1); + SkyscrapersCell left = getCell(loc.x - 1, loc.y); + if (up != null && (up.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(up); } - - /** - * @return westClues a list of the western clues ordered from loc.y = 0 to max - */ - public ArrayList getWestClues() { - return westClues; + if (right != null && (right.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(right); } - - /** - * @return northClues a list of the northern clues ordered from loc.x = 0 to max - */ - public ArrayList getNorthClues() { - return northClues; + if (down != null && (down.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(down); } - - public boolean getDupeFlag() { - return dupeFlag; + if (left != null && (left.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(left); } - - public boolean getViewFlag() { - return viewFlag; + return adj; + } + + /** + * Gets the cells of a certain type directly diagonal to a given cell + * + * @param cell at the center, + * @param type of cell to collect + * @return list of cells of the given type + */ + public List getDiagonals(SkyscrapersCell cell, SkyscrapersType type) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + SkyscrapersCell upRight = getCell(loc.x + 1, loc.y - 1); + SkyscrapersCell downRight = getCell(loc.x + 1, loc.y + 1); + SkyscrapersCell downLeft = getCell(loc.x - 1, loc.y + 1); + SkyscrapersCell upLeft = getCell(loc.x - 1, loc.y - 1); + if (upRight != null && (upRight.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(upRight); } - - public void setDupeFlag(boolean newFlag) { - dupeFlag = newFlag; + if (downLeft != null && (downLeft.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(downLeft); } - - public void setViewFlag(boolean newFlag) { - viewFlag = newFlag; + if (downRight != null && (downRight.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(downRight); } - - @Override - public SkyscrapersCell getCell(int x, int y) { - return (SkyscrapersCell) super.getCell(x, y); + if (upLeft != null && (upLeft.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(upLeft); } - - public int getSize() { - return this.getWidth(); + return dia; + } + + /** + * Gets the cells of a certain type in a given row/column + * + * @param index: y pos of row or x pos of col, + * @param type of cell to collect, + * @param isRow true if row, false if col + * @return list of cells of the given type, ordered west to east or north to south + */ + public List getRowCol(int index, SkyscrapersType type, boolean isRow) { + List list = new ArrayList<>(); + for (int i = 0; i < dimension.height; i++) { + SkyscrapersCell cell; + if (isRow) { + cell = getCell(i, index); + } else { + cell = getCell(index, i); + } + + if (cell.getType() == type || type == SkyscrapersType.ANY) { + list.add(cell); + } } - - @Override - public PuzzleElement getPuzzleElement(PuzzleElement element) { - // If the element index is -2, it is a clue and should be returned separately - if (element.getIndex() == -2) { - return element; + return list; + } + + /** Prints a semblance of the board to console (helps in debugging) */ + public void printBoard() { + for (int i = 0; i < this.dimension.height; i++) { + for (SkyscrapersCell cell : this.getRowCol(i, SkyscrapersType.ANY, true)) { + if (cell.getType() == SkyscrapersType.Number) { + System.out.print(cell.getData() + " "); + } else { + System.out.print(0 + " "); } - return super.getPuzzleElement(element); + } + System.out.println(); } - - - /** - * Gets the cells of a certain type directly adjacent to a given cell - * - * @param cell at the center, - * @param type of cell to collect - * @return list of cells of the given type - */ - public List getAdjacent(SkyscrapersCell cell, SkyscrapersType type) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - SkyscrapersCell up = getCell(loc.x, loc.y - 1); - SkyscrapersCell right = getCell(loc.x + 1, loc.y); - SkyscrapersCell down = getCell(loc.x, loc.y + 1); - SkyscrapersCell left = getCell(loc.x - 1, loc.y); - if (up != null && (up.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(up); - } - if (right != null && (right.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(right); + } + + /** + * @param x position of cell + * @param y position of cell + * @param e Element to be placed (null if nothing selected) + * @param m MouseEvent Increases clue values if in editor mode. Currently allows for presetting + * tile values, though they will not be saved. + */ + @Override + public void setCell(int x, int y, Element e, MouseEvent m) { + SkyscrapersClue clue = this.getClue(x, y); + if (e == null) return; + if (clue != null) { + if (!e.getElementID().equals("SKYS-UNPL-0003")) { + return; + } + + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.height) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); } - if (down != null && (down.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(down); + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.height); } - if (left != null && (left.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(left); - } - return adj; + } + } else { + super.setCell(x - 1, y - 1, e, m); } - - /** - * Gets the cells of a certain type directly diagonal to a given cell - * - * @param cell at the center, - * @param type of cell to collect - * @return list of cells of the given type - */ - public List getDiagonals(SkyscrapersCell cell, SkyscrapersType type) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - SkyscrapersCell upRight = getCell(loc.x + 1, loc.y - 1); - SkyscrapersCell downRight = getCell(loc.x + 1, loc.y + 1); - SkyscrapersCell downLeft = getCell(loc.x - 1, loc.y + 1); - SkyscrapersCell upLeft = getCell(loc.x - 1, loc.y - 1); - if (upRight != null && (upRight.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(upRight); - } - if (downLeft != null && (downLeft.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(downLeft); - } - if (downRight != null && (downRight.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(downRight); - } - if (upLeft != null && (upLeft.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(upLeft); - } - return dia; - } - - /** - * Gets the cells of a certain type in a given row/column - * - * @param index: y pos of row or x pos of col, - * @param type of cell to collect, - * @param isRow true if row, false if col - * @return list of cells of the given type, ordered west to east or north to south - */ - public List getRowCol(int index, SkyscrapersType type, boolean isRow) { - List list = new ArrayList<>(); - for (int i = 0; i < dimension.height; i++) { - SkyscrapersCell cell; - if (isRow) { - cell = getCell(i, index); - } - else { - cell = getCell(index, i); - } - - if (cell.getType() == type || type == SkyscrapersType.ANY) { - list.add(cell); - } - } - return list; - } - - /** - * Prints a semblance of the board to console (helps in debugging) - */ - public void printBoard() { - for (int i = 0; i < this.dimension.height; i++) { - for (SkyscrapersCell cell : this.getRowCol(i, SkyscrapersType.ANY, true)) { - if (cell.getType() == SkyscrapersType.Number) { - System.out.print(cell.getData() + " "); - } - else { - System.out.print(0 + " "); - } - } - System.out.println(); - } - } - - /** - * - * @param x position of cell - * @param y position of cell - * @param e Element to be placed (null if nothing selected) - * @param m MouseEvent - * Increases clue values if in editor mode. Currently allows for - * presetting tile values, though they will not be saved. - */ - @Override - public void setCell(int x, int y, Element e, MouseEvent m) { - SkyscrapersClue clue = this.getClue(x, y); - if (e == null) return; - if (clue != null) { - if (!e.getElementID().equals("SKYS-UNPL-0003")) { - return; - } - - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.height) { - clue.setData(clue.getData() + 1); - } - else { - clue.setData(0); - } - } - else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } - else { - clue.setData(dimension.height); - } - } - } - else { - super.setCell(x - 1, y - 1, e, m); - } + } + + /** + * @param x position of element on boardView + * @param y position of element on boardView + * @return The clue at the given position + */ + public SkyscrapersClue getClue(int x, int y) { + int viewIndex = getSize() + 1; + if (x == 0 && y > 0 && y < viewIndex) { + return westClues.get(y - 1); + } else if (x == viewIndex && y > 0 && y < viewIndex) { + return eastClues.get(y - 1); + } else if (y == 0 && x > 0 && x < viewIndex) { + return northClues.get(x - 1); + } else if (y == viewIndex && x > 0 && x < viewIndex) { + return southClues.get(x - 1); } - - /** - * - * @param x position of element on boardView - * @param y position of element on boardView - * @return The clue at the given position - */ - public SkyscrapersClue getClue(int x, int y) { - int viewIndex = getSize() + 1; - if (x == 0 && y > 0 && y < viewIndex) { - return westClues.get(y-1); - } - else if (x == viewIndex && y > 0 && y < viewIndex) { - return eastClues.get(y-1); - } - else if (y == 0 && x > 0 && x < viewIndex) { - return northClues.get(x-1); - } - else if (y == viewIndex && x > 0 && x < viewIndex) { - return southClues.get(x-1); - } - return null; + return null; + } + + @Override + public SkyscrapersBoard copy() { + SkyscrapersBoard copy = new SkyscrapersBoard(dimension.width); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } - - @Override - public SkyscrapersBoard copy() { - SkyscrapersBoard copy = new SkyscrapersBoard(dimension.width); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.eastClues = eastClues; - copy.southClues = southClues; - copy.westClues = westClues; - copy.northClues = northClues; - - copy.dupeFlag = dupeFlag; - copy.viewFlag = viewFlag; - return copy; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + copy.eastClues = eastClues; + copy.southClues = southClues; + copy.westClues = westClues; + copy.northClues = northClues; + + copy.dupeFlag = dupeFlag; + copy.viewFlag = viewFlag; + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java index 409555b83..a315ac788 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java @@ -1,70 +1,66 @@ package edu.rpi.legup.puzzle.skyscrapers; +import static edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType.convertToSkyType; + import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.GridCell; - import java.awt.*; import java.awt.event.MouseEvent; -import static edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType.convertToSkyType; - public class SkyscrapersCell extends GridCell { - private int max; + private int max; - public SkyscrapersCell(Integer value, Point location, int size) { - super(value, location); - this.max = size; - } + public SkyscrapersCell(Integer value, Point location, int size) { + super(value, location); + this.max = size; + } - public SkyscrapersType getType() { - switch (convertToSkyType(data)){ - case UNKNOWN: - return SkyscrapersType.UNKNOWN; - default: - return SkyscrapersType.Number; - } + public SkyscrapersType getType() { + switch (convertToSkyType(data)) { + case UNKNOWN: + return SkyscrapersType.UNKNOWN; + default: + return SkyscrapersType.Number; } + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()){ - case "SKYS-UNPL-0001": - this.data = 0; - break; - case "SKYS-UNPL-0002": - switch (m.getButton()){ - case MouseEvent.BUTTON1: - if (this.data <= 0 || this.data >= this.max) { - this.data = 1; - } - else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 1) { - this.data = this.data - 1; - } - else { - this.data = this.max; - } - break; - } - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "SKYS-UNPL-0001": + this.data = 0; + break; + case "SKYS-UNPL-0002": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data <= 0 || this.data >= this.max) { + this.data = 1; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 1) { + this.data = this.data - 1; + } else { + this.data = this.max; + } + break; } + break; } + } + public int getMax() { + return max; + } - public int getMax() { - return max; - } - - @Override - public SkyscrapersCell copy() { - SkyscrapersCell copy = new SkyscrapersCell(data, (Point) location.clone(), max); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public SkyscrapersCell copy() { + SkyscrapersCell copy = new SkyscrapersCell(data, (Point) location.clone(), max); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java index 5f6de7369..1f10b31d3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java @@ -4,72 +4,71 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class SkyscrapersCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if input is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Skyscrapers Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if input is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: unknown puzzleElement puzzleElement"); + } - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - int size = skyscrapersBoard.getSize(); - NamedNodeMap attributeList = node.getAttributes(); + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + int size = skyscrapersBoard.getSize(); + NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= size || y >= size) { - throw new InvalidFileFormatException("Skyscrapers Factory: cell location out of bounds"); - } - if (value < 0 || value > size) { - throw new InvalidFileFormatException("Skyscrapers Factory: cell unknown value"); - } + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= size || y >= size) { + throw new InvalidFileFormatException("Skyscrapers Factory: cell location out of bounds"); + } + if (value < 0 || value > size) { + throw new InvalidFileFormatException("Skyscrapers Factory: cell unknown value"); + } - SkyscrapersCell cell = new SkyscrapersCell(value, new Point(x, y), size); - cell.setIndex(y * size + x); + SkyscrapersCell cell = new SkyscrapersCell(value, new Point(x, y), size); + cell.setIndex(y * size + x); - return cell; - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Skyscrapers Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("Skyscrapers Factory: could not find attribute(s)"); - } + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Skyscrapers Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java index 1e7b1b45e..dd2bc5412 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java @@ -3,53 +3,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class SkyscrapersClue extends PuzzleElement { - private SkyscrapersType type; - private int clueIndex; - - public SkyscrapersClue(int value, int clueIndex, SkyscrapersType type) { - super(value); - this.index = -2; - this.clueIndex = clueIndex;//index in list - this.type = type; - this.setModifiable(false); + private SkyscrapersType type; + private int clueIndex; + + public SkyscrapersClue(int value, int clueIndex, SkyscrapersType type) { + super(value); + this.index = -2; + this.clueIndex = clueIndex; // index in list + this.type = type; + this.setModifiable(false); + } + + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; } - - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; - } - return sb.reverse().toString(); - } - - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; - } - return result; - } - - public int getClueIndex() { - return clueIndex; - } - - public SkyscrapersType getType() { - return type; - } - - public void setType(SkyscrapersType type) { - this.type = type; - } - - public SkyscrapersClue copy() { - SkyscrapersClue copy = new SkyscrapersClue(data, clueIndex, type); - copy.setIndex(index); - copy.setModifiable(isModifiable); - return copy; + return sb.reverse().toString(); + } + + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; } + return result; + } + + public int getClueIndex() { + return clueIndex; + } + + public SkyscrapersType getType() { + return type; + } + + public void setType(SkyscrapersType type) { + this.type = type; + } + + public SkyscrapersClue copy() { + SkyscrapersClue copy = new SkyscrapersClue(data, clueIndex, type); + copy.setIndex(index); + copy.setModifiable(isModifiable); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java index 649f85f4e..bd9abc162 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java @@ -1,60 +1,59 @@ package edu.rpi.legup.puzzle.skyscrapers; import edu.rpi.legup.ui.boardview.ElementView; - import java.awt.*; public class SkyscrapersClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public SkyscrapersClueView(SkyscrapersClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public SkyscrapersClue getPuzzleElement() { - return (SkyscrapersClue) super.getPuzzleElement(); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public SkyscrapersClueView(SkyscrapersClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public SkyscrapersClue getPuzzleElement() { + return (SkyscrapersClue) super.getPuzzleElement(); + } + + @Override + public void draw(Graphics2D graphics2D) { + drawElement(graphics2D); + if (this.isShowCasePicker() && this.isCaseRulePickable()) { + drawCase(graphics2D); + if (this.isHover()) { + drawHover(graphics2D); + } } - - @Override - public void draw(Graphics2D graphics2D) { - drawElement(graphics2D); - if (this.isShowCasePicker() && this.isCaseRulePickable()) { - drawCase(graphics2D); - if (this.isHover()) { - drawHover(graphics2D); - } - } + } + + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + SkyscrapersClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + case CLUE_EAST: + case CLUE_SOUTH: + case CLUE_WEST: + value = String.valueOf(clue.getData()); + break; + default: + value = ""; } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - SkyscrapersClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - case CLUE_EAST: - case CLUE_SOUTH: - case CLUE_WEST: - value = String.valueOf(clue.getData()); - break; - default: - value = ""; - } - - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java index 8e338a351..e0503382e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java @@ -2,37 +2,33 @@ import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.event.MouseEvent; public class SkyscrapersController extends ElementController { - public SkyscrapersController() { - super(); - } + public SkyscrapersController() { + super(); + } - @Override - public void changeCell(MouseEvent e, PuzzleElement element) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (e.getButton() == MouseEvent.BUTTON1) { - if (cell.getData() < cell.getMax()) { - int num = cell.getData() + 1; - cell.setData(num); - } - else { - cell.setData(SkyscrapersType.UNKNOWN.toValue()); - } - } - else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() > 0) { - int num = cell.getData() - 1; - cell.setData(num); - } - else { - cell.setData(cell.getMax()); - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement element) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (e.getButton() == MouseEvent.BUTTON1) { + if (cell.getData() < cell.getMax()) { + int num = cell.getData() + 1; + cell.setData(num); + } else { + cell.setData(SkyscrapersType.UNKNOWN.toValue()); + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() > 0) { + int num = cell.getData() - 1; + cell.setData(num); + } else { + cell.setData(cell.getMax()); } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java index 9884b4a3c..397ab5a93 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java @@ -1,37 +1,36 @@ package edu.rpi.legup.puzzle.skyscrapers; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; public class SkyscrapersElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = new Color(0x212121); - private static final Color BORDER_COLOR = new Color(0x424242); - private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = new Color(0x212121); + private static final Color BORDER_COLOR = new Color(0x424242); + private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); - public SkyscrapersElementView(SkyscrapersCell cell) { - super(cell); - } + public SkyscrapersElementView(SkyscrapersCell cell) { + super(cell); + } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BACKGROUND_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BORDER_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BACKGROUND_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BORDER_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - int val = cell.getData(); - if (val != 0) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(val); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + int val = cell.getData(); + if (val != 0) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(val); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java index f784fb2d9..5d85d950e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java @@ -6,58 +6,58 @@ public class SkyscrapersExporter extends PuzzleExporter { - public SkyscrapersExporter(Skyscrapers skyscrapers) { - super(skyscrapers); + public SkyscrapersExporter(Skyscrapers skyscrapers) { + super(skyscrapers); + } + + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + SkyscrapersBoard board; + if (puzzle.getTree() != null) { + board = (SkyscrapersBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (SkyscrapersBoard) puzzle.getBoardView().getBoard(); } - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - SkyscrapersBoard board; - if (puzzle.getTree() != null) { - board = (SkyscrapersBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (SkyscrapersBoard) puzzle.getBoardView().getBoard(); - } - - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("size", String.valueOf(board.getWidth())); - - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - if (cell.getData() != 0) { - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); - - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (int i=0; i northClues; - private ArrayList eastClues; - private ArrayList southClues; - private ArrayList westClues; - - public SkyscrapersView(SkyscrapersBoard board) { - super(new BoardController(), new SkyscrapersController(), board.getDimension()); - - this.northClues = new ArrayList<>(); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); - SkyscrapersElementView elementView = new SkyscrapersElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); - elementViews.add(elementView); - } + private static final Logger LOGGER = LogManager.getLogger(SkyscrapersView.class.getName()); + + private ArrayList northClues; + private ArrayList eastClues; + private ArrayList southClues; + private ArrayList westClues; + + public SkyscrapersView(SkyscrapersBoard board) { + super(new BoardController(), new SkyscrapersController(), board.getDimension()); + + this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); + SkyscrapersElementView elementView = new SkyscrapersElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); + elementViews.add(elementView); + } - for (int i = 0; i < gridSize.height; i++) { - SkyscrapersClueView row = new SkyscrapersClueView(board.getWestClues().get(i)); - row.setLocation(new Point(0, (i + 1) * elementSize.height)); - row.setSize(elementSize); + for (int i = 0; i < gridSize.height; i++) { + SkyscrapersClueView row = new SkyscrapersClueView(board.getWestClues().get(i)); + row.setLocation(new Point(0, (i + 1) * elementSize.height)); + row.setSize(elementSize); - SkyscrapersClueView clue = new SkyscrapersClueView(board.getEastClues().get(i)); - clue.setLocation(new Point((gridSize.height + 1) * elementSize.height, (i + 1) * elementSize.height)); - clue.setSize(elementSize); + SkyscrapersClueView clue = new SkyscrapersClueView(board.getEastClues().get(i)); + clue.setLocation( + new Point((gridSize.height + 1) * elementSize.height, (i + 1) * elementSize.height)); + clue.setSize(elementSize); - westClues.add(row); - eastClues.add(clue); - } + westClues.add(row); + eastClues.add(clue); + } - for (int i = 0; i < gridSize.width; i++) { - SkyscrapersClueView col = new SkyscrapersClueView(board.getNorthClues().get(i)); - col.setLocation(new Point((i + 1) * elementSize.width, 0)); - col.setSize(elementSize); + for (int i = 0; i < gridSize.width; i++) { + SkyscrapersClueView col = new SkyscrapersClueView(board.getNorthClues().get(i)); + col.setLocation(new Point((i + 1) * elementSize.width, 0)); + col.setSize(elementSize); - SkyscrapersClueView clue = new SkyscrapersClueView(board.getSouthClues().get(i)); - clue.setLocation(new Point((i + 1) * elementSize.width, (gridSize.width + 1) * elementSize.width)); - clue.setSize(elementSize); + SkyscrapersClueView clue = new SkyscrapersClueView(board.getSouthClues().get(i)); + clue.setLocation( + new Point((i + 1) * elementSize.width, (gridSize.width + 1) * elementSize.width)); + clue.setSize(elementSize); - northClues.add(col); - southClues.add(clue); - } + northClues.add(col); + southClues.add(clue); } - - /** - * Gets the ElementView from the location specified or - * null if one does not exists at that location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - @Override - public ElementView getElement(Point point) { - Point scaledPoint = new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - for (SkyscrapersClueView clueView : northClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : eastClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : southClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : westClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - return null; - } - - public ArrayList getNorthClues() { - return northClues; - } - - public ArrayList getWestClues() { - return westClues; - } - - @Override - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = (gridSize.width + 2) * elementSize.width; - boardViewSize.height = (gridSize.height + 2) * elementSize.height; - return boardViewSize; - } - - /** - * Sets the board associated with this view - * - * @param board board - */ - @Override - public void setBoard(Board board) { - if (this.board != board) { - this.board = board; - - if (board instanceof CaseBoard) { - setCasePickable(); - } - else { - for (ElementView elementView : elementViews) { - elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); - elementView.setShowCasePicker(false); - } - for (SkyscrapersClueView clueView : northClues) { - clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); - clueView.setShowCasePicker(false); - } - for (SkyscrapersClueView clueView : westClues) { - clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); - clueView.setShowCasePicker(false); - } - } - } + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + @Override + public ElementView getElement(Point point) { + Point scaledPoint = + new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } } - - @Override - protected void setCasePickable() { - CaseBoard caseBoard = (CaseBoard) board; - Board baseBoard = caseBoard.getBaseBoard(); - + for (SkyscrapersClueView clueView : northClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : eastClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : southClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : westClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + return null; + } + + public ArrayList getNorthClues() { + return northClues; + } + + public ArrayList getWestClues() { + return westClues; + } + + @Override + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = (gridSize.width + 2) * elementSize.width; + boardViewSize.height = (gridSize.height + 2) * elementSize.height; + return boardViewSize; + } + + /** + * Sets the board associated with this view + * + * @param board board + */ + @Override + public void setBoard(Board board) { + if (this.board != board) { + this.board = board; + + if (board instanceof CaseBoard) { + setCasePickable(); + } else { for (ElementView elementView : elementViews) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); - elementView.setPuzzleElement(puzzleElement); - elementView.setShowCasePicker(true); - elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); + elementView.setShowCasePicker(false); } for (SkyscrapersClueView clueView : northClues) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); - clueView.setPuzzleElement(puzzleElement); - clueView.setShowCasePicker(true); - clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); + clueView.setShowCasePicker(false); } for (SkyscrapersClueView clueView : westClues) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); - clueView.setPuzzleElement(puzzleElement); - clueView.setShowCasePicker(true); - clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); + clueView.setShowCasePicker(false); } + } + } + } + + @Override + protected void setCasePickable() { + CaseBoard caseBoard = (CaseBoard) board; + Board baseBoard = caseBoard.getBaseBoard(); + + for (ElementView elementView : elementViews) { + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); + elementView.setPuzzleElement(puzzleElement); + elementView.setShowCasePicker(true); + elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + for (SkyscrapersClueView clueView : northClues) { + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); + clueView.setPuzzleElement(puzzleElement); + clueView.setShowCasePicker(true); + clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + for (SkyscrapersClueView clueView : westClues) { + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); + clueView.setPuzzleElement(puzzleElement); + clueView.setShowCasePicker(true); + clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); } + } - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); - for (SkyscrapersClueView clueView : northClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : northClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : eastClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : eastClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : southClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : southClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : westClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : westClues) { + clueView.draw(graphics2D); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java index 8505de523..e66e67f1c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java @@ -4,7 +4,11 @@ public class ClueTile extends NonPlaceableElement { - public ClueTile() { - super("SKYS-UNPL-0003", "Clue Tile", "Clue Updater", "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); - } + public ClueTile() { + super( + "SKYS-UNPL-0003", + "Clue Tile", + "Clue Updater", + "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java index 8f78fb1cf..6df519c96 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - public NumberTile() { - super("SKYS-UNPL-0002", "Number Tile", "A numbered tile", "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); - } + public NumberTile() { + super( + "SKYS-UNPL-0002", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java index 3559dc332..ee25f38c0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super("SKYS-UNPL-0001", "Unknown", "A blank tile", "edu/rpi/legup/images/skyscrapers/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "SKYS-UNPL-0001", + "Unknown", + "A blank tile", + "edu/rpi/legup/images/skyscrapers/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java index 01527294a..0889b0c25 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java @@ -6,169 +6,190 @@ import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.*; -import org.apache.commons.lang3.ObjectUtils; - -import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; -import java.util.Set; -import java.util.TreeSet; +import javax.swing.*; public class CellForNumberCaseRule extends CaseRule { - public CellForNumberCaseRule() { - super("SKYS-CASE-0002", "Cell For Number", - "A number (1-n) must appear in any given row/column", - "edu/rpi/legup/images/skyscrapers/cases/CellForNumber.png"); + public CellForNumberCaseRule() { + super( + "SKYS-CASE-0002", + "Cell For Number", + "A number (1-n) must appear in any given row/column", + "edu/rpi/legup/images/skyscrapers/cases/CellForNumber.png"); + } + + private Integer selectedNumber; + + @Override + public CaseBoard getCaseBoard(Board board) { + SkyscrapersBoard currentBoard = (SkyscrapersBoard) board.copy(); + currentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(currentBoard, this); + for (SkyscrapersClue data : currentBoard.getWestClues()) { + // System.out.println(data.getType()); + caseBoard.addPickableElement(data); } - - private Integer selectedNumber; - - @Override - public CaseBoard getCaseBoard(Board board) { - SkyscrapersBoard currentBoard = (SkyscrapersBoard) board.copy(); - currentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(currentBoard, this); - for (SkyscrapersClue data : currentBoard.getWestClues()) { - //System.out.println(data.getType()); - caseBoard.addPickableElement(data); - } - for (SkyscrapersClue data : currentBoard.getNorthClues()) { - //System.out.println(data.getType()); - caseBoard.addPickableElement(data); - } - - //selects integer before checking Command.canExecute for use in Command.getErrorString - int size = ((SkyscrapersBoard) board).getWidth(); - Object[] possibleValues = new Object[size]; - for (int i = 0; i < size; i++) { - possibleValues[i] = i + 1; - } - Object selectedValue; - do { - selectedValue = JOptionPane.showInputDialog(null, - "Pick the number to be added", "Cell For Number", - JOptionPane.INFORMATION_MESSAGE, null, - possibleValues, possibleValues[0]); - } - while (selectedValue == null); - selectedNumber = (Integer) selectedValue; - - return caseBoard; + for (SkyscrapersClue data : currentBoard.getNorthClues()) { + // System.out.println(data.getType()); + caseBoard.addPickableElement(data); } - public ArrayList getCasesFor(Board board, PuzzleElement puzzleElement, Integer number) { - ArrayList cases = new ArrayList<>(); - - SkyscrapersClue clue = (SkyscrapersClue) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - - List openCells = skyscrapersboard.getRowCol(clue.getClueIndex(), SkyscrapersType.UNKNOWN, clue.getType() == SkyscrapersType.CLUE_WEST); - for (SkyscrapersCell cell : openCells) { - SkyscrapersBoard newCase = skyscrapersboard.copy(); - PuzzleElement newCell = newCase.getPuzzleElement(cell); - newCell.setData(number); - newCase.addModifiedData(newCell); - - //if flags - boolean passed = true; - if (skyscrapersboard.getDupeFlag()) { - DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); - passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; - } - if (skyscrapersboard.getViewFlag()) { - PreemptiveVisibilityContradictionRule ViewRule = new PreemptiveVisibilityContradictionRule(); - passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; - } - if (passed) { - cases.add(newCase); - } - - - } - return cases; + // selects integer before checking Command.canExecute for use in Command.getErrorString + int size = ((SkyscrapersBoard) board).getWidth(); + Object[] possibleValues = new Object[size]; + for (int i = 0; i < size; i++) { + possibleValues[i] = i + 1; } - - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - return getCasesFor(board, puzzleElement, selectedNumber); + Object selectedValue; + do { + selectedValue = + JOptionPane.showInputDialog( + null, + "Pick the number to be added", + "Cell For Number", + JOptionPane.INFORMATION_MESSAGE, + null, + possibleValues, + possibleValues[0]); + } while (selectedValue == null); + selectedNumber = (Integer) selectedValue; + + return caseBoard; + } + + public ArrayList getCasesFor(Board board, PuzzleElement puzzleElement, Integer number) { + ArrayList cases = new ArrayList<>(); + + SkyscrapersClue clue = (SkyscrapersClue) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + + List openCells = + skyscrapersboard.getRowCol( + clue.getClueIndex(), + SkyscrapersType.UNKNOWN, + clue.getType() == SkyscrapersType.CLUE_WEST); + for (SkyscrapersCell cell : openCells) { + SkyscrapersBoard newCase = skyscrapersboard.copy(); + PuzzleElement newCell = newCase.getPuzzleElement(cell); + newCell.setData(number); + newCase.addModifiedData(newCell); + + // if flags + boolean passed = true; + if (skyscrapersboard.getDupeFlag()) { + DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); + passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; + } + if (skyscrapersboard.getViewFlag()) { + PreemptiveVisibilityContradictionRule ViewRule = + new PreemptiveVisibilityContradictionRule(); + passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; + } + if (passed) { + cases.add(newCase); + } } - - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - SkyscrapersBoard oldBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - if (childTransitions.size() == 0) { - return "This case rule must have at least one child."; - } - - if (childTransitions.size() != getCasesFor(oldBoard, oldBoard.getPuzzleElement(transition.getSelection()), (Integer) childTransitions.get(0).getBoard().getModifiedData().iterator().next().getData()).size()) { - //System.out.println("Wrong number of cases."); - return "Wrong number of cases."; - } - - for (TreeTransition newTree : childTransitions) { - SkyscrapersBoard newBoard = (SkyscrapersBoard) newTree.getBoard(); - if (newBoard.getModifiedData().size() != 1) { - //System.out.println("Only one cell should be modified."); - return "Only one cell should be modified."; - } - SkyscrapersCell newCell = (SkyscrapersCell) newBoard.getModifiedData().iterator().next(); - if (newCell.getType() != SkyscrapersType.Number) { - //System.out.println("Changed value should be a number."); - return "Changed value should be a number."; - } - } - return null; + return cases; + } + + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + return getCasesFor(board, puzzleElement, selectedNumber); + } + + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + SkyscrapersBoard oldBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + if (childTransitions.size() == 0) { + return "This case rule must have at least one child."; } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + if (childTransitions.size() + != getCasesFor( + oldBoard, + oldBoard.getPuzzleElement(transition.getSelection()), + (Integer) + childTransitions + .get(0) + .getBoard() + .getModifiedData() + .iterator() + .next() + .getData()) + .size()) { + // System.out.println("Wrong number of cases."); + return "Wrong number of cases."; } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be valid - * Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends upon. - * Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; - SkyscrapersClue clue = (SkyscrapersClue)puzzleBoard.getPuzzleElement(puzzleElement); - - // check each point in modified row/col - List data = puzzleBoard.getRowCol(clue.getClueIndex(),SkyscrapersType.ANY,clue.getType() == SkyscrapersType.CLUE_WEST); - for (SkyscrapersCell point : data) { - List cells = new ArrayList<>(List.of(point)); - - // if dependent on row/col - if ((puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) && point.getType() == SkyscrapersType.UNKNOWN) { - // get perpendicular row/col intersecting this point - int index; - if (clue.getType() == SkyscrapersType.CLUE_WEST) { - index = point.getLocation().x; - } - else { - index = point.getLocation().y; - } - cells.addAll(puzzleBoard.getRowCol(index,SkyscrapersType.ANY,clue.getType() != SkyscrapersType.CLUE_WEST)); - } - - // add all to result - for (SkyscrapersCell cell : cells) { - if (!elements.contains(board.getPuzzleElement(cell))) { - elements.add(board.getPuzzleElement(cell)); - } - } + for (TreeTransition newTree : childTransitions) { + SkyscrapersBoard newBoard = (SkyscrapersBoard) newTree.getBoard(); + if (newBoard.getModifiedData().size() != 1) { + // System.out.println("Only one cell should be modified."); + return "Only one cell should be modified."; + } + SkyscrapersCell newCell = (SkyscrapersCell) newBoard.getModifiedData().iterator().next(); + if (newCell.getType() != SkyscrapersType.Number) { + // System.out.println("Changed value should be a number."); + return "Changed value should be a number."; + } + } + return null; + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; + SkyscrapersClue clue = (SkyscrapersClue) puzzleBoard.getPuzzleElement(puzzleElement); + + // check each point in modified row/col + List data = + puzzleBoard.getRowCol( + clue.getClueIndex(), SkyscrapersType.ANY, clue.getType() == SkyscrapersType.CLUE_WEST); + for (SkyscrapersCell point : data) { + List cells = new ArrayList<>(List.of(point)); + + // if dependent on row/col + if ((puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) + && point.getType() == SkyscrapersType.UNKNOWN) { + // get perpendicular row/col intersecting this point + int index; + if (clue.getType() == SkyscrapersType.CLUE_WEST) { + index = point.getLocation().x; + } else { + index = point.getLocation().y; } - - return elements; + cells.addAll( + puzzleBoard.getRowCol( + index, SkyscrapersType.ANY, clue.getType() != SkyscrapersType.CLUE_WEST)); + } + + // add all to result + for (SkyscrapersCell cell : cells) { + if (!elements.contains(board.getPuzzleElement(cell))) { + elements.add(board.getPuzzleElement(cell)); + } + } } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java index 620a87f68..194bb905b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java @@ -6,55 +6,63 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.awt.*; import java.util.HashSet; import java.util.Set; public class DuplicateNumberContradictionRule extends ContradictionRule { - public DuplicateNumberContradictionRule() { - super("SKYS-CONT-0001", "Duplicate Number", - "Skyscrapers of same height cannot be placed in the same row or column.", - "edu/rpi/legup/images/skyscrapers/contradictions/DuplicateNumber.png"); + public DuplicateNumberContradictionRule() { + super( + "SKYS-CONT-0001", + "Duplicate Number", + "Skyscrapers of same height cannot be placed in the same row or column.", + "edu/rpi/legup/images/skyscrapers/contradictions/DuplicateNumber.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); + + Set candidates = new HashSet(); + + // check row + for (int i = 0; i < skyscrapersboard.getWidth(); i++) { + SkyscrapersCell c = skyscrapersboard.getCell(i, loc.y); + if (i != loc.x + && cell.getType() == SkyscrapersType.Number + && c.getType() == SkyscrapersType.Number + && c.getData() == cell.getData()) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + return null; + } } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); - - Set candidates = new HashSet(); - - //check row - for (int i = 0; i < skyscrapersboard.getWidth(); i++) { - SkyscrapersCell c = skyscrapersboard.getCell(i, loc.y); - if (i != loc.x && cell.getType() == SkyscrapersType.Number && c.getType() == SkyscrapersType.Number && c.getData() == cell.getData()) { - //System.out.print(c.getData()); - //System.out.println(cell.getData()); - return null; - } - } - - // check column - for (int i = 0; i < skyscrapersboard.getHeight(); i++) { - SkyscrapersCell c = skyscrapersboard.getCell(loc.x, i); - if (i != loc.y && cell.getType() == SkyscrapersType.Number && c.getType() == SkyscrapersType.Number && c.getData() == cell.getData()) { - //System.out.print(c.getData()); - //System.out.println(cell.getData()); - return null; - } - } - - return super.getNoContradictionMessage(); + // check column + for (int i = 0; i < skyscrapersboard.getHeight(); i++) { + SkyscrapersCell c = skyscrapersboard.getCell(loc.x, i); + if (i != loc.y + && cell.getType() == SkyscrapersType.Number + && c.getType() == SkyscrapersType.Number + && c.getData() == cell.getData()) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + return null; + } } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java index e38018745..08929e856 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java @@ -6,134 +6,133 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.awt.*; import java.util.Collections; -import java.util.HashSet; import java.util.List; -import java.util.Set; public class ExceedingVisibilityContradictionRule extends ContradictionRule { - public ExceedingVisibilityContradictionRule() { - super("SKYS-CONT-0002", "Exceeding Visibility", - "More skyscrapers are visible than there should be.", - "edu/rpi/legup/images/skyscrapers/contradictions/ExceedingVisibility.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + public ExceedingVisibilityContradictionRule() { + super( + "SKYS-CONT-0002", + "Exceeding Visibility", + "More skyscrapers are visible than there should be.", + "edu/rpi/legup/images/skyscrapers/contradictions/ExceedingVisibility.png"); + } - //get borders - int west = skyscrapersboard.getWestClues().get(loc.y).getData(); - int east = skyscrapersboard.getEastClues().get(loc.y).getData(); - int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); - int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - //check row - int max = 0; - int count = 0; - List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); - if (row.size() == skyscrapersboard.getWidth()) { - //from west border - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - //System.out.print(c.getData()); - //System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > west) { - return null; - } + // get borders + int west = skyscrapersboard.getWestClues().get(loc.y).getData(); + int east = skyscrapersboard.getEastClues().get(loc.y).getData(); + int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); + int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); - max = 0; - count = 0; - //from east border - Collections.reverse(row); - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - //System.out.print(c.getData()); - //System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > east) { - return null; - } + // check row + int max = 0; + int count = 0; + List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); + if (row.size() == skyscrapersboard.getWidth()) { + // from west border + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; } + } + if (count > west) { + return null; + } - //check column - List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); - if (col.size() == skyscrapersboard.getHeight()) { - //from north border - max = 0; - count = 0; - for (SkyscrapersCell c : col) { - //System.out.println(c.getData()); - if (c.getData() > max) { - - //System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > north) { - return null; - } + max = 0; + count = 0; + // from east border + Collections.reverse(row); + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > east) { + return null; + } + } - //from south border - max = 0; - count = 0; - Collections.reverse(col); - for (SkyscrapersCell c : col) { - //System.out.println(c.getData()); - if (c.getData() > max) { + // check column + List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); + if (col.size() == skyscrapersboard.getHeight()) { + // from north border + max = 0; + count = 0; + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - //System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > south) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; } + } + if (count > north) { + return null; + } - //System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); - } + // from south border + max = 0; + count = 0; + Collections.reverse(col); + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - /** - * Checks whether the Skyscraper cell has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the Skyscraper cell contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - //checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; } - return "No instance of the contradiction " + this.ruleName + " here"; + } + if (count > south) { + return null; + } } + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } + + /** + * Checks whether the Skyscraper cell has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the Skyscraper cell contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java index 7d405f122..d969a3415 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java @@ -6,133 +6,134 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.awt.*; import java.util.Collections; -import java.util.HashSet; import java.util.List; -import java.util.Set; public class InsufficientVisibilityContradictionRule extends ContradictionRule { - public InsufficientVisibilityContradictionRule() { - super("SKYS-CONT-0003", "Insufficient Visibility", - "Less skyscrapers are visible than there should be.", - "edu/rpi/legup/images/skyscrapers/contradictions/InsufficientVisibility.png"); - } + public InsufficientVisibilityContradictionRule() { + super( + "SKYS-CONT-0003", + "Insufficient Visibility", + "Less skyscrapers are visible than there should be.", + "edu/rpi/legup/images/skyscrapers/contradictions/InsufficientVisibility.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - //get borders - int west = skyscrapersboard.getWestClues().get(loc.y).getData(); - int east = skyscrapersboard.getEastClues().get(loc.y).getData(); - int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); - int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); + // get borders + int west = skyscrapersboard.getWestClues().get(loc.y).getData(); + int east = skyscrapersboard.getEastClues().get(loc.y).getData(); + int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); + int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); - //check row - int max = 0; - int count = 0; - java.util.List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); - if (row.size() == skyscrapersboard.getWidth()) { - //from west border - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - //System.out.print(c.getData()); - //System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < west) { - return null; - } + // check row + int max = 0; + int count = 0; + java.util.List row = + skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); + if (row.size() == skyscrapersboard.getWidth()) { + // from west border + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < west) { + return null; + } - max = 0; - count = 0; - //from east border - Collections.reverse(row); - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - //System.out.print(c.getData()); - //System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < east) { - return null; - } + max = 0; + count = 0; + // from east border + Collections.reverse(row); + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; } + } + if (count < east) { + return null; + } + } - //check column - List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); - if (col.size() == skyscrapersboard.getHeight()) { - //from north border - max = 0; - count = 0; - for (SkyscrapersCell c : col) { - //System.out.println(c.getData()); - if (c.getData() > max) { + // check column + List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); + if (col.size() == skyscrapersboard.getHeight()) { + // from north border + max = 0; + count = 0; + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - //System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < north) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < north) { + return null; + } - //from south border - max = 0; - count = 0; - Collections.reverse(col); - for (SkyscrapersCell c : col) { - //System.out.println(c.getData()); - if (c.getData() > max) { + // from south border + max = 0; + count = 0; + Collections.reverse(col); + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - //System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < south) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; } - - //System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); + } + if (count < south) { + return null; + } } - /** - * Checks whether the Skyscraper cell has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the Skyscraper cell contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - //checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } - } - return "No instance of the contradiction " + this.ruleName + " here"; + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } + + /** + * Checks whether the Skyscraper cell has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the Skyscraper cell contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } } + return "No instance of the contradiction " + this.ruleName + " here"; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java index 6aed653f6..42f6aeeeb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java @@ -8,107 +8,118 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.util.ArrayList; public class LastSingularCellDirectRule extends DirectRule { - public LastSingularCellDirectRule() { - super("SKYS-BASC-0002", "Last Cell for Number", - "There is only one cell on this row/col for this number that does not create a duplicate contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); - } + public LastSingularCellDirectRule() { + super( + "SKYS-BASC-0002", + "Last Cell for Number", + "There is only one cell on this row/col for this number that does not create a duplicate contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN + && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } - //set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getWestClues().get(finalCell.getLocation().y), (Integer) finalCell.getData()); - ArrayList YCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getNorthClues().get(finalCell.getLocation().x), (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getWestClues().get(finalCell.getLocation().y), + (Integer) finalCell.getData()); + ArrayList YCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getNorthClues().get(finalCell.getLocation().x), + (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - //System.out.println(XCandidates.size()); - //System.out.println(YCandidates.size()); + // System.out.println(XCandidates.size()); + // System.out.println(YCandidates.size()); - //return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + // return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; } + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + } - //helper to check if candidate list is valid - private String candidateCheck(ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; + // helper to check if candidate list is valid + private String candidateCheck( + ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() + == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; } - return ": This cell is not forced."; + return ": Wrong number in the cell."; + } + return ": No case for this cell."; } + return ": This cell is not forced."; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java index e9bacd7a6..bcb5a2608 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java @@ -8,90 +8,92 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.util.ArrayList; public class LastSingularNumberDirectRule extends DirectRule { - public LastSingularNumberDirectRule() { - super("SKYS-BASC-0003", "Last Number for Cell", - "There is only one number for this cell that does not create a duplicate contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); - } + public LastSingularNumberDirectRule() { + super( + "SKYS-BASC-0003", + "Last Number for Cell", + "There is only one number for this cell that does not create a duplicate contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - //set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - //check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + // check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java index 62b22041e..b80143d7a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java @@ -8,109 +8,121 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.util.ArrayList; public class LastVisibleCellDirectRule extends DirectRule { - public LastVisibleCellDirectRule() { - super("SKYS-BASC-0001", "Last Visible Cell", - "There is only one cell on this row/col for this number that does not create a visibility contradiction", - "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); - } + public LastVisibleCellDirectRule() { + super( + "SKYS-BASC-0001", + "Last Visible Cell", + "There is only one cell on this row/col for this number that does not create a visibility contradiction", + "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - //last cell for number based on preemptive visibility rules - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + // last cell for number based on preemptive visibility rules + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - //set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getWestClues().get(finalCell.getLocation().y), (Integer) finalCell.getData()); - ArrayList YCandidates = caseRule.getCasesFor(initialBoard, initialBoard.getNorthClues().get(finalCell.getLocation().x), (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getWestClues().get(finalCell.getLocation().y), + (Integer) finalCell.getData()); + ArrayList YCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getNorthClues().get(finalCell.getLocation().x), + (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - //System.out.println(XCandidates.size()); - //System.out.println(YCandidates.size()); + // System.out.println(XCandidates.size()); + // System.out.println(YCandidates.size()); - //return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + // return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; } + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + } - //helper to check if candidate list is valid - private String candidateCheck(ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; + // helper to check if candidate list is valid + private String candidateCheck( + ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() + == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; } - return ": This cell is not forced."; + return ": Wrong number in the cell."; + } + return ": No case for this cell."; } + return ": This cell is not forced."; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(modBoard.getPuzzleElements().size()); - for (PuzzleElement element : modBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - modBoard.addModifiedData(cell); - } - } - //System.out.println(modBoard.getModifiedData().isEmpty()); - if (modBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return modBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(modBoard.getPuzzleElements().size()); + for (PuzzleElement element : modBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + modBoard.addModifiedData(cell); + } + } + // System.out.println(modBoard.getModifiedData().isEmpty()); + if (modBoard.getModifiedData().isEmpty()) { + return null; + } else { + return modBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java index 255d1eab6..b53afaba6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java @@ -8,91 +8,93 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.util.ArrayList; public class LastVisibleNumberDirectRule extends DirectRule { - public LastVisibleNumberDirectRule() { - super("SKYS-BASC-0005", "Last Visible Number", - "There is only one number for this cell that does not create a visibility contradiction", - "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); - } + public LastVisibleNumberDirectRule() { + super( + "SKYS-BASC-0005", + "Last Visible Number", + "There is only one number for this cell that does not create a visibility contradiction", + "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - //last number for cell based upon preemptive visibility rules - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must transition from unknown to number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + // last number for cell based upon preemptive visibility rules + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - //set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - //check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + // check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java index db5d60440..79a478f9b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java @@ -8,92 +8,96 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.awt.Point; public class NEdgeDirectRule extends DirectRule { - public NEdgeDirectRule() { - super("SKYS-BASC-0004", "N Edge", - "If the maximum number appears on an edge, the row or column's numbers appear in ascending order, starting at that edge.", - "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); - } + public NEdgeDirectRule() { + super( + "SKYS-BASC-0004", + "N Edge", + "If the maximum number appears on an edge, the row or column's numbers appear in ascending order, starting at that edge.", + "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN + && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } - SkyscrapersBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); - Point loc = finalCell.getLocation(); - int max = initialBoard.getHeight(); + SkyscrapersBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); + Point loc = finalCell.getLocation(); + int max = initialBoard.getHeight(); - if (initialBoard.getWestClues().get(loc.y).getData() == max && finalCell.getData() == loc.x + 1) { - return null; - } - if (initialBoard.getEastClues().get(loc.y).getData() == max && finalCell.getData() == max - loc.x) { - return null; - } - if (initialBoard.getNorthClues().get(loc.x).getData() == max && finalCell.getData() == loc.y + 1) { - return null; - } - if (initialBoard.getSouthClues().get(loc.x).getData() == max && finalCell.getData() == max - loc.y) { - return null; - } + if (initialBoard.getWestClues().get(loc.y).getData() == max + && finalCell.getData() == loc.x + 1) { + return null; + } + if (initialBoard.getEastClues().get(loc.y).getData() == max + && finalCell.getData() == max - loc.x) { + return null; + } + if (initialBoard.getNorthClues().get(loc.x).getData() == max + && finalCell.getData() == loc.y + 1) { + return null; + } + if (initialBoard.getSouthClues().get(loc.x).getData() == max + && finalCell.getData() == max - loc.y) { + return null; + } - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; + } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - //System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - //cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return lightUpBoard; - } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java index 02000cd6e..9b6f67ca0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java @@ -7,9 +7,7 @@ import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersClue; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.awt.*; import java.util.ArrayList; import java.util.HashSet; @@ -18,151 +16,158 @@ public class NumberForCellCaseRule extends CaseRule { - public NumberForCellCaseRule() { - super("SKYS-CASE-0001", "Number For Cell", - "A blank cell must have height of 1 to n.", - "edu/rpi/legup/images/skyscrapers/cases/NumberForCell.png"); + public NumberForCellCaseRule() { + super( + "SKYS-CASE-0001", + "Number For Cell", + "A blank cell must have height of 1 to n.", + "edu/rpi/legup/images/skyscrapers/cases/NumberForCell.png"); + } + + @Override + public CaseBoard getCaseBoard(Board board) { + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) board.copy(); + lightUpBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((SkyscrapersCell) data).getType() == SkyscrapersType.UNKNOWN) { + caseBoard.addPickableElement(data); + } } - - @Override - public CaseBoard getCaseBoard(Board board) { - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) board.copy(); - lightUpBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((SkyscrapersCell) data).getType() == SkyscrapersType.UNKNOWN) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); + + Set candidates = new HashSet(); + for (int i = 1; i <= skyscrapersboard.getWidth(); i++) { + Board newCase = board.copy(); + PuzzleElement newCell = newCase.getPuzzleElement(puzzleElement); + newCell.setData(i); + newCase.addModifiedData(newCell); + + // if flags + boolean passed = true; + if (skyscrapersboard.getDupeFlag()) { + DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); + passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; + } + if (skyscrapersboard.getViewFlag()) { + PreemptiveVisibilityContradictionRule ViewRule = + new PreemptiveVisibilityContradictionRule(); + passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; + } + // how should unresolved be handled? should it be? + if (passed) { + cases.add(newCase); + } } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); - - Set candidates = new HashSet(); - for (int i = 1; i <= skyscrapersboard.getWidth(); i++) { - Board newCase = board.copy(); - PuzzleElement newCell = newCase.getPuzzleElement(puzzleElement); - newCell.setData(i); - newCase.addModifiedData(newCell); - - //if flags - boolean passed = true; - if (skyscrapersboard.getDupeFlag()) { - DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); - passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; - } - if (skyscrapersboard.getViewFlag()) { - PreemptiveVisibilityContradictionRule ViewRule = new PreemptiveVisibilityContradictionRule(); - passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; - } - //how should unresolved be handled? should it be? - if (passed) { - cases.add(newCase); - } - } - - return cases; + return cases; + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "This case rule must have at least one child."; + } else { + if (childTransitions.size() + != getCases( + transition.getBoard(), + childTransitions.get(0).getBoard().getModifiedData().iterator().next()) + .size()) { + return "Wrong number of children."; + } } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "This case rule must have at least one child."; - } - else { - if (childTransitions.size() != getCases(transition.getBoard(), childTransitions.get(0).getBoard().getModifiedData().iterator().next()).size()) { - return "Wrong number of children."; - } - } - - - //TreeTransition case1 = childTransitions.get(0); - //TreeTransition case2 = childTransitions.get(1); - TreeTransition case1 = childTransitions.get(0); - SkyscrapersCell mod1 = (SkyscrapersCell) case1.getBoard().getModifiedData().iterator().next(); - for (int i = 0; i < childTransitions.size(); i++) { - TreeTransition case2 = childTransitions.get(i); - if (case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 1 modified cell for each case."; - } - SkyscrapersCell mod2 = (SkyscrapersCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must modify the same cell for each case."; - } - if (!(mod2.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must assign a number."; - } - } - //System.out.println("no contradiction"); - return null; + // TreeTransition case1 = childTransitions.get(0); + // TreeTransition case2 = childTransitions.get(1); + TreeTransition case1 = childTransitions.get(0); + SkyscrapersCell mod1 = (SkyscrapersCell) case1.getBoard().getModifiedData().iterator().next(); + for (int i = 0; i < childTransitions.size(); i++) { + TreeTransition case2 = childTransitions.get(i); + if (case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } + SkyscrapersCell mod2 = (SkyscrapersCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } + if (!(mod2.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must assign a number."; + } } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + // System.out.println("no contradiction"); + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; + SkyscrapersCell point = (SkyscrapersCell) puzzleBoard.getPuzzleElement(puzzleElement); + + List cells = new ArrayList<>(List.of(point)); + + // if dependent on row/col + if (puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) { + // add all cells in row/col intersecting given point + cells.addAll(puzzleBoard.getRowCol(point.getLocation().x, SkyscrapersType.ANY, false)); + cells.addAll(puzzleBoard.getRowCol(point.getLocation().y, SkyscrapersType.ANY, true)); } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be valid - * Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends upon. - * Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; - SkyscrapersCell point = (SkyscrapersCell)puzzleBoard.getPuzzleElement(puzzleElement); - - List cells = new ArrayList<>(List.of(point)); - - // if dependent on row/col - if (puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) { - // add all cells in row/col intersecting given point - cells.addAll(puzzleBoard.getRowCol(point.getLocation().x,SkyscrapersType.ANY,false)); - cells.addAll(puzzleBoard.getRowCol(point.getLocation().y,SkyscrapersType.ANY,true)); - } - - for (SkyscrapersCell cell : cells) { - if (!elements.contains(board.getPuzzleElement(cell))) { - elements.add(board.getPuzzleElement(cell)); - } - } - - return elements; + for (SkyscrapersCell cell : cells) { + if (!elements.contains(board.getPuzzleElement(cell))) { + elements.add(board.getPuzzleElement(cell)); + } } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java index 1be26f49a..2d3095fdc 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java @@ -6,187 +6,191 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.awt.*; -import java.util.Queue; import java.util.LinkedList; import java.util.List; +import java.util.Queue; public class PreemptiveVisibilityContradictionRule extends ContradictionRule { - public PreemptiveVisibilityContradictionRule() { - super("SKYS-CONT-0006", "Preemptive Visibility", - "Visibility constraints are not met given an incomplete row/col", - "edu/rpi/legup/images/skyscrapers/contradictions/PreemptiveVisibility.png"); - } - - /** - * Checks whether there is an instance of a visibility contradiction in every possible row/col based on the specific - * puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the all possible rows/cols contain a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); - - //Initialize instances of necessary contradiction and case rules - InsufficientVisibilityContradictionRule tooFew = new InsufficientVisibilityContradictionRule(); - ExceedingVisibilityContradictionRule tooMany = new ExceedingVisibilityContradictionRule(); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - - //Initialize skyscraperBoard queues for rows and cols - Queue rowQ = new LinkedList<>(); - rowQ.add(skyscrapersBoard); - Queue colQ = new LinkedList<>(); - colQ.add(skyscrapersBoard); - - // find all cases for the corresponding row and column for each possible skyscraper height - - //Add every possible case for all heights for each corresponding row and column - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - int num = i + 1; - - //check row west clue - List rows; - - int size = rowQ.size(); - for (int j = 0; j < size; j++) { - SkyscrapersBoard temp = rowQ.poll(); //get row from the top of the stack - - //don't do anything if already in row - boolean exists = false; - for (SkyscrapersCell c : temp.getRowCol(loc.y, SkyscrapersType.Number, true)) { - if (c.getData() == num) { - exists = true; - break; - } - } - - if (exists) { - rowQ.add(temp); - } - else { - //set flags - boolean dupeTemp = temp.getDupeFlag(); - boolean viewTemp = temp.getViewFlag(); - temp.setDupeFlag(false); - temp.setViewFlag(false); - - //get all cases for corresponding row based on west clue - rows = caseRule.getCasesFor(temp, skyscrapersBoard.getWestClues().get(loc.y), num); - - //reset flags - temp.setDupeFlag(dupeTemp); - temp.setViewFlag(viewTemp); - - //add all row cases to row queue - for (Board k : rows) { - rowQ.add((SkyscrapersBoard) k); - } - } - } - - //check col north clue - List cols; - - size = colQ.size(); - for (int j = 0; j < size; j++) { - SkyscrapersBoard temp = colQ.poll(); //get row from the top of the stack - - //don't do anything if already in col - boolean exists = false; - for (SkyscrapersCell c : temp.getRowCol(loc.x, SkyscrapersType.Number, false)) { - if (c.getData() == num) { - exists = true; - break; - } - } - - if (exists) { - colQ.add(temp); - } - else { - //set flags - boolean dupeTemp = temp.getDupeFlag(); - boolean viewTemp = temp.getViewFlag(); - temp.setDupeFlag(false); - temp.setViewFlag(false); - - //get all cases for corresponding col based on north clue - cols = caseRule.getCasesFor(temp, skyscrapersBoard.getNorthClues().get(loc.x), num); - - //reset flags - temp.setDupeFlag(dupeTemp); - temp.setViewFlag(viewTemp); - - //add all row cases to row queue - for (Board k : cols) { - colQ.add((SkyscrapersBoard) k); - } - } - } + public PreemptiveVisibilityContradictionRule() { + super( + "SKYS-CONT-0006", + "Preemptive Visibility", + "Visibility constraints are not met given an incomplete row/col", + "edu/rpi/legup/images/skyscrapers/contradictions/PreemptiveVisibility.png"); + } + + /** + * Checks whether there is an instance of a visibility contradiction in every possible row/col + * based on the specific puzzleElement index using this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the all possible rows/cols contain a contradiction at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); + + // Initialize instances of necessary contradiction and case rules + InsufficientVisibilityContradictionRule tooFew = new InsufficientVisibilityContradictionRule(); + ExceedingVisibilityContradictionRule tooMany = new ExceedingVisibilityContradictionRule(); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + + // Initialize skyscraperBoard queues for rows and cols + Queue rowQ = new LinkedList<>(); + rowQ.add(skyscrapersBoard); + Queue colQ = new LinkedList<>(); + colQ.add(skyscrapersBoard); + + // find all cases for the corresponding row and column for each possible skyscraper height + + // Add every possible case for all heights for each corresponding row and column + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + int num = i + 1; + + // check row west clue + List rows; + + int size = rowQ.size(); + for (int j = 0; j < size; j++) { + SkyscrapersBoard temp = rowQ.poll(); // get row from the top of the stack + + // don't do anything if already in row + boolean exists = false; + for (SkyscrapersCell c : temp.getRowCol(loc.y, SkyscrapersType.Number, true)) { + if (c.getData() == num) { + exists = true; + break; + } } - String rowTooFew; - String rowTooMany; - boolean rowContradiction = true; - //check if each case board has a contradiction - while (rowQ.size() > 0) { - SkyscrapersBoard fullRow = rowQ.poll(); - - //checks if there is a contradiction given the row based on the west clue - rowTooFew = tooFew.checkContradictionAt(fullRow, cell); // is cell the correct puzzle element to check? - rowTooMany = tooMany.checkContradictionAt(fullRow, cell); - - //boolean that checks if there is a contradiction within all rows - rowContradiction = rowContradiction && (rowTooFew == null || rowTooMany == null);// !null means there isn't a contradiction, so there must be a valid permutation of the array + if (exists) { + rowQ.add(temp); + } else { + // set flags + boolean dupeTemp = temp.getDupeFlag(); + boolean viewTemp = temp.getViewFlag(); + temp.setDupeFlag(false); + temp.setViewFlag(false); + + // get all cases for corresponding row based on west clue + rows = caseRule.getCasesFor(temp, skyscrapersBoard.getWestClues().get(loc.y), num); + + // reset flags + temp.setDupeFlag(dupeTemp); + temp.setViewFlag(viewTemp); + + // add all row cases to row queue + for (Board k : rows) { + rowQ.add((SkyscrapersBoard) k); + } } - - String colTooFew; - String colTooMany; - boolean colContradiction = true; - while (colQ.size() > 0) { - SkyscrapersBoard fullCol = colQ.poll(); - - //checks if there is a contradiction given the col baesd on the north clue - colTooFew = tooFew.checkContradictionAt(fullCol, cell); - colTooMany = tooMany.checkContradictionAt(fullCol, cell); - - //boolean that checks if there is a contradiction within all the cols - colContradiction = colContradiction && (colTooFew == null || colTooMany == null); + } + + // check col north clue + List cols; + + size = colQ.size(); + for (int j = 0; j < size; j++) { + SkyscrapersBoard temp = colQ.poll(); // get row from the top of the stack + + // don't do anything if already in col + boolean exists = false; + for (SkyscrapersCell c : temp.getRowCol(loc.x, SkyscrapersType.Number, false)) { + if (c.getData() == num) { + exists = true; + break; + } } - //if every possible permutation results in contradictions return null, else no contradiction - if (rowContradiction || colContradiction) { - return null; + if (exists) { + colQ.add(temp); + } else { + // set flags + boolean dupeTemp = temp.getDupeFlag(); + boolean viewTemp = temp.getViewFlag(); + temp.setDupeFlag(false); + temp.setViewFlag(false); + + // get all cases for corresponding col based on north clue + cols = caseRule.getCasesFor(temp, skyscrapersBoard.getNorthClues().get(loc.x), num); + + // reset flags + temp.setDupeFlag(dupeTemp); + temp.setViewFlag(viewTemp); + + // add all row cases to row queue + for (Board k : cols) { + colQ.add((SkyscrapersBoard) k); + } } - return super.getNoContradictionMessage(); + } } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - //checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } - } - return "No instance of the contradiction " + this.ruleName + " here"; + String rowTooFew; + String rowTooMany; + boolean rowContradiction = true; + // check if each case board has a contradiction + while (rowQ.size() > 0) { + SkyscrapersBoard fullRow = rowQ.poll(); + + // checks if there is a contradiction given the row based on the west clue + rowTooFew = + tooFew.checkContradictionAt( + fullRow, cell); // is cell the correct puzzle element to check? + rowTooMany = tooMany.checkContradictionAt(fullRow, cell); + + // boolean that checks if there is a contradiction within all rows + rowContradiction = + rowContradiction + && (rowTooFew == null + || rowTooMany + == null); // !null means there isn't a contradiction, so there must be a valid + // permutation of the array } + String colTooFew; + String colTooMany; + boolean colContradiction = true; + while (colQ.size() > 0) { + SkyscrapersBoard fullCol = colQ.poll(); + + // checks if there is a contradiction given the col baesd on the north clue + colTooFew = tooFew.checkContradictionAt(fullCol, cell); + colTooMany = tooMany.checkContradictionAt(fullCol, cell); + // boolean that checks if there is a contradiction within all the cols + colContradiction = colContradiction && (colTooFew == null || colTooMany == null); + } + + // if every possible permutation results in contradictions return null, else no contradiction + if (rowContradiction || colContradiction) { + return null; + } + return super.getNoContradictionMessage(); + } + + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java index ada47efde..a34fe0730 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java @@ -3,41 +3,38 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.ContradictionRule; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.awt.*; import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; public class UnresolvedCellContradictionRule extends ContradictionRule { - public UnresolvedCellContradictionRule() { - super("SKYS-CONT-0004", "Unresolved Cell", - "Elimination leaves no possible number for a cell.", - "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedCell.png"); + public UnresolvedCellContradictionRule() { + super( + "SKYS-CONT-0004", + "Unresolved Cell", + "Elimination leaves no possible number for a cell.", + "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedCell.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList cases = caseRule.getCases(board, puzzleElement); + + if (cases.size() == 0) { + return null; } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList cases = caseRule.getCases(board, puzzleElement); - - if (cases.size() == 0) { - return null; - } - - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java index 21a48caaf..b08fa67f3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java @@ -1,97 +1,98 @@ package edu.rpi.legup.puzzle.skyscrapers.rules; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.ContradictionRule; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersType; - import java.awt.*; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; public class UnresolvedNumberContradictionRule extends ContradictionRule { - public UnresolvedNumberContradictionRule() { - super("SKYS-CONT-0005", "Unresolved Number", - "No possible cell for a number without a duplicate contradiction.", - //specify a number? defaulting to every number for now. expand to more than duplicate? - "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedNumber.png"); - } + public UnresolvedNumberContradictionRule() { + super( + "SKYS-CONT-0005", + "Unresolved Number", + "No possible cell for a number without a duplicate contradiction.", + // specify a number? defaulting to every number for now. expand to more than duplicate? + "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - int num = i + 1; - //check row - //isn't already present - boolean exists = false; - for (SkyscrapersCell presentCell : skyscrapersBoard.getRowCol(loc.y, SkyscrapersType.Number, true)) { - if (presentCell.getData() == num) { - exists = true; - break; - } - } - if (!exists) { - //and no possible cases - if (caseRule.getCasesFor(board, skyscrapersBoard.getWestClues().get(loc.y), num).size() == 0) { - return null; - } - } - - //check col - //same process as for row - exists = false; - for (SkyscrapersCell presentCell : skyscrapersBoard.getRowCol(loc.x, SkyscrapersType.Number, false)) { - if (presentCell.getData() == num) { - exists = true; - break; - } - } - if (!exists) { - if (caseRule.getCasesFor(board, skyscrapersBoard.getNorthClues().get(loc.x), num).size() == 0) { - return null; - } - } + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + int num = i + 1; + // check row + // isn't already present + boolean exists = false; + for (SkyscrapersCell presentCell : + skyscrapersBoard.getRowCol(loc.y, SkyscrapersType.Number, true)) { + if (presentCell.getData() == num) { + exists = true; + break; + } + } + if (!exists) { + // and no possible cases + if (caseRule.getCasesFor(board, skyscrapersBoard.getWestClues().get(loc.y), num).size() + == 0) { + return null; } + } - //System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); + // check col + // same process as for row + exists = false; + for (SkyscrapersCell presentCell : + skyscrapersBoard.getRowCol(loc.x, SkyscrapersType.Number, false)) { + if (presentCell.getData() == num) { + exists = true; + break; + } + } + if (!exists) { + if (caseRule.getCasesFor(board, skyscrapersBoard.getNorthClues().get(loc.x), num).size() + == 0) { + return null; + } + } } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - //checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return null; - } - } - return "No instance of the contradiction " + this.ruleName + " here"; + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } + + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return null; + } } + return "No instance of the contradiction " + this.ruleName + " here"; + } } - diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java index a716258fa..e0583a13b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java @@ -1,5 +1,7 @@ package edu.rpi.legup.puzzle.sudoku; public enum GroupType { - REGION, ROW, COLUMN + REGION, + ROW, + COLUMN } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java index 8af2aca2e..e81bc909e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java @@ -3,85 +3,82 @@ import edu.rpi.legup.model.gameboard.CaseBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.puzzle.sudoku.rules.PossibleNumberCaseRule; - import java.awt.event.MouseEvent; import java.util.HashSet; import java.util.Set; public class PossibleNumberCaseBoard extends CaseBoard { - private SudokuCell cell; - private Set pickableRegions; - private Set pickableRows; - private Set pickableCols; + private SudokuCell cell; + private Set pickableRegions; + private Set pickableRows; + private Set pickableCols; + public PossibleNumberCaseBoard( + SudokuBoard baseBoard, PossibleNumberCaseRule caseRule, SudokuCell cell) { + super(baseBoard, caseRule); + this.cell = cell; + this.pickableRegions = new HashSet<>(); + this.pickableRows = new HashSet<>(); + this.pickableCols = new HashSet<>(); + } - public PossibleNumberCaseBoard(SudokuBoard baseBoard, PossibleNumberCaseRule caseRule, SudokuCell cell) { - super(baseBoard, caseRule); - this.cell = cell; - this.pickableRegions = new HashSet<>(); - this.pickableRows = new HashSet<>(); - this.pickableCols = new HashSet<>(); + @Override + public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { + if (e == null) { + return false; } - @Override - public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { - if (e == null) { - return false; + SudokuCell sudokuCell = (SudokuCell) puzzleElement; + if (e.isShiftDown()) { + for (int r : pickableRows) { + if (r == sudokuCell.getLocation().y) { + return true; } - - SudokuCell sudokuCell = (SudokuCell) puzzleElement; - if (e.isShiftDown()) { - for (int r : pickableRows) { - if (r == sudokuCell.getLocation().y) { - return true; - } - } + } + } else { + if (e.isControlDown()) { + for (int c : pickableCols) { + if (c == sudokuCell.getLocation().x) { + return true; + } } - else { - if (e.isControlDown()) { - for (int c : pickableCols) { - if (c == sudokuCell.getLocation().x) { - return true; - } - } - } - else { - for (int r : pickableRegions) { - if (r == sudokuCell.getGroupIndex()) { - return true; - } - } - } + } else { + for (int r : pickableRegions) { + if (r == sudokuCell.getGroupIndex()) { + return true; + } } - return false; + } } + return false; + } - public void addPickableRegion(int region) { - this.pickableRegions.add(region); - } + public void addPickableRegion(int region) { + this.pickableRegions.add(region); + } - public void addPickableRow(int row) { - this.pickableRows.add(row); - } + public void addPickableRow(int row) { + this.pickableRows.add(row); + } - public void addPickableCol(int col) { - this.pickableCols.add(col); - } + public void addPickableCol(int col) { + this.pickableCols.add(col); + } - public SudokuCell getCell() { - return cell; - } + public SudokuCell getCell() { + return cell; + } - public Set getPickableRegions() { - return pickableRegions; - } + public Set getPickableRegions() { + return pickableRegions; + } - public Set getPickableRows() { - return pickableRows; - } + public Set getPickableRows() { + return pickableRows; + } - public Set getPickableCols() { - return pickableCols; - } + public Set getPickableCols() { + return pickableCols; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java index ac082e427..30aa78aac 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java @@ -7,107 +7,102 @@ import edu.rpi.legup.ui.boardview.BoardView; public class Sudoku extends Puzzle { - private SudokuView boardView; - - /** - * Sudoku Constructor - */ - public Sudoku() { - super(); - - this.name = "Sudoku"; - - this.importer = new SudokuImporter(this); - this.exporter = new SudokuExporter(this); - - this.factory = new SudokuCellFactory(); + private SudokuView boardView; + + /** Sudoku Constructor */ + public Sudoku() { + super(); + + this.name = "Sudoku"; + + this.importer = new SudokuImporter(this); + this.exporter = new SudokuExporter(this); + + this.factory = new SudokuCellFactory(); + } + + public BoardView getBoardView() { + return boardView; + } + + /** Initializes the game board */ + @Override + public void initializeView() { + boardView = new SudokuView((SudokuBoard) currentBoard); + } + + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } + + @Override + /** + * Determines if the given dimensions are valid for Sudoku + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Sudoku, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // The number of rows and columns must be greater than 1 + if (rows <= 1 || columns <= 1) { + return false; } - public BoardView getBoardView() { - return boardView; + // The number of rows and columns must be equal + if (rows != columns) { + return false; } - /** - * Initializes the game board - */ - @Override - public void initializeView() { - boardView = new SudokuView((SudokuBoard) currentBoard); + // For Sudoku, the number of rows and columns must be a perfect square + // Note: we don't need to check the columns since by this point, we have verified that the + // number of rows + // equals the number of columns + double sqrtRows = Math.sqrt(rows); + if (sqrtRows - Math.floor(sqrtRows) != 0) { + return false; } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; + return true; + } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(sudokuBoard) == null) { + return false; + } } - @Override - /** - * Determines if the given dimensions are valid for Sudoku - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Sudoku, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // The number of rows and columns must be greater than 1 - if (rows <= 1 || columns <= 1) { - return false; - } - - // The number of rows and columns must be equal - if (rows != columns) { - return false; - } - - // For Sudoku, the number of rows and columns must be a perfect square - // Note: we don't need to check the columns since by this point, we have verified that the number of rows - // equals the number of columns - double sqrtRows = Math.sqrt(rows); - if (sqrtRows - Math.floor(sqrtRows) != 0) { - return false; - } - - return true; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(sudokuBoard) == null) { - return false; - } - } - - for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { - SudokuCell cell = (SudokuCell) puzzleElement; - if (cell.getData() == 0) { - return false; - } - } - return true; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { - + for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { + SudokuCell cell = (SudokuCell) puzzleElement; + if (cell.getData() == 0) { + return false; + } } + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java index ed3048c88..095dbf64c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java @@ -2,173 +2,171 @@ import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.*; import java.util.HashSet; import java.util.Set; public class SudokuBoard extends GridBoard { - private int size; - private int groupSize; - - /** - * SudokuBoard Constructor - create a new Sudoku board - * - * @param size size of one side of the sudoku board, must be an integer square root - */ - public SudokuBoard(int size) { - super(size, size); - this.size = size; - this.groupSize = (int) Math.sqrt(dimension.width); - } - - /** - * Gets a SudokuCell from the board - * - * @param x x location of the cell - * @param y y location of the cell - * @return SudokuCell at location (x, y) - */ - @Override - public SudokuCell getCell(int x, int y) { - return (SudokuCell) super.getCell(x, y); - } - - /** - * Gets the SudokuCell in the specified group index at the x and y location given - * The group index must be by less than the width (or height) of the board and the - * x and y location is relative to the group. This means the x and y values must be - * less the square root of the width (or height) of the board. - * - * @param groupIndex group index of the cell - * @param x x location relative to the group - * @param y y location relative to the group - * @return cell in the specified group index at the given x and y location - */ - public SudokuCell getCell(int groupIndex, int x, int y) { - return getCell(x + (groupIndex % groupSize) * groupSize, y + (groupIndex / groupSize) * groupSize); - } - - /** - * Gets the size of the sudoku board - * Standard board is 9x9 - * - * @return size of the board - */ - public int getSize() { - return size; - } - - /** - * Gets the minor group size of the sudoku board - * Standard board is 3x3x3x3 - * - * @return minor group size - */ - public int getGroupSize() { - return groupSize; + private int size; + private int groupSize; + + /** + * SudokuBoard Constructor - create a new Sudoku board + * + * @param size size of one side of the sudoku board, must be an integer square root + */ + public SudokuBoard(int size) { + super(size, size); + this.size = size; + this.groupSize = (int) Math.sqrt(dimension.width); + } + + /** + * Gets a SudokuCell from the board + * + * @param x x location of the cell + * @param y y location of the cell + * @return SudokuCell at location (x, y) + */ + @Override + public SudokuCell getCell(int x, int y) { + return (SudokuCell) super.getCell(x, y); + } + + /** + * Gets the SudokuCell in the specified group index at the x and y location given The group index + * must be by less than the width (or height) of the board and the x and y location is relative to + * the group. This means the x and y values must be less the square root of the width (or height) + * of the board. + * + * @param groupIndex group index of the cell + * @param x x location relative to the group + * @param y y location relative to the group + * @return cell in the specified group index at the given x and y location + */ + public SudokuCell getCell(int groupIndex, int x, int y) { + return getCell( + x + (groupIndex % groupSize) * groupSize, y + (groupIndex / groupSize) * groupSize); + } + + /** + * Gets the size of the sudoku board Standard board is 9x9 + * + * @return size of the board + */ + public int getSize() { + return size; + } + + /** + * Gets the minor group size of the sudoku board Standard board is 3x3x3x3 + * + * @return minor group size + */ + public int getGroupSize() { + return groupSize; + } + + /** + * Gets all the cells in the specified row + * + * @param rowNum row index + * @return list of all the cells in the row + */ + public Set getRow(int rowNum) { + Set row = new HashSet<>(); + for (int i = 0; i < size; i++) { + row.add(getCell(i, rowNum)); } - - /** - * Gets all the cells in the specified row - * - * @param rowNum row index - * @return list of all the cells in the row - */ - public Set getRow(int rowNum) { - Set row = new HashSet<>(); - for (int i = 0; i < size; i++) { - row.add(getCell(i, rowNum)); - } - return row; + return row; + } + + /** + * Gets all the cells in the specified column + * + * @param colNum column index + * @return list of all the cells in the column + */ + public Set getCol(int colNum) { + Set col = new HashSet<>(); + for (int i = 0; i < size; i++) { + col.add(getCell(colNum, i)); } - - /** - * Gets all the cells in the specified column - * - * @param colNum column index - * @return list of all the cells in the column - */ - public Set getCol(int colNum) { - Set col = new HashSet<>(); - for (int i = 0; i < size; i++) { - col.add(getCell(colNum, i)); - } - return col; + return col; + } + + /** + * Gets all the cells in the specified region + * + * @param regionNum region index + * @return list of all the cells in the region + */ + public Set getRegion(int regionNum) { + Set region = new HashSet<>(); + for (int i = 0; i < size; i++) { + region.add(getCell(regionNum, i % groupSize, i / groupSize)); } - - /** - * Gets all the cells in the specified region - * - * @param regionNum region index - * @return list of all the cells in the region - */ - public Set getRegion(int regionNum) { - Set region = new HashSet<>(); - for (int i = 0; i < size; i++) { - region.add(getCell(regionNum, i % groupSize, i / groupSize)); - } - return region; + return region; + } + + public Set getAffected(SudokuCell cell) { + Point loc = cell.getLocation(); + cell = getCell(loc.x, loc.y); + Set affected = new HashSet<>(); + affected.addAll(getRegion(cell.getGroupIndex())); + affected.addAll(getRow(loc.y)); + affected.addAll(getCol(loc.x)); + + return affected; + } + + public Set getPossibleValues(SudokuCell cell) { + Point loc = cell.getLocation(); + cell = getCell(loc.x, loc.y); + Set possible = getAffected(cell); + + Set possibleValues = new HashSet<>(); + for (int i = 0; i < size; i++) { + possibleValues.add(i); } - - public Set getAffected(SudokuCell cell) { - Point loc = cell.getLocation(); - cell = getCell(loc.x, loc.y); - Set affected = new HashSet<>(); - affected.addAll(getRegion(cell.getGroupIndex())); - affected.addAll(getRow(loc.y)); - affected.addAll(getCol(loc.x)); - - return affected; + for (SudokuCell c : possible) { + possibleValues.remove(c.getData()); } - public Set getPossibleValues(SudokuCell cell) { - Point loc = cell.getLocation(); - cell = getCell(loc.x, loc.y); - Set possible = getAffected(cell); - - Set possibleValues = new HashSet<>(); - for (int i = 0; i < size; i++) { - possibleValues.add(i); - } - for (SudokuCell c : possible) { - possibleValues.remove(c.getData()); - } - - return possibleValues; + return possibleValues; + } + + /** + * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent + * puzzle element with the new data. + * + * @param puzzleElement equivalent puzzle element with the new data. + */ + @Override + public void notifyChange(PuzzleElement puzzleElement) { + super.notifyChange(puzzleElement); + Set affected = getAffected((SudokuCell) puzzleElement); + for (SudokuCell c : affected) { + c.setAnnotations(getPossibleValues(c)); } - - /** - * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent puzzle element with - * the new data. - * - * @param puzzleElement equivalent puzzle element with the new data. - */ - @Override - public void notifyChange(PuzzleElement puzzleElement) { - super.notifyChange(puzzleElement); - Set affected = getAffected((SudokuCell) puzzleElement); - for (SudokuCell c : affected) { - c.setAnnotations(getPossibleValues(c)); - } + } + + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + @Override + public SudokuBoard copy() { + SudokuBoard copy = new SudokuBoard(size); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } - - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - @Override - public SudokuBoard copy() { - SudokuBoard copy = new SudokuBoard(size); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java index 0e1595d03..4b9ea2b4c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java @@ -1,63 +1,62 @@ package edu.rpi.legup.puzzle.sudoku; import edu.rpi.legup.model.gameboard.GridCell; - import java.awt.*; import java.util.HashSet; import java.util.Set; public class SudokuCell extends GridCell { - private int groupIndex; - private Set annotations; - private int max; - - /** - * SudokuCell Constructor - creates a new Sudoku cell to hold the puzzleElement - * - * @param value value of the sudoku cell - * @param location location of the cell on the board - * @param groupIndex index of the group the cell is in on the board - * @param size size of the sudoku cell - */ - public SudokuCell(int value, Point location, int groupIndex, int size) { - super(value, location); - this.groupIndex = groupIndex; - this.annotations = new HashSet<>(); - this.max = size; - } - - /** - * Gets the group index of the cell - * - * @return group index of the cell - */ - public int getGroupIndex() { - return groupIndex; - } - - public int getMax() { - return max; - } - - public Set getAnnotations() { - return annotations; - } - - public void setAnnotations(Set annotations) { - this.annotations = annotations; - } - - /** - * Performs a deep copy on the SudokuCell - * - * @return a new copy of the SudokuCell that is independent of this one - */ - @Override - public SudokuCell copy() { - SudokuCell copy = new SudokuCell(data, (Point) location.clone(), groupIndex, max); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + private int groupIndex; + private Set annotations; + private int max; + + /** + * SudokuCell Constructor - creates a new Sudoku cell to hold the puzzleElement + * + * @param value value of the sudoku cell + * @param location location of the cell on the board + * @param groupIndex index of the group the cell is in on the board + * @param size size of the sudoku cell + */ + public SudokuCell(int value, Point location, int groupIndex, int size) { + super(value, location); + this.groupIndex = groupIndex; + this.annotations = new HashSet<>(); + this.max = size; + } + + /** + * Gets the group index of the cell + * + * @return group index of the cell + */ + public int getGroupIndex() { + return groupIndex; + } + + public int getMax() { + return max; + } + + public Set getAnnotations() { + return annotations; + } + + public void setAnnotations(Set annotations) { + this.annotations = annotations; + } + + /** + * Performs a deep copy on the SudokuCell + * + * @return a new copy of the SudokuCell that is independent of this one + */ + @Override + public SudokuCell copy() { + SudokuCell copy = new SudokuCell(data, (Point) location.clone(), groupIndex, max); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java index b25ddfe08..edb095519 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java @@ -2,38 +2,36 @@ import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.model.gameboard.PuzzleElement; - - import java.awt.event.MouseEvent; public class SudokuCellController extends ElementController { - @Override - - public void changeCell(MouseEvent e, PuzzleElement data) { - SudokuCell cell = (SudokuCell) data; - System.out.print(111); - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView.getSelectionPopupMenu().show(boardView, this.boardView.getCanvas().getX() + e.getX(), this.boardView.getCanvas().getY() + e.getY()); - } - else { - if (cell.getData() < cell.getMax()) { - data.setData(cell.getData() + 1); - } - else { - data.setData(0); - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + SudokuCell cell = (SudokuCell) data; + System.out.print(111); + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() < cell.getMax()) { + data.setData(cell.getData() + 1); + } else { + data.setData(0); } - else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() > 0) { - data.setData(cell.getData() - 1); - } - else { - data.setData(cell.getMax()); - } - } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() > 0) { + data.setData(cell.getData() - 1); + } else { + data.setData(cell.getMax()); } + } } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java index 90f84d519..7214193be 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java @@ -4,72 +4,69 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class SudokuCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public SudokuCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Sudoku Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public SudokuCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException("Sudoku Factory: unknown puzzleElement puzzleElement"); + } - SudokuBoard sudokuBoard = (SudokuBoard) board; - int size = sudokuBoard.getSize(); - int minorSize = (int) Math.sqrt(size); + SudokuBoard sudokuBoard = (SudokuBoard) board; + int size = sudokuBoard.getSize(); + int minorSize = (int) Math.sqrt(size); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= size || y >= size) { - throw new InvalidFileFormatException("Sudoku Factory: cell location out of bounds"); - } - if (value < 0 || value > 9) { - throw new InvalidFileFormatException("Sudoku Factory: cell unknown value"); - } - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(value, new Point(x, y), groupIndex, size); - cell.setIndex(y * size + x); - return cell; - } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Sudoku Factory: unknown value where integer expected"); - } - catch (NullPointerException e) { - throw new InvalidFileFormatException("Sudoku Factory: could not find attribute(s)"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= size || y >= size) { + throw new InvalidFileFormatException("Sudoku Factory: cell location out of bounds"); + } + if (value < 0 || value > 9) { + throw new InvalidFileFormatException("Sudoku Factory: cell unknown value"); + } + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(value, new Point(x, y), groupIndex, size); + cell.setIndex(y * size + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("Sudoku Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Sudoku Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - SudokuCell cell = (SudokuCell) puzzleElement; - Point loc = cell.getLocation(); + SudokuCell cell = (SudokuCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java index 46d7e4ec7..142cf8f88 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java @@ -3,67 +3,68 @@ import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.model.gameboard.GridCell; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; public class SudokuElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Font ANNOTATE_FONT = new Font("TimesRoman", Font.BOLD, 8); - private static final Color FONT_COLOR = new Color(0x212121); - private static final Color BORDER_COLOR = new Color(0x424242); - private static final Color GIVEN_COLOR = new Color(0x75, 0x75, 0x75, 0x80); - private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Font ANNOTATE_FONT = new Font("TimesRoman", Font.BOLD, 8); + private static final Color FONT_COLOR = new Color(0x212121); + private static final Color BORDER_COLOR = new Color(0x424242); + private static final Color GIVEN_COLOR = new Color(0x75, 0x75, 0x75, 0x80); + private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); - public SudokuElementView(GridCell cell) { - super(cell); - } + public SudokuElementView(GridCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public SudokuCell getPuzzleElement() { - return (SudokuCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public SudokuCell getPuzzleElement() { + return (SudokuCell) super.getPuzzleElement(); + } - @Override - public void drawGiven(Graphics2D graphics2D) { - graphics2D.setColor(GIVEN_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } + @Override + public void drawGiven(Graphics2D graphics2D) { + graphics2D.setColor(GIVEN_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BACKGROUND_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BORDER_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BACKGROUND_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BORDER_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - SudokuCell cell = (SudokuCell) puzzleElement; - int val = cell.getData(); - if (val != 0) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(val); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } - else { - boolean annotate = LegupPreferences.getInstance().getUserPref(LegupPreferences.SHOW_ANNOTATIONS).equalsIgnoreCase(Boolean.toString(true)); - if (annotate) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(ANNOTATE_FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getAnnotations()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } - } + SudokuCell cell = (SudokuCell) puzzleElement; + int val = cell.getData(); + if (val != 0) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(val); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } else { + boolean annotate = + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.SHOW_ANNOTATIONS) + .equalsIgnoreCase(Boolean.toString(true)); + if (annotate) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(ANNOTATE_FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getAnnotations()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java index 45e320293..3bb78e9e9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java @@ -2,38 +2,37 @@ import edu.rpi.legup.model.PuzzleExporter; import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import org.w3c.dom.Document; public class SudokuExporter extends PuzzleExporter { - public SudokuExporter(Sudoku sudoku) { - super(sudoku); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - SudokuBoard board; - if (puzzle.getTree() != null) { - board = (SudokuBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (SudokuBoard) puzzle.getBoardView().getBoard(); - } + public SudokuExporter(Sudoku sudoku) { + super(sudoku); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("size", String.valueOf(board.getSize())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + SudokuBoard board; + if (puzzle.getTree() != null) { + board = (SudokuBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (SudokuBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SudokuCell cell = (SudokuCell) puzzleElement; - if (cell.getData() != 0) { - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("size", String.valueOf(board.getSize())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SudokuCell cell = (SudokuCell) puzzleElement; + if (cell.getData() != 0) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java index dccec52d4..fd310a78e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java @@ -2,129 +2,127 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.awt.*; - public class SudokuImporter extends PuzzleImporter { - public SudokuImporter(Sudoku sudoku) { - super(sudoku); - } + public SudokuImporter(Sudoku sudoku) { + super(sudoku); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - SudokuBoard sudokuBoard; - int minorSize = (int) Math.sqrt(rows); - sudokuBoard = new SudokuBoard(rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + SudokuBoard sudokuBoard; + int minorSize = (int) Math.sqrt(rows); + sudokuBoard = new SudokuBoard(rows); - for (int y = 0; y < columns; y++) { - for (int x = 0; x < rows; x++) { - if (sudokuBoard.getCell(x, y) == null) { - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, rows); - cell.setIndex(y * rows + x); - cell.setModifiable(true); - sudokuBoard.setCell(x, y, cell); - } - } + for (int y = 0; y < columns; y++) { + for (int x = 0; x < rows; x++) { + if (sudokuBoard.getCell(x, y) == null) { + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, rows); + cell.setIndex(y * rows + x); + cell.setModifiable(true); + sudokuBoard.setCell(x, y, cell); } - - puzzle.setCurrentBoard(sudokuBoard); + } } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Sudoku Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Sudoku Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - SudokuBoard sudokuBoard; - int size; - int minorSize; - if (!boardElement.getAttribute("size").isEmpty()) { - size = Integer.valueOf(boardElement.getAttribute("size")); - minorSize = (int) Math.sqrt(size); - if (minorSize * minorSize != size) { - throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); - } - sudokuBoard = new SudokuBoard(size); - } - else { - throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); - } + puzzle.setCurrentBoard(sudokuBoard); + } - for (int i = 0; i < elementDataList.getLength(); i++) { - SudokuCell cell = (SudokuCell) puzzle.getFactory().importCell(elementDataList.item(i), sudokuBoard); - Point loc = cell.getLocation(); - if (cell.getData() != 0) { - cell.setModifiable(false); - cell.setGiven(true); - } - sudokuBoard.setCell(loc.x, loc.y, cell); - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("Sudoku Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("Sudoku Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - if (sudokuBoard.getCell(x, y) == null) { - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - sudokuBoard.setCell(x, y, cell); - } - } - } -// -// for(int y = 0; y < size; y++) -// { -// for(int x = 0; x < size; x++) -// { -// SudokuCell cell = sudokuBoard.getCell(x, y); -// System.err.println("(" + x + ", " + y + ") - " + cell.getGroupIndex()); -// } -// } + SudokuBoard sudokuBoard; + int size; + int minorSize; + if (!boardElement.getAttribute("size").isEmpty()) { + size = Integer.valueOf(boardElement.getAttribute("size")); + minorSize = (int) Math.sqrt(size); + if (minorSize * minorSize != size) { + throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); + } + sudokuBoard = new SudokuBoard(size); + } else { + throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); + } - puzzle.setCurrentBoard(sudokuBoard); + for (int i = 0; i < elementDataList.getLength(); i++) { + SudokuCell cell = + (SudokuCell) puzzle.getFactory().importCell(elementDataList.item(i), sudokuBoard); + Point loc = cell.getLocation(); + if (cell.getData() != 0) { + cell.setModifiable(false); + cell.setGiven(true); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("Sudoku Importer: unknown value where integer expected"); + sudokuBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + if (sudokuBoard.getCell(x, y) == null) { + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + sudokuBoard.setCell(x, y, cell); + } } - } + } + // + // for(int y = 0; y < size; y++) + // { + // for(int x = 0; x < size; x++) + // { + // SudokuCell cell = sudokuBoard.getCell(x, y); + // System.err.println("(" + x + ", " + y + ") - " + cell.getGroupIndex()); + // } + // } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Sudoku cannot accept text input"); + puzzle.setCurrentBoard(sudokuBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("Sudoku Importer: unknown value where integer expected"); } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Sudoku cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java index bb25c3e21..43939bbd4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java @@ -5,161 +5,165 @@ import edu.rpi.legup.ui.boardview.ElementView; import edu.rpi.legup.ui.boardview.GridBoardView; import edu.rpi.legup.ui.boardview.SelectionItemView; - -import javax.swing.*; import java.awt.*; import java.util.Set; +import javax.swing.*; public class SudokuView extends GridBoardView { - private static final Color STROKE_COLOR = new Color(0, 0, 0); - private static final Stroke MINOR_STOKE = new BasicStroke(1); - private static final Stroke MAJOR_STOKE = new BasicStroke(4); - - public SudokuView(SudokuBoard board) { - super(new BoardController(), new SudokuCellController(), board.getDimension()); - - int minorSize = (int) Math.sqrt(gridSize.width); - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - Point location = new Point(k * elementSize.width + (k / minorSize) * 4 + 5, - i * elementSize.height + (i / minorSize) * 4 + 5); - SudokuElementView element = new SudokuElementView(board.getCell(k, i)); - element.setIndex(i * gridSize.width + k); - element.setSize(elementSize); - element.setLocation(location); - elementViews.add(element); - } - } - + private static final Color STROKE_COLOR = new Color(0, 0, 0); + private static final Stroke MINOR_STOKE = new BasicStroke(1); + private static final Stroke MAJOR_STOKE = new BasicStroke(4); + + public SudokuView(SudokuBoard board) { + super(new BoardController(), new SudokuCellController(), board.getDimension()); + + int minorSize = (int) Math.sqrt(gridSize.width); + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + Point location = + new Point( + k * elementSize.width + (k / minorSize) * 4 + 5, + i * elementSize.height + (i / minorSize) * 4 + 5); + SudokuElementView element = new SudokuElementView(board.getCell(k, i)); + element.setIndex(i * gridSize.width + k); + element.setSize(elementSize); + element.setLocation(location); + elementViews.add(element); + } } - - /** - * Gets the SudokuElementView from the puzzleElement index or - * null if out of bounds - * - * @param index index of the ElementView - * @return SudokuElementView at the specified index - */ - @Override - public SudokuElementView getElement(int index) { - return (SudokuElementView) super.getElement(index); + } + + /** + * Gets the SudokuElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return SudokuElementView at the specified index + */ + @Override + public SudokuElementView getElement(int index) { + return (SudokuElementView) super.getElement(index); + } + + public void drawGrid(Graphics2D graphics2D) { + int minorSize = (int) Math.sqrt(gridSize.width); + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MAJOR_STOKE); + graphics2D.drawRect( + 3, + 3, + gridSize.width * (elementSize.width + 1) + 3, + gridSize.height * (elementSize.height + 1) + 3); + + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MAJOR_STOKE); + for (int i = 1; i < minorSize; i++) { + int x = i * minorSize * elementSize.width + i * ((minorSize + 1)) + 3; + graphics2D.drawLine(x, 3, x, gridSize.height * (elementSize.height + 1) + 6); } - - public void drawGrid(Graphics2D graphics2D) { - int minorSize = (int) Math.sqrt(gridSize.width); - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MAJOR_STOKE); - graphics2D.drawRect(3, 3, - gridSize.width * (elementSize.width + 1) + 3, - gridSize.height * (elementSize.height + 1) + 3); - - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MAJOR_STOKE); - for (int i = 1; i < minorSize; i++) { - int x = i * minorSize * elementSize.width + i * ((minorSize + 1)) + 3; - graphics2D.drawLine(x, 3, x, gridSize.height * (elementSize.height + 1) + 6); - } - for (int i = 1; i < minorSize; i++) { - int y = i * minorSize * elementSize.height + i * ((minorSize + 1)) + 3; - graphics2D.drawLine(3, y, gridSize.width * (elementSize.width + 1) + 6, y); - } + for (int i = 1; i < minorSize; i++) { + int y = i * minorSize * elementSize.height + i * ((minorSize + 1)) + 3; + graphics2D.drawLine(3, y, gridSize.width * (elementSize.width + 1) + 6, y); } + } - @Override - public void drawBoard(Graphics2D graphics2D) { - drawGrid(graphics2D); + @Override + public void drawBoard(Graphics2D graphics2D) { + drawGrid(graphics2D); - if (board instanceof PossibleNumberCaseBoard) { - drawCaseBoard(graphics2D); - return; - } - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MINOR_STOKE); - ElementView hover = null; - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - ElementView element = elementViews.get(i * gridSize.height + k); - if (!element.isHover()) { - element.draw(graphics2D); - } - else { - hover = element; - } - } - } - - if (hover != null) { - hover.draw(graphics2D); - } + if (board instanceof PossibleNumberCaseBoard) { + drawCaseBoard(graphics2D); + return; } - - public void drawCaseBoard(Graphics2D graphics2D) { - drawGrid(graphics2D); - - PossibleNumberCaseBoard caseBoard = (PossibleNumberCaseBoard) board; - SudokuBoard sudokuBoard = (SudokuBoard) caseBoard.getBaseBoard(); - - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MINOR_STOKE); - ElementView hover = null; - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - ElementView element = elementViews.get(i * gridSize.height + k); - if (!element.isHover()) { - element.draw(graphics2D); - } - else { - hover = element; - } - } + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MINOR_STOKE); + ElementView hover = null; + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + ElementView element = elementViews.get(i * gridSize.height + k); + if (!element.isHover()) { + element.draw(graphics2D); + } else { + hover = element; } + } + } - graphics2D.setColor(new Color(0x1A, 0x23, 0x7E, 200)); - for (int r : caseBoard.getPickableRegions()) { - Set region = sudokuBoard.getRegion(r); - int x = Integer.MAX_VALUE, y = Integer.MAX_VALUE, w = Integer.MIN_VALUE, h = Integer.MIN_VALUE; - for (SudokuCell c : region) { - x = Math.min(x, c.getLocation().x); - y = Math.min(y, c.getLocation().y); - w = Math.max(w, c.getLocation().x); - h = Math.max(h, c.getLocation().y); - } - - SudokuElementView firstElement = getElement(y * gridSize.width + x); - SudokuElementView lastElement = getElement(h * gridSize.width + w); - x = firstElement.getLocation().x; - y = firstElement.getLocation().y; - w = (lastElement.getLocation().x + elementSize.width) - x; - h = (lastElement.getLocation().y + elementSize.height) - y; - graphics2D.fillRect(x + 4, y + 4, w - 8, h - 8); + if (hover != null) { + hover.draw(graphics2D); + } + } + + public void drawCaseBoard(Graphics2D graphics2D) { + drawGrid(graphics2D); + + PossibleNumberCaseBoard caseBoard = (PossibleNumberCaseBoard) board; + SudokuBoard sudokuBoard = (SudokuBoard) caseBoard.getBaseBoard(); + + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MINOR_STOKE); + ElementView hover = null; + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + ElementView element = elementViews.get(i * gridSize.height + k); + if (!element.isHover()) { + element.draw(graphics2D); + } else { + hover = element; } - -// if(hover != null) -// hover.draw(graphics2D); + } } - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = gridSize.width * (elementSize.width + 1) + 9; - boardViewSize.height = gridSize.height * (elementSize.height + 1) + 9; - return boardViewSize; + graphics2D.setColor(new Color(0x1A, 0x23, 0x7E, 200)); + for (int r : caseBoard.getPickableRegions()) { + Set region = sudokuBoard.getRegion(r); + int x = Integer.MAX_VALUE, + y = Integer.MAX_VALUE, + w = Integer.MIN_VALUE, + h = Integer.MIN_VALUE; + for (SudokuCell c : region) { + x = Math.min(x, c.getLocation().x); + y = Math.min(y, c.getLocation().y); + w = Math.max(w, c.getLocation().x); + h = Math.max(h, c.getLocation().y); + } + + SudokuElementView firstElement = getElement(y * gridSize.width + x); + SudokuElementView lastElement = getElement(h * gridSize.width + w); + x = firstElement.getLocation().x; + y = firstElement.getLocation().y; + w = (lastElement.getLocation().x + elementSize.width) - x; + h = (lastElement.getLocation().y + elementSize.height) - y; + graphics2D.fillRect(x + 4, y + 4, w - 8, h - 8); } - public DataSelectionView getSelectionPopupMenu() { - DataSelectionView selectionView = new DataSelectionView(elementController); - GridLayout layout = new GridLayout(3, 3); - selectionView.setLayout(layout); - for (int r = 1; r <= 3; r++) { - for (int c = 1; c <= 3; c++) { - SudokuElementView element = new SudokuElementView(new SudokuCell((r - 1) * 3 + c, null, 0, gridSize.width)); - element.setSize(new Dimension(32, 32)); - element.setLocation(new Point(0, 0)); - SelectionItemView item = new SelectionItemView(element.getPuzzleElement(), new ImageIcon(element.getImage())); - item.addActionListener(elementController); - item.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item); - } - } - return selectionView; + // if(hover != null) + // hover.draw(graphics2D); + } + + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = gridSize.width * (elementSize.width + 1) + 9; + boardViewSize.height = gridSize.height * (elementSize.height + 1) + 9; + return boardViewSize; + } + + public DataSelectionView getSelectionPopupMenu() { + DataSelectionView selectionView = new DataSelectionView(elementController); + GridLayout layout = new GridLayout(3, 3); + selectionView.setLayout(layout); + for (int r = 1; r <= 3; r++) { + for (int c = 1; c <= 3; c++) { + SudokuElementView element = + new SudokuElementView(new SudokuCell((r - 1) * 3 + c, null, 0, gridSize.width)); + element.setSize(new Dimension(32, 32)); + element.setLocation(new Point(0, 0)); + SelectionItemView item = + new SelectionItemView(element.getPuzzleElement(), new ImageIcon(element.getImage())); + item.addActionListener(elementController); + item.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item); + } } + return selectionView; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java index e3159d87c..4a122dbcf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java @@ -3,26 +3,24 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class NumberTile extends PlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super("SUDO-PLAC-0001", "Number Tile", "A numbered tile", null); - object_num = 0; - } - - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } - - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + public NumberTile() { + super("SUDO-PLAC-0001", "Number Tile", "A numbered tile", null); + object_num = 0; + } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java index d3bca5d12..8db5163e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java @@ -10,87 +10,88 @@ public class AdvancedDeductionDirectRule extends DirectRule { - public AdvancedDeductionDirectRule() { - super("SUDO-BASC-0001", "Advanced Deduction", - "Use of group logic deduces more answers by means of forced by Location and forced by Deduction", - "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); - } + public AdvancedDeductionDirectRule() { + super( + "SUDO-BASC-0001", + "Advanced Deduction", + "Use of group logic deduces more answers by means of forced by Location and forced by Deduction", + "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - int index = cell.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int relX = rowIndex / groupDim; - int relY = colIndex % groupDim; - int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; - boolean[][] possible = new boolean[groupDim][groupDim]; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - SudokuCell c = initialBoard.getCell(groupNum, x, y); - if (c.getData() == cell.getData() && x != relX && y != relY) { - return super.getRuleName() + ": Duplicate value in sub-region"; - } - possible[y][x] = c.getData() == 0; - } + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + int index = cell.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int relX = rowIndex / groupDim; + int relY = colIndex % groupDim; + int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; + boolean[][] possible = new boolean[groupDim][groupDim]; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + SudokuCell c = initialBoard.getCell(groupNum, x, y); + if (c.getData() == cell.getData() && x != relX && y != relY) { + return super.getRuleName() + ": Duplicate value in sub-region"; } - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupSize; x++) { - SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); - SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); - if (r.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[y][i] = false; - } - } - if (c.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[i][y] = false; - } - } - } + possible[y][x] = c.getData() == 0; + } + } + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupSize; x++) { + SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); + SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); + if (r.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[y][i] = false; + } } - boolean isForced = false; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - if (possible[y][x] && !isForced) { - isForced = true; - } - else { - if (possible[y][x]) { - return super.getInvalidUseOfRuleMessage() + ": Not forced"; - } - } - } + if (c.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[i][y] = false; + } } - if (!isForced) { + } + } + boolean isForced = false; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + if (possible[y][x] && !isForced) { + isForced = true; + } else { + if (possible[y][x]) { return super.getInvalidUseOfRuleMessage() + ": Not forced"; + } } - return null; + } } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + if (!isForced) { + return super.getInvalidUseOfRuleMessage() + ": Not forced"; } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java index 501bfa86b..fe32fc450 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java @@ -7,87 +7,88 @@ import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.sudoku.SudokuBoard; import edu.rpi.legup.puzzle.sudoku.SudokuCell; - import java.util.Set; public class LastCellForNumberDirectRule extends DirectRule { - public LastCellForNumberDirectRule() { - super("SUDO-BASC-0002", "Last Cell for Number", - "This is the only cell open in its group for some number.", - "edu/rpi/legup/images/sudoku/forcedByElimination.png"); - } + public LastCellForNumberDirectRule() { + super( + "SUDO-BASC-0002", + "Last Cell for Number", + "This is the only cell open in its group for some number.", + "edu/rpi/legup/images/sudoku/forcedByElimination.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; - } + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } - int size = initialBoard.getSize(); + int size = initialBoard.getSize(); - Set region = initialBoard.getRegion(cell.getGroupIndex()); - Set row = initialBoard.getRow(cell.getLocation().y); - Set col = initialBoard.getCol(cell.getLocation().x); + Set region = initialBoard.getRegion(cell.getGroupIndex()); + Set row = initialBoard.getRow(cell.getLocation().y); + Set col = initialBoard.getCol(cell.getLocation().x); - boolean contains = false; - if (region.size() == size - 1) { - for (SudokuCell c : region) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } - } - if (row.size() == size - 1) { - contains = false; - for (SudokuCell c : row) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } + boolean contains = false; + if (region.size() == size - 1) { + for (SudokuCell c : region) { + if (cell.getData() == c.getData()) { + contains = true; + break; } - if (col.size() == size - 1) { - contains = false; - for (SudokuCell c : col) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } + } + if (!contains) { + return null; + } + } + if (row.size() == size - 1) { + contains = false; + for (SudokuCell c : row) { + if (cell.getData() == c.getData()) { + contains = true; + break; } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } + if (!contains) { + return null; + } } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + if (col.size() == size - 1) { + contains = false; + for (SudokuCell c : col) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { return null; + } } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java index 9a6834182..881df8455 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java @@ -7,71 +7,73 @@ import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.sudoku.SudokuBoard; import edu.rpi.legup.puzzle.sudoku.SudokuCell; - import java.util.HashSet; public class LastNumberForCellDirectRule extends DirectRule { - public LastNumberForCellDirectRule() { - super("SUDO-BASC-0003", "Last Number for Cell", - "This is the only number left that can fit in the cell of a group.", - "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); - } + public LastNumberForCellDirectRule() { + super( + "SUDO-BASC-0003", + "Last Number for Cell", + "This is the only number left that can fit in the cell of a group.", + "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - int index = puzzleElement.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; - HashSet numbers = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - numbers.add(i); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); - numbers.remove(cell.getData()); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(i, colIndex); - numbers.remove(cell.getData()); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(rowIndex, i); - numbers.remove(cell.getData()); - } - if (numbers.size() > 1) { - return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; - } - else { - if (numbers.size() == 1 && numbers.iterator().next() != finalBoard.getPuzzleElement(puzzleElement).getData()) { - return super.getInvalidUseOfRuleMessage() + ": The number at the index is forced but not correct"; - } - } - return null; + int index = puzzleElement.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; + HashSet numbers = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + numbers.add(i); } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); + numbers.remove(cell.getData()); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(i, colIndex); + numbers.remove(cell.getData()); } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(rowIndex, i); + numbers.remove(cell.getData()); + } + if (numbers.size() > 1) { + return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; + } else { + if (numbers.size() == 1 + && numbers.iterator().next() != finalBoard.getPuzzleElement(puzzleElement).getData()) { + return super.getInvalidUseOfRuleMessage() + + ": The number at the index is forced but not correct"; + } + } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java index fb87764fe..e87b77492 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java @@ -5,58 +5,60 @@ import edu.rpi.legup.model.rules.ContradictionRule; import edu.rpi.legup.puzzle.sudoku.SudokuBoard; import edu.rpi.legup.puzzle.sudoku.SudokuCell; - import java.util.HashSet; import java.util.Set; public class NoSolutionContradictionRule extends ContradictionRule { - public NoSolutionContradictionRule() { - super("SUDO-CONT-0001", "No Solution for Cell", - "Process of elimination yields no valid numbers for an empty cell.", - "edu/rpi/legup/images/sudoku/NoSolution.png"); + public NoSolutionContradictionRule() { + super( + "SUDO-CONT-0001", + "No Solution for Cell", + "Process of elimination yields no valid numbers for an empty cell.", + "edu/rpi/legup/images/sudoku/NoSolution.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); + if (cell.getData() != 0) { + return super.getNoContradictionMessage(); + } + + int groupSize = sudokuBoard.getSize(); + + Set region = sudokuBoard.getRegion(cell.getGroupIndex()); + Set row = sudokuBoard.getRow(cell.getLocation().y); + Set col = sudokuBoard.getCol(cell.getLocation().x); + Set solution = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + solution.add(i); } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); - if (cell.getData() != 0) { - return super.getNoContradictionMessage(); - } - - int groupSize = sudokuBoard.getSize(); - - Set region = sudokuBoard.getRegion(cell.getGroupIndex()); - Set row = sudokuBoard.getRow(cell.getLocation().y); - Set col = sudokuBoard.getCol(cell.getLocation().x); - Set solution = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - solution.add(i); - } - - for (SudokuCell c : region) { - solution.remove(c.getData()); - } - for (SudokuCell c : row) { - solution.remove(c.getData()); - } - for (SudokuCell c : col) { - solution.remove(c.getData()); - } - - if (solution.isEmpty()) { - return null; - } - - return super.getNoContradictionMessage(); + for (SudokuCell c : region) { + solution.remove(c.getData()); } + for (SudokuCell c : row) { + solution.remove(c.getData()); + } + for (SudokuCell c : col) { + solution.remove(c.getData()); + } + + if (solution.isEmpty()) { + return null; + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java index 373b60457..be1875c90 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java @@ -7,103 +7,104 @@ import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.sudoku.SudokuBoard; import edu.rpi.legup.puzzle.sudoku.SudokuCell; - import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class PossibleCellCaseRule extends CaseRule { - public PossibleCellCaseRule() { - super("SUDO-CASE-0001", "Possible Cells for Number", - "A number has a limited set of cells in which it can be placed.", - "edu/rpi/legup/images/sudoku/possible_cells_number.png"); - } + public PossibleCellCaseRule() { + super( + "SUDO-CASE-0001", + "Possible Cells for Number", + "A number has a limited set of cells in which it can be placed.", + "edu/rpi/legup/images/sudoku/possible_cells_number.png"); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - @Override - public CaseBoard getCaseBoard(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(sudokuBoard, this); - for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { - if (((SudokuCell) puzzleElement).getData() == 0) { - caseBoard.addPickableElement(puzzleElement); - } - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(sudokuBoard, this); + for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { + if (((SudokuCell) puzzleElement).getData() == 0) { + caseBoard.addPickableElement(puzzleElement); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) puzzleElement; - - Set possibleValue = new HashSet<>(); - for (int i = 1; i <= sudokuBoard.getSize(); i++) { - possibleValue.add(i); - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) puzzleElement; - int groupNum = cell.getGroupIndex(); - for (SudokuCell c : sudokuBoard.getRegion(groupNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + Set possibleValue = new HashSet<>(); + for (int i = 1; i <= sudokuBoard.getSize(); i++) { + possibleValue.add(i); + } - int rowNum = cell.getLocation().y; - for (SudokuCell c : sudokuBoard.getRegion(rowNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int groupNum = cell.getGroupIndex(); + for (SudokuCell c : sudokuBoard.getRegion(groupNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - int colNum = cell.getLocation().x; - for (SudokuCell c : sudokuBoard.getRegion(colNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int rowNum = cell.getLocation().y; + for (SudokuCell c : sudokuBoard.getRegion(rowNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - for (Integer i : possibleValue) { - SudokuBoard newCase = sudokuBoard.copy(); + int colNum = cell.getLocation().x; + for (SudokuCell c : sudokuBoard.getRegion(colNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - PuzzleElement newCasePuzzleElement = newCase.getPuzzleElement(puzzleElement); - newCasePuzzleElement.setData(i); - newCase.addModifiedData(newCasePuzzleElement); - cases.add(newCase); - } + for (Integer i : possibleValue) { + SudokuBoard newCase = sudokuBoard.copy(); - return cases; + PuzzleElement newCasePuzzleElement = newCase.getPuzzleElement(puzzleElement); + newCasePuzzleElement.setData(i); + newCase.addModifiedData(newCasePuzzleElement); + cases.add(newCase); } + + return cases; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java index 27d6b58b7..f638fbbb6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java @@ -9,123 +9,123 @@ import edu.rpi.legup.puzzle.sudoku.PossibleNumberCaseBoard; import edu.rpi.legup.puzzle.sudoku.SudokuBoard; import edu.rpi.legup.puzzle.sudoku.SudokuCell; - import java.util.ArrayList; import java.util.List; import java.util.Set; public class PossibleNumberCaseRule extends CaseRule { - public PossibleNumberCaseRule() { - super("SUDO-CASE-0002", "Possible Numbers for Cell", - "An empty cell has a limited set of possible numbers that can fill it.", - "edu/rpi/legup/images/sudoku/PossibleValues.png"); - } + public PossibleNumberCaseRule() { + super( + "SUDO-CASE-0002", + "Possible Numbers for Cell", + "An empty cell has a limited set of possible numbers that can fill it.", + "edu/rpi/legup/images/sudoku/PossibleValues.png"); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - @Override - public CaseBoard getCaseBoard(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - PossibleNumberCaseBoard caseBoard = new PossibleNumberCaseBoard(sudokuBoard, this, null); - for (int i = 0; i < sudokuBoard.getSize(); i++) { - caseBoard.addPickableRegion(i); - caseBoard.addPickableRow(i); - caseBoard.addPickableCol(i); - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + PossibleNumberCaseBoard caseBoard = new PossibleNumberCaseBoard(sudokuBoard, this, null); + for (int i = 0; i < sudokuBoard.getSize(); i++) { + caseBoard.addPickableRegion(i); + caseBoard.addPickableRow(i); + caseBoard.addPickableCol(i); } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - return getCases(board, puzzleElement, 1, GroupType.REGION); - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + return getCases(board, puzzleElement, 1, GroupType.REGION); + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @param value value that the rule will be applied from - * @param groupType group type - * @return a list of elements the specified could be - */ - public ArrayList getCases(Board board, PuzzleElement puzzleElement, int value, GroupType groupType) { - ArrayList cases = new ArrayList<>(); - SudokuBoard sudokuBoard = (SudokuBoard) board; - List caseCells = new ArrayList<>(); - SudokuCell cell = (SudokuCell) puzzleElement; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @param value value that the rule will be applied from + * @param groupType group type + * @return a list of elements the specified could be + */ + public ArrayList getCases( + Board board, PuzzleElement puzzleElement, int value, GroupType groupType) { + ArrayList cases = new ArrayList<>(); + SudokuBoard sudokuBoard = (SudokuBoard) board; + List caseCells = new ArrayList<>(); + SudokuCell cell = (SudokuCell) puzzleElement; - Set group; - if (groupType == GroupType.REGION) { - group = sudokuBoard.getRegion(cell.getGroupIndex()); - } - else { - if (groupType == GroupType.ROW) { - group = sudokuBoard.getRow(cell.getLocation().y); - } - else { - group = sudokuBoard.getCol(cell.getLocation().x); - } - } + Set group; + if (groupType == GroupType.REGION) { + group = sudokuBoard.getRegion(cell.getGroupIndex()); + } else { + if (groupType == GroupType.ROW) { + group = sudokuBoard.getRow(cell.getLocation().y); + } else { + group = sudokuBoard.getCol(cell.getLocation().x); + } + } - for (SudokuCell c : group) { - if (c.getData() == 0) { - Set blockableCells = sudokuBoard.getRegion(c.getGroupIndex()); - blockableCells.addAll(sudokuBoard.getRow(c.getLocation().y)); - blockableCells.addAll(sudokuBoard.getCol(c.getLocation().x)); + for (SudokuCell c : group) { + if (c.getData() == 0) { + Set blockableCells = sudokuBoard.getRegion(c.getGroupIndex()); + blockableCells.addAll(sudokuBoard.getRow(c.getLocation().y)); + blockableCells.addAll(sudokuBoard.getCol(c.getLocation().x)); - boolean repeat = false; - for (SudokuCell bc : blockableCells) { - if (bc.getData() == value) { - repeat = true; - break; - } - } - if (!repeat) { - caseCells.add(c); - } - } + boolean repeat = false; + for (SudokuCell bc : blockableCells) { + if (bc.getData() == value) { + repeat = true; + break; + } } - - for (SudokuCell c : caseCells) { - Board newCase = sudokuBoard.copy(); - PuzzleElement element = newCase.getPuzzleElement(c); - element.setData(value); - newCase.addModifiedData(element); - cases.add(newCase); + if (!repeat) { + caseCells.add(c); } + } + } - return cases; + for (SudokuCell c : caseCells) { + Board newCase = sudokuBoard.copy(); + PuzzleElement element = newCase.getPuzzleElement(c); + element.setData(value); + newCase.addModifiedData(element); + cases.add(newCase); } + + return cases; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java index 4a5cc2074..cf0bfa600 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java @@ -5,63 +5,65 @@ import edu.rpi.legup.model.rules.ContradictionRule; import edu.rpi.legup.puzzle.sudoku.SudokuBoard; import edu.rpi.legup.puzzle.sudoku.SudokuCell; - import java.util.HashSet; import java.util.Set; public class RepeatedNumberContradictionRule extends ContradictionRule { - public RepeatedNumberContradictionRule() { - super("SUDO-CONT-0002", "Repeated Numbers", - "Two identical numbers are placed in the same group.", - "edu/rpi/legup/images/sudoku/RepeatedNumber.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getNoContradictionMessage(); - } + public RepeatedNumberContradictionRule() { + super( + "SUDO-CONT-0002", + "Repeated Numbers", + "Two identical numbers are placed in the same group.", + "edu/rpi/legup/images/sudoku/RepeatedNumber.png"); + } - Set region = sudokuBoard.getRegion(cell.getGroupIndex()); - Set row = sudokuBoard.getRow(cell.getLocation().y); - Set col = sudokuBoard.getCol(cell.getLocation().x); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getNoContradictionMessage(); + } - Set regionDup = new HashSet<>(); - Set rowDup = new HashSet<>(); - Set colDup = new HashSet<>(); + Set region = sudokuBoard.getRegion(cell.getGroupIndex()); + Set row = sudokuBoard.getRow(cell.getLocation().y); + Set col = sudokuBoard.getCol(cell.getLocation().x); - for (SudokuCell c : region) { - if (regionDup.contains(c.getData())) { - return null; - } - regionDup.add(c.getData()); - } + Set regionDup = new HashSet<>(); + Set rowDup = new HashSet<>(); + Set colDup = new HashSet<>(); - for (SudokuCell c : row) { - if (rowDup.contains(c.getData())) { - return null; - } - rowDup.add(c.getData()); - } + for (SudokuCell c : region) { + if (regionDup.contains(c.getData())) { + return null; + } + regionDup.add(c.getData()); + } - for (SudokuCell c : col) { - if (colDup.contains(c.getData())) { - return null; - } - colDup.add(c.getData()); - } + for (SudokuCell c : row) { + if (rowDup.contains(c.getData())) { + return null; + } + rowDup.add(c.getData()); + } - return super.getNoContradictionMessage(); + for (SudokuCell c : col) { + if (colDup.contains(c.getData())) { + return null; + } + colDup.add(c.getData()); } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java b/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java index 30af5af51..fa66fcb1b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java @@ -1,5 +1,7 @@ package edu.rpi.legup.puzzle.treetent; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.history.CommandError; import edu.rpi.legup.history.PuzzleCommand; import edu.rpi.legup.model.Puzzle; @@ -7,181 +9,175 @@ import edu.rpi.legup.ui.proofeditorui.treeview.TreeElementView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class ClueCommand extends PuzzleCommand { - private TreeViewSelection selection; - private TreeTentClueView clueView; - private Map addTran; - private List> emptyCells; - - public ClueCommand(TreeViewSelection selection, TreeTentClueView clueView) { - this.selection = selection; - this.clueView = clueView; - this.addTran = new HashMap<>(); - this.emptyCells = new ArrayList<>(); - } - - /** - * Executes a command - */ - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - - final TreeViewSelection newSelection = new TreeViewSelection(); - for (int i = 0; i < selection.getSelectedViews().size(); i++) { - TreeElementView selectedView = selection.getSelectedViews().get(i); - TreeElement treeElement = selectedView.getTreeElement(); - - final TreeTransition finalTran; - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - List tempList = emptyCells.get(i); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - TreeTransition transition = addTran.get(treeNode); - if (transition == null) { - transition = tree.addNewTransition(treeNode); - addTran.put(treeNode, transition); - } - else { - treeNode.addChild(transition); - } - - finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(finalTran)); - board = (TreeTentBoard) finalTran.getBoard(); - } - else { - finalTran = (TreeTransition) treeElement; - newSelection.addToSelection(treeView.getElementView(treeElement)); - } - - for (TreeTentCell cell : tempList) { - cell = (TreeTentCell) board.getPuzzleElement(cell); - cell.setData(TreeTentType.GRASS); - board.addModifiedData(cell); - finalTran.propagateChange(cell); - - final TreeTentCell finalCell = cell; - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); - } - if (i == 0) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); - } + private TreeViewSelection selection; + private TreeTentClueView clueView; + private Map addTran; + private List> emptyCells; + + public ClueCommand(TreeViewSelection selection, TreeTentClueView clueView) { + this.selection = selection; + this.clueView = clueView; + this.addTran = new HashMap<>(); + this.emptyCells = new ArrayList<>(); + } + + /** Executes a command */ + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + + final TreeViewSelection newSelection = new TreeViewSelection(); + for (int i = 0; i < selection.getSelectedViews().size(); i++) { + TreeElementView selectedView = selection.getSelectedViews().get(i); + TreeElement treeElement = selectedView.getTreeElement(); + + final TreeTransition finalTran; + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + List tempList = emptyCells.get(i); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + TreeTransition transition = addTran.get(treeNode); + if (transition == null) { + transition = tree.addNewTransition(treeNode); + addTran.put(treeNode, transition); + } else { + treeNode.addChild(transition); } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + + finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(finalTran)); + board = (TreeTentBoard) finalTran.getBoard(); + } else { + finalTran = (TreeTransition) treeElement; + newSelection.addToSelection(treeView.getElementView(treeElement)); + } + + for (TreeTentCell cell : tempList) { + cell = (TreeTentCell) board.getPuzzleElement(cell); + cell.setData(TreeTentType.GRASS); + board.addModifiedData(cell); + finalTran.propagateChange(cell); + + final TreeTentCell finalCell = cell; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); + } + if (i == 0) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); + } + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + if (selection.getSelectedViews().isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - if (selection.getSelectedViews().isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + emptyCells.clear(); + for (TreeElementView view : selection.getSelectedViews()) { + TreeElement treeElement = view.getTreeElement(); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) treeElement; + if (!node.getChildren().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); } - - emptyCells.clear(); - for (TreeElementView view : selection.getSelectedViews()) { - TreeElement treeElement = view.getTreeElement(); - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) treeElement; - if (!node.getChildren().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - else { - if (!board.isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - - List tempList = new ArrayList<>(); - TreeTentClue clue = clueView.getPuzzleElement(); - if (clue.getType() == TreeTentType.CLUE_NORTH || clue.getType() == TreeTentType.CLUE_SOUTH) { - int col = clue.getType() == TreeTentType.CLUE_NORTH ? clue.getClueIndex() : clue.getClueIndex() - 1; - for (int i = 0; i < board.getWidth(); i++) { - TreeTentCell cell = board.getCell(col, i); - if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { - tempList.add(cell); - } - } - } - else { - int row = clue.getType() == TreeTentType.CLUE_WEST ? clue.getClueIndex() : clue.getClueIndex() - 1; - for (int i = 0; i < board.getWidth(); i++) { - TreeTentCell cell = board.getCell(i, row); - if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { - tempList.add(cell); - } - } - } - if (tempList.isEmpty()) { - return "There are no modifiable unknown cells in every selected tree element."; - } - emptyCells.add(tempList); + } else { + if (!board.isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); } - return null; - } - - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - - for (int i = 0; i < selection.getSelectedViews().size(); i++) { - TreeElementView selectedView = selection.getSelectedViews().get(i); - TreeElement treeElement = selectedView.getTreeElement(); - - final TreeTransition finalTran; - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - List tempList = emptyCells.get(i); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - finalTran = treeNode.getChildren().get(0); - tree.removeTreeElement(finalTran); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); - - board = (TreeTentBoard) finalTran.getBoard(); - } - else { - finalTran = (TreeTransition) treeElement; - } - - for (TreeTentCell cell : tempList) { - cell = (TreeTentCell) board.getPuzzleElement(cell); - cell.setData(TreeTentType.UNKNOWN); - board.removeModifiedData(cell); - - final TreeTentCell finalCell = cell; - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); - } - - if (i == 0) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); - } + } + + List tempList = new ArrayList<>(); + TreeTentClue clue = clueView.getPuzzleElement(); + if (clue.getType() == TreeTentType.CLUE_NORTH || clue.getType() == TreeTentType.CLUE_SOUTH) { + int col = + clue.getType() == TreeTentType.CLUE_NORTH + ? clue.getClueIndex() + : clue.getClueIndex() - 1; + for (int i = 0; i < board.getWidth(); i++) { + TreeTentCell cell = board.getCell(col, i); + if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { + tempList.add(cell); + } + } + } else { + int row = + clue.getType() == TreeTentType.CLUE_WEST + ? clue.getClueIndex() + : clue.getClueIndex() - 1; + for (int i = 0; i < board.getWidth(); i++) { + TreeTentCell cell = board.getCell(i, row); + if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { + tempList.add(cell); + } } - final TreeViewSelection newSelection = selection; - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + if (tempList.isEmpty()) { + return "There are no modifiable unknown cells in every selected tree element."; + } + emptyCells.add(tempList); + } + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + + for (int i = 0; i < selection.getSelectedViews().size(); i++) { + TreeElementView selectedView = selection.getSelectedViews().get(i); + TreeElement treeElement = selectedView.getTreeElement(); + + final TreeTransition finalTran; + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + List tempList = emptyCells.get(i); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + finalTran = treeNode.getChildren().get(0); + tree.removeTreeElement(finalTran); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); + + board = (TreeTentBoard) finalTran.getBoard(); + } else { + finalTran = (TreeTransition) treeElement; + } + + for (TreeTentCell cell : tempList) { + cell = (TreeTentCell) board.getPuzzleElement(cell); + cell.setData(TreeTentType.UNKNOWN); + board.removeModifiedData(cell); + + final TreeTentCell finalCell = cell; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); + } + + if (i == 0) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); + } } + final TreeViewSelection newSelection = selection; + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java b/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java index d2f8575f1..4420d791e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java @@ -1,5 +1,7 @@ package edu.rpi.legup.puzzle.treetent; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.history.CommandError; import edu.rpi.legup.history.PuzzleCommand; import edu.rpi.legup.model.Puzzle; @@ -8,227 +10,216 @@ import edu.rpi.legup.ui.proofeditorui.treeview.TreeElementView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; - import java.awt.*; import java.util.List; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class EditLineCommand extends PuzzleCommand { - private TreeTentElementView start; - private TreeTentElementView end; - - private TreeViewSelection selection; - - public EditLineCommand(TreeViewSelection selection, TreeTentElementView start, ElementView endDrag) { - this.selection = selection; - this.start = start; - this.end = getViewInDirection(endDrag); + private TreeTentElementView start; + private TreeTentElementView end; + + private TreeViewSelection selection; + + public EditLineCommand( + TreeViewSelection selection, TreeTentElementView start, ElementView endDrag) { + this.selection = selection; + this.start = start; + this.end = getViewInDirection(endDrag); + } + + /** Executes a command */ + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + TreeTentCell startCell; + TreeTentCell endCell; + + final TreeTransition transition; + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + transition = tree.addNewTransition(treeNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + + board = (TreeTentBoard) transition.getBoard(); + } else { + transition = (TreeTransition) treeElement; } - /** - * Executes a command - */ - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - TreeTentCell startCell; - TreeTentCell endCell; - - final TreeTransition transition; - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - transition = tree.addNewTransition(treeNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - - board = (TreeTentBoard) transition.getBoard(); - } - else { - transition = (TreeTransition) treeElement; - } - - startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); - endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); + endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); - TreeTentLine line = new TreeTentLine(startCell, endCell); + TreeTentLine line = new TreeTentLine(startCell, endCell); - TreeTentLine dupLine = null; - for (TreeTentLine l : board.getLines()) { - if (line.compare(l)) { - dupLine = l; - break; - } - } - - final TreeTentLine notifyLine; - if (dupLine == null) { - board.addModifiedData(line); - board.getLines().add(line); - notifyLine = line; - transition.propagateAddition(notifyLine); - } - else { - board.removeModifiedData(dupLine); - board.getLines().remove(dupLine); - notifyLine = dupLine; - transition.propagateDeletion(notifyLine); - } - - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); - - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(transition)); - - final TreeViewSelection newSelection = new TreeViewSelection(treeView.getElementView(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + TreeTentLine dupLine = null; + for (TreeTentLine l : board.getLines()) { + if (line.compare(l)) { + dupLine = l; + break; + } } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); - } - - if (start == null || end == null) { - return "The line must connect a tree to a tent."; - } - - TreeElementView view = selection.getFirstSelection(); - TreeElement treeElement = view.getTreeElement(); - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) treeElement; - if (!node.getChildren().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - else { - if (!board.isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - TreeTentLine line = new TreeTentLine((TreeTentCell) start.getPuzzleElement(), (TreeTentCell) end.getPuzzleElement()); - for (TreeTentLine l : board.getLines()) { - if (line.compare(l) && !l.isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); - } - } - - TreeTentCell startCell = (TreeTentCell) start.getPuzzleElement(); - TreeTentCell endCell = (TreeTentCell) end.getPuzzleElement(); - if (!((startCell.getType() == TreeTentType.TENT && endCell.getType() == TreeTentType.TREE) || - (endCell.getType() == TreeTentType.TENT && startCell.getType() == TreeTentType.TREE))) { - return "The line must connect a tree to a tent."; - } + final TreeTentLine notifyLine; + if (dupLine == null) { + board.addModifiedData(line); + board.getLines().add(line); + notifyLine = line; + transition.propagateAddition(notifyLine); + } else { + board.removeModifiedData(dupLine); + board.getLines().remove(dupLine); + notifyLine = dupLine; + transition.propagateDeletion(notifyLine); + } - return null; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(transition)); + + final TreeViewSelection newSelection = + new TreeViewSelection(treeView.getElementView(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); } - /** - * Undoes an command - */ - @Override - public void undoCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - TreeTentCell startCell; - TreeTentCell endCell; - TreeTransition transition; - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - transition = treeNode.getChildren().get(0); - - tree.removeTreeElement(transition); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - - board = (TreeTentBoard) transition.getBoard(); - } - else { - transition = (TreeTransition) treeElement; - } + if (start == null || end == null) { + return "The line must connect a tree to a tent."; + } - startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); - endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + TreeElementView view = selection.getFirstSelection(); + TreeElement treeElement = view.getTreeElement(); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) treeElement; + if (!node.getChildren().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } else { + if (!board.isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } + TreeTentLine line = + new TreeTentLine( + (TreeTentCell) start.getPuzzleElement(), (TreeTentCell) end.getPuzzleElement()); + for (TreeTentLine l : board.getLines()) { + if (line.compare(l) && !l.isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); + } + } - TreeTentLine line = new TreeTentLine(startCell, endCell); + TreeTentCell startCell = (TreeTentCell) start.getPuzzleElement(); + TreeTentCell endCell = (TreeTentCell) end.getPuzzleElement(); + if (!((startCell.getType() == TreeTentType.TENT && endCell.getType() == TreeTentType.TREE) + || (endCell.getType() == TreeTentType.TENT && startCell.getType() == TreeTentType.TREE))) { + return "The line must connect a tree to a tent."; + } - TreeTentLine dupLine = null; - for (TreeTentLine l : board.getLines()) { - if (line.compare(l)) { - dupLine = l; - break; - } - } + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + TreeTentCell startCell; + TreeTentCell endCell; + TreeTransition transition; + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + transition = treeNode.getChildren().get(0); + + tree.removeTreeElement(transition); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + + board = (TreeTentBoard) transition.getBoard(); + } else { + transition = (TreeTransition) treeElement; + } - final TreeTentLine notifyLine; - if (dupLine == null) { - board.addModifiedData(line); - board.getLines().add(line); - notifyLine = line; - } - else { - board.removeModifiedData(dupLine); - board.getLines().remove(dupLine); - notifyLine = dupLine; - } - transition.propagateChange(notifyLine); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); + endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + TreeTentLine line = new TreeTentLine(startCell, endCell); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + TreeTentLine dupLine = null; + for (TreeTentLine l : board.getLines()) { + if (line.compare(l)) { + dupLine = l; + break; + } } - private TreeTentElementView getViewInDirection(ElementView endDrag) { - TreeTentView boardView = (TreeTentView) getInstance().getLegupUI().getBoardView(); - Dimension size = boardView.getElementSize(); - int xIndex, yIndex; - - Point startLoc = start.getLocation(); - Point endLoc = endDrag.getLocation(); - double radians = Math.atan2(startLoc.y - endLoc.y, endLoc.x - startLoc.x); - if (radians >= Math.PI / 4 && radians < 3 * Math.PI / 4) { - //up - xIndex = startLoc.x / size.width; - yIndex = (startLoc.y / size.height) - 1; - } - else { - if (radians >= -Math.PI / 4 && radians < Math.PI / 4) { - //right - xIndex = (startLoc.x / size.width) + 1; - yIndex = startLoc.y / size.height; - } - else { - if (radians >= -3 * Math.PI / 4 && radians < -Math.PI / 4) { - //down - xIndex = startLoc.x / size.width; - yIndex = (startLoc.y / size.height) + 1; - } - else { - //left - xIndex = (startLoc.x / size.width) - 1; - yIndex = startLoc.y / size.height; - } - } - } - return (TreeTentElementView) boardView.getElement(xIndex - 1, yIndex - 1); + final TreeTentLine notifyLine; + if (dupLine == null) { + board.addModifiedData(line); + board.getLines().add(line); + notifyLine = line; + } else { + board.removeModifiedData(dupLine); + board.getLines().remove(dupLine); + notifyLine = dupLine; + } + transition.propagateChange(notifyLine); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } + + private TreeTentElementView getViewInDirection(ElementView endDrag) { + TreeTentView boardView = (TreeTentView) getInstance().getLegupUI().getBoardView(); + Dimension size = boardView.getElementSize(); + int xIndex, yIndex; + + Point startLoc = start.getLocation(); + Point endLoc = endDrag.getLocation(); + double radians = Math.atan2(startLoc.y - endLoc.y, endLoc.x - startLoc.x); + if (radians >= Math.PI / 4 && radians < 3 * Math.PI / 4) { + // up + xIndex = startLoc.x / size.width; + yIndex = (startLoc.y / size.height) - 1; + } else { + if (radians >= -Math.PI / 4 && radians < Math.PI / 4) { + // right + xIndex = (startLoc.x / size.width) + 1; + yIndex = startLoc.y / size.height; + } else { + if (radians >= -3 * Math.PI / 4 && radians < -Math.PI / 4) { + // down + xIndex = startLoc.x / size.width; + yIndex = (startLoc.y / size.height) + 1; + } else { + // left + xIndex = (startLoc.x / size.width) - 1; + yIndex = startLoc.y / size.height; + } + } } + return (TreeTentElementView) boardView.getElement(xIndex - 1, yIndex - 1); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java index 172584cd0..94381b031 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java @@ -3,92 +3,86 @@ import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.util.List; public class TreeTent extends Puzzle { - public TreeTent() { - super(); - - this.name = "TreeTent"; + public TreeTent() { + super(); - this.importer = new TreeTentImporter(this); - this.exporter = new TreeTentExporter(this); + this.name = "TreeTent"; - this.factory = new TreeTentCellFactory(); - } + this.importer = new TreeTentImporter(this); + this.exporter = new TreeTentExporter(this); - /** - * Initializes the game board. Called by the invoker of the class - */ - @Override - public void initializeView() { - TreeTentBoard board = (TreeTentBoard) currentBoard; - boardView = new TreeTentView((TreeTentBoard) currentBoard); - boardView.setBoard(board); - } + this.factory = new TreeTentCellFactory(); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + TreeTentBoard board = (TreeTentBoard) currentBoard; + boardView = new TreeTentView((TreeTentBoard) currentBoard); + boardView.setBoard(board); + } - @Override - /** - * Determines if the given dimensions are valid for Tree Tent - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Tree Tent, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - return rows > 0 && columns > 0; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + @Override + /** + * Determines if the given dimensions are valid for Tree Tent + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Tree Tent, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + return rows > 0 && columns > 0; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) { + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - } + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} - /** - * @return if it is valid - * TreeTent puzzle must have same number of clues as the dimension size - */ - @Override - public boolean checkValidity() { - TreeTentBoard b = (TreeTentBoard) this.getBoardView().getBoard(); - List elements = b.getPuzzleElements(); - int treeCount = 0; - for (PuzzleElement element : elements) { - TreeTentCell c = (TreeTentCell) element; - if (c.getType() == TreeTentType.TREE) { - treeCount++; - } - } - return treeCount != 0; + /** + * @return if it is valid TreeTent puzzle must have same number of clues as the dimension size + */ + @Override + public boolean checkValidity() { + TreeTentBoard b = (TreeTentBoard) this.getBoardView().getBoard(); + List elements = b.getPuzzleElements(); + int treeCount = 0; + for (PuzzleElement element : elements) { + TreeTentCell c = (TreeTentCell) element; + if (c.getType() == TreeTentType.TREE) { + treeCount++; + } } + return treeCount != 0; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java index dc809f34d..ac1dcca38 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java @@ -3,240 +3,240 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.GridBoard; import edu.rpi.legup.model.gameboard.PuzzleElement; - import java.awt.*; import java.util.ArrayList; import java.util.List; public class TreeTentBoard extends GridBoard { - private ArrayList lines; + private ArrayList lines; - private ArrayList rowClues; - private ArrayList colClues; + private ArrayList rowClues; + private ArrayList colClues; - public TreeTentBoard(int width, int height) { - super(width, height); + public TreeTentBoard(int width, int height) { + super(width, height); - this.lines = new ArrayList<>(); + this.lines = new ArrayList<>(); - this.rowClues = new ArrayList<>(); - this.colClues = new ArrayList<>(); + this.rowClues = new ArrayList<>(); + this.colClues = new ArrayList<>(); - for (int i = 0; i < height; i++) { - rowClues.add(null); - } - for (int i = 0; i < width; i++) { - colClues.add(null); - } + for (int i = 0; i < height; i++) { + rowClues.add(null); } - - public TreeTentBoard(int size) { - this(size, size); + for (int i = 0; i < width; i++) { + colClues.add(null); } - - public ArrayList getLines() { - return lines; + } + + public TreeTentBoard(int size) { + this(size, size); + } + + public ArrayList getLines() { + return lines; + } + + public ArrayList getRowClues() { + return rowClues; + } + + public ArrayList getColClues() { + return colClues; + } + + @Override + public TreeTentCell getCell(int x, int y) { + return (TreeTentCell) super.getCell(x, y); + } + + @Override + public PuzzleElement getPuzzleElement(PuzzleElement element) { + switch (element.getIndex()) { + case -2: + return element; + case -1: + TreeTentLine line = (TreeTentLine) element; + TreeTentLine thisLine = null; + for (TreeTentLine l : lines) { + if (line.compare(l)) { + thisLine = l; + break; + } + } + return thisLine; + default: + return super.getPuzzleElement(element); } - - public ArrayList getRowClues() { - return rowClues; + } + + public TreeTentClue getClue(int x, int y) { + if (x == getWidth() && 0 <= y && y < getHeight()) { + return rowClues.get(y); + } else { + if (y == getHeight() && 0 <= x && x < getWidth()) { + return colClues.get(x); + } } - - public ArrayList getColClues() { - return colClues; + return null; + } + + /** + * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element + * with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + @Override + public void notifyAddition(PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + lines.add((TreeTentLine) puzzleElement); } - - @Override - public TreeTentCell getCell(int x, int y) { - return (TreeTentCell) super.getCell(x, y); + } + + /** + * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + @Override + public void notifyDeletion(PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + for (TreeTentLine line : lines) { + if (line.compare((TreeTentLine) puzzleElement)) { + lines.remove(line); + break; + } + } } - - @Override - public PuzzleElement getPuzzleElement(PuzzleElement element) { - switch (element.getIndex()) { - case -2: - return element; - case -1: - TreeTentLine line = (TreeTentLine) element; - TreeTentLine thisLine = null; - for (TreeTentLine l : lines) { - if (line.compare(l)) { - thisLine = l; - break; - } - } - return thisLine; - default: - return super.getPuzzleElement(element); - } + } + + /** + * Get a list of all orthogonally adjacent cells. + * + * @param cell The cell to get adjacent cells from. + * @param type The cell types to get. + * @return List of adjacent cells in the form { up, right, down, left }. If an adjacent cell is + * null, it will not be added to the list. + */ + public List getAdjacent(TreeTentCell cell, TreeTentType type) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + for (int i = -2; i < 2; i++) { + TreeTentCell adjCell = getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); + if (adjCell != null && adjCell.getType() == type) { + adj.add(adjCell); + } } - - public TreeTentClue getClue(int x, int y) { - if (x == getWidth() && 0 <= y && y < getHeight()) { - return rowClues.get(y); - } - else { - if (y == getHeight() && 0 <= x && x < getWidth()) { - return colClues.get(x); - } - } - return null; - } - - /** - * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - @Override - public void notifyAddition(PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - lines.add((TreeTentLine) puzzleElement); - } + return adj; + } + + /** + * Gets all cells of a specified type that are diagonals of a specified cell + * + * @param cell the base cell + * @param type the type to look for + * @return a list of TreeTentCells that are diagonals of the given TreeTentCell and are of the + * given TreeTentType + */ + public List getDiagonals(TreeTentCell cell, TreeTentType type) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + TreeTentCell upRight = getCell(loc.x + 1, loc.y - 1); + TreeTentCell downRight = getCell(loc.x + 1, loc.y + 1); + TreeTentCell downLeft = getCell(loc.x - 1, loc.y + 1); + TreeTentCell upLeft = getCell(loc.x - 1, loc.y - 1); + if (upRight != null && upRight.getType() == type) { + dia.add(upRight); } - - /** - * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - @Override - public void notifyDeletion(PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - for (TreeTentLine line : lines) { - if (line.compare((TreeTentLine) puzzleElement)) { - lines.remove(line); - break; - } - } - } + if (downLeft != null && downLeft.getType() == type) { + dia.add(downLeft); } - - /** - * Get a list of all orthogonally adjacent cells. - * - * @param cell The cell to get adjacent cells from. - * @param type The cell types to get. - * @return List of adjacent cells in the form { up, right, down, left }. - * If an adjacent cell is null, it will not be added to the list. - */ - public List getAdjacent(TreeTentCell cell, TreeTentType type) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - for (int i = -2; i < 2; i++) { - TreeTentCell adjCell = getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); - if (adjCell != null && adjCell.getType() == type) { - adj.add(adjCell); - } - } - return adj; - } - - /** - * Gets all cells of a specified type that are diagonals of a specified cell - * - * @param cell the base cell - * @param type the type to look for - * @return a list of TreeTentCells that are diagonals of the given TreeTentCell and are of the given TreeTentType - */ - public List getDiagonals(TreeTentCell cell, TreeTentType type) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - TreeTentCell upRight = getCell(loc.x + 1, loc.y - 1); - TreeTentCell downRight = getCell(loc.x + 1, loc.y + 1); - TreeTentCell downLeft = getCell(loc.x - 1, loc.y + 1); - TreeTentCell upLeft = getCell(loc.x - 1, loc.y - 1); - if (upRight != null && upRight.getType() == type) { - dia.add(upRight); - } - if (downLeft != null && downLeft.getType() == type) { - dia.add(downLeft); - } - if (downRight != null && downRight.getType() == type) { - dia.add(downRight); - } - if (upLeft != null && upLeft.getType() == type) { - dia.add(upLeft); - } - return dia; - } - - /** - * Creates and returns a list of TreeTentCells that match the given TreeTentType - * - * @param index the row or column number - * @param type type of TreeTent element - * @param isRow boolean value beased on whether a row of column is being checked - * @return List of TreeTentCells that match the given TreeTentType - */ - public List getRowCol(int index, TreeTentType type, boolean isRow) { - List list = new ArrayList<>(); - if (isRow) { - for (int i = 0; i < dimension.height; i++) { - TreeTentCell cell = getCell(i, index); - if (cell.getType() == type) { - list.add(cell); - } - } - } - else { - for (int i = 0; i < dimension.width; i++) { - TreeTentCell cell = getCell(index, i); - if (cell.getType() == type) { - list.add(cell); - } - } - } - return list; - } - - /** - * Determines if this board contains the equivalent puzzle elements as the one specified - * - * @param board board to check equivalence - * @return true if the boards are equivalent, false otherwise - */ - @Override - public boolean equalsBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - for (TreeTentLine l1 : lines) { - boolean hasLine = false; - for (TreeTentLine l2 : treeTentBoard.lines) { - if (l1.compare(l2)) { - hasLine = true; - } - } - if (!hasLine) { - return false; - } - } - return super.equalsBoard(treeTentBoard); - } - - /** - * Performs a deep copy of the TreeTentBoard - * - * @return a TreeTentBoard object that is a deep copy of the current TreeTentBoard - */ - @Override - public TreeTentBoard copy() { - TreeTentBoard copy = new TreeTentBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (TreeTentLine line : lines) { - TreeTentLine lineCpy = line.copy(); - lineCpy.setModifiable(false); - copy.getLines().add(lineCpy); - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.rowClues = rowClues; - copy.colClues = colClues; - return copy; + if (downRight != null && downRight.getType() == type) { + dia.add(downRight); + } + if (upLeft != null && upLeft.getType() == type) { + dia.add(upLeft); + } + return dia; + } + + /** + * Creates and returns a list of TreeTentCells that match the given TreeTentType + * + * @param index the row or column number + * @param type type of TreeTent element + * @param isRow boolean value beased on whether a row of column is being checked + * @return List of TreeTentCells that match the given TreeTentType + */ + public List getRowCol(int index, TreeTentType type, boolean isRow) { + List list = new ArrayList<>(); + if (isRow) { + for (int i = 0; i < dimension.height; i++) { + TreeTentCell cell = getCell(i, index); + if (cell.getType() == type) { + list.add(cell); + } + } + } else { + for (int i = 0; i < dimension.width; i++) { + TreeTentCell cell = getCell(index, i); + if (cell.getType() == type) { + list.add(cell); + } + } + } + return list; + } + + /** + * Determines if this board contains the equivalent puzzle elements as the one specified + * + * @param board board to check equivalence + * @return true if the boards are equivalent, false otherwise + */ + @Override + public boolean equalsBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + for (TreeTentLine l1 : lines) { + boolean hasLine = false; + for (TreeTentLine l2 : treeTentBoard.lines) { + if (l1.compare(l2)) { + hasLine = true; + } + } + if (!hasLine) { + return false; + } + } + return super.equalsBoard(treeTentBoard); + } + + /** + * Performs a deep copy of the TreeTentBoard + * + * @return a TreeTentBoard object that is a deep copy of the current TreeTentBoard + */ + @Override + public TreeTentBoard copy() { + TreeTentBoard copy = new TreeTentBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (TreeTentLine line : lines) { + TreeTentLine lineCpy = line.copy(); + lineCpy.setModifiable(false); + copy.getLines().add(lineCpy); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + copy.rowClues = rowClues; + copy.colClues = colClues; + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java index b6411a5cf..e19c8b3a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java @@ -2,56 +2,55 @@ import edu.rpi.legup.model.elements.Element; import edu.rpi.legup.model.gameboard.GridCell; - import java.awt.*; import java.awt.event.MouseEvent; public class TreeTentCell extends GridCell { - public TreeTentCell(TreeTentType value, Point location) { - super(value, location); - } - - public TreeTentType getType() { - return data; - } - - public int getValue() { - switch (data) { - case TREE: - return 1; - case GRASS: - return 2; - case TENT: - return 3; - default: - return 0; - } - } - - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementName()) { - case "Unknown Tile": - this.data = TreeTentType.UNKNOWN; - break; - case "Tree Tile": - this.data = TreeTentType.TREE; - break; - case "Grass Tile": - this.data = TreeTentType.GRASS; - break; - case "Tent Tile": - this.data = TreeTentType.TENT; - } + public TreeTentCell(TreeTentType value, Point location) { + super(value, location); + } + + public TreeTentType getType() { + return data; + } + + public int getValue() { + switch (data) { + case TREE: + return 1; + case GRASS: + return 2; + case TENT: + return 3; + default: + return 0; } - - @Override - public TreeTentCell copy() { - TreeTentCell copy = new TreeTentCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; + } + + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementName()) { + case "Unknown Tile": + this.data = TreeTentType.UNKNOWN; + break; + case "Tree Tile": + this.data = TreeTentType.TREE; + break; + case "Grass Tile": + this.data = TreeTentType.GRASS; + break; + case "Tent Tile": + this.data = TreeTentType.TENT; } + } + + @Override + public TreeTentCell copy() { + TreeTentCell copy = new TreeTentCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java index 20b8066a4..10bcf77c7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java @@ -4,102 +4,98 @@ import edu.rpi.legup.model.gameboard.ElementFactory; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import java.awt.*; - public class TreeTentCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - int width = treeTentBoard.getWidth(); - int height = treeTentBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - if (node.getNodeName().equalsIgnoreCase("cell")) { - - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("TreeTent Factory: cell location out of bounds"); - } - if (value < 0 || value > 3) { - throw new InvalidFileFormatException("TreeTent Factory: cell unknown value"); - } - - TreeTentCell cell = new TreeTentCell(TreeTentType.valueOf(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } - else { - if (node.getNodeName().equalsIgnoreCase("line")) { - int x1 = Integer.valueOf(attributeList.getNamedItem("x1").getNodeValue()); - int y1 = Integer.valueOf(attributeList.getNamedItem("y1").getNodeValue()); - int x2 = Integer.valueOf(attributeList.getNamedItem("x2").getNodeValue()); - int y2 = Integer.valueOf(attributeList.getNamedItem("y2").getNodeValue()); - if (x1 >= width || y1 >= height || x2 >= width || y2 >= height) { - throw new InvalidFileFormatException("TreeTent Factory: line location out of bounds"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { + try { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + int width = treeTentBoard.getWidth(); + int height = treeTentBoard.getHeight(); + NamedNodeMap attributeList = node.getAttributes(); + if (node.getNodeName().equalsIgnoreCase("cell")) { - TreeTentCell c1 = treeTentBoard.getCell(x1, y1); - TreeTentCell c2 = treeTentBoard.getCell(x2, y2); - return new TreeTentLine(c1, c2); - } - else { - throw new InvalidFileFormatException("TreeTent Factory: unknown puzzleElement puzzleElement"); - } - } + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("TreeTent Factory: cell location out of bounds"); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("TreeTent Factory: unknown value where integer expected"); + if (value < 0 || value > 3) { + throw new InvalidFileFormatException("TreeTent Factory: cell unknown value"); } - catch (NullPointerException e) { - throw new InvalidFileFormatException("TreeTent Factory: could not find attribute(s)"); + + TreeTentCell cell = new TreeTentCell(TreeTentType.valueOf(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } else { + if (node.getNodeName().equalsIgnoreCase("line")) { + int x1 = Integer.valueOf(attributeList.getNamedItem("x1").getNodeValue()); + int y1 = Integer.valueOf(attributeList.getNamedItem("y1").getNodeValue()); + int x2 = Integer.valueOf(attributeList.getNamedItem("x2").getNodeValue()); + int y2 = Integer.valueOf(attributeList.getNamedItem("y2").getNodeValue()); + if (x1 >= width || y1 >= height || x2 >= width || y2 >= height) { + throw new InvalidFileFormatException("TreeTent Factory: line location out of bounds"); + } + + TreeTentCell c1 = treeTentBoard.getCell(x1, y1); + TreeTentCell c2 = treeTentBoard.getCell(x2, y2); + return new TreeTentLine(c1, c2); + } else { + throw new InvalidFileFormatException( + "TreeTent Factory: unknown puzzleElement puzzleElement"); } + } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "TreeTent Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("TreeTent Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentCell) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentCell) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); + TreeTentCell cell = (TreeTentCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getValue())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getValue())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } - else { - org.w3c.dom.Element lineElement = document.createElement("line"); + return cellElement; + } else { + org.w3c.dom.Element lineElement = document.createElement("line"); - TreeTentLine line = (TreeTentLine) puzzleElement; + TreeTentLine line = (TreeTentLine) puzzleElement; - lineElement.setAttribute("x1", String.valueOf(line.getC1().getLocation().x)); - lineElement.setAttribute("y1", String.valueOf(line.getC1().getLocation().y)); - lineElement.setAttribute("x2", String.valueOf(line.getC2().getLocation().x)); - lineElement.setAttribute("y2", String.valueOf(line.getC2().getLocation().y)); + lineElement.setAttribute("x1", String.valueOf(line.getC1().getLocation().x)); + lineElement.setAttribute("y1", String.valueOf(line.getC1().getLocation().y)); + lineElement.setAttribute("x2", String.valueOf(line.getC2().getLocation().x)); + lineElement.setAttribute("y2", String.valueOf(line.getC2().getLocation().y)); - return lineElement; - } + return lineElement; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java index bcba7dc94..df9e7eed2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java @@ -3,53 +3,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class TreeTentClue extends PuzzleElement { - private TreeTentType type; - private int clueIndex; - - public TreeTentClue(int value, int clueIndex, TreeTentType type) { - super(value); - this.index = -2; - this.clueIndex = clueIndex; - this.type = type; - } - - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; - } - return sb.reverse().toString(); - } - - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; - } - return result; - } - - public int getClueIndex() { - return clueIndex; - } - - public void setClueIndex(int clueIndex) { - this.clueIndex = clueIndex; - } - - public TreeTentType getType() { - return type; - } - - public void setType(TreeTentType type) { - this.type = type; - } - - public TreeTentClue copy() { - return null; - } + private TreeTentType type; + private int clueIndex; + + public TreeTentClue(int value, int clueIndex, TreeTentType type) { + super(value); + this.index = -2; + this.clueIndex = clueIndex; + this.type = type; + } + + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; + } + return sb.reverse().toString(); + } + + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; + } + return result; + } + + public int getClueIndex() { + return clueIndex; + } + + public void setClueIndex(int clueIndex) { + this.clueIndex = clueIndex; + } + + public TreeTentType getType() { + return type; + } + + public void setType(TreeTentType type) { + this.type = type; + } + + public TreeTentClue copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java index 4e7b24b13..e59c86f62 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java @@ -1,55 +1,54 @@ package edu.rpi.legup.puzzle.treetent; import edu.rpi.legup.ui.boardview.ElementView; - import java.awt.*; public class TreeTentClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public TreeTentClueView(TreeTentClue clue) { - super(clue); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public TreeTentClueView(TreeTentClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public TreeTentClue getPuzzleElement() { + return (TreeTentClue) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + TreeTentClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + value = String.valueOf(clue.getData() + 1); + break; + case CLUE_EAST: + value = String.valueOf(clue.getData()); + break; + case CLUE_SOUTH: + value = String.valueOf(clue.getData()); + break; + case CLUE_WEST: + value = TreeTentClue.colNumToString(clue.getData() + 1); + break; + default: + value = ""; } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public TreeTentClue getPuzzleElement() { - return (TreeTentClue) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - TreeTentClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - value = String.valueOf(clue.getData() + 1); - break; - case CLUE_EAST: - value = String.valueOf(clue.getData()); - break; - case CLUE_SOUTH: - value = String.valueOf(clue.getData()); - break; - case CLUE_WEST: - value = TreeTentClue.colNumToString(clue.getData() + 1); - break; - default: - value = ""; - } - - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java index 1f431594c..d3a4b3d26 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java @@ -1,5 +1,7 @@ package edu.rpi.legup.puzzle.treetent; +import static edu.rpi.legup.app.GameBoardFacade.getInstance; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.history.AutoCaseRuleCommand; @@ -13,130 +15,119 @@ import edu.rpi.legup.ui.proofeditorui.treeview.TreePanel; import edu.rpi.legup.ui.proofeditorui.treeview.TreeView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; - import java.awt.event.MouseEvent; -import static edu.rpi.legup.app.GameBoardFacade.getInstance; - public class TreeTentController extends ElementController { - private ElementView lastCellPressed; - private ElementView dragStart; + private ElementView lastCellPressed; + private ElementView dragStart; - public TreeTentController() { - super(); - this.dragStart = null; - this.lastCellPressed = null; - } + public TreeTentController() { + super(); + this.dragStart = null; + this.lastCellPressed = null; + } - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() != MouseEvent.BUTTON2) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - dragStart = boardView.getElement(e.getPoint()); - lastCellPressed = boardView.getElement(e.getPoint()); - } + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() != MouseEvent.BUTTON2) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + dragStart = boardView.getElement(e.getPoint()); + lastCellPressed = boardView.getElement(e.getPoint()); } + } - @Override - public void mouseReleased(MouseEvent e) { - if (GameBoardFacade.getInstance().getLegupUI().getTreePanel() != null && e.getButton() != MouseEvent.BUTTON2) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - lastCellPressed = boardView.getElement(e.getPoint()); - Board board = boardView.getBoard(); - TreeViewSelection selection = treeView.getSelection(); + @Override + public void mouseReleased(MouseEvent e) { + if (GameBoardFacade.getInstance().getLegupUI().getTreePanel() != null + && e.getButton() != MouseEvent.BUTTON2) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + lastCellPressed = boardView.getElement(e.getPoint()); + Board board = boardView.getBoard(); + TreeViewSelection selection = treeView.getSelection(); - if (dragStart != null) { - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - AutoCaseRuleCommand autoCaseRuleCommand = new AutoCaseRuleCommand(dragStart, selection, caseBoard.getCaseRule(), caseBoard, e); - if (autoCaseRuleCommand.canExecute()) { - autoCaseRuleCommand.execute(); - getInstance().getHistory().pushChange(autoCaseRuleCommand); - treePanel.updateError(""); - } - else { - treePanel.updateError(autoCaseRuleCommand.getError()); - } - } - else { - if (dragStart == lastCellPressed) { - if (dragStart.getPuzzleElement().getIndex() >= 0) { - ICommand edit = new EditDataCommand(lastCellPressed, selection, e); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - treePanel.updateError(""); - } - else { - treePanel.updateError(edit.getError()); - } - } - else { - ClueCommand edit = new ClueCommand(selection, (TreeTentClueView) dragStart); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - treePanel.updateError(""); - } - else { - treePanel.updateError(edit.getError()); - } - } - } - else { - if (lastCellPressed != null) { - if (dragStart instanceof TreeTentElementView) { - ICommand editLine = new EditLineCommand(selection, (TreeTentElementView) dragStart, lastCellPressed); - if (editLine.canExecute()) { - editLine.execute(); - getInstance().getHistory().pushChange(editLine); - } - else { - treePanel.updateError(editLine.getError()); - } - } - } - } + if (dragStart != null) { + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + AutoCaseRuleCommand autoCaseRuleCommand = + new AutoCaseRuleCommand(dragStart, selection, caseBoard.getCaseRule(), caseBoard, e); + if (autoCaseRuleCommand.canExecute()) { + autoCaseRuleCommand.execute(); + getInstance().getHistory().pushChange(autoCaseRuleCommand); + treePanel.updateError(""); + } else { + treePanel.updateError(autoCaseRuleCommand.getError()); + } + } else { + if (dragStart == lastCellPressed) { + if (dragStart.getPuzzleElement().getIndex() >= 0) { + ICommand edit = new EditDataCommand(lastCellPressed, selection, e); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + treePanel.updateError(""); + } else { + treePanel.updateError(edit.getError()); + } + } else { + ClueCommand edit = new ClueCommand(selection, (TreeTentClueView) dragStart); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + treePanel.updateError(""); + } else { + treePanel.updateError(edit.getError()); + } + } + } else { + if (lastCellPressed != null) { + if (dragStart instanceof TreeTentElementView) { + ICommand editLine = + new EditLineCommand( + selection, (TreeTentElementView) dragStart, lastCellPressed); + if (editLine.canExecute()) { + editLine.execute(); + getInstance().getHistory().pushChange(editLine); + } else { + treePanel.updateError(editLine.getError()); } + } } - dragStart = null; - lastCellPressed = null; + } } + } + dragStart = null; + lastCellPressed = null; } + } - @Override - public void changeCell(MouseEvent e, PuzzleElement element) { - TreeTentCell cell = (TreeTentCell) element; - if (e.getButton() == MouseEvent.BUTTON1) { - if (cell.getData() == TreeTentType.UNKNOWN) { - element.setData(TreeTentType.GRASS); - } - else { - if (cell.getData() == TreeTentType.GRASS) { - element.setData(TreeTentType.TENT); - } - else { - element.setData(TreeTentType.UNKNOWN); - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement element) { + TreeTentCell cell = (TreeTentCell) element; + if (e.getButton() == MouseEvent.BUTTON1) { + if (cell.getData() == TreeTentType.UNKNOWN) { + element.setData(TreeTentType.GRASS); + } else { + if (cell.getData() == TreeTentType.GRASS) { + element.setData(TreeTentType.TENT); + } else { + element.setData(TreeTentType.UNKNOWN); } - else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == TreeTentType.UNKNOWN) { - element.setData(TreeTentType.TENT); - } - else { - if (cell.getData() == TreeTentType.GRASS) { - element.setData(TreeTentType.UNKNOWN); - } - else { - element.setData(TreeTentType.GRASS); - } - } - } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == TreeTentType.UNKNOWN) { + element.setData(TreeTentType.TENT); + } else { + if (cell.getData() == TreeTentType.GRASS) { + element.setData(TreeTentType.UNKNOWN); + } else { + element.setData(TreeTentType.GRASS); + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java index 0c8698f83..740ea5ea8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java @@ -1,52 +1,55 @@ package edu.rpi.legup.puzzle.treetent; import edu.rpi.legup.ui.boardview.GridElementView; - import java.awt.*; import java.awt.geom.Rectangle2D; public class TreeTentElementView extends GridElementView { - public TreeTentElementView(TreeTentCell cell) { - super(cell); - } + public TreeTentElementView(TreeTentCell cell) { + super(cell); + } - /** - * Draws on the given frame based on the type of the cell of the current puzzleElement - * - * @param graphics2D the frame to be drawn on - */ - @Override - public void drawElement(Graphics2D graphics2D) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - TreeTentType type = cell.getType(); - graphics2D.setStroke(new BasicStroke(0)); - if (type == TreeTentType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fill(new Rectangle2D.Double(location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); + /** + * Draws on the given frame based on the type of the cell of the current puzzleElement + * + * @param graphics2D the frame to be drawn on + */ + @Override + public void drawElement(Graphics2D graphics2D) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + TreeTentType type = cell.getType(); + graphics2D.setStroke(new BasicStroke(0)); + if (type == TreeTentType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fill( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); + graphics2D.setColor(Color.BLACK); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); + } else { + if (type == TreeTentType.TREE) { + graphics2D.drawImage( + TreeTentView.TREE, location.x, location.y, size.width, size.height, null, null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == TreeTentType.GRASS) { + graphics2D.drawImage( + TreeTentView.GRASS, location.x, location.y, size.width, size.height, null, null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == TreeTentType.TENT) { + graphics2D.drawImage( + TreeTentView.TENT, location.x, location.y, size.width, size.height, null, null); graphics2D.setColor(Color.BLACK); - graphics2D.draw(new Rectangle2D.Double(location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); - } - else { - if (type == TreeTentType.TREE) { - graphics2D.drawImage(TreeTentView.TREE, location.x, location.y, size.width, size.height, null, null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - else { - if (type == TreeTentType.GRASS) { - graphics2D.drawImage(TreeTentView.GRASS, location.x, location.y, size.width, size.height, null, null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - else { - if (type == TreeTentType.TENT) { - graphics2D.drawImage(TreeTentView.TENT, location.x, location.y, size.width, size.height, null, null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - } - } + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java index c438d8ee4..621ea0a38 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java @@ -6,68 +6,68 @@ public class TreeTentExporter extends PuzzleExporter { - public TreeTentExporter(TreeTent treeTent) { - super(treeTent); - } + public TreeTentExporter(TreeTent treeTent) { + super(treeTent); + } - /** - * Creates and returns a new board element in the XML document specified - * - * @param newDocument the XML document to append to - * @return the new board element - */ - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - TreeTentBoard board; - if (puzzle.getTree() != null) { - board = (TreeTentBoard) puzzle.getTree().getRootNode().getBoard(); - } - else { - board = (TreeTentBoard) puzzle.getBoardView().getBoard(); - } + /** + * Creates and returns a new board element in the XML document specified + * + * @param newDocument the XML document to append to + * @return the new board element + */ + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + TreeTentBoard board; + if (puzzle.getTree() != null) { + board = (TreeTentBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (TreeTentBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getData() != TreeTentType.UNKNOWN) { - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getData() != TreeTentType.UNKNOWN) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (TreeTentClue clue : board.getRowClues()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", TreeTentClue.colNumToString(clue.getClueIndex())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (TreeTentClue clue : board.getRowClues()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", TreeTentClue.colNumToString(clue.getClueIndex())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (TreeTentClue clue : board.getRowClues()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", String.valueOf(clue.getClueIndex())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (TreeTentClue clue : board.getRowClues()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", String.valueOf(clue.getClueIndex())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); - if (!board.getLines().isEmpty()) { - org.w3c.dom.Element linesElement = newDocument.createElement("lines"); - for (PuzzleElement data : board.getLines()) { - org.w3c.dom.Element lineElement = puzzle.getFactory().exportCell(newDocument, data); - linesElement.appendChild(lineElement); - } - boardElement.appendChild(linesElement); - } - return boardElement; + if (!board.getLines().isEmpty()) { + org.w3c.dom.Element linesElement = newDocument.createElement("lines"); + for (PuzzleElement data : board.getLines()) { + org.w3c.dom.Element lineElement = puzzle.getFactory().exportCell(newDocument, data); + linesElement.appendChild(lineElement); + } + boardElement.appendChild(linesElement); } + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java index 2b4861c9f..a446d96cd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java @@ -2,191 +2,208 @@ import edu.rpi.legup.model.PuzzleImporter; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.awt.*; - public class TreeTentImporter extends PuzzleImporter { - public TreeTentImporter(TreeTent treeTent) { - super(treeTent); + public TreeTentImporter(TreeTent treeTent) { + super(treeTent); + } + + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } + + @Override + public boolean acceptsTextInput() { + return false; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + TreeTentBoard treeTentBoard = new TreeTentBoard(columns, rows); + + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + if (treeTentBoard.getCell(x, y) == null) { + TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + treeTentBoard.setCell(x, y, cell); + } + } } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; + for (int i = 0; i < rows; i++) { + treeTentBoard.getRowClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_EAST)); } - @Override - public boolean acceptsTextInput() { - return false; + for (int i = 0; i < columns; i++) { + treeTentBoard.getColClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_SOUTH)); } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - TreeTentBoard treeTentBoard = new TreeTentBoard(columns, rows); - - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - if (treeTentBoard.getCell(x, y) == null) { - TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - treeTentBoard.setCell(x, y, cell); - } - } + puzzle.setCurrentBoard(treeTentBoard); + } + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("TreeTent Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("TreeTent Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + TreeTentBoard treeTentBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + treeTentBoard = new TreeTentBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + treeTentBoard = new TreeTentBoard(width, height); } - - for (int i = 0; i < rows; i++) { - treeTentBoard.getRowClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_EAST)); + } + + if (treeTentBoard == null) { + throw new InvalidFileFormatException("TreeTent Importer: invalid board dimensions"); + } + + int width = treeTentBoard.getWidth(); + int height = treeTentBoard.getHeight(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + TreeTentCell cell = + (TreeTentCell) puzzle.getFactory().importCell(elementDataList.item(i), treeTentBoard); + Point loc = cell.getLocation(); + if (cell.getData() != TreeTentType.UNKNOWN) { + cell.setModifiable(false); + cell.setGiven(true); } - - for (int i = 0; i < columns; i++) { - treeTentBoard.getColClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_SOUTH)); + treeTentBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (treeTentBoard.getCell(x, y) == null) { + TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + treeTentBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("TreeTent Importer: cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { + throw new InvalidFileFormatException( + "TreeTent Importer: side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "TreeTent Importer: axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != treeTentBoard.getHeight() + || southClues.getLength() != treeTentBoard.getWidth()) { + throw new InvalidFileFormatException( + "TreeTent Importer: there must be same number of clues as the dimension of the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = TreeTentClue.colStringToColNum(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > treeTentBoard.getHeight()) { + throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); } - puzzle.setCurrentBoard(treeTentBoard); - } + if (treeTentBoard.getRowClues().get(index - 1) != null) { + throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); + } + treeTentBoard + .getRowClues() + .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > treeTentBoard.getWidth()) { + throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("TreeTent Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("TreeTent Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - TreeTentBoard treeTentBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - treeTentBoard = new TreeTentBoard(size); - } - else { - if (!boardElement.getAttribute("width").isEmpty() && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - treeTentBoard = new TreeTentBoard(width, height); - } - } - - if (treeTentBoard == null) { - throw new InvalidFileFormatException("TreeTent Importer: invalid board dimensions"); - } - - int width = treeTentBoard.getWidth(); - int height = treeTentBoard.getHeight(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - TreeTentCell cell = (TreeTentCell) puzzle.getFactory().importCell(elementDataList.item(i), treeTentBoard); - Point loc = cell.getLocation(); - if (cell.getData() != TreeTentType.UNKNOWN) { - cell.setModifiable(false); - cell.setGiven(true); - } - treeTentBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (treeTentBoard.getCell(x, y) == null) { - TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - treeTentBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("TreeTent Importer: cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { - throw new InvalidFileFormatException("TreeTent Importer: side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) || - !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException("TreeTent Importer: axes must be different and be {east | south}"); - } - NodeList eastClues = side1.equalsIgnoreCase("east") ? axis1.getElementsByTagName("clue") : axis2.getElementsByTagName("clue"); - NodeList southClues = side1.equalsIgnoreCase("south") ? axis1.getElementsByTagName("clue") : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != treeTentBoard.getHeight() || southClues.getLength() != treeTentBoard.getWidth()) { - throw new InvalidFileFormatException("TreeTent Importer: there must be same number of clues as the dimension of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = TreeTentClue.colStringToColNum(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > treeTentBoard.getHeight()) { - throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); - } - - if (treeTentBoard.getRowClues().get(index - 1) != null) { - throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); - } - treeTentBoard.getRowClues().set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > treeTentBoard.getWidth()) { - throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); - } - - if (treeTentBoard.getColClues().get(index - 1) != null) { - throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); - } - treeTentBoard.getColClues().set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_SOUTH)); - } - - if (boardElement.getElementsByTagName("lines").getLength() == 1) { - Element linesElement = (Element) boardElement.getElementsByTagName("lines").item(0); - NodeList linesList = linesElement.getElementsByTagName("line"); - for (int i = 0; i < linesList.getLength(); i++) { - treeTentBoard.getLines().add((TreeTentLine) puzzle.getFactory().importCell(linesList.item(i), treeTentBoard)); - } - } - - puzzle.setCurrentBoard(treeTentBoard); + if (treeTentBoard.getColClues().get(index - 1) != null) { + throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); } - catch (NumberFormatException e) { - throw new InvalidFileFormatException("TreeTent Importer: unknown value where integer expected"); + treeTentBoard + .getColClues() + .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_SOUTH)); + } + + if (boardElement.getElementsByTagName("lines").getLength() == 1) { + Element linesElement = (Element) boardElement.getElementsByTagName("lines").item(0); + NodeList linesList = linesElement.getElementsByTagName("line"); + for (int i = 0; i < linesList.getLength(); i++) { + treeTentBoard + .getLines() + .add((TreeTentLine) puzzle.getFactory().importCell(linesList.item(i), treeTentBoard)); } - } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Tree Tent cannot accept text input"); + puzzle.setCurrentBoard(treeTentBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "TreeTent Importer: unknown value where integer expected"); } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Tree Tent cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java index 9444cb425..bc252b0ba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java @@ -5,38 +5,40 @@ public class TreeTentLine extends PuzzleElement> { - public TreeTentLine(TreeTentCell c1, TreeTentCell c2) { - this.data = new Entry<>(c1, c2); - } - - public TreeTentCell getC1() { - return data.getKey(); - } - - public void setC1(TreeTentCell c1) { - this.data.setKey(c1); - } - - public TreeTentCell getC2() { - return data.getValue(); - } - - public void setC2(TreeTentCell c2) { - this.data.setValue(c2); - } - - public boolean compare(TreeTentLine line) { - return ((line.getC1().getLocation().equals(data.getKey().getLocation()) && line.getC2().getLocation().equals(data.getValue().getLocation())) || - (line.getC1().getLocation().equals(data.getValue().getLocation()) && line.getC2().getLocation().equals(data.getKey().getLocation()))); - } - - /** - * Copies this elements puzzleElement to a new PuzzleElement object - * - * @return copied PuzzleElement object - */ - @Override - public TreeTentLine copy() { - return new TreeTentLine(data.getKey().copy(), data.getValue().copy()); - } + public TreeTentLine(TreeTentCell c1, TreeTentCell c2) { + this.data = new Entry<>(c1, c2); + } + + public TreeTentCell getC1() { + return data.getKey(); + } + + public void setC1(TreeTentCell c1) { + this.data.setKey(c1); + } + + public TreeTentCell getC2() { + return data.getValue(); + } + + public void setC2(TreeTentCell c2) { + this.data.setValue(c2); + } + + public boolean compare(TreeTentLine line) { + return ((line.getC1().getLocation().equals(data.getKey().getLocation()) + && line.getC2().getLocation().equals(data.getValue().getLocation())) + || (line.getC1().getLocation().equals(data.getValue().getLocation()) + && line.getC2().getLocation().equals(data.getKey().getLocation()))); + } + + /** + * Copies this elements puzzleElement to a new PuzzleElement object + * + * @return copied PuzzleElement object + */ + @Override + public TreeTentLine copy() { + return new TreeTentLine(data.getKey().copy(), data.getValue().copy()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java index 833dcb5b5..b2e6ed7b5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java @@ -1,32 +1,31 @@ package edu.rpi.legup.puzzle.treetent; import edu.rpi.legup.ui.boardview.ElementView; - import java.awt.*; public class TreeTentLineView extends ElementView { - private final Color LINE_COLOR = Color.GREEN; - - private final Stroke LINE_STROKE = new BasicStroke(2); - - public TreeTentLineView(TreeTentLine line) { - super(line); - } - - @Override - public void draw(Graphics2D graphics2D) { - - TreeTentLine line = (TreeTentLine) puzzleElement; - Point p1 = line.getC1().getLocation(); - Point p2 = line.getC2().getLocation(); - int x1 = (p1.x + 1) * size.width + size.width / 2; - int y1 = (p1.y + 1) * size.height + size.height / 2; - - int x2 = (p2.x + 1) * size.width + size.width / 2; - int y2 = (p2.y + 1) * size.height + size.height / 2; - //graphics2D.setColor(LINE_COLOR); - graphics2D.setColor(line.isModified() ? Color.GREEN : Color.WHITE); - graphics2D.setStroke(LINE_STROKE); - graphics2D.drawLine(x1, y1, x2, y2); - } + private final Color LINE_COLOR = Color.GREEN; + + private final Stroke LINE_STROKE = new BasicStroke(2); + + public TreeTentLineView(TreeTentLine line) { + super(line); + } + + @Override + public void draw(Graphics2D graphics2D) { + + TreeTentLine line = (TreeTentLine) puzzleElement; + Point p1 = line.getC1().getLocation(); + Point p2 = line.getC2().getLocation(); + int x1 = (p1.x + 1) * size.width + size.width / 2; + int y1 = (p1.y + 1) * size.height + size.height / 2; + + int x2 = (p2.x + 1) * size.width + size.width / 2; + int y2 = (p2.y + 1) * size.height + size.height / 2; + // graphics2D.setColor(LINE_COLOR); + graphics2D.setColor(line.isModified() ? Color.GREEN : Color.WHITE); + graphics2D.setStroke(LINE_STROKE); + graphics2D.drawLine(x1, y1, x2, y2); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java index 890cdfe29..b1e480335 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java @@ -1,21 +1,25 @@ package edu.rpi.legup.puzzle.treetent; -import edu.rpi.legup.puzzle.masyu.MasyuType; - public enum TreeTentType { - UNKNOWN, TREE, GRASS, TENT, - CLUE_NORTH, CLUE_EAST, CLUE_SOUTH, CLUE_WEST; + UNKNOWN, + TREE, + GRASS, + TENT, + CLUE_NORTH, + CLUE_EAST, + CLUE_SOUTH, + CLUE_WEST; - public static TreeTentType valueOf(int num) { - switch (num) { - case 1: - return TREE; - case 2: - return GRASS; - case 3: - return TENT; - default: - return UNKNOWN; - } + public static TreeTentType valueOf(int num) { + switch (num) { + case 1: + return TREE; + case 2: + return GRASS; + case 3: + return TENT; + default: + return UNKNOWN; } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java index 23a500231..0973f9452 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java @@ -6,202 +6,209 @@ import edu.rpi.legup.model.tree.TreeElement; import edu.rpi.legup.ui.boardview.ElementView; import edu.rpi.legup.ui.boardview.GridBoardView; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.imageio.ImageIO; import java.awt.*; import java.io.IOException; import java.util.ArrayList; +import javax.imageio.ImageIO; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class TreeTentView extends GridBoardView { - private final static Logger LOGGER = LogManager.getLogger(TreeTentView.class.getName()); - - static Image TREE, GRASS, TENT; - - static { - try { - TREE = ImageIO.read(ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tree.png")); - GRASS = ImageIO.read(ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/grass.png")); - TENT = ImageIO.read(ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tent.png")); - } - catch (IOException e) { - LOGGER.error("Failed to open TreeTent images"); - } - } - - private ArrayList lineViews; - - private ArrayList northClues; - private ArrayList eastClues; - private ArrayList southClues; - private ArrayList westClues; - - public TreeTentView(TreeTentBoard board) { - super(new BoardController(), new TreeTentController(), board.getDimension()); - - this.lineViews = new ArrayList<>(); - - this.northClues = new ArrayList<>(); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - TreeTentElementView elementView = new TreeTentElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); - elementViews.add(elementView); - } - - for (TreeTentLine line : board.getLines()) { - TreeTentLineView lineView = new TreeTentLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - - for (int i = 0; i < gridSize.height; i++) { - TreeTentClueView row = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_WEST)); - row.setLocation(new Point(0, (i + 1) * elementSize.height)); - row.setSize(elementSize); - - TreeTentClueView clue = new TreeTentClueView(board.getRowClues().get(i)); - clue.setLocation(new Point((gridSize.width + 1) * elementSize.width, (i + 1) * elementSize.height)); - clue.setSize(elementSize); - - westClues.add(row); - eastClues.add(clue); - } - - for (int i = 0; i < gridSize.width; i++) { - TreeTentClueView col = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_NORTH)); - col.setLocation(new Point((i + 1) * elementSize.width, 0)); - col.setSize(elementSize); - - TreeTentClueView clue = new TreeTentClueView(board.getColClues().get(i)); - clue.setLocation(new Point((i + 1) * elementSize.width, (gridSize.height + 1) * elementSize.height)); - clue.setSize(elementSize); - - northClues.add(col); - southClues.add(clue); - } - } - - /** - * Gets the ElementView from the location specified or - * null if one does not exists at that location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - @Override - public ElementView getElement(Point point) { - Point scaledPoint = new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - for (TreeTentClueView clueView : northClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : eastClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : southClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : westClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - return null; - } - - public ArrayList getLineViews() { - return lineViews; - } - - public ArrayList getNorthClues() { - return northClues; - } - - public ArrayList getEastClues() { - return eastClues; - } - - public ArrayList getSouthClues() { - return southClues; - } - - public ArrayList getWestClues() { - return westClues; - } - - @Override - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = (gridSize.width + 2) * elementSize.width; - boardViewSize.height = (gridSize.height + 2) * elementSize.height; - return boardViewSize; - } - - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - super.onTreeElementChanged(treeElement); - TreeTentBoard treeTentBoard; - if (board instanceof CaseBoard) { - treeTentBoard = (TreeTentBoard) ((CaseBoard) board).getBaseBoard(); - } - else { - treeTentBoard = (TreeTentBoard) board; - } - - lineViews.clear(); - for (TreeTentLine line : treeTentBoard.getLines()) { - TreeTentLineView lineView = new TreeTentLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - } - - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); - - for (TreeTentLineView view : lineViews) { - view.draw(graphics2D); - } - - for (TreeTentClueView clueView : northClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : eastClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : southClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : westClues) { - clueView.draw(graphics2D); - } + private static final Logger LOGGER = LogManager.getLogger(TreeTentView.class.getName()); + + static Image TREE, GRASS, TENT; + + static { + try { + TREE = + ImageIO.read( + ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tree.png")); + GRASS = + ImageIO.read( + ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/grass.png")); + TENT = + ImageIO.read( + ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tent.png")); + } catch (IOException e) { + LOGGER.error("Failed to open TreeTent images"); + } + } + + private ArrayList lineViews; + + private ArrayList northClues; + private ArrayList eastClues; + private ArrayList southClues; + private ArrayList westClues; + + public TreeTentView(TreeTentBoard board) { + super(new BoardController(), new TreeTentController(), board.getDimension()); + + this.lineViews = new ArrayList<>(); + + this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + Point loc = cell.getLocation(); + TreeTentElementView elementView = new TreeTentElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); + elementViews.add(elementView); + } + + for (TreeTentLine line : board.getLines()) { + TreeTentLineView lineView = new TreeTentLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + + for (int i = 0; i < gridSize.height; i++) { + TreeTentClueView row = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_WEST)); + row.setLocation(new Point(0, (i + 1) * elementSize.height)); + row.setSize(elementSize); + + TreeTentClueView clue = new TreeTentClueView(board.getRowClues().get(i)); + clue.setLocation( + new Point((gridSize.width + 1) * elementSize.width, (i + 1) * elementSize.height)); + clue.setSize(elementSize); + + westClues.add(row); + eastClues.add(clue); + } + + for (int i = 0; i < gridSize.width; i++) { + TreeTentClueView col = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_NORTH)); + col.setLocation(new Point((i + 1) * elementSize.width, 0)); + col.setSize(elementSize); + + TreeTentClueView clue = new TreeTentClueView(board.getColClues().get(i)); + clue.setLocation( + new Point((i + 1) * elementSize.width, (gridSize.height + 1) * elementSize.height)); + clue.setSize(elementSize); + + northClues.add(col); + southClues.add(clue); + } + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + @Override + public ElementView getElement(Point point) { + Point scaledPoint = + new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + for (TreeTentClueView clueView : northClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : eastClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : southClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : westClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + return null; + } + + public ArrayList getLineViews() { + return lineViews; + } + + public ArrayList getNorthClues() { + return northClues; + } + + public ArrayList getEastClues() { + return eastClues; + } + + public ArrayList getSouthClues() { + return southClues; + } + + public ArrayList getWestClues() { + return westClues; + } + + @Override + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = (gridSize.width + 2) * elementSize.width; + boardViewSize.height = (gridSize.height + 2) * elementSize.height; + return boardViewSize; + } + + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + super.onTreeElementChanged(treeElement); + TreeTentBoard treeTentBoard; + if (board instanceof CaseBoard) { + treeTentBoard = (TreeTentBoard) ((CaseBoard) board).getBaseBoard(); + } else { + treeTentBoard = (TreeTentBoard) board; + } + + lineViews.clear(); + for (TreeTentLine line : treeTentBoard.getLines()) { + TreeTentLineView lineView = new TreeTentLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + } + + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); + + for (TreeTentLineView view : lineViews) { + view.draw(graphics2D); + } + + for (TreeTentClueView clueView : northClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : eastClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : southClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : westClues) { + clueView.draw(graphics2D); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java index b85b5e337..4d452f48d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java @@ -4,8 +4,11 @@ public class GrassTile extends PlaceableElement { - public GrassTile() { - super("TREE-PlAC-0002", "Grass Tile", "The grass crest tile", "edu/rpi/legup/images/treetent/grass.png"); - } - -} \ No newline at end of file + public GrassTile() { + super( + "TREE-PlAC-0002", + "Grass Tile", + "The grass crest tile", + "edu/rpi/legup/images/treetent/grass.png"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java index 2f4fee1eb..249b22b04 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java @@ -4,8 +4,7 @@ public class TentTile extends PlaceableElement { - public TentTile() { - super("TREE-PLAC-0001", "Tent Tile", "The tent tile", "edu/rpi/legup/images/treetent/tent.png"); - } - -} \ No newline at end of file + public TentTile() { + super("TREE-PLAC-0001", "Tent Tile", "The tent tile", "edu/rpi/legup/images/treetent/tent.png"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java index a91928fe4..eab34e0b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java @@ -1,12 +1,10 @@ package edu.rpi.legup.puzzle.treetent.elements; import edu.rpi.legup.model.elements.NonPlaceableElement; -import edu.rpi.legup.model.elements.PlaceableElement; public class TreeTile extends NonPlaceableElement { - public TreeTile() { - super("TREE-UNPL-0001", "Tree Tile", "The tree tile", "edu/rpi/legup/images/treetent/tree.png"); - } - + public TreeTile() { + super("TREE-UNPL-0001", "Tree Tile", "The tree tile", "edu/rpi/legup/images/treetent/tree.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java index 73c8ca263..589053d5a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super("TREE-UNPL-0002", "Unknown Tile", "The blank tile", "edu/rpi/legup/images/treetent/UnknownTile.png"); - } -} \ No newline at end of file + public UnknownTile() { + super( + "TREE-UNPL-0002", + "Unknown Tile", + "The blank tile", + "edu/rpi/legup/images/treetent/UnknownTile.png"); + } +} diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java index 6fec1ee0d..2e7b7a031 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java @@ -9,79 +9,80 @@ import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.util.List; public class EmptyFieldDirectRule extends DirectRule { - public EmptyFieldDirectRule() { - super("TREE-BASC-0001", "Empty Field", - "Blank cells not adjacent to an unlinked tree are grass.", - "edu/rpi/legup/images/treetent/noTreesAround.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; - } + public EmptyFieldDirectRule() { + super( + "TREE-BASC-0001", + "Empty Field", + "Blank cells not adjacent to an unlinked tree are grass.", + "edu/rpi/legup/images/treetent/noTreesAround.png"); + } - if (isForced(finalBoard, finalCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS + && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; } - /** - * Returns a boolean value based on whether the specified cell has adjacent cells (true - no adjacent, false - has adjacent) - * - * @param board the TreeTent board - * @param cell the specified TreeTent cell - * @return true - no adjacent, false - has adjacent - */ - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjCells = board.getAdjacent(cell, TreeTentType.TREE); - return adjCells.isEmpty(); + if (isForced(finalBoard, finalCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; } + } + + /** + * Returns a boolean value based on whether the specified cell has adjacent cells (true - no + * adjacent, false - has adjacent) + * + * @param board the TreeTent board + * @param cell the specified TreeTent cell + * @return true - no adjacent, false - has adjacent + */ + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjCells = board.getAdjacent(cell, TreeTentType.TREE); + return adjCells.isEmpty(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java index 698b3aa5e..16db6e662 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java @@ -7,182 +7,198 @@ import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.TreeTentClue; - +import edu.rpi.legup.puzzle.treetent.TreeTentType; +import java.awt.*; import java.util.ArrayList; import java.util.List; -import java.awt.*; public class FillinRowCaseRule extends CaseRule { - public FillinRowCaseRule() { - super("TREE-CASE-0001", "Fill In row", - "A row must have the number of tents of its clue.", - "edu/rpi/legup/images/treetent/case_rowcount.png"); + public FillinRowCaseRule() { + super( + "TREE-CASE-0001", + "Fill In row", + "A row must have the number of tents of its clue.", + "edu/rpi/legup/images/treetent/case_rowcount.png"); + } + + /** + * Gets the case board that indicates where this case rule can be applied on the given Board. + * + * @param board the given board + * @return the case board object + */ + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + ArrayList clues = treeTentBoard.getRowClues(); + clues.addAll(treeTentBoard.getColClues()); + for (PuzzleElement element : clues) { + // if ((((TreeTentCell) element).getType() == TreeTentType.CLUE_SOUTH && + // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().y, TreeTentType.UNKNOWN, + // true).size() != 0) || + // (((TreeTentCell) element).getType() == TreeTentType.CLUE_EAST && + // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().x, TreeTentType.UNKNOWN, + // false).size() != 0)) { + // caseBoard.addPickableElement(element); + // } + caseBoard.addPickableElement(element); } - - /** - * Gets the case board that indicates where this case rule can be applied on the given Board. - * - * @param board the given board - * @return the case board object - */ - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - ArrayList clues = treeTentBoard.getRowClues(); - clues.addAll(treeTentBoard.getColClues()); - for (PuzzleElement element : clues) { - // if ((((TreeTentCell) element).getType() == TreeTentType.CLUE_SOUTH && treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().y, TreeTentType.UNKNOWN, true).size() != 0) || - // (((TreeTentCell) element).getType() == TreeTentType.CLUE_EAST && treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().x, TreeTentType.UNKNOWN, false).size() != 0)) { - // caseBoard.addPickableElement(element); - // } - caseBoard.addPickableElement(element); - } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - List group; - int tentsLeft; - TreeTentClue clue = ((TreeTentClue) puzzleElement); - int clueIndex = clue.getClueIndex() - 1; - TreeTentBoard tBoard = (TreeTentBoard) board; - if (clue.getType() == TreeTentType.CLUE_SOUTH) { - group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, false); - tentsLeft = tBoard.getRowClues().get(clueIndex).getData() - tBoard.getRowCol(clueIndex, TreeTentType.TENT, false).size(); - cases = genCombinations(tBoard, group, tentsLeft, clueIndex, false); - } - else { - group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, true); - tentsLeft = tBoard.getRowClues().get(clueIndex).getData() - tBoard.getRowCol(clueIndex, TreeTentType.TENT, true).size(); - cases = genCombinations(tBoard, group, tentsLeft, clueIndex, true); - } - - //generate every combination (nCr) - //call goodBoard for each generated combination - //alternitive would be to implement collision avoidance while generating instead of after - if (cases.size() > 0) { - return cases; - } - return null; + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + List group; + int tentsLeft; + TreeTentClue clue = ((TreeTentClue) puzzleElement); + int clueIndex = clue.getClueIndex() - 1; + TreeTentBoard tBoard = (TreeTentBoard) board; + if (clue.getType() == TreeTentType.CLUE_SOUTH) { + group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, false); + tentsLeft = + tBoard.getRowClues().get(clueIndex).getData() + - tBoard.getRowCol(clueIndex, TreeTentType.TENT, false).size(); + cases = genCombinations(tBoard, group, tentsLeft, clueIndex, false); + } else { + group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, true); + tentsLeft = + tBoard.getRowClues().get(clueIndex).getData() + - tBoard.getRowCol(clueIndex, TreeTentType.TENT, true).size(); + cases = genCombinations(tBoard, group, tentsLeft, clueIndex, true); } - private ArrayList genCombinations(TreeTentBoard iBoard, List tiles, int target, Integer index, boolean isRow) { - return genCombRecursive(iBoard, tiles, tiles, target, 0, new ArrayList(), index, isRow); + // generate every combination (nCr) + // call goodBoard for each generated combination + // alternitive would be to implement collision avoidance while generating instead of after + if (cases.size() > 0) { + return cases; } - - private ArrayList genCombRecursive(TreeTentBoard iBoard, List original, List tiles, int target, int current, List selected, Integer index, boolean isRow) { - ArrayList b = new ArrayList<>(); - if (target == current) { - TreeTentBoard temp = iBoard.copy(); - for (TreeTentCell c : original) { - if (selected.contains(c)) { - PuzzleElement change = temp.getPuzzleElement(c); - change.setData(TreeTentType.TENT); - temp.addModifiedData(change); - } - else { - PuzzleElement change = temp.getPuzzleElement(c); - change.setData(TreeTentType.GRASS); - temp.addModifiedData(change); - } - - } - if (goodBoard(temp, index, isRow)) { - b.add(temp); - } - return b; - } - for (int i = 0; i < tiles.size(); ++i) { - List sub = tiles.subList(i + 1, tiles.size()); - List next = new ArrayList(selected); - next.add(tiles.get(i)); - b.addAll(genCombRecursive(iBoard, original, sub, target, current + 1, next, index, isRow)); + return null; + } + + private ArrayList genCombinations( + TreeTentBoard iBoard, List tiles, int target, Integer index, boolean isRow) { + return genCombRecursive( + iBoard, tiles, tiles, target, 0, new ArrayList(), index, isRow); + } + + private ArrayList genCombRecursive( + TreeTentBoard iBoard, + List original, + List tiles, + int target, + int current, + List selected, + Integer index, + boolean isRow) { + ArrayList b = new ArrayList<>(); + if (target == current) { + TreeTentBoard temp = iBoard.copy(); + for (TreeTentCell c : original) { + if (selected.contains(c)) { + PuzzleElement change = temp.getPuzzleElement(c); + change.setData(TreeTentType.TENT); + temp.addModifiedData(change); + } else { + PuzzleElement change = temp.getPuzzleElement(c); + change.setData(TreeTentType.GRASS); + temp.addModifiedData(change); } - return b; + } + if (goodBoard(temp, index, isRow)) { + b.add(temp); + } + return b; } - - //Effectively runs TouchingTents check on all the added tents to make sure that the proposed board is valid. - //Could check more or less in the future depending on how "smart" this case rule should be. - private boolean goodBoard(TreeTentBoard board, Integer index, boolean isRow) { - List tents; - if (isRow) { - tents = board.getRowCol(index, TreeTentType.TENT, true); - } - else { - tents = board.getRowCol(index, TreeTentType.TENT, false); - } - - for (TreeTentCell t : tents) { - List adj = board.getAdjacent(t, TreeTentType.TENT); - List diag = board.getDiagonals(t, TreeTentType.TENT); - if (adj.size() > 0 || diag.size() > 0) { - return false; - } - } - return true; + for (int i = 0; i < tiles.size(); ++i) { + List sub = tiles.subList(i + 1, tiles.size()); + List next = new ArrayList(selected); + next.add(tiles.get(i)); + b.addAll(genCombRecursive(iBoard, original, sub, target, current + 1, next, index, isRow)); } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; + return b; + } + + // Effectively runs TouchingTents check on all the added tents to make sure that the proposed + // board is valid. + // Could check more or less in the future depending on how "smart" this case rule should be. + private boolean goodBoard(TreeTentBoard board, Integer index, boolean isRow) { + List tents; + if (isRow) { + tents = board.getRowCol(index, TreeTentType.TENT, true); + } else { + tents = board.getRowCol(index, TreeTentType.TENT, false); } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; + for (TreeTentCell t : tents) { + List adj = board.getAdjacent(t, TreeTentType.TENT); + List diag = board.getDiagonals(t, TreeTentType.TENT); + if (adj.size() > 0 || diag.size() > 0) { + return false; + } } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be valid - * Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends upon. - * Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentClue clue = (TreeTentClue) puzzleElement; - - // add all elements of filled row - for (int i = 0; i < treeTentBoard.getWidth(); i++) { - TreeTentCell cell = treeTentBoard.getCell(i, clue.getClueIndex()-1); - elements.add(board.getPuzzleElement((cell))); - } - - return elements; + return true; + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentClue clue = (TreeTentClue) puzzleElement; + + // add all elements of filled row + for (int i = 0; i < treeTentBoard.getWidth(); i++) { + TreeTentCell cell = treeTentBoard.getCell(i, clue.getClueIndex() - 1); + elements.add(board.getPuzzleElement((cell))); } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java index 69b5d8ca2..bb371c52b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java @@ -9,78 +9,78 @@ import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.awt.*; import java.util.List; public class FinishWithGrassDirectRule extends DirectRule { - public FinishWithGrassDirectRule() { - super("TREE-BASC-0002", "Finish with Grass", - "Grass can be added to finish a row or column that has reached its tent limit.", - "edu/rpi/legup/images/treetent/finishGrass.png"); - } + public FinishWithGrassDirectRule() { + super( + "TREE-BASC-0002", + "Finish with Grass", + "Grass can be added to finish a row or column that has reached its tent limit.", + "edu/rpi/legup/images/treetent/finishGrass.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS + && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; + } - if (isForced(initialBoard, initCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; - } + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; } + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - return tentsRow.size() >= board.getRowClues().get(loc.y).getData() || - tentsCol.size() >= board.getColClues().get(loc.x).getData(); - } + return tentsRow.size() >= board.getRowClues().get(loc.y).getData() + || tentsCol.size() >= board.getColClues().get(loc.x).getData(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java index 3a782e191..cae95b4ff 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java @@ -9,80 +9,79 @@ import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.awt.*; import java.util.List; public class FinishWithTentsDirectRule extends DirectRule { - public FinishWithTentsDirectRule() { - super("TREE-BASC-0003", "Finish with Tents", - "Tents can be added to finish a row or column that has one open spot per required tent.", - "edu/rpi/legup/images/treetent/finishTent.png"); - } + public FinishWithTentsDirectRule() { + super( + "TREE-BASC-0003", + "Finish with Tents", + "Tents can be added to finish a row or column that has one open spot per required tent.", + "edu/rpi/legup/images/treetent/finishTent.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - if (isForced(initialBoard, initCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; } + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); - return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() || - unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); - } + return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() + || unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java index 3be401fd0..bfa432cfa 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java @@ -9,94 +9,92 @@ import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.util.List; public class LastCampingSpotDirectRule extends DirectRule { - public LastCampingSpotDirectRule() { - super("TREE-BASC-0004", "Last Camping Spot", - "If an unlinked tree is adjacent to only one blank cell and not adjacent to any unlinked tents, the blank cell must be a tent.", - "edu/rpi/legup/images/treetent/oneTentPosition.png"); - } + public LastCampingSpotDirectRule() { + super( + "TREE-BASC-0004", + "Last Camping Spot", + "If an unlinked tree is adjacent to only one blank cell and not adjacent to any unlinked tents, the blank cell must be a tent.", + "edu/rpi/legup/images/treetent/oneTentPosition.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - if (isForced(finalBoard, finalCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } + if (isForced(finalBoard, finalCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; } + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); - for (TreeTentCell c : adjTrees) { - List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); - List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); - if (unkAroundTree.size() == 0) { - if (tntAroundTree.size() == 1) { - return true; - } - else { - for (TreeTentCell t : tntAroundTree) { - if (t == cell) { - continue; - } - List treesAroundTents = board.getAdjacent(t, TreeTentType.TREE); - if (treesAroundTents.size() == 1) { - return false; - } - } - return true; - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); + for (TreeTentCell c : adjTrees) { + List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); + List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); + if (unkAroundTree.size() == 0) { + if (tntAroundTree.size() == 1) { + return true; + } else { + for (TreeTentCell t : tntAroundTree) { + if (t == cell) { + continue; + } + List treesAroundTents = board.getAdjacent(t, TreeTentType.TREE); + if (treesAroundTents.size() == 1) { + return false; } + } + return true; } - return false; + } } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java index 39b1d0251..fec820260 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java @@ -6,162 +6,172 @@ import edu.rpi.legup.model.rules.CaseRule; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; - +import edu.rpi.legup.puzzle.treetent.TreeTentType; import java.util.ArrayList; import java.util.List; import java.util.Set; public class LinkTentCaseRule extends CaseRule { - public LinkTentCaseRule() { - super("TREE-CASE-0002", "Links from tent", - "A tent must link to exactly one adjacent tree.", - "edu/rpi/legup/images/treetent/caseLinkTent.png"); - } + public LinkTentCaseRule() { + super( + "TREE-CASE-0002", + "Links from tent", + "A tent must link to exactly one adjacent tree.", + "edu/rpi/legup/images/treetent/caseLinkTent.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.TENT && !getCases(board, element).isEmpty()) { - Boolean canAdd = true; - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { - canAdd = false; - break; - } - } - if (canAdd) { - caseBoard.addPickableElement(element); - } - } + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.TENT + && !getCases(board, element).isEmpty()) { + Boolean canAdd = true; + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) + || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { + canAdd = false; + break; + } + } + if (canAdd) { + caseBoard.addPickableElement(element); } - return caseBoard; + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - TreeTentCell cell = (TreeTentCell) puzzleElement; - List adj = ((TreeTentBoard) board).getAdjacent(cell, TreeTentType.TREE); - List lines = ((TreeTentBoard) board).getLines(); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + TreeTentCell cell = (TreeTentCell) puzzleElement; + List adj = ((TreeTentBoard) board).getAdjacent(cell, TreeTentType.TREE); + List lines = ((TreeTentBoard) board).getLines(); - for (TreeTentCell tree : adj) { - Boolean makeline = true; - for (TreeTentLine l : ((TreeTentBoard) board).getLines()) { - if (l.getC1().getLocation().equals(tree.getLocation()) || l.getC2().getLocation().equals(tree.getLocation())) { - makeline = false; - } - } - if (makeline) { - TreeTentBoard temp = ((TreeTentBoard) board).copy(); - TreeTentLine l = new TreeTentLine((TreeTentCell) temp.getPuzzleElement(cell), (TreeTentCell) temp.getPuzzleElement(tree)); - temp.getLines().add(l); - temp.addModifiedData(l); - cases.add(temp); - } + for (TreeTentCell tree : adj) { + Boolean makeline = true; + for (TreeTentLine l : ((TreeTentBoard) board).getLines()) { + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + makeline = false; } - return cases; + } + if (makeline) { + TreeTentBoard temp = ((TreeTentBoard) board).copy(); + TreeTentLine l = + new TreeTentLine( + (TreeTentCell) temp.getPuzzleElement(cell), + (TreeTentCell) temp.getPuzzleElement(tree)); + temp.getLines().add(l); + temp.addModifiedData(l); + cases.add(temp); + } } + return cases; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() != 1) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 1 modified cell for each case"; - } - PuzzleElement mod = modCells.iterator().next(); - TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; - if (line == null) { - return super.getInvalidUseOfRuleMessage() + ": This case rule only involves tree and tent connection lines"; - } - TreeTentCell tent = null; - if (line.getC1().getType() == TreeTentType.TENT) { - tent = line.getC1(); - } - if (line.getC2().getType() == TreeTentType.TENT) { - tent = line.getC2(); - } - if (tent == null) { - return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; + } + PuzzleElement mod = modCells.iterator().next(); + TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; + if (line == null) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; + } + TreeTentCell tent = null; + if (line.getC1().getType() == TreeTentType.TENT) { + tent = line.getC1(); + } + if (line.getC2().getType() == TreeTentType.TENT) { + tent = line.getC2(); + } + if (tent == null) { + return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; + } - TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - ArrayList cases = getCases(parentBoard, tent); - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != cases.size()) { - return super.getInvalidUseOfRuleMessage(); + TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + ArrayList cases = getCases(parentBoard, tent); + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != cases.size()) { + return super.getInvalidUseOfRuleMessage(); + } + for (Board caseBoard : cases) { + TreeTentBoard cBoard = (TreeTentBoard) caseBoard; + TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); + boolean hasLine = false; + for (TreeTransition tran : childTransitions) { + TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); + if (tBoard.getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage(); } - for (Board caseBoard : cases) { - TreeTentBoard cBoard = (TreeTentBoard) caseBoard; - TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); - boolean hasLine = false; - for (TreeTransition tran : childTransitions) { - TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); - if (tBoard.getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage(); - } - PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); - if (!(tElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": This case rule only involves tree and tent connection lines"; - } - if (cLine.compare((TreeTentLine) tElement)) { - hasLine = true; - break; - } - } - if (!hasLine) { - return super.getInvalidUseOfRuleMessage(); - } + PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); + if (!(tElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; } - - return null; + if (cLine.compare((TreeTentLine) tElement)) { + hasLine = true; + break; + } + } + if (!hasLine) { + return super.getInvalidUseOfRuleMessage(); + } } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + return null; + } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be valid - * Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends upon. - * Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - return List.of(board.getPuzzleElement(puzzleElement)); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + return List.of(board.getPuzzleElement(puzzleElement)); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java index 72ffd62eb..65bc52723 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java @@ -9,7 +9,6 @@ import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.awt.Point; import java.util.ArrayList; import java.util.List; @@ -17,168 +16,174 @@ public class LinkTreeCaseRule extends CaseRule { - public LinkTreeCaseRule() { - super("TREE-CASE-0003", "Links from tree", - "A tree must link to exactly one adjacent tent.", - "edu/rpi/legup/images/treetent/caseLinkTree.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.TREE && - !getCases(treeTentBoard, element).isEmpty()) { - - Boolean canAdd = true; - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { - canAdd = false; - break; - } - } - if (canAdd) { - caseBoard.addPickableElement(element); - } - - } + public LinkTreeCaseRule() { + super( + "TREE-CASE-0003", + "Links from tree", + "A tree must link to exactly one adjacent tent.", + "edu/rpi/legup/images/treetent/caseLinkTree.png"); + } + + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.TREE + && !getCases(treeTentBoard, element).isEmpty()) { + + Boolean canAdd = true; + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) + || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { + canAdd = false; + break; + } + } + if (canAdd) { + caseBoard.addPickableElement(element); } - return caseBoard; + } } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - List adjCells = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); - for (TreeTentCell c : adjCells) { - Boolean makeline = true; - for (TreeTentLine l : treeTentBoard.getLines()) { - if (l.getC1().getLocation().equals(c.getLocation()) || l.getC2().getLocation().equals(c.getLocation())) { - makeline = false; - } - } - if (makeline) { - TreeTentBoard caseBoard = (TreeTentBoard) board.copy(); - TreeTentLine line = new TreeTentLine(cell, c); - caseBoard.getLines().add(line); - caseBoard.addModifiedData(line); - cases.add(caseBoard); - } + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + List adjCells = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); + for (TreeTentCell c : adjCells) { + Boolean makeline = true; + for (TreeTentLine l : treeTentBoard.getLines()) { + if (l.getC1().getLocation().equals(c.getLocation()) + || l.getC2().getLocation().equals(c.getLocation())) { + makeline = false; } - return cases; + } + if (makeline) { + TreeTentBoard caseBoard = (TreeTentBoard) board.copy(); + TreeTentLine line = new TreeTentLine(cell, c); + caseBoard.getLines().add(line); + caseBoard.addModifiedData(line); + cases.add(caseBoard); + } + } + return cases; + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; + } + PuzzleElement mod = modCells.iterator().next(); + TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; + if (line == null) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; + } + TreeTentCell tree = null; + if (line.getC1().getType() == TreeTentType.TREE) { + tree = line.getC1(); + } + if (line.getC2().getType() == TreeTentType.TREE) { + tree = line.getC2(); + } + if (tree == null) { + return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() != 1) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 1 modified cell for each case"; - } - PuzzleElement mod = modCells.iterator().next(); - TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; - if (line == null) { - return super.getInvalidUseOfRuleMessage() + ": This case rule only involves tree and tent connection lines"; - } - TreeTentCell tree = null; - if (line.getC1().getType() == TreeTentType.TREE) { - tree = line.getC1(); - } - if (line.getC2().getType() == TreeTentType.TREE) { - tree = line.getC2(); - } - if (tree == null) { - return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; + TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + ArrayList cases = getCases(parentBoard, tree); + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != cases.size()) { + return super.getInvalidUseOfRuleMessage(); + } + for (Board caseBoard : cases) { + TreeTentBoard cBoard = (TreeTentBoard) caseBoard; + TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); + boolean hasLine = false; + for (TreeTransition tran : childTransitions) { + TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); + if (tBoard.getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage(); } - - TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - ArrayList cases = getCases(parentBoard, tree); - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != cases.size()) { - return super.getInvalidUseOfRuleMessage(); + PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); + if (!(tElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; } - for (Board caseBoard : cases) { - TreeTentBoard cBoard = (TreeTentBoard) caseBoard; - TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); - boolean hasLine = false; - for (TreeTransition tran : childTransitions) { - TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); - if (tBoard.getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage(); - } - PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); - if (!(tElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": This case rule only involves tree and tent connection lines"; - } - if (cLine.compare((TreeTentLine) tElement)) { - hasLine = true; - break; - } - } - if (!hasLine) { - return super.getInvalidUseOfRuleMessage(); - } + if (cLine.compare((TreeTentLine) tElement)) { + hasLine = true; + break; } - - return null; + } + if (!hasLine) { + return super.getInvalidUseOfRuleMessage(); + } } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(List.of(board.getPuzzleElement(puzzleElement))); + + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell point = (TreeTentCell) puzzleElement; + + // get all adjacent cells + Point loc = point.getLocation(); + for (int i = -2; i < 2; i++) { + TreeTentCell cell = treeTentBoard.getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); + if (cell != null) { + elements.add(board.getPuzzleElement(cell)); + } } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be valid - * Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends upon. - * Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(List.of(board.getPuzzleElement(puzzleElement))); - - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell point = (TreeTentCell) puzzleElement; - - // get all adjacent cells - Point loc = point.getLocation(); - for (int i = -2; i < 2; i++) { - TreeTentCell cell = treeTentBoard.getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); - if (cell != null) { - elements.add(board.getPuzzleElement(cell)); - } - } - - return elements; - } + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java index 2e5c2f043..900c37d92 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java @@ -5,61 +5,64 @@ import edu.rpi.legup.model.rules.ContradictionRule; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.TreeTentLine; - -import java.util.List; +import edu.rpi.legup.puzzle.treetent.TreeTentType; import java.util.Iterator; +import java.util.List; public class NoTentForTreeContradictionRule extends ContradictionRule { - public NoTentForTreeContradictionRule() { - super("TREE-CONT-0001", "No Tent For Tree", - "Each tree must link to a tent.", - "edu/rpi/legup/images/treetent/contra_NoTentForTree.png"); - } + public NoTentForTreeContradictionRule() { + super( + "TREE-CONT-0001", + "No Tent For Tree", + "Each tree must link to a tent.", + "edu/rpi/legup/images/treetent/contra_NoTentForTree.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TREE) { - return super.getNoContradictionMessage(); - } - int adjTent = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); - int adjUnknown = treeTentBoard.getAdjacent(cell, TreeTentType.UNKNOWN).size(); - if (adjTent == 0 && adjUnknown == 0) { - return null; - } - else { - if (adjTent != 0) { - List lines = treeTentBoard.getLines(); - List adjTents = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); - for (TreeTentLine l : lines) { - Iterator i = adjTents.iterator(); - while (i.hasNext()) { - TreeTentCell t = i.next(); - if (t.getLocation().equals(l.getC1().getLocation()) && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - if (t.getLocation().equals(l.getC2().getLocation()) && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - } - } - if (adjTents.size() == 0 && adjUnknown == 0) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TREE) { + return super.getNoContradictionMessage(); + } + int adjTent = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); + int adjUnknown = treeTentBoard.getAdjacent(cell, TreeTentType.UNKNOWN).size(); + if (adjTent == 0 && adjUnknown == 0) { + return null; + } else { + if (adjTent != 0) { + List lines = treeTentBoard.getLines(); + List adjTents = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); + for (TreeTentLine l : lines) { + Iterator i = adjTents.iterator(); + while (i.hasNext()) { + TreeTentCell t = i.next(); + if (t.getLocation().equals(l.getC1().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); } - return super.getNoContradictionMessage(); + if (t.getLocation().equals(l.getC2().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + } + } + if (adjTents.size() == 0 && adjUnknown == 0) { + return null; } + } + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java index 67f023dd7..c6cf2fc35 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java @@ -7,53 +7,56 @@ import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentType; - -import java.util.List; import java.util.Iterator; +import java.util.List; public class NoTreeForTentContradictionRule extends ContradictionRule { - public NoTreeForTentContradictionRule() { - super("TREE-CONT-0002", "No Tree For Tent", - "Each tent must link to a tree.", - "edu/rpi/legup/images/treetent/contra_NoTreeForTent.png"); - } + public NoTreeForTentContradictionRule() { + super( + "TREE-CONT-0002", + "No Tree For Tent", + "Each tent must link to a tree.", + "edu/rpi/legup/images/treetent/contra_NoTreeForTent.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TENT) { - return super.getNoContradictionMessage(); - } - List adjTrees = treeTentBoard.getAdjacent(cell, TreeTentType.TREE); - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - Iterator i = adjTrees.iterator(); - while (i.hasNext()) { - TreeTentCell t = i.next(); - if (t.getLocation().equals(l.getC1().getLocation()) && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - if (t.getLocation().equals(l.getC2().getLocation()) && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - } - } - int adjTree = adjTrees.size(); - if (adjTree == 0) { - return null; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TENT) { + return super.getNoContradictionMessage(); + } + List adjTrees = treeTentBoard.getAdjacent(cell, TreeTentType.TREE); + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + Iterator i = adjTrees.iterator(); + while (i.hasNext()) { + TreeTentCell t = i.next(); + if (t.getLocation().equals(l.getC1().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); } - else { - return super.getNoContradictionMessage(); + if (t.getLocation().equals(l.getC2().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); } + } + } + int adjTree = adjTrees.size(); + if (adjTree == 0) { + return null; + } else { + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java index 01f9e7058..447bbcde0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java @@ -9,77 +9,77 @@ import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.util.List; public class SurroundTentWithGrassDirectRule extends DirectRule { - public SurroundTentWithGrassDirectRule() { - super("TREE-BASC-0005", "Surround Tent with Grass", - "Blank cells adjacent or diagonal to a tent are grass.", - "edu/rpi/legup/images/treetent/aroundTent.png"); - } - - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement == null) { - return null; - } - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.GRASS)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } + public SurroundTentWithGrassDirectRule() { + super( + "TREE-BASC-0005", + "Surround Tent with Grass", + "Blank cells adjacent or diagonal to a tent are grass.", + "edu/rpi/legup/images/treetent/aroundTent.png"); + } - if (isForced(initialBoard, initCell)) { - return null; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement == null) { + return null; + } + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN + && finalCell.getType() == TreeTentType.GRASS)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List tents = board.getAdjacent(cell, TreeTentType.TENT); - tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); - return !tents.isEmpty(); + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; } + } + + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List tents = board.getAdjacent(cell, TreeTentType.TENT); + tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); + return !tents.isEmpty(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } - else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java index fd10c5d73..5091068a8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java @@ -9,116 +9,114 @@ import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.util.ArrayList; - import java.util.List; public class TentForTreeDirectRule extends DirectRule { - public TentForTreeDirectRule() { - super("TREE-BASC-0006", "Tent for Tree", - "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the unlinked tree must link to the unlinked tent.", - "edu/rpi/legup/images/treetent/NewTreeLink.png"); - } + public TentForTreeDirectRule() { + super( + "TREE-BASC-0006", + "Tent for Tree", + "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the unlinked tree must link to the unlinked tent.", + "edu/rpi/legup/images/treetent/NewTreeLink.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } - else { - if (line.getC2().getType() == TreeTentType.TREE && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } - else { - return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; - } - } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; - } - else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; - } - else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This tree and tent don't need to be linked."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE + && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); + } else { + if (line.getC2().getType() == TreeTentType.TREE + && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } else { + return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This tree and tent don't need to be linked."; } + } } + } - private Integer isForced(TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTents = board.getAdjacent(tree, TreeTentType.TENT); - adjTents.remove(tent); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTents) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tree.getLocation())) { - return -1; - } - toRemove.add(c); + private Integer isForced( + TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTents = board.getAdjacent(tree, TreeTentType.TENT); + adjTents.remove(tent); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTents) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); - } - else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tree.getLocation())) { - return -1; - } - toRemove.add(c); - } - } - } - for (TreeTentCell c : toRemove) { - adjTents.remove(c); + } else { + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tree.getLocation())) { + return -1; } - toRemove.clear(); - } - if (adjTents.size() == 0) { - return 1; - } - else { - return 0; + toRemove.add(c); + } } + } + for (TreeTentCell c : toRemove) { + adjTents.remove(c); + } + toRemove.clear(); } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + if (adjTents.size() == 0) { + return 1; + } else { + return 0; } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java index b0e9db109..2b6afd5d0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java @@ -8,102 +8,106 @@ import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.util.ArrayList; import java.util.List; public class TentOrGrassCaseRule extends CaseRule { - public TentOrGrassCaseRule() { - super("TREE-CASE-0004", "Tent or Grass", - "Each blank cell is either a tent or grass.", - "edu/rpi/legup/images/treetent/caseTentOrGrass.png"); - } + public TentOrGrassCaseRule() { + super( + "TREE-CASE-0004", + "Tent or Grass", + "Each blank cell is either a tent or grass.", + "edu/rpi/legup/images/treetent/caseTentOrGrass.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.UNKNOWN) { - caseBoard.addPickableElement(element); - } - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.UNKNOWN) { + caseBoard.addPickableElement(element); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(TreeTentType.TENT); - case1.addModifiedData(data1); - cases.add(case1); - - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(TreeTentType.GRASS); - case2.addModifiedData(data2); - cases.add(case2); - - return cases; - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(TreeTentType.TENT); + case1.addModifiedData(data1); + cases.add(case1); - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; - } + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(TreeTentType.GRASS); + case2.addModifiedData(data2); + cases.add(case2); - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 || - case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 1 modified cell for each case."; - } + return cases; + } - TreeTentCell mod1 = (TreeTentCell) case1.getBoard().getModifiedData().iterator().next(); - TreeTentCell mod2 = (TreeTentCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must modify the same cell for each case."; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - if (!((mod1.getType() == TreeTentType.TENT && mod2.getType() == TreeTentType.GRASS) || - (mod2.getType() == TreeTentType.TENT && mod1.getType() == TreeTentType.GRASS))) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have a tent and a grass cell."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - return null; + TreeTentCell mod1 = (TreeTentCell) case1.getBoard().getModifiedData().iterator().next(); + TreeTentCell mod2 = (TreeTentCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + if (!((mod1.getType() == TreeTentType.TENT && mod2.getType() == TreeTentType.GRASS) + || (mod2.getType() == TreeTentType.TENT && mod1.getType() == TreeTentType.GRASS))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have a tent and a grass cell."; } + + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java index 92b951feb..220a9aeb0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java @@ -6,42 +6,43 @@ import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.awt.*; public class TooFewTentsContradictionRule extends ContradictionRule { - public TooFewTentsContradictionRule() { - super("TREE-CONT-0003", "Too Few Tents", - "Rows and columns cannot have fewer tents than their clue.", - "edu/rpi/legup/images/treetent/too_few_tents.png"); - } + public TooFewTentsContradictionRule() { + super( + "TREE-CONT-0003", + "Too Few Tents", + "Rows and columns cannot have fewer tents than their clue.", + "edu/rpi/legup/images/treetent/too_few_tents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); - int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); - int rowUnknowns = treeTentBoard.getRowCol(loc.y, TreeTentType.UNKNOWN, true).size(); - int colUnknowns = treeTentBoard.getRowCol(loc.x, TreeTentType.UNKNOWN, false).size(); + Point loc = cell.getLocation(); + int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); + int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); + int rowUnknowns = treeTentBoard.getRowCol(loc.y, TreeTentType.UNKNOWN, true).size(); + int colUnknowns = treeTentBoard.getRowCol(loc.x, TreeTentType.UNKNOWN, false).size(); - if (rowTents + rowUnknowns < treeTentBoard.getRowClues().get(loc.y).getData() || - colTents + colUnknowns < treeTentBoard.getColClues().get(loc.x).getData()) { - return null; - } - else { - return super.getNoContradictionMessage(); - } + if (rowTents + rowUnknowns < treeTentBoard.getRowClues().get(loc.y).getData() + || colTents + colUnknowns < treeTentBoard.getColClues().get(loc.x).getData()) { + return null; + } else { + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java index 8bc908d0c..da2a3964d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java @@ -6,40 +6,41 @@ import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.TreeTentType; - import java.awt.*; public class TooManyTentsContradictionRule extends ContradictionRule { - public TooManyTentsContradictionRule() { - super("TREE-CONT-0004", "Too Many Tents", - "Rows and columns cannot have more tents than their clue.", - "edu/rpi/legup/images/treetent/too_many_tents.png"); - } + public TooManyTentsContradictionRule() { + super( + "TREE-CONT-0004", + "Too Many Tents", + "Rows and columns cannot have more tents than their clue.", + "edu/rpi/legup/images/treetent/too_many_tents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); - int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); + Point loc = cell.getLocation(); + int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); + int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); - if (rowTents > treeTentBoard.getRowClues().get(loc.y).getData() || - colTents > treeTentBoard.getColClues().get(loc.x).getData()) { - return null; - } - else { - return super.getNoContradictionMessage(); - } + if (rowTents > treeTentBoard.getRowClues().get(loc.y).getData() + || colTents > treeTentBoard.getColClues().get(loc.x).getData()) { + return null; + } else { + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java index a07153a31..075003130 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java @@ -9,36 +9,36 @@ public class TouchingTentsContradictionRule extends ContradictionRule { - public TouchingTentsContradictionRule() { - super("TREE-CONT-0005", "Touching Tents", - "Tents cannot touch other tents.", - "edu/rpi/legup/images/treetent/contra_adjacentTents.png"); - } + public TouchingTentsContradictionRule() { + super( + "TREE-CONT-0005", + "Touching Tents", + "Tents cannot touch other tents.", + "edu/rpi/legup/images/treetent/contra_adjacentTents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific - * {@link PuzzleElement} index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent {@link PuzzleElement} - * @return null if the transition contains a - * contradiction at the specified puzzleElement, - * otherwise error message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TENT) { - return super.getNoContradictionMessage(); - } - int adjTree = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); - int diagTree = treeTentBoard.getDiagonals(cell, TreeTentType.TENT).size(); - if (adjTree > 0 || diagTree > 0) { - return null; - } - else { - return super.getNoContradictionMessage(); - } + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent {@link PuzzleElement} + * @return null if the transition contains a contradiction at the specified + * puzzleElement, otherwise error message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TENT) { + return super.getNoContradictionMessage(); + } + int adjTree = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); + int diagTree = treeTentBoard.getDiagonals(cell, TreeTentType.TENT).size(); + if (adjTree > 0 || diagTree > 0) { + return null; + } else { + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java index 62e1af51c..a6c213c28 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java @@ -1,122 +1,121 @@ package edu.rpi.legup.puzzle.treetent.rules; -import java.util.List; -import java.util.ArrayList; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.rules.DirectRule; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.treetent.TreeTentLine; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.TreeTentCell; +import edu.rpi.legup.puzzle.treetent.TreeTentLine; +import edu.rpi.legup.puzzle.treetent.TreeTentType; +import java.util.ArrayList; +import java.util.List; public class TreeForTentDirectRule extends DirectRule { - public TreeForTentDirectRule() { - super("TREE-BASC-0007", "Tree for Tent", - "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must link to the unlinked tree.", - "edu/rpi/legup/images/treetent/NewTentLink.png"); - } + public TreeForTentDirectRule() { + super( + "TREE-BASC-0007", + "Tree for Tent", + "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must link to the unlinked tree.", + "edu/rpi/legup/images/treetent/NewTentLink.png"); + } - /** - * Checks whether the child node logically follows from the parent node - * at the specific puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } - else { - if (line.getC2().getType() == TreeTentType.TREE && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } - else { - return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; - } - } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; - } - else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; - } - else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; - } - else { - return super.getInvalidUseOfRuleMessage() + ": This tree and tent don't need to be linked."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE + && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); + } else { + if (line.getC2().getType() == TreeTentType.TREE + && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } else { + return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This tree and tent don't need to be linked."; } + } } + } - private Integer isForced(TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); - adjTrees.remove(tree); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTrees) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tent.getLocation())) { - return -1; - } - toRemove.add(c); + private Integer isForced( + TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); + adjTrees.remove(tree); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTrees) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); - } - else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tent.getLocation())) { - return -1; - } - toRemove.add(c); - } - } - } - for (TreeTentCell c : toRemove) { - adjTrees.remove(c); + } else { + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tent.getLocation())) { + return -1; } - toRemove.clear(); - } - if (adjTrees.size() == 0) { - return 1; - } - else { - return 0; + toRemove.add(c); + } } + } + for (TreeTentCell c : toRemove) { + adjTrees.remove(c); + } + toRemove.clear(); } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + if (adjTrees.size() == 0) { + return 1; + } else { + return 0; } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/save/ExportFileException.java b/src/main/java/edu/rpi/legup/save/ExportFileException.java index 46ebac9e0..70eec7868 100644 --- a/src/main/java/edu/rpi/legup/save/ExportFileException.java +++ b/src/main/java/edu/rpi/legup/save/ExportFileException.java @@ -2,8 +2,7 @@ public class ExportFileException extends Exception { - public ExportFileException(String message) { - super("Export File Exception: " + message); - } - + public ExportFileException(String message) { + super("Export File Exception: " + message); + } } diff --git a/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java b/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java index 94c229411..9207aeaa6 100644 --- a/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java +++ b/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java @@ -2,8 +2,7 @@ public class InvalidFileFormatException extends Exception { - public InvalidFileFormatException(String message) { - super("InvalidFileFormatException: " + message); - } - + public InvalidFileFormatException(String message) { + super("InvalidFileFormatException: " + message); + } } diff --git a/src/main/java/edu/rpi/legup/save/SavableBoard.java b/src/main/java/edu/rpi/legup/save/SavableBoard.java index a7799a15a..a0d141dea 100644 --- a/src/main/java/edu/rpi/legup/save/SavableBoard.java +++ b/src/main/java/edu/rpi/legup/save/SavableBoard.java @@ -1,23 +1,16 @@ package edu.rpi.legup.save; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; import java.io.FileInputStream; import java.io.InputStream; public class SavableBoard { - private static final String LEGUP_HEADER = "edu.rpi.legup.Legup"; - - private String filePath; - private InputStream inputStream; - - public SavableBoard(String filePath) throws Exception { - this.filePath = filePath; - this.inputStream = new FileInputStream(filePath); + private static final String LEGUP_HEADER = "edu.rpi.legup.Legup"; + private String filePath; + private InputStream inputStream; - } + public SavableBoard(String filePath) throws Exception { + this.filePath = filePath; + this.inputStream = new FileInputStream(filePath); + } } diff --git a/src/main/java/edu/rpi/legup/save/SavableProof.java b/src/main/java/edu/rpi/legup/save/SavableProof.java index 101e56125..4f6e4697c 100644 --- a/src/main/java/edu/rpi/legup/save/SavableProof.java +++ b/src/main/java/edu/rpi/legup/save/SavableProof.java @@ -1,5 +1,3 @@ package edu.rpi.legup.save; -public class SavableProof { - -} +public class SavableProof {} diff --git a/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java b/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java index fa049ab38..65af81f7f 100644 --- a/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java +++ b/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java @@ -3,88 +3,90 @@ import edu.rpi.legup.app.Config; import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.controller.CursorController; - -import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Objects; +import javax.swing.*; public class CreatePuzzleDialog extends JDialog { - private HomePanel homePanel; + private HomePanel homePanel; - private String[] games; - private JComboBox gameBox; - private ActionListener gameBoxListener = new ActionListener() { + private String[] games; + private JComboBox gameBox; + private ActionListener gameBoxListener = + new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - JComboBox comboBox = (JComboBox) e.getSource(); - String puzzleName = (String) comboBox.getSelectedItem(); - if (puzzleName.equals("ShortTruthTable")) { - textInputScrollPane.setVisible(true); - rowsLabel.setVisible(false); - rows.setVisible(false); - columnsLabel.setVisible(false); - columns.setVisible(false); - } - else { - textInputScrollPane.setVisible(false); - rowsLabel.setVisible(true); - rows.setVisible(true); - columnsLabel.setVisible(true); - columns.setVisible(true); - } + JComboBox comboBox = (JComboBox) e.getSource(); + String puzzleName = (String) comboBox.getSelectedItem(); + if (puzzleName.equals("ShortTruthTable")) { + textInputScrollPane.setVisible(true); + rowsLabel.setVisible(false); + rows.setVisible(false); + columnsLabel.setVisible(false); + columns.setVisible(false); + } else { + textInputScrollPane.setVisible(false); + rowsLabel.setVisible(true); + rows.setVisible(true); + columnsLabel.setVisible(true); + columns.setVisible(true); + } } - }; + }; - private JLabel puzzleLabel; - private JLabel rowsLabel; - private JTextField rows; - private JLabel columnsLabel; - private JTextField columns; + private JLabel puzzleLabel; + private JLabel rowsLabel; + private JTextField rows; + private JLabel columnsLabel; + private JTextField columns; - private JTextArea textArea; - private JScrollPane textInputScrollPane; + private JTextArea textArea; + private JScrollPane textInputScrollPane; - private JButton ok = new JButton("Ok"); - private ActionListener okButtonListener = new ActionListener() { + private JButton ok = new JButton("Ok"); + private ActionListener okButtonListener = + new ActionListener() { /** * Attempts to open the puzzle editor interface for the given game with the given dimensions + * * @param ae the event to be processed */ @Override public void actionPerformed(ActionEvent ae) { - String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); - - // Check if all 3 TextFields are filled - if (game.equals("ShortTruthTable") && textArea.getText().equals("")) { - System.out.println("Unfilled fields"); - return; - } - if (!game.equals("ShortTruthTable") && (game.equals("") || rows.getText().equals("") || columns.getText().equals(""))) { - System.out.println("Unfilled fields"); - return; - } - - try { - if (game.equals("ShortTruthTable")) { - homePanel.openEditorWithNewPuzzle("ShortTruthTable", textArea.getText().split("\n")); - } - else { - homePanel.openEditorWithNewPuzzle(game, Integer.valueOf(rows.getText()), Integer.valueOf(columns.getText())); - } - setVisible(false); - } - catch (IllegalArgumentException e) { - System.out.println("Failed to open editor with new puzzle"); - e.printStackTrace(System.out); + String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); + + // Check if all 3 TextFields are filled + if (game.equals("ShortTruthTable") && textArea.getText().isEmpty()) { + System.out.println("Unfilled fields"); + return; + } + if (!game.equals("ShortTruthTable") + && (game.isEmpty() || rows.getText().isEmpty() || columns.getText().isEmpty())) { + System.out.println("Unfilled fields"); + return; + } + + try { + if (game.equals("ShortTruthTable")) { + homePanel.openEditorWithNewPuzzle("ShortTruthTable", textArea.getText().split("\n")); + } else { + homePanel.openEditorWithNewPuzzle( + game, Integer.valueOf(rows.getText()), Integer.valueOf(columns.getText())); } + setVisible(false); + } catch (IllegalArgumentException e) { + System.out.println("Failed to open editor with new puzzle"); + e.printStackTrace(System.out); + } } - }; + }; - private JButton cancel = new JButton("Cancel"); - private ActionListener cancelButtonListener = new ActionListener() { + private JButton cancel = new JButton("Cancel"); + private ActionListener cancelButtonListener = + new ActionListener() { /** * Dispose the puzzle creation dialog * @@ -92,116 +94,122 @@ public void actionPerformed(ActionEvent ae) { */ @Override public void actionPerformed(ActionEvent e) { - dispose(); + dispose(); } - }; + }; - public CreatePuzzleDialog(JFrame parent, HomePanel homePanel) { - super(parent, true); + public CreatePuzzleDialog(JFrame parent, HomePanel homePanel) { + super(parent, true); - this.homePanel = homePanel; + this.homePanel = homePanel; - initPuzzles(); + initPuzzles(); - Rectangle b = parent.getBounds(); + Rectangle b = parent.getBounds(); - setSize(350, 200); - setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); + setSize(350, 200); + setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); - Container c = getContentPane(); - c.setLayout(null); + Container c = getContentPane(); + c.setLayout(null); - puzzleLabel = new JLabel("Puzzle:"); - puzzleLabel.setBounds(10, 30, 70, 25); - gameBox.setBounds(80, 30, 190, 25); + puzzleLabel = new JLabel("Puzzle:"); + puzzleLabel.setBounds(10, 30, 70, 25); + gameBox.setBounds(80, 30, 190, 25); - ok.setBounds(20, 130, 60, 25); - cancel.setBounds(170, 130, 90, 25); + ok.setBounds(20, 130, 60, 25); + cancel.setBounds(170, 130, 90, 25); - c.add(puzzleLabel); - c.add(gameBox); + c.add(puzzleLabel); + c.add(gameBox); - rows = new JTextField(); - columns = new JTextField(); + rows = new JTextField(); + columns = new JTextField(); - rowsLabel = new JLabel("Rows:"); - columnsLabel = new JLabel("Columns:"); + rowsLabel = new JLabel("Rows:"); + columnsLabel = new JLabel("Columns:"); - rowsLabel.setBounds(30, 70, 60, 25); - columnsLabel.setBounds(30, 95, 60, 25); + rowsLabel.setBounds(30, 70, 60, 25); + columnsLabel.setBounds(30, 95, 60, 25); - rows.setBounds(100, 70, 60, 25); - columns.setBounds(100, 95, 60, 25); + rows.setBounds(100, 70, 60, 25); + columns.setBounds(100, 95, 60, 25); - c.add(rowsLabel); - c.add(columnsLabel); + c.add(rowsLabel); + c.add(columnsLabel); - c.add(rows); - c.add(columns); + c.add(rows); + c.add(columns); - textArea = new JTextArea(); - textInputScrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - textInputScrollPane.setBounds(10, 70, this.getWidth() - 30, 50); - c.add(textInputScrollPane); + textArea = new JTextArea(); + textInputScrollPane = + new JScrollPane( + textArea, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + textInputScrollPane.setBounds(10, 70, this.getWidth() - 30, 50); + c.add(textInputScrollPane); - c.add(ok); - c.add(cancel); + c.add(ok); + c.add(cancel); - if (Objects.equals(this.gameBox.getSelectedItem(), "ShortTruthTable")) { - textInputScrollPane.setVisible(true); - rowsLabel.setVisible(false); - rows.setVisible(false); - columnsLabel.setVisible(false); - columns.setVisible(false); - } - else { - textInputScrollPane.setVisible(false); - rowsLabel.setVisible(true); - rows.setVisible(true); - columnsLabel.setVisible(true); - columns.setVisible(true); - } - - ActionListener cursorSelectedGame = CursorController.createListener(this, gameBoxListener); - gameBox.addActionListener(cursorSelectedGame); - ActionListener cursorPressedOk = CursorController.createListener(this, okButtonListener); - ok.addActionListener(cursorPressedOk); - ActionListener cursorPressedCancel = CursorController.createListener(this, cancelButtonListener); - cancel.addActionListener(cursorPressedCancel); - } - - public void initPuzzles() { - this.games = GameBoardFacade.getInstance().getConfig().getFileCreationEnabledPuzzles().toArray(new String[0]); - Arrays.sort(this.games); - gameBox = new JComboBox(this.games); + if (Objects.equals(this.gameBox.getSelectedItem(), "ShortTruthTable")) { + textInputScrollPane.setVisible(true); + rowsLabel.setVisible(false); + rows.setVisible(false); + columnsLabel.setVisible(false); + columns.setVisible(false); + } else { + textInputScrollPane.setVisible(false); + rowsLabel.setVisible(true); + rows.setVisible(true); + columnsLabel.setVisible(true); + columns.setVisible(true); } - // ^This method seems useless and never got covered - public void actionPerformed(ActionEvent e) { - if (e.getSource() == ok) { - String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); - - try { - if (game.equals("ShortTruthTable")) { - this.homePanel.openEditorWithNewPuzzle("ShortTruthTable", this.textArea.getText().split("\n")); - } - else { - this.homePanel.openEditorWithNewPuzzle(game, Integer.valueOf(this.rows.getText()), Integer.valueOf(this.columns.getText())); - - } - this.setVisible(false); - } - catch (IllegalArgumentException exception) { - // Don't do anything. This is here to prevent the dialog from closing if the dimensions are invalid. - } - } - else { - if (e.getSource() == cancel) { - this.setVisible(false); - } - else { - // Unknown Action Event - } + ActionListener cursorSelectedGame = CursorController.createListener(this, gameBoxListener); + gameBox.addActionListener(cursorSelectedGame); + ActionListener cursorPressedOk = CursorController.createListener(this, okButtonListener); + ok.addActionListener(cursorPressedOk); + ActionListener cursorPressedCancel = + CursorController.createListener(this, cancelButtonListener); + cancel.addActionListener(cursorPressedCancel); + } + + public void initPuzzles() { + this.games = + GameBoardFacade.getInstance() + .getConfig() + .getFileCreationEnabledPuzzles() + .toArray(new String[0]); + Arrays.sort(this.games); + gameBox = new JComboBox(this.games); + } + + // ^This method seems useless and never got covered + public void actionPerformed(ActionEvent e) { + if (e.getSource() == ok) { + String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); + + try { + if (game.equals("ShortTruthTable")) { + this.homePanel.openEditorWithNewPuzzle( + "ShortTruthTable", this.textArea.getText().split("\n")); + } else { + this.homePanel.openEditorWithNewPuzzle( + game, Integer.valueOf(this.rows.getText()), Integer.valueOf(this.columns.getText())); } + this.setVisible(false); + } catch (IllegalArgumentException exception) { + // Don't do anything. This is here to prevent the dialog from closing if the dimensions are + // invalid. + } + } else { + if (e.getSource() == cancel) { + this.setVisible(false); + } else { + // Unknown Action Event + } } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/ui/DynamicView.java b/src/main/java/edu/rpi/legup/ui/DynamicView.java index 038f87d23..1dea7a905 100644 --- a/src/main/java/edu/rpi/legup/ui/DynamicView.java +++ b/src/main/java/edu/rpi/legup/ui/DynamicView.java @@ -1,216 +1,220 @@ package edu.rpi.legup.ui; +import static java.awt.BorderLayout.*; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialColors; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialFonts; - -import javax.imageio.ImageIO; -import javax.swing.*; -import javax.swing.event.ChangeEvent; import java.awt.*; import java.awt.event.*; import java.io.IOException; import java.util.Hashtable; import java.util.Objects; - -import static java.awt.BorderLayout.*; +import javax.imageio.ImageIO; +import javax.swing.*; +import javax.swing.event.ChangeEvent; public class DynamicView extends JPanel { - private ScrollView scrollView; - private JPanel zoomWrapper; - private JPanel zoomer; - private JLabel status; - - private static final Font ERROR_FONT = MaterialFonts.ITALIC; - private static final Color ERROR_COLOR = MaterialColors.RED_700; - - private static final Font INFO_FONT = MaterialFonts.REGULAR; - private static final Color INFO_COLOR = MaterialColors.GRAY_900; - - public DynamicView(ScrollView scrollView, DynamicViewType type) { - this.scrollView = scrollView; - - setLayout(new BorderLayout()); - - add(scrollView, CENTER); - add(setUpZoomer(type), SOUTH); + private ScrollView scrollView; + private JPanel zoomWrapper; + private JPanel zoomer; + private JLabel status; + + private static final Font ERROR_FONT = MaterialFonts.ITALIC; + private static final Color ERROR_COLOR = MaterialColors.RED_700; + + private static final Font INFO_FONT = MaterialFonts.REGULAR; + private static final Color INFO_COLOR = MaterialColors.GRAY_900; + + public DynamicView(ScrollView scrollView, DynamicViewType type) { + this.scrollView = scrollView; + + setLayout(new BorderLayout()); + + add(scrollView, CENTER); + add(setUpZoomer(type), SOUTH); + } + + /** + * Sets up the zoomer for the given DynamicViewType + * + * @param type The DynamicView that we are setting up the zoomer for (so the zoomer for the board + * view or the zoomer for the proof tree view) + * @return A JPanel containing the zoomer + */ + private JPanel setUpZoomer(DynamicViewType type) { + if (type == DynamicViewType.BOARD) { + return setUpBoardZoomer(); + } else { + if (type == DynamicViewType.PROOF_TREE) { + return setUpProofTreeZoomer(); + } } - /** - * Sets up the zoomer for the given DynamicViewType - * - * @param type The DynamicView that we are setting up the zoomer for (so - * the zoomer for the board view or the zoomer for the proof - * tree view) - * @return A JPanel containing the zoomer - */ - private JPanel setUpZoomer(DynamicViewType type) { - if (type == DynamicViewType.BOARD) { - return setUpBoardZoomer(); - } - else { - if (type == DynamicViewType.PROOF_TREE) { - return setUpProofTreeZoomer(); + // Should never reach here; if you reach here, that's a problem! + return null; + } + + /** + * Sets up the zoomer for the board view + * + * @return A JPanel containing the zoomer + */ + private JPanel setUpBoardZoomer() { + final String label = "Resize Board"; + ActionListener listener = (ActionListener) -> this.fitBoardViewToScreen(); + return this.setUpZoomerHelper(label, listener); + } + + /** + * Sets up the zoomer for the proof tree view + * + * @return A JPanel containing the zoomer + */ + private JPanel setUpProofTreeZoomer() { + final String label = "Resize Proof"; + ActionListener listener = + (ActionListener) -> + GameBoardFacade.getInstance().getLegupUI().getProofEditor().fitTreeViewToScreen(); + return this.setUpZoomerHelper(label, listener); + } + + /** + * Creates the zoomer + * + * @param label A string containing the label to be displayed on the fit to screen button + * @param listener A listener that determines what the resize button will do + * @return A JPanel containing the zoomer + */ + private JPanel setUpZoomerHelper(final String label, ActionListener listener) { + zoomWrapper = new JPanel(); + try { + zoomer = new JPanel(); + + // Create and add the resize button to the zoomer + JButton resizeButton = new JButton(label); + resizeButton.setFocusPainted(false); + resizeButton.setFocusPainted(false); + resizeButton.setEnabled(true); + resizeButton.setSize(100, 50); + resizeButton.addActionListener(listener); + zoomer.add(resizeButton); + + JLabel zoomLabel = new JLabel("100%"); + zoomLabel.setFont(MaterialFonts.getRegularFont(16f)); + + JSlider zoomSlider = new JSlider(25, 400, 100); + + JButton plus = + new JButton( + new ImageIcon( + ImageIO.read( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/imgs/add.png"))))); + plus.setFocusPainted(false); + plus.setFont(MaterialFonts.getRegularFont(10f)); + plus.setPreferredSize(new Dimension(20, 20)); + plus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() + 25)); + + JButton minus = + new JButton( + new ImageIcon( + ImageIO.read( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/imgs/remove.png"))))); + minus.setFocusPainted(false); + minus.setPreferredSize(new Dimension(20, 20)); + minus.setFont(MaterialFonts.getRegularFont(10f)); + minus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() - 25)); + this.scrollView.setWheelScrollingEnabled(true); + + zoomSlider.setPreferredSize(new Dimension(160, 30)); + + scrollView.addComponentListener( + new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + zoomSlider.setValue(scrollView.getZoom()); + zoomLabel.setText(zoomSlider.getValue() + "%"); } - } - - // Should never reach here; if you reach here, that's a problem! - return null; - } - - /** - * Sets up the zoomer for the board view - * - * @return A JPanel containing the zoomer - */ - private JPanel setUpBoardZoomer() { - final String label = "Resize Board"; - ActionListener listener = (ActionListener) -> this.fitBoardViewToScreen(); - return this.setUpZoomerHelper(label, listener); - } - - /** - * Sets up the zoomer for the proof tree view - * - * @return A JPanel containing the zoomer - */ - private JPanel setUpProofTreeZoomer() { - final String label = "Resize Proof"; - ActionListener listener = (ActionListener) -> GameBoardFacade.getInstance().getLegupUI().getProofEditor().fitTreeViewToScreen(); - return this.setUpZoomerHelper(label, listener); - } - - /** - * Creates the zoomer - * - * @param label A string containing the label to be displayed - * on the fit to screen button - * @param listener A listener that determines what the resize - * button will do - * @return A JPanel containing the zoomer - */ - private JPanel setUpZoomerHelper(final String label, ActionListener listener) { - zoomWrapper = new JPanel(); - try { - zoomer = new JPanel(); - - // Create and add the resize button to the zoomer - JButton resizeButton = new JButton(label); - resizeButton.setFocusPainted(false); - resizeButton.setFocusPainted(false); - resizeButton.setEnabled(true); - resizeButton.setSize(100, 50); - resizeButton.addActionListener(listener); - zoomer.add(resizeButton); - - JLabel zoomLabel = new JLabel("100%"); - zoomLabel.setFont(MaterialFonts.getRegularFont(16f)); - - JSlider zoomSlider = new JSlider(25, 400, 100); - - JButton plus = new JButton(new ImageIcon(ImageIO.read( - Objects.requireNonNull(ClassLoader.getSystemClassLoader().getResource( - "edu/rpi/legup/imgs/add.png"))))); - plus.setFocusPainted(false); - plus.setFont(MaterialFonts.getRegularFont(10f)); - plus.setPreferredSize(new Dimension(20, 20)); - plus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() + 25)); - - - JButton minus = new JButton(new ImageIcon(ImageIO.read( - Objects.requireNonNull(ClassLoader.getSystemClassLoader().getResource( - "edu/rpi/legup/imgs/remove.png"))))); - minus.setFocusPainted(false); - minus.setPreferredSize(new Dimension(20, 20)); - minus.setFont(MaterialFonts.getRegularFont(10f)); - minus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() - 25)); - this.scrollView.setWheelScrollingEnabled(true); - - zoomSlider.setPreferredSize(new Dimension(160, 30)); - - scrollView.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - zoomSlider.setValue(scrollView.getZoom()); - zoomLabel.setText(zoomSlider.getValue() + "%"); - } - }); - - zoomSlider.addChangeListener((ChangeEvent e) -> { - scrollView.zoomTo(zoomSlider.getValue() / 100.0); - zoomLabel.setText(zoomSlider.getValue() + "%"); - }); - - - zoomSlider.setMajorTickSpacing(100); - zoomSlider.setMinorTickSpacing(25); - zoomSlider.setPaintTicks(true); - - Hashtable labelTable = new Hashtable<>(); - labelTable.put(0, new JLabel("25%")); - labelTable.put(100, new JLabel("100%")); - labelTable.put(400, new JLabel("400%")); - zoomSlider.setLabelTable(labelTable); - - zoomer.setLayout(new FlowLayout()); - - zoomer.add(minus); - zoomer.add(zoomSlider); - zoomer.add(plus); - zoomer.add(zoomLabel); - - status = new JLabel(); - - zoomWrapper.setLayout(new BorderLayout()); - zoomWrapper.add(status, WEST); - zoomWrapper.add(zoomer, EAST); - } - catch (IOException e) { - e.printStackTrace(); - } - return zoomWrapper; - } - - public ScrollView getScrollView() { - return this.scrollView; - } - - public JPanel getZoomWrapper() { - return this.zoomWrapper; - } - - public JPanel getZoomer() { - return this.zoomer; - } - - public void updateInfo(String message) { - status.setFont(INFO_FONT); - status.setForeground(INFO_COLOR); - status.setText(message); - } - - public void updateError(String message) { - status.setFont(ERROR_FONT); - status.setForeground(ERROR_COLOR); - status.setText(message); - } - - public void resetStatus() { - status.setText(""); - } - - public void reset() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - Board board1 = GameBoardFacade.getInstance().getBoard(); - board1.setModifiable(true); - Dimension bi = new Dimension(1200, 900); - this.getScrollView().zoomFit(); - } - - protected void fitBoardViewToScreen() { - scrollView.zoomFit(); + }); + + zoomSlider.addChangeListener( + (ChangeEvent e) -> { + scrollView.zoomTo(zoomSlider.getValue() / 100.0); + zoomLabel.setText(zoomSlider.getValue() + "%"); + }); + + zoomSlider.setMajorTickSpacing(100); + zoomSlider.setMinorTickSpacing(25); + zoomSlider.setPaintTicks(true); + + Hashtable labelTable = new Hashtable<>(); + labelTable.put(0, new JLabel("25%")); + labelTable.put(100, new JLabel("100%")); + labelTable.put(400, new JLabel("400%")); + zoomSlider.setLabelTable(labelTable); + + zoomer.setLayout(new FlowLayout()); + + zoomer.add(minus); + zoomer.add(zoomSlider); + zoomer.add(plus); + zoomer.add(zoomLabel); + + status = new JLabel(); + + zoomWrapper.setLayout(new BorderLayout()); + zoomWrapper.add(status, WEST); + zoomWrapper.add(zoomer, EAST); + } catch (IOException e) { + e.printStackTrace(); } + return zoomWrapper; + } + + public ScrollView getScrollView() { + return this.scrollView; + } + + public JPanel getZoomWrapper() { + return this.zoomWrapper; + } + + public JPanel getZoomer() { + return this.zoomer; + } + + public void updateInfo(String message) { + status.setFont(INFO_FONT); + status.setForeground(INFO_COLOR); + status.setText(message); + } + + public void updateError(String message) { + status.setFont(ERROR_FONT); + status.setForeground(ERROR_COLOR); + status.setText(message); + } + + public void resetStatus() { + status.setText(""); + } + + public void reset() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + Board board1 = GameBoardFacade.getInstance().getBoard(); + board1.setModifiable(true); + Dimension bi = new Dimension(1200, 900); + this.getScrollView().zoomFit(); + } + + protected void fitBoardViewToScreen() { + scrollView.zoomFit(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/DynamicViewType.java b/src/main/java/edu/rpi/legup/ui/DynamicViewType.java index 8c2f285cd..cf345c4e1 100644 --- a/src/main/java/edu/rpi/legup/ui/DynamicViewType.java +++ b/src/main/java/edu/rpi/legup/ui/DynamicViewType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.ui; public enum DynamicViewType { - BOARD, - PROOF_TREE + BOARD, + PROOF_TREE } diff --git a/src/main/java/edu/rpi/legup/ui/HomePanel.java b/src/main/java/edu/rpi/legup/ui/HomePanel.java index 2270c92b8..9097b648c 100644 --- a/src/main/java/edu/rpi/legup/ui/HomePanel.java +++ b/src/main/java/edu/rpi/legup/ui/HomePanel.java @@ -3,662 +3,660 @@ import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.controller.CursorController; -import edu.rpi.legup.save.InvalidFileFormatException; import edu.rpi.legup.model.Puzzle; -import edu.rpi.legup.model.PuzzleExporter; -import edu.rpi.legup.save.ExportFileException; - -import javax.swing.*; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.parsers.ParserConfigurationException; +import edu.rpi.legup.save.InvalidFileFormatException; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; +import java.io.FileWriter; +import java.net.URI; +import java.net.URL; import java.util.Objects; - +import javax.swing.*; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; -import java.io.FileWriter; -import java.net.URI; -import java.net.URL; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - public class HomePanel extends LegupPanel { - private final static Logger LOGGER = LogManager.getLogger(HomePanel.class.getName()); - private LegupUI legupUI; - private JFrame frame; - private JButton[] buttons; - private JLabel[] text; - private JMenuBar menuBar; - private JFileChooser folderBrowser; - - private final int buttonSize = 100; - - private ActionListener openProofListener = new ActionListener() { + private static final Logger LOGGER = LogManager.getLogger(HomePanel.class.getName()); + private LegupUI legupUI; + private JFrame frame; + private JButton[] buttons; + private JLabel[] text; + private JMenuBar menuBar; + private JFileChooser folderBrowser; + + private final int buttonSize = 100; + + private ActionListener openProofListener = + new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Object[] items = legupUI.getProofEditor().promptPuzzle(); - if (items == null) { - // The attempt to prompt a puzzle ended gracefully (cancel) - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - legupUI.getProofEditor().loadPuzzle(fileName, puzzleFile); + Object[] items = legupUI.getProofEditor().promptPuzzle(); + if (items == null) { + // The attempt to prompt a puzzle ended gracefully (cancel) + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + legupUI.getProofEditor().loadPuzzle(fileName, puzzleFile); } - }; + }; - private ActionListener openPuzzleListener = new ActionListener() { + private ActionListener openPuzzleListener = + new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Object[] items = legupUI.getPuzzleEditor().promptPuzzle(); - if (items == null) { - // The attempt to prompt a puzzle ended gracefully (cancel) - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - legupUI.getPuzzleEditor().loadPuzzle(fileName, puzzleFile); + Object[] items = legupUI.getPuzzleEditor().promptPuzzle(); + if (items == null) { + // The attempt to prompt a puzzle ended gracefully (cancel) + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + legupUI.getPuzzleEditor().loadPuzzle(fileName, puzzleFile); } - }; - - public HomePanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.legupUI = legupUI; - this.frame = frame; - setLayout(new GridLayout(1, 2)); - initText(); - initButtons(); - } - - public JMenuBar getMenuBar() { - this.menuBar = new JMenuBar(); - JMenu settings = new JMenu("Settings"); - menuBar.add(settings); - JMenuItem preferences = new JMenuItem("Preferences"); - preferences.addActionListener(a -> { - PreferencesDialog preferencesDialog = new PreferencesDialog(this.frame); - System.out.println("Preferences clicked"); + }; + + public HomePanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.legupUI = legupUI; + this.frame = frame; + setLayout(new GridLayout(1, 2)); + initText(); + initButtons(); + } + + public JMenuBar getMenuBar() { + this.menuBar = new JMenuBar(); + JMenu settings = new JMenu("Settings"); + menuBar.add(settings); + JMenuItem preferences = new JMenuItem("Preferences"); + preferences.addActionListener( + a -> { + PreferencesDialog preferencesDialog = new PreferencesDialog(this.frame); + System.out.println("Preferences clicked"); }); - settings.addSeparator(); - settings.add(preferences); - - JMenuItem contribute = new JMenuItem("Contribute to Legup"); - contribute.addActionListener(l -> { - try { - java.awt.Desktop.getDesktop().browse(URI.create("https://github.com/Bram-Hub/Legup")); - } - catch (IOException e) { - LOGGER.error("Can't open web page"); - } + settings.addSeparator(); + settings.add(preferences); + + JMenuItem contribute = new JMenuItem("Contribute to Legup"); + contribute.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop().browse(URI.create("https://github.com/Bram-Hub/Legup")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } }); - settings.add(contribute); - - return this.menuBar; - } - - @Override - public void makeVisible() { - render(); - frame.setJMenuBar(this.getMenuBar()); - } - - private static ImageIcon resizeButtonIcon(ImageIcon icon, int width, int height) { - Image image = icon.getImage(); - Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); - return new ImageIcon(resizedImage); - } - - private void initButtons() { - this.buttons = new JButton[4]; - - this.buttons[0] = new JButton("Solve Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } + settings.add(contribute); + + return this.menuBar; + } + + @Override + public void makeVisible() { + render(); + frame.setJMenuBar(this.getMenuBar()); + } + + private static ImageIcon resizeButtonIcon(ImageIcon icon, int width, int height) { + Image image = icon.getImage(); + Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); + return new ImageIcon(resizedImage); + } + + private void initButtons() { + this.buttons = new JButton[4]; + + this.buttons[0] = + new JButton("Solve Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } }; - URL button0IconLocation = ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/homepanel/proof_file.png"); - ImageIcon button0Icon = new ImageIcon(button0IconLocation); - this.buttons[0].setFocusPainted(false); - this.buttons[0].setIcon(resizeButtonIcon(button0Icon, this.buttonSize, this.buttonSize)); - this.buttons[0].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[0].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[0].addActionListener(CursorController.createListener(this, openProofListener)); - - this.buttons[1] = new JButton("Create Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } + URL button0IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/proof_file.png"); + ImageIcon button0Icon = new ImageIcon(button0IconLocation); + this.buttons[0].setFocusPainted(false); + this.buttons[0].setIcon(resizeButtonIcon(button0Icon, this.buttonSize, this.buttonSize)); + this.buttons[0].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[0].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[0].addActionListener(CursorController.createListener(this, openProofListener)); + + this.buttons[1] = + new JButton("Create Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } }; - URL button1IconLocation = ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/homepanel/new_puzzle_file.png"); - ImageIcon button1Icon = new ImageIcon(button1IconLocation); - this.buttons[1].setFocusPainted(false); - this.buttons[1].setIcon(resizeButtonIcon(button1Icon, this.buttonSize, this.buttonSize)); - this.buttons[1].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[1].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[1].addActionListener(l -> this.openNewPuzzleDialog()); - - this.buttons[2] = new JButton("Edit Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } + URL button1IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/new_puzzle_file.png"); + ImageIcon button1Icon = new ImageIcon(button1IconLocation); + this.buttons[1].setFocusPainted(false); + this.buttons[1].setIcon(resizeButtonIcon(button1Icon, this.buttonSize, this.buttonSize)); + this.buttons[1].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[1].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[1].addActionListener(l -> this.openNewPuzzleDialog()); + + this.buttons[2] = + new JButton("Edit Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } }; - URL button2IconLocation = ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/homepanel/puzzle_file.png"); - ImageIcon button2Icon = new ImageIcon(button2IconLocation); - this.buttons[2].setFocusPainted(false); - this.buttons[2].setIcon(resizeButtonIcon(button2Icon, this.buttonSize, this.buttonSize)); - this.buttons[2].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[2].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[2].addActionListener(CursorController.createListener(this, openPuzzleListener)); // PLACEHOLDER - - for (int i = 0; i < this.buttons.length-1; i++) { // -1 to avoid the batch grader button - this.buttons[i].setBounds(200, 200, 700, 700); - } - this.buttons[3] = new JButton("Batch Grader"); - this.buttons[3].setFocusPainted(false); - this.buttons[3].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[3].setVerticalTextPosition(AbstractButton.BOTTOM); - - this.buttons[3].addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - try { - use_xml_to_check(); - } - catch (Exception ex) { - throw new RuntimeException(ex); - } - System.out.println("finished checking the folder"); - + URL button2IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/puzzle_file.png"); + ImageIcon button2Icon = new ImageIcon(button2IconLocation); + this.buttons[2].setFocusPainted(false); + this.buttons[2].setIcon(resizeButtonIcon(button2Icon, this.buttonSize, this.buttonSize)); + this.buttons[2].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[2].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[2].addActionListener( + CursorController.createListener(this, openPuzzleListener)); // PLACEHOLDER + + for (int i = 0; i < this.buttons.length - 1; i++) { // -1 to avoid the batch grader button + this.buttons[i].setBounds(200, 200, 700, 700); + } + this.buttons[3] = new JButton("Batch Grader"); + this.buttons[3].setFocusPainted(false); + this.buttons[3].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[3].setVerticalTextPosition(AbstractButton.BOTTOM); + + this.buttons[3].addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + use_xml_to_check(); + } catch (Exception ex) { + throw new RuntimeException(ex); } + System.out.println("finished checking the folder"); + } }); - } + } + + public void checkFolder() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ - public void checkFolder() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - - JFileChooser folderBrowser = new JFileChooser(); - - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - File folder = folderBrowser.getSelectedFile(); - - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name"); - writer.append(","); - writer.append("File Name"); + JFileChooser folderBrowser = new JFileChooser(); + + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + File folder = folderBrowser.getSelectedFile(); + + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name"); + writer.append(","); + writer.append("File Name"); + writer.append(","); + writer.append("Solved?"); + writer.append("\n"); + + for (final File folderEntry : folder.listFiles(File::isDirectory)) { + writer.append(folderEntry.getName()); + writer.append(","); + int count1 = 0; + for (final File fileEntry : folderEntry.listFiles()) { + if (fileEntry.getName().charAt(0) == '.') { + continue; + } + count1++; + if (count1 > 1) { + writer.append(folderEntry.getName()); writer.append(","); - writer.append("Solved?"); - writer.append("\n"); - - for (final File folderEntry : folder.listFiles(File::isDirectory)) { - writer.append(folderEntry.getName()); - writer.append(","); - int count1 = 0; - for (final File fileEntry : folderEntry.listFiles()) { - if (fileEntry.getName().charAt(0) == '.') { - continue; - } - count1++; - if (count1 > 1) { - writer.append(folderEntry.getName()); - writer.append(","); - } - writer.append(fileEntry.getName()); - writer.append(","); - String fileName = folderEntry.getAbsolutePath() + File.separator + fileEntry.getName(); - System.out.println("This is path " + fileName); - File puzzleFile = new File(fileName); - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(1); - legupUI.getProofEditor(); - GameBoardFacade.getInstance().loadPuzzle(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - legupUI.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - if (puzzle.isPuzzleComplete()) { - writer.append("Solved"); - System.out.println(fileEntry.getName() + " solved"); - } - else { - writer.append("Not Solved"); - System.out.println(fileEntry.getName() + " not solved"); - } - writer.append("\n"); - } - catch (InvalidFileFormatException e) { - LOGGER.error(e.getMessage()); - } - } - } - if (count1 == 0) { - writer.append("No file"); - writer.append("\n"); - } + } + writer.append(fileEntry.getName()); + writer.append(","); + String fileName = folderEntry.getAbsolutePath() + File.separator + fileEntry.getName(); + System.out.println("This is path " + fileName); + File puzzleFile = new File(fileName); + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(1); + legupUI.getProofEditor(); + GameBoardFacade.getInstance().loadPuzzle(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + legupUI.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + if (puzzle.isPuzzleComplete()) { + writer.append("Solved"); + System.out.println(fileEntry.getName() + " solved"); + } else { + writer.append("Not Solved"); + System.out.println(fileEntry.getName() + " not solved"); + } + writer.append("\n"); + } catch (InvalidFileFormatException e) { + LOGGER.error(e.getMessage()); } + } } - catch (IOException ex) { - LOGGER.error(ex.getMessage()); - this.buttons[3].addActionListener((ActionEvent e) -> use_xml_to_check()); + if (count1 == 0) { + writer.append("No file"); + writer.append("\n"); } + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + this.buttons[3].addActionListener((ActionEvent e) -> use_xml_to_check()); } - - /** - * @effect batch grade using .xml parser - go through a collection of files and report their "solved?" status - */ - private void use_xml_to_check() { - /* Select a folder, go through each .xml file in the subfolders, look for "isSolved" flag */ - JFileChooser folderBrowser = new JFileChooser(); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - folderBrowser.setSelectedFile(null); - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - File folder = folderBrowser.getSelectedFile(); - - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Solved?,Last Saved\n"); - // Go through student folders, recurse for inner folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - String path = folderEntry.getName(); - // use this helper function to write to the .csv file - recursive_parser(folderEntry, writer, path, path); - } - } - catch (IOException ex) { - LOGGER.error(ex.getMessage()); - } - if (resultFile.exists()) { - try { - Desktop desktop = Desktop.getDesktop(); - desktop.open(resultFile); - } - catch (IOException ex) { - LOGGER.error(ex.getMessage()); - } - } - JOptionPane.showMessageDialog(null, "Batch grading complete."); - + } + + /** + * @effect batch grade using .xml parser - go through a collection of files and report their + * "solved?" status + */ + private void use_xml_to_check() { + /* Select a folder, go through each .xml file in the subfolders, look for "isSolved" flag */ + JFileChooser folderBrowser = new JFileChooser(); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + folderBrowser.setSelectedFile(null); + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + File folder = folderBrowser.getSelectedFile(); + + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Solved?,Last Saved\n"); + // Go through student folders, recurse for inner folders + for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + String path = folderEntry.getName(); + // use this helper function to write to the .csv file + recursive_parser(folderEntry, writer, path, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } - - /** - * @param file - the input file - * @return true if it is a .xml file, else return false - */ - public boolean isxmlfile(File file) { - boolean flag = true; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - builder.parse(file); - flag = true; + if (resultFile.exists()) { + try { + Desktop desktop = Desktop.getDesktop(); + desktop.open(resultFile); + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + } + } + JOptionPane.showMessageDialog(null, "Batch grading complete."); + } + + /** + * @param file - the input file + * @return true if it is a .xml file, else return false + */ + public boolean isxmlfile(File file) { + boolean flag = true; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + builder.parse(file); + flag = true; + } catch (Exception e) { + flag = false; + } + return flag; + } + + /** + * @param folder - the input folder + * @param writer - write to .csv + * @param path - the current path + * @param name - student's name (the first subfolders of the main folder) + * @throws IOException + */ + private void recursive_parser(File folder, BufferedWriter writer, String path, String name) + throws IOException { + // Empty folder + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,Ungradeable\n"); + return; + } + // Go through every other file in the folder + try { + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser saxParser = spf.newSAXParser(); + for (final File fileEntry : Objects.requireNonNull(folder.listFiles())) { + if (fileEntry.getName().equals("result.csv")) { + continue; } - catch (Exception e) { - flag = false; + // Recurse if it is a subfolder + if (fileEntry.isDirectory()) { + recursive_parser(fileEntry, writer, path + "/" + fileEntry.getName(), name); + continue; } - return flag; - } - - /** - * @param folder - the input folder - * @param writer - write to .csv - * @param path - the current path - * @param name - student's name (the first subfolders of the main folder) - * @throws IOException - */ - private void recursive_parser(File folder, BufferedWriter writer, String path, String name) throws IOException { - // Empty folder - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,Ungradeable\n"); - return; + // Set path name + String fName = fileEntry.getName(); + String fPath = fileEntry.getAbsolutePath(); + if (fileEntry.getName().charAt(0) == '.') { + continue; } - // Go through every other file in the folder - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxParser = spf.newSAXParser(); - for (final File fileEntry : Objects.requireNonNull(folder.listFiles())) { - if (fileEntry.getName().equals("result.csv")) { - continue; - } - // Recurse if it is a subfolder - if (fileEntry.isDirectory()) { - recursive_parser(fileEntry, writer, path + "/" + fileEntry.getName(), name); - continue; - } - // Set path name - String fName = fileEntry.getName(); - String fPath = fileEntry.getAbsolutePath(); - if (fileEntry.getName().charAt(0) == '.') { - continue; - } - // write data - writer.write(name); - writer.write(","); - writer.write(fName); - writer.write(","); - path = folder.getAbsolutePath() + File.separator + fileEntry.getName(); - System.out.println(path); - if (isxmlfile(fileEntry)) { - saxParser.parse(path, new DefaultHandler() { - @Override - public void startDocument() throws SAXException { - } - boolean solvedFlagExists = false; - boolean puzzleTypeExists = false; - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - // append file type to the writer - if (qName.equals("puzzle") && attributes.getQName(0) == "name" && !puzzleTypeExists) { - try { - writer.write(attributes.getValue(0)); - writer.write(","); - puzzleTypeExists = true; - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - // append the "solved?" status of the proof to the writer - else if (qName.equals("solved") && !solvedFlagExists) { - String isSolved = attributes.getValue(0); - String lastSaved = attributes.getValue(1); - if (isSolved != null) { - if (isSolved.equals("true")) { - try { - writer.write("Solved"); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - else if (isSolved.equals("false")) { - try { - writer.write("Not Solved"); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - else { - try { - writer.write("Error"); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - } - // append when is this proof last saved - if (lastSaved != null) { - try { - writer.write(","); - writer.write(lastSaved); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - solvedFlagExists = true; - } - } - @Override - public void characters(char[] ch, int start, int length) throws SAXException { + // write data + writer.write(name); + writer.write(","); + writer.write(fName); + writer.write(","); + path = folder.getAbsolutePath() + File.separator + fileEntry.getName(); + System.out.println(path); + if (isxmlfile(fileEntry)) { + saxParser.parse( + path, + new DefaultHandler() { + @Override + public void startDocument() throws SAXException {} + + boolean solvedFlagExists = false; + boolean puzzleTypeExists = false; + + @Override + public void startElement( + String uri, String localName, String qName, Attributes attributes) + throws SAXException { + // append file type to the writer + if (qName.equals("puzzle") + && attributes.getQName(0) == "name" + && !puzzleTypeExists) { + try { + writer.write(attributes.getValue(0)); + writer.write(","); + puzzleTypeExists = true; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + // append the "solved?" status of the proof to the writer + else if (qName.equals("solved") && !solvedFlagExists) { + String isSolved = attributes.getValue(0); + String lastSaved = attributes.getValue(1); + if (isSolved != null) { + if (isSolved.equals("true")) { + try { + writer.write("Solved"); + } catch (IOException e) { + throw new RuntimeException(e); } - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { + } else if (isSolved.equals("false")) { + try { + writer.write("Not Solved"); + } catch (IOException e) { + throw new RuntimeException(e); } - @Override - public void endDocument() throws SAXException { - if (!puzzleTypeExists) { - try { - writer.write("not a LEGUP puzzle!"); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - else if (!solvedFlagExists) { - try { - writer.write("missing flag!"); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } + } else { + try { + writer.write("Error"); + } catch (IOException e) { + throw new RuntimeException(e); } - }); + } + } + // append when is this proof last saved + if (lastSaved != null) { + try { + writer.write(","); + writer.write(lastSaved); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + solvedFlagExists = true; + } } - // If wrong file type, ungradeable - else { - writer.write("not a \".xml\" file!"); + + @Override + public void characters(char[] ch, int start, int length) throws SAXException {} + + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException {} + + @Override + public void endDocument() throws SAXException { + if (!puzzleTypeExists) { + try { + writer.write("not a LEGUP puzzle!"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else if (!solvedFlagExists) { + try { + writer.write("missing flag!"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } } - writer.write("\n"); - } + }); } - catch (ParserConfigurationException | SAXException | IOException e) { - LOGGER.error(e.getMessage()); + // If wrong file type, ungradeable + else { + writer.write("not a \".xml\" file!"); } + writer.write("\n"); + } + } catch (ParserConfigurationException | SAXException | IOException e) { + LOGGER.error(e.getMessage()); } - - private void initText() { - // TODO: add version text after auto-changing version label is implemented. (text[2] = version) - this.text = new JLabel[2]; - - JLabel welcome = new JLabel("Welcome to LEGUP"); - welcome.setFont(new Font("Roboto", Font.BOLD, 23)); - welcome.setAlignmentX(Component.CENTER_ALIGNMENT); - - JLabel credits = new JLabel("A project by Dr. Bram van Heuveln"); - credits.setFont(new Font("Roboto", Font.PLAIN, 12)); - credits.setAlignmentX(Component.CENTER_ALIGNMENT); - - JLabel version = new JLabel("Version 5.1.0"); // This should be autochanged in the future - version.setFont(new Font("Roboto", Font.ITALIC, 10)); - version.setAlignmentX(Component.CENTER_ALIGNMENT); - - this.text[0] = welcome; - this.text[1] = credits; + } + + private void initText() { + // TODO: add version text after auto-changing version label is implemented. (text[2] = version) + this.text = new JLabel[2]; + + JLabel welcome = new JLabel("Welcome to LEGUP"); + welcome.setFont(new Font("Roboto", Font.BOLD, 23)); + welcome.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel credits = new JLabel("A project by Dr. Bram van Heuveln"); + credits.setFont(new Font("Roboto", Font.PLAIN, 12)); + credits.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel version = new JLabel("Version 5.1.0"); // This should be autochanged in the future + version.setFont(new Font("Roboto", Font.ITALIC, 10)); + version.setAlignmentX(Component.CENTER_ALIGNMENT); + + this.text[0] = welcome; + this.text[1] = credits; + } + + private void render() { + this.removeAll(); + + this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + this.legupUI.setTitle("LEGUP: A Better Way to Learn Formal Logic"); + + JPanel buttons = new JPanel(); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[0]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[1]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[2]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + + JPanel batchGraderButton = new JPanel(); + batchGraderButton.add(this.buttons[3]); + batchGraderButton.setAlignmentX(Component.CENTER_ALIGNMENT); + + this.add(Box.createRigidArea(new Dimension(0, 5))); + for (int i = 0; i < this.text.length; i++) { + this.add(this.text[i]); } + this.add(buttons); + this.add(batchGraderButton); + this.add(Box.createRigidArea(new Dimension(0, 5))); + } + + private void openNewPuzzleDialog() { + CreatePuzzleDialog cpd = new CreatePuzzleDialog(this.frame, this); + cpd.setVisible(true); + } + + private void checkProofAll() { + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ - private void render() { - this.removeAll(); - - this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); - this.legupUI.setTitle("LEGUP: A Better Way to Learn Formal Logic"); - - JPanel buttons = new JPanel(); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[0]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[1]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[2]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - - JPanel batchGraderButton = new JPanel(); - batchGraderButton.add(this.buttons[3]); - batchGraderButton.setAlignmentX(Component.CENTER_ALIGNMENT); - - - this.add(Box.createRigidArea(new Dimension(0, 5))); - for (int i = 0; i < this.text.length; i++) { - this.add(this.text[i]); - } - this.add(buttons); - this.add(batchGraderButton); - this.add(Box.createRigidArea(new Dimension(0, 5))); + LegupPreferences preferences = LegupPreferences.getInstance(); + File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); + folderBrowser = new JFileChooser(preferredDirectory); + + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + + File folder = folderBrowser.getSelectedFile(); + + // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); + + // Go through student folders + for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + // Write path + String path = folderEntry.getName(); + traverseDir(folderEntry, writer, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } - - private void openNewPuzzleDialog() { - CreatePuzzleDialog cpd = new CreatePuzzleDialog(this.frame, this); - cpd.setVisible(true); + JOptionPane.showMessageDialog(null, "Batch grading complete."); + } + + private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { + // Recursively traverse directory + GameBoardFacade facade = GameBoardFacade.getInstance(); + // Folder is empty + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,Ungradeable\n"); + return; } - - private void checkProofAll() { - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - - LegupPreferences preferences = LegupPreferences.getInstance(); - File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); - folderBrowser = new JFileChooser(preferredDirectory); - - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - - File folder = folderBrowser.getSelectedFile(); - - // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); - - // Go through student folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - // Write path - String path = folderEntry.getName(); - traverseDir(folderEntry, writer, path); - } - } - catch (IOException ex) { - LOGGER.error(ex.getMessage()); + // Travese directory, recurse if sub-directory found + // If ungradeable, do not leave a score (0, 1) + for (final File f : Objects.requireNonNull(folder.listFiles())) { + // Recurse + if (f.isDirectory()) { + traverseDir(f, writer, path + "/" + f.getName()); + continue; + } + + // Set path name + writer.append(path).append(","); + + // Load puzzle, run checker + // If wrong file type, ungradeable + String fName = f.getName(); + String fPath = f.getAbsolutePath(); + File puzzleFile = new File(fPath); + if (puzzleFile.exists()) { + // Try to load file. If invalid, note in csv + try { + // Load puzzle, run checker + GameBoardFacade.getInstance().loadPuzzle(fPath); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + + // Write data + writer.append(fName).append(","); + writer.append(puzzle.getName()).append(","); + if (puzzle.isPuzzleComplete()) { + writer.append("Solved\n"); + } else { + writer.append("Unsolved\n"); + } + } catch (InvalidFileFormatException e) { + writer.append(fName).append("InvalidFile,Ungradeable\n"); } - JOptionPane.showMessageDialog(null, "Batch grading complete."); + } else { + LOGGER.debug("Failed to run sim"); + } } - - private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { - // Recursively traverse directory - GameBoardFacade facade = GameBoardFacade.getInstance(); - // Folder is empty - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,Ungradeable\n"); - return; - } - // Travese directory, recurse if sub-directory found - // If ungradeable, do not leave a score (0, 1) - for (final File f : Objects.requireNonNull(folder.listFiles())) { - // Recurse - if (f.isDirectory()) { - traverseDir(f, writer, path + "/" + f.getName()); - continue; - } - - // Set path name - writer.append(path).append(","); - - // Load puzzle, run checker - // If wrong file type, ungradeable - String fName = f.getName(); - String fPath = f.getAbsolutePath(); - File puzzleFile = new File(fPath); - if (puzzleFile.exists()) { - // Try to load file. If invalid, note in csv - try { - // Load puzzle, run checker - GameBoardFacade.getInstance().loadPuzzle(fPath); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - - // Write data - writer.append(fName).append(","); - writer.append(puzzle.getName()).append(","); - if (puzzle.isPuzzleComplete()) { - writer.append("Solved\n"); - } - else { - writer.append("Unsolved\n"); - } - } - catch (InvalidFileFormatException e) { - writer.append(fName).append("InvalidFile,Ungradeable\n"); - } - } - else { - LOGGER.debug("Failed to run sim"); - } - } + } + + public void openEditorWithNewPuzzle(String game, int rows, int columns) + throws IllegalArgumentException { + // Validate the dimensions + GameBoardFacade facade = GameBoardFacade.getInstance(); + boolean isValidDimensions = facade.validateDimensions(game, rows, columns); + if (!isValidDimensions) { + JOptionPane.showMessageDialog( + null, + "The dimensions you entered are invalid. Please double check \n" + + "the number of rows and columns and try again.", + "ERROR: Invalid Dimensions", + JOptionPane.ERROR_MESSAGE); + throw new IllegalArgumentException("ERROR: Invalid dimensions given"); } - public void openEditorWithNewPuzzle(String game, int rows, int columns) throws IllegalArgumentException { - // Validate the dimensions - GameBoardFacade facade = GameBoardFacade.getInstance(); - boolean isValidDimensions = facade.validateDimensions(game, rows, columns); - if (!isValidDimensions) { - JOptionPane.showMessageDialog(null, - "The dimensions you entered are invalid. Please double check \n" + - "the number of rows and columns and try again.", - "ERROR: Invalid Dimensions", - JOptionPane.ERROR_MESSAGE); - throw new IllegalArgumentException("ERROR: Invalid dimensions given"); - } - - // Set game type on the puzzle editor - this.legupUI.displayPanel(2); - this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, rows, columns); + // Set game type on the puzzle editor + this.legupUI.displayPanel(2); + this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, rows, columns); + } + + /** + * Opens the puzzle editor for the specified game with the given statements + * + * @param game a String containing the name of the game + * @param statements an array of statements + */ + public void openEditorWithNewPuzzle(String game, String[] statements) { + // Validate the text input + GameBoardFacade facade = GameBoardFacade.getInstance(); + boolean isValidTextInput = facade.validateTextInput(game, statements); + if (!isValidTextInput) { + JOptionPane.showMessageDialog( + null, + "The input you entered is invalid. Please double check \n" + + "your statements and try again.", + "ERROR: Invalid Text Input", + JOptionPane.ERROR_MESSAGE); + throw new IllegalArgumentException("ERROR: Invalid dimensions given"); } - /** - * Opens the puzzle editor for the specified game with the given statements - * - * @param game a String containing the name of the game - * @param statements an array of statements - */ - public void openEditorWithNewPuzzle(String game, String[] statements) { - // Validate the text input - GameBoardFacade facade = GameBoardFacade.getInstance(); - boolean isValidTextInput = facade.validateTextInput(game, statements); - if (!isValidTextInput) { - JOptionPane.showMessageDialog(null, - "The input you entered is invalid. Please double check \n" + - "your statements and try again.", - "ERROR: Invalid Text Input", - JOptionPane.ERROR_MESSAGE); - throw new IllegalArgumentException("ERROR: Invalid dimensions given"); - } - - // Set game type on the puzzle editor - this.legupUI.displayPanel(2); - this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, statements); - } + // Set game type on the puzzle editor + this.legupUI.displayPanel(2); + this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, statements); + } } diff --git a/src/main/java/edu/rpi/legup/ui/LegupPanel.java b/src/main/java/edu/rpi/legup/ui/LegupPanel.java index 708348145..d671e1c4d 100644 --- a/src/main/java/edu/rpi/legup/ui/LegupPanel.java +++ b/src/main/java/edu/rpi/legup/ui/LegupPanel.java @@ -3,11 +3,8 @@ import javax.swing.*; public abstract class LegupPanel extends JPanel { - /** - * Alerts panel that it will be going visible now - */ + /** Alerts panel that it will be going visible now */ + protected final int TOOLBAR_ICON_SCALE = 40; - protected final int TOOLBAR_ICON_SCALE = 40; - - public abstract void makeVisible(); + public abstract void makeVisible(); } diff --git a/src/main/java/edu/rpi/legup/ui/LegupUI.java b/src/main/java/edu/rpi/legup/ui/LegupUI.java index 452bbb487..562d73ffd 100644 --- a/src/main/java/edu/rpi/legup/ui/LegupUI.java +++ b/src/main/java/edu/rpi/legup/ui/LegupUI.java @@ -1,210 +1,201 @@ package edu.rpi.legup.ui; -import java.awt.*; -import java.awt.event.*; -import java.security.InvalidParameterException; -import java.util.Objects; - -import javax.swing.*; - - -import com.formdev.flatlaf.FlatLightLaf; import com.formdev.flatlaf.FlatDarkLaf; +import com.formdev.flatlaf.FlatLightLaf; import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.ui.boardview.BoardView; import edu.rpi.legup.ui.proofeditorui.treeview.TreePanel; - +import java.awt.*; +import java.awt.event.*; +import java.security.InvalidParameterException; +import java.util.Objects; +import javax.swing.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class LegupUI extends JFrame implements WindowListener { - private final static Logger LOGGER = LogManager.getLogger(LegupUI.class.getName()); - - protected FileDialog fileDialog; - protected JPanel window; - protected LegupPanel[] panels; - - /** - * Identifies operating system - * @return operating system, either mac or win - */ - public static String getOS() { - String os = System.getProperty("os.name").toLowerCase(); - if (os.contains("mac")) { - os = "mac"; - } - else { - os = "win"; - } - return os; - } - - /** - * LegupUI Constructor - creates a new LegupUI to setup the menu and toolbar - */ - public LegupUI() { - setTitle("LEGUP"); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - LegupPreferences prefs = LegupPreferences.getInstance(); - - try { - if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { - UIManager.setLookAndFeel(new FlatDarkLaf()); - } - else { - UIManager.setLookAndFeel(new FlatLightLaf()); - } - } - catch (UnsupportedLookAndFeelException e) { - System.err.println("Not supported ui look and feel"); - } - - fileDialog = new FileDialog(this); - - initPanels(); - displayPanel(0); - - setIconImage(new ImageIcon(Objects.requireNonNull(ClassLoader.getSystemClassLoader().getResource( - "edu/rpi/legup/images/Legup/Direct Rules.gif"))).getImage()); - - if (LegupPreferences.getInstance().getUserPref(LegupPreferences.START_FULL_SCREEN).equals(Boolean.toString(true))) { - setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); - } - - this.addWindowListener(this); - addKeyListener(new KeyAdapter() { - /** - * Invoked when a key has been typed. - * This event occurs when a key press is followed by a key release. - * - * @param e - */ - @Override - public void keyTyped(KeyEvent e) { - System.err.println(e.getKeyChar()); - super.keyTyped(e); - } + private static final Logger LOGGER = LogManager.getLogger(LegupUI.class.getName()); + + protected FileDialog fileDialog; + protected JPanel window; + protected LegupPanel[] panels; + + /** + * Identifies operating system + * + * @return operating system, either mac or win + */ + public static String getOS() { + String os = System.getProperty("os.name").toLowerCase(); + if (os.contains("mac")) { + os = "mac"; + } else { + os = "win"; + } + return os; + } + + /** LegupUI Constructor - creates a new LegupUI to setup the menu and toolbar */ + public LegupUI() { + setTitle("LEGUP"); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + LegupPreferences prefs = LegupPreferences.getInstance(); + + try { + if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { + UIManager.setLookAndFeel(new FlatDarkLaf()); + } else { + UIManager.setLookAndFeel(new FlatLightLaf()); + } + } catch (UnsupportedLookAndFeelException e) { + System.err.println("Not supported ui look and feel"); + } + + fileDialog = new FileDialog(this); + + initPanels(); + displayPanel(0); + + setIconImage( + new ImageIcon( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif"))) + .getImage()); + + if (LegupPreferences.getInstance() + .getUserPref(LegupPreferences.START_FULL_SCREEN) + .equals(Boolean.toString(true))) { + setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); + } + + this.addWindowListener(this); + addKeyListener( + new KeyAdapter() { + /** + * Invoked when a key has been typed. This event occurs when a key press is followed by a + * key release. + * + * @param e + */ + @Override + public void keyTyped(KeyEvent e) { + System.err.println(e.getKeyChar()); + super.keyTyped(e); + } }); - setMinimumSize(getPreferredSize()); - setVisible(true); - } - - private void initPanels() { - window = new JPanel(); - window.setLayout(new BorderLayout()); - add(window); - panels = new LegupPanel[3]; - - panels[0] = new HomePanel(this.fileDialog, this, this); - panels[1] = new ProofEditorPanel(this.fileDialog, this, this); - panels[2] = new PuzzleEditorPanel(this.fileDialog, this, this); - - } - - protected void displayPanel(int option) { - if (option > panels.length || option < 0) { - throw new InvalidParameterException("Invalid option"); - } - this.window.removeAll(); - panels[option].makeVisible(); - this.window.add(panels[option]); - pack(); - setLocationRelativeTo(null); - revalidate(); - repaint(); - } - - public ProofEditorPanel getProofEditor() { - return (ProofEditorPanel) panels[1]; - } - - public PuzzleEditorPanel getPuzzleEditor() { - return (PuzzleEditorPanel) panels[2]; - } - - public void repaintTree() { - getProofEditor().repaintTree(); - } - - private void directions() { - JOptionPane.showMessageDialog(null, "For every move you make, you must provide a rules for it (located in the Rules panel).\n" + "While working on the edu.rpi.legup.puzzle, you may click on the \"Check\" button to test your proof for correctness.", "Directions", JOptionPane.PLAIN_MESSAGE); - } - - public void showStatus(String status, boolean error) { - showStatus(status, error, 1); - } - - public void errorEncountered(String error) { - JOptionPane.showMessageDialog(null, error); - } - - public void showStatus(String status, boolean error, int timer) { - // TODO: implement - } - - //ask to edu.rpi.legup.save current proof - public boolean noquit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - @Override - public void windowOpened(WindowEvent e) { - - } - - public void windowClosing(WindowEvent e) { - if (GameBoardFacade.getInstance().getHistory().getIndex() > -1) { - if (noquit("Exiting LEGUP?")) { - this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - } - else { - this.setDefaultCloseOperation(EXIT_ON_CLOSE); - } - } - else { - this.setDefaultCloseOperation(EXIT_ON_CLOSE); - } - } - - public void windowClosed(WindowEvent e) { - System.exit(0); - } - - public void windowIconified(WindowEvent e) { - - } - - public void windowDeiconified(WindowEvent e) { - - } - - public void windowActivated(WindowEvent e) { - - } - - public void windowDeactivated(WindowEvent e) { - - } - - public BoardView getBoardView() { - return getProofEditor().getBoardView(); - } - - public BoardView getEditorBoardView() { - return getPuzzleEditor().getBoardView(); - } - - public DynamicView getDynamicBoardView() { - return getProofEditor().getDynamicBoardView(); - } - - public DynamicView getEditorDynamicBoardView() { - return getPuzzleEditor().getDynamicBoardView(); - } - - public TreePanel getTreePanel() { - return getProofEditor().getTreePanel(); - } + setMinimumSize(getPreferredSize()); + setVisible(true); + } + + private void initPanels() { + window = new JPanel(); + window.setLayout(new BorderLayout()); + add(window); + panels = new LegupPanel[3]; + + panels[0] = new HomePanel(this.fileDialog, this, this); + panels[1] = new ProofEditorPanel(this.fileDialog, this, this); + panels[2] = new PuzzleEditorPanel(this.fileDialog, this, this); + } + + protected void displayPanel(int option) { + if (option > panels.length || option < 0) { + throw new InvalidParameterException("Invalid option"); + } + this.window.removeAll(); + panels[option].makeVisible(); + this.window.add(panels[option]); + pack(); + setLocationRelativeTo(null); + revalidate(); + repaint(); + } + + public ProofEditorPanel getProofEditor() { + return (ProofEditorPanel) panels[1]; + } + + public PuzzleEditorPanel getPuzzleEditor() { + return (PuzzleEditorPanel) panels[2]; + } + + public void repaintTree() { + getProofEditor().repaintTree(); + } + + private void directions() { + JOptionPane.showMessageDialog( + null, + "For every move you make, you must provide a rules for it (located in the Rules panel).\n" + + "While working on the edu.rpi.legup.puzzle, you may click on the \"Check\" button to test your proof for correctness.", + "Directions", + JOptionPane.PLAIN_MESSAGE); + } + + public void showStatus(String status, boolean error) { + showStatus(status, error, 1); + } + + public void errorEncountered(String error) { + JOptionPane.showMessageDialog(null, error); + } + + public void showStatus(String status, boolean error, int timer) { + // TODO: implement + } + + // ask to edu.rpi.legup.save current proof + public boolean noquit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + @Override + public void windowOpened(WindowEvent e) {} + + public void windowClosing(WindowEvent e) { + if (GameBoardFacade.getInstance().getHistory().getIndex() > -1) { + if (noquit("Exiting LEGUP?")) { + this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } else { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + } else { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + } + + public void windowClosed(WindowEvent e) { + System.exit(0); + } + + public void windowIconified(WindowEvent e) {} + + public void windowDeiconified(WindowEvent e) {} + + public void windowActivated(WindowEvent e) {} + + public void windowDeactivated(WindowEvent e) {} + + public BoardView getBoardView() { + return getProofEditor().getBoardView(); + } + + public BoardView getEditorBoardView() { + return getPuzzleEditor().getBoardView(); + } + + public DynamicView getDynamicBoardView() { + return getProofEditor().getDynamicBoardView(); + } + + public DynamicView getEditorDynamicBoardView() { + return getPuzzleEditor().getDynamicBoardView(); + } + + public TreePanel getTreePanel() { + return getProofEditor().getTreePanel(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java b/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java index 6e3fb4f67..43cb35584 100644 --- a/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java +++ b/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java @@ -1,13 +1,9 @@ package edu.rpi.legup.ui; -import javax.swing.*; import java.awt.*; +import javax.swing.*; public class ManualPuzzleCreatorDialog extends JDialog { - - public ManualPuzzleCreatorDialog() { - - } - + public ManualPuzzleCreatorDialog() {} } diff --git a/src/main/java/edu/rpi/legup/ui/PickGameDialog.java b/src/main/java/edu/rpi/legup/ui/PickGameDialog.java index 24fc4602f..acdc99bee 100644 --- a/src/main/java/edu/rpi/legup/ui/PickGameDialog.java +++ b/src/main/java/edu/rpi/legup/ui/PickGameDialog.java @@ -1,15 +1,11 @@ package edu.rpi.legup.ui; - import edu.rpi.legup.app.GameBoardFacade; - import java.awt.Container; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - import java.io.File; - import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; @@ -20,159 +16,156 @@ import javax.swing.JTextField; public class PickGameDialog extends JDialog implements ActionListener { - JLabel gameLabel = new JLabel("Game:"); - String[] games; - JComboBox gameBox; - - JLabel puzzleLabel = new JLabel("Puzzle:"); - String[][] puzzles; - String puzzle; - - JTextField puzzleBox; - - JButton puzzleButton = new JButton("..."); - JFileChooser puzzleChooser = new JFileChooser(); - - JButton ok = new JButton("Ok"); - JButton cancel = new JButton("Cancel"); - - - JCheckBox autotreeCheckBox = new JCheckBox("Auto-tree"); - JCheckBox showtreeCheckBox = new JCheckBox("Show tree"); - JCheckBox autojustifyCheckBox = new JCheckBox("Auto-justify"); - - public boolean okPressed = false; - private boolean pickBoth; - - /** - * Initialize the dialog - * - * @param parent the parent JFrame - * @param pickBothAtOnce if true they can pick a game type and a specific edu.rpi.legup.puzzle, if - * false they can only pick a game type - */ - public PickGameDialog(JFrame parent, boolean pickBothAtOnce) { - super(parent, true); - - pickBoth = pickBothAtOnce; - initPuzzles(); - - Rectangle b = parent.getBounds(); - - setSize(350, 200); - setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); - setTitle("Select Puzzle"); - - // listeners - gameBox.addActionListener(this); - ok.addActionListener(this); - cancel.addActionListener(this); - - // add components - Container c = getContentPane(); - c.setLayout(null); - - if (pickBoth) { - gameLabel.setBounds(10, 10, 70, 25); - gameBox.setBounds(80, 10, 190, 25); - } - else { - gameLabel.setBounds(10, 30, 70, 25); - gameBox.setBounds(80, 30, 190, 25); - } - - puzzleLabel.setBounds(10, 40, 70, 25); - - - puzzleBox.setBounds(80, 40, 190, 25); - puzzleButton.setBounds(270, 40, 25, 25); - - ok.setBounds(20, 130, 60, 25); - cancel.setBounds(170, 130, 90, 25); - - c.add(gameLabel); - c.add(gameBox); - + JLabel gameLabel = new JLabel("Game:"); + String[] games; + JComboBox gameBox; + + JLabel puzzleLabel = new JLabel("Puzzle:"); + String[][] puzzles; + String puzzle; + + JTextField puzzleBox; + + JButton puzzleButton = new JButton("..."); + JFileChooser puzzleChooser = new JFileChooser(); + + JButton ok = new JButton("Ok"); + JButton cancel = new JButton("Cancel"); + + JCheckBox autotreeCheckBox = new JCheckBox("Auto-tree"); + JCheckBox showtreeCheckBox = new JCheckBox("Show tree"); + JCheckBox autojustifyCheckBox = new JCheckBox("Auto-justify"); + + public boolean okPressed = false; + private boolean pickBoth; + + /** + * Initialize the dialog + * + * @param parent the parent JFrame + * @param pickBothAtOnce if true they can pick a game type and a specific edu.rpi.legup.puzzle, if + * false they can only pick a game type + */ + public PickGameDialog(JFrame parent, boolean pickBothAtOnce) { + super(parent, true); + + pickBoth = pickBothAtOnce; + initPuzzles(); + + Rectangle b = parent.getBounds(); + + setSize(350, 200); + setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); + setTitle("Select Puzzle"); + + // listeners + gameBox.addActionListener(this); + ok.addActionListener(this); + cancel.addActionListener(this); + + // add components + Container c = getContentPane(); + c.setLayout(null); + + if (pickBoth) { + gameLabel.setBounds(10, 10, 70, 25); + gameBox.setBounds(80, 10, 190, 25); + } else { + gameLabel.setBounds(10, 30, 70, 25); + gameBox.setBounds(80, 30, 190, 25); + } - if (pickBoth) { - c.add(puzzleLabel); - c.add(puzzleBox); - } + puzzleLabel.setBounds(10, 40, 70, 25); - c.add(puzzleButton); - puzzleButton.addActionListener(this); + puzzleBox.setBounds(80, 40, 190, 25); + puzzleButton.setBounds(270, 40, 25, 25); - c.add(ok); - c.add(cancel); + ok.setBounds(20, 130, 60, 25); + cancel.setBounds(170, 130, 90, 25); - autotreeCheckBox.setBounds(20, 70, 100, 25); - showtreeCheckBox.setBounds(20, 90, 100, 25); - autojustifyCheckBox.setBounds(20, 110, 100, 25); + c.add(gameLabel); + c.add(gameBox); - c.add(autotreeCheckBox); - c.add(showtreeCheckBox); - c.add(autojustifyCheckBox); + if (pickBoth) { + c.add(puzzleLabel); + c.add(puzzleBox); } - public void initPuzzles() { - Object[] o = GameBoardFacade.getInstance().getConfig().getPuzzleClassNames().toArray(); + c.add(puzzleButton); + puzzleButton.addActionListener(this); - games = new String[o.length]; + c.add(ok); + c.add(cancel); - for (int x = 0; x < o.length; ++x) { - games[x] = (String) o[x]; - } + autotreeCheckBox.setBounds(20, 70, 100, 25); + showtreeCheckBox.setBounds(20, 90, 100, 25); + autojustifyCheckBox.setBounds(20, 110, 100, 25); - puzzles = new String[games.length][]; - puzzleBox = new JTextField(); - for (int x = 0; x < games.length; ++x) { - puzzles[x] = new String[o.length]; + c.add(autotreeCheckBox); + c.add(showtreeCheckBox); + c.add(autojustifyCheckBox); + } - for (int y = 0; y < o.length; ++y) { - puzzles[x][y] = (String) o[y]; - } - } + public void initPuzzles() { + Object[] o = GameBoardFacade.getInstance().getConfig().getPuzzleClassNames().toArray(); - gameBox = new JComboBox(games); - } + games = new String[o.length]; - public String getPuzzle() { - return puzzleBox.getText(); + for (int x = 0; x < o.length; ++x) { + games[x] = (String) o[x]; } - public String getGame() { - return (String) gameBox.getSelectedItem(); + puzzles = new String[games.length][]; + puzzleBox = new JTextField(); + for (int x = 0; x < games.length; ++x) { + puzzles[x] = new String[o.length]; + + for (int y = 0; y < o.length; ++y) { + puzzles[x][y] = (String) o[y]; + } } - public void actionPerformed(ActionEvent e) { - if (e.getSource() == gameBox) { - int index = gameBox.getSelectedIndex(); - } - else { - if (e.getSource() == ok) { - okPressed = true; - setVisible(false); + gameBox = new JComboBox(games); + } + + public String getPuzzle() { + return puzzleBox.getText(); + } + + public String getGame() { + return (String) gameBox.getSelectedItem(); + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == gameBox) { + int index = gameBox.getSelectedIndex(); + } else { + if (e.getSource() == ok) { + okPressed = true; + setVisible(false); + } else { + if (e.getSource() == cancel) { + okPressed = false; + setVisible(false); + } else { + if (e.getSource() == puzzleButton) { + File f = + new File( + "puzzlefiles" + + File.separator + + gameBox.getSelectedItem().toString().toLowerCase() + + File.separator); + if (f.exists() && f.isDirectory()) { + puzzleChooser = new JFileChooser(f); + } else { + puzzleChooser = new JFileChooser(); } - else { - if (e.getSource() == cancel) { - okPressed = false; - setVisible(false); - } - else { - if (e.getSource() == puzzleButton) { - File f = new File("puzzlefiles" + File.separator + gameBox.getSelectedItem().toString().toLowerCase() + File.separator); - if (f.exists() && f.isDirectory()) { - puzzleChooser = new JFileChooser(f); - } - else { - puzzleChooser = new JFileChooser(); - } - if (puzzleChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - puzzleBox.setText(puzzleChooser.getSelectedFile().getAbsolutePath()); - } - } - } + if (puzzleChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + puzzleBox.setText(puzzleChooser.getSelectedFile().getAbsolutePath()); } + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java b/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java index 4eee69d4d..68adb2bae 100644 --- a/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java +++ b/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java @@ -1,375 +1,430 @@ package edu.rpi.legup.ui; +import com.formdev.flatlaf.FlatDarkLaf; +import com.formdev.flatlaf.FlatLightLaf; import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.rules.Rule; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialBorders; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialFonts; - -import javax.imageio.ImageIO; -import javax.swing.*; +import edu.rpi.legup.ui.proofeditorui.rulesview.RuleFrame; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; - -import com.formdev.flatlaf.FlatLightLaf; -import com.formdev.flatlaf.FlatDarkLaf; -import edu.rpi.legup.ui.proofeditorui.rulesview.RuleFrame; -import edu.rpi.legup.ui.proofeditorui.rulesview.RulePanel; +import javax.imageio.ImageIO; +import javax.swing.*; public class PreferencesDialog extends JDialog { + private RuleFrame rulesFrame; - private RuleFrame rulesFrame; - - private final static Logger LOGGER = Logger.getLogger(PreferencesDialog.class.getName()); + private static final Logger LOGGER = Logger.getLogger(PreferencesDialog.class.getName()); - private JCheckBox fullScreen, autoUpdate, darkMode, showMistakes, showAnnotations, allowDefault, generateCases, immFeedback, colorBlind; + private JCheckBox fullScreen, + autoUpdate, + darkMode, + showMistakes, + showAnnotations, + allowDefault, + generateCases, + immFeedback, + colorBlind; - private JTextField workDirectory; + private JTextField workDirectory; - private static Image folderIcon; + private static Image folderIcon; - static { - try { - folderIcon = ImageIO.read(PreferencesDialog.class.getResource("/edu/rpi/legup/imgs/folder.png")); - } - catch (IOException e) { - LOGGER.log(Level.SEVERE, "Unable to locate icons"); - } + static { + try { + folderIcon = + ImageIO.read(PreferencesDialog.class.getResource("/edu/rpi/legup/imgs/folder.png")); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Unable to locate icons"); } + } - public static PreferencesDialog CreateDialogForProofEditor(Frame frame, RuleFrame rules) { - PreferencesDialog p = new PreferencesDialog(frame); - p.rulesFrame = rules; - return p; - } + public static PreferencesDialog CreateDialogForProofEditor(Frame frame, RuleFrame rules) { + PreferencesDialog p = new PreferencesDialog(frame); + p.rulesFrame = rules; + return p; + } - public PreferencesDialog(Frame frame) { - super(frame); + public PreferencesDialog(Frame frame) { + super(frame); - setTitle("Preferences"); + setTitle("Preferences"); - JPanel mainPanel = new JPanel(); - mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - mainPanel.setLayout(new BorderLayout()); + JPanel mainPanel = new JPanel(); + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + mainPanel.setLayout(new BorderLayout()); - mainPanel.add(createGeneralTab()); + mainPanel.add(createGeneralTab()); - JPanel bottomPanel = new JPanel(); - bottomPanel.setBorder(null); - bottomPanel.setLayout(new BorderLayout()); + JPanel bottomPanel = new JPanel(); + bottomPanel.setBorder(null); + bottomPanel.setLayout(new BorderLayout()); - JToolBar toolbar = new JToolBar(); - toolbar.setBorder(null); - JButton okButton = new JButton("Ok"); - okButton.addActionListener(l -> { - applyPreferences(); - this.setVisible(false); - this.dispose(); + JToolBar toolbar = new JToolBar(); + toolbar.setBorder(null); + JButton okButton = new JButton("Ok"); + okButton.addActionListener( + l -> { + applyPreferences(); + this.setVisible(false); + this.dispose(); }); - toolbar.add(okButton); - JButton cancelButton = new JButton("Cancel"); - cancelButton.addActionListener(l -> { - this.setVisible(false); - this.dispose(); + toolbar.add(okButton); + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener( + l -> { + this.setVisible(false); + this.dispose(); }); - toolbar.add(cancelButton); - JButton applyButton = new JButton("Apply"); - applyButton.addActionListener(l -> { - applyPreferences(); + toolbar.add(cancelButton); + JButton applyButton = new JButton("Apply"); + applyButton.addActionListener( + l -> { + applyPreferences(); }); - toolbar.add(applyButton); - bottomPanel.add(toolbar, BorderLayout.EAST); - - mainPanel.add(bottomPanel, BorderLayout.SOUTH); - - setContentPane(mainPanel); - - setSize(600, 400); - setLocationRelativeTo(frame); - setVisible(true); + toolbar.add(applyButton); + bottomPanel.add(toolbar, BorderLayout.EAST); + + mainPanel.add(bottomPanel, BorderLayout.SOUTH); + + setContentPane(mainPanel); + + setSize(600, 400); + setLocationRelativeTo(frame); + setVisible(true); + } + + private void toggleDarkMode(LegupPreferences prefs) { + try { + if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { + UIManager.setLookAndFeel(new FlatDarkLaf()); + } else { + UIManager.setLookAndFeel(new FlatLightLaf()); + } + com.formdev.flatlaf.FlatLaf.updateUI(); + } catch (UnsupportedLookAndFeelException e) { + System.err.println("Not supported ui look and feel"); } - - private void toggleDarkMode(LegupPreferences prefs) { - try { - if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { - UIManager.setLookAndFeel(new FlatDarkLaf()); - } - else { - UIManager.setLookAndFeel(new FlatLightLaf()); - } - com.formdev.flatlaf.FlatLaf.updateUI(); - } - catch (UnsupportedLookAndFeelException e) { - System.err.println("Not supported ui look and feel"); - } + } + + private JScrollPane createGeneralTab() { + LegupPreferences prefs = LegupPreferences.getInstance(); + JScrollPane scrollPane = new JScrollPane(); + JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); + + contentPane.add(createLeftLabel("General Preferences")); + contentPane.add(createLineSeparator()); + + JPanel workRow = new JPanel(); + workRow.setLayout(new BorderLayout()); + JLabel workDirLabel = new JLabel("Work Directory"); + workDirLabel.setToolTipText("This is where the open and save dialogs will open to."); + workRow.add(workDirLabel, BorderLayout.WEST); + workDirectory = new JTextField(prefs.getUserPref(LegupPreferences.WORK_DIRECTORY)); + workRow.add(workDirectory, BorderLayout.CENTER); + JButton openDir = new JButton(new ImageIcon(folderIcon)); + openDir.addActionListener( + a -> { + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(workDirectory.getText())); + chooser.setDialogTitle("Choose work directory"); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setAcceptAllFileFilterUsed(false); + chooser.setVisible(true); + + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + File newFile = chooser.getSelectedFile(); + workDirectory.setText(newFile.toString()); + } + }); + workRow.add(openDir, BorderLayout.EAST); + workRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, workRow.getPreferredSize().height)); + contentPane.add(workRow); + + fullScreen = + new JCheckBox( + "Full Screen", Boolean.valueOf(prefs.getUserPref(LegupPreferences.START_FULL_SCREEN))); + fullScreen.setToolTipText("If checked this starts Legup in full screen."); + JPanel fullScreenRow = new JPanel(); + fullScreenRow.setLayout(new BorderLayout()); + fullScreenRow.add(fullScreen, BorderLayout.WEST); + fullScreenRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, fullScreenRow.getPreferredSize().height)); + contentPane.add(fullScreenRow); + + autoUpdate = + new JCheckBox( + "Automatically Check for Updates", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_UPDATE))); + autoUpdate.setToolTipText( + "If checked this automatically checks for updates on startup of Legup"); + JPanel autoUpdateRow = new JPanel(); + autoUpdateRow.setLayout(new BorderLayout()); + autoUpdateRow.add(autoUpdate, BorderLayout.WEST); + autoUpdateRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, autoUpdateRow.getPreferredSize().height)); + contentPane.add(autoUpdateRow); + // contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + darkMode = + new JCheckBox("Dark Mode", Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))); + darkMode.setToolTipText("This turns dark mode on and off"); + JPanel darkModeRow = new JPanel(); + darkModeRow.setLayout(new BorderLayout()); + darkModeRow.add(darkMode, BorderLayout.WEST); + darkModeRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, darkModeRow.getPreferredSize().height)); + contentPane.add(darkModeRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + contentPane.add(createLeftLabel("Board View Preferences")); + contentPane.add(createLineSeparator()); + showMistakes = + new JCheckBox( + "Show Mistakes", Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_MISTAKES))); + showMistakes.setToolTipText( + "If checked this show incorrectly applied rule applications in red on the board"); + JPanel showMistakesRow = new JPanel(); + showMistakesRow.setLayout(new BorderLayout()); + showMistakesRow.add(showMistakes, BorderLayout.WEST); + showMistakesRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); + contentPane.add(showMistakesRow); + + showAnnotations = + new JCheckBox( + "Show Annotations", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_ANNOTATIONS))); + showAnnotations.setToolTipText( + "If checked this show incorrectly applied rule applications in red on the board"); + JPanel showAnnotationsRow = new JPanel(); + showAnnotationsRow.setLayout(new BorderLayout()); + showAnnotationsRow.add(showAnnotations, BorderLayout.WEST); + showAnnotationsRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showAnnotationsRow.getPreferredSize().height)); + contentPane.add(showAnnotationsRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + contentPane.add(createLeftLabel("Tree View Preferences")); + contentPane.add(createLineSeparator()); + + allowDefault = + new JCheckBox( + "Allow Default Rule Applications", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES))); + allowDefault.setEnabled(false); + allowDefault.setToolTipText( + "If checked this automatically applies a rule where it can on the board"); + + JPanel allowDefaultRow = new JPanel(); + allowDefaultRow.setLayout(new BorderLayout()); + allowDefaultRow.add(allowDefault, BorderLayout.WEST); + allowDefaultRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, allowDefaultRow.getPreferredSize().height)); + contentPane.add(allowDefaultRow); + + generateCases = + new JCheckBox( + "Automatically Generate Cases", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_GENERATE_CASES))); + generateCases.setToolTipText( + "If checked this automatically generates all cases for a case rule"); + JPanel generateCasesRow = new JPanel(); + generateCasesRow.setLayout(new BorderLayout()); + generateCasesRow.add(generateCases, BorderLayout.WEST); + generateCasesRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, generateCasesRow.getPreferredSize().height)); + contentPane.add(generateCasesRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + immFeedback = + new JCheckBox( + "Provide Immediate Feedback", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); + immFeedback.setToolTipText( + "If checked this will update the colors of the tree view elements immediately"); + JPanel immFeedbackRow = new JPanel(); + immFeedbackRow.setLayout(new BorderLayout()); + immFeedbackRow.add(immFeedback, BorderLayout.WEST); + immFeedbackRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); + contentPane.add(immFeedbackRow); + + contentPane.add(createLeftLabel("Instructor Preferences")); + contentPane.add(createLineSeparator()); + immFeedback = + new JCheckBox( + "Instructor Mode", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); + immFeedback.setToolTipText("Currently unimplemented, this does nothing right now"); + immFeedbackRow.setLayout(new BorderLayout()); + immFeedbackRow.add(immFeedback, BorderLayout.WEST); + immFeedbackRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); + contentPane.add(immFeedbackRow); + + contentPane.add(createLeftLabel("Color Preferences")); + contentPane.add(createLineSeparator()); + colorBlind = + new JCheckBox( + "Deuteranomaly(red/green colorblindness)", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.COLOR_BLIND))); + + JPanel colorBlindRow = new JPanel(); + colorBlindRow.setLayout(new BorderLayout()); + colorBlindRow.add(colorBlind, BorderLayout.WEST); + colorBlindRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); + contentPane.add(colorBlindRow); + + scrollPane.setViewportView(contentPane); + return scrollPane; + } + + private JScrollPane createPuzzleTab(Puzzle puzzle) { + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + + JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); + + contentPane.add(createLeftLabel("Rules")); + contentPane.add(createLineSeparator()); + + contentPane.add(createLeftLabel("Direct Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getDirectRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); } - private JScrollPane createGeneralTab() { - LegupPreferences prefs = LegupPreferences.getInstance(); - JScrollPane scrollPane = new JScrollPane(); - JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); - - contentPane.add(createLeftLabel("General Preferences")); - contentPane.add(createLineSeparator()); - - JPanel workRow = new JPanel(); - workRow.setLayout(new BorderLayout()); - JLabel workDirLabel = new JLabel("Work Directory"); - workDirLabel.setToolTipText("This is where the open and save dialogs will open to."); - workRow.add(workDirLabel, BorderLayout.WEST); - workDirectory = new JTextField(prefs.getUserPref(LegupPreferences.WORK_DIRECTORY)); - workRow.add(workDirectory, BorderLayout.CENTER); - JButton openDir = new JButton(new ImageIcon(folderIcon)); - openDir.addActionListener(a -> { - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(workDirectory.getText())); - chooser.setDialogTitle("Choose work directory"); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setAcceptAllFileFilterUsed(false); - chooser.setVisible(true); - - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - File newFile = chooser.getSelectedFile(); - workDirectory.setText(newFile.toString()); - } - }); - workRow.add(openDir, BorderLayout.EAST); - workRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, workRow.getPreferredSize().height)); - contentPane.add(workRow); - - fullScreen = new JCheckBox("Full Screen", Boolean.valueOf(prefs.getUserPref(LegupPreferences.START_FULL_SCREEN))); - fullScreen.setToolTipText("If checked this starts Legup in full screen."); - JPanel fullScreenRow = new JPanel(); - fullScreenRow.setLayout(new BorderLayout()); - fullScreenRow.add(fullScreen, BorderLayout.WEST); - fullScreenRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, fullScreenRow.getPreferredSize().height)); - contentPane.add(fullScreenRow); - - autoUpdate = new JCheckBox("Automatically Check for Updates", Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_UPDATE))); - autoUpdate.setToolTipText("If checked this automatically checks for updates on startup of Legup"); - JPanel autoUpdateRow = new JPanel(); - autoUpdateRow.setLayout(new BorderLayout()); - autoUpdateRow.add(autoUpdate, BorderLayout.WEST); - autoUpdateRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, autoUpdateRow.getPreferredSize().height)); - contentPane.add(autoUpdateRow); -// contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - darkMode = new JCheckBox("Dark Mode", Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))); - darkMode.setToolTipText("This turns dark mode on and off"); - JPanel darkModeRow = new JPanel(); - darkModeRow.setLayout(new BorderLayout()); - darkModeRow.add(darkMode, BorderLayout.WEST); - darkModeRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, darkModeRow.getPreferredSize().height)); - contentPane.add(darkModeRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - contentPane.add(createLeftLabel("Board View Preferences")); - contentPane.add(createLineSeparator()); - showMistakes = new JCheckBox("Show Mistakes", Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_MISTAKES))); - showMistakes.setToolTipText("If checked this show incorrectly applied rule applications in red on the board"); - JPanel showMistakesRow = new JPanel(); - showMistakesRow.setLayout(new BorderLayout()); - showMistakesRow.add(showMistakes, BorderLayout.WEST); - showMistakesRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); - contentPane.add(showMistakesRow); - - showAnnotations = new JCheckBox("Show Annotations", Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_ANNOTATIONS))); - showAnnotations.setToolTipText("If checked this show incorrectly applied rule applications in red on the board"); - JPanel showAnnotationsRow = new JPanel(); - showAnnotationsRow.setLayout(new BorderLayout()); - showAnnotationsRow.add(showAnnotations, BorderLayout.WEST); - showAnnotationsRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, showAnnotationsRow.getPreferredSize().height)); - contentPane.add(showAnnotationsRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - contentPane.add(createLeftLabel("Tree View Preferences")); - contentPane.add(createLineSeparator()); - - allowDefault = new JCheckBox("Allow Default Rule Applications", Boolean.valueOf(prefs.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES))); - allowDefault.setEnabled(false); - allowDefault.setToolTipText("If checked this automatically applies a rule where it can on the board"); - - JPanel allowDefaultRow = new JPanel(); - allowDefaultRow.setLayout(new BorderLayout()); - allowDefaultRow.add(allowDefault, BorderLayout.WEST); - allowDefaultRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, allowDefaultRow.getPreferredSize().height)); - contentPane.add(allowDefaultRow); - - generateCases = new JCheckBox("Automatically Generate Cases", Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_GENERATE_CASES))); - generateCases.setToolTipText("If checked this automatically generates all cases for a case rule"); - JPanel generateCasesRow = new JPanel(); - generateCasesRow.setLayout(new BorderLayout()); - generateCasesRow.add(generateCases, BorderLayout.WEST); - generateCasesRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, generateCasesRow.getPreferredSize().height)); - contentPane.add(generateCasesRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - immFeedback = new JCheckBox("Provide Immediate Feedback", Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); - immFeedback.setToolTipText("If checked this will update the colors of the tree view elements immediately"); - JPanel immFeedbackRow = new JPanel(); - immFeedbackRow.setLayout(new BorderLayout()); - immFeedbackRow.add(immFeedback, BorderLayout.WEST); - immFeedbackRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); - contentPane.add(immFeedbackRow); - - contentPane.add(createLeftLabel("Instructor Preferences")); - contentPane.add(createLineSeparator()); - immFeedback = new JCheckBox("Instructor Mode", Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); - immFeedback.setToolTipText("Currently unimplemented, this does nothing right now"); - immFeedbackRow.setLayout(new BorderLayout()); - immFeedbackRow.add(immFeedback, BorderLayout.WEST); - immFeedbackRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); - contentPane.add(immFeedbackRow); - - contentPane.add(createLeftLabel("Color Preferences")); - contentPane.add(createLineSeparator()); - colorBlind = new JCheckBox("Deuteranomaly(red/green colorblindness)", Boolean.valueOf(prefs.getUserPref(LegupPreferences.COLOR_BLIND))); - - JPanel colorBlindRow = new JPanel(); - colorBlindRow.setLayout(new BorderLayout()); - colorBlindRow.add(colorBlind, BorderLayout.WEST); - colorBlindRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); - contentPane.add(colorBlindRow); - - scrollPane.setViewportView(contentPane); - return scrollPane; + contentPane.add(createLeftLabel("Case Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getCaseRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); } - private JScrollPane createPuzzleTab(Puzzle puzzle) { - JScrollPane scrollPane = new JScrollPane(); - scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - - JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); - - contentPane.add(createLeftLabel("Rules")); - contentPane.add(createLineSeparator()); - - contentPane.add(createLeftLabel("Direct Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getDirectRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - } - - contentPane.add(createLeftLabel("Case Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getCaseRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - } - - contentPane.add(createLeftLabel("Contradiction Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getContradictionRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - } - - scrollPane.setViewportView(contentPane); - return scrollPane; + contentPane.add(createLeftLabel("Contradiction Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getContradictionRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); } - private JPanel createRuleRow(Rule rule) { - JPanel ruleRow = new JPanel(); - ruleRow.setLayout(new BorderLayout()); - - JLabel ruleLabel = new JLabel(rule.getRuleName()); - ruleRow.add(ruleLabel, BorderLayout.WEST); - - JLabel ruleAcc = new JLabel(); - ruleAcc.setHorizontalAlignment(JLabel.CENTER); - ruleAcc.setBorder(MaterialBorders.LIGHT_LINE_BORDER); - ruleAcc.setPreferredSize(new Dimension(60, 20)); - ruleAcc.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent e) { - ruleAcc.requestFocusInWindow(); - } + scrollPane.setViewportView(contentPane); + return scrollPane; + } + + private JPanel createRuleRow(Rule rule) { + JPanel ruleRow = new JPanel(); + ruleRow.setLayout(new BorderLayout()); + + JLabel ruleLabel = new JLabel(rule.getRuleName()); + ruleRow.add(ruleLabel, BorderLayout.WEST); + + JLabel ruleAcc = new JLabel(); + ruleAcc.setHorizontalAlignment(JLabel.CENTER); + ruleAcc.setBorder(MaterialBorders.LIGHT_LINE_BORDER); + ruleAcc.setPreferredSize(new Dimension(60, 20)); + ruleAcc.addMouseListener( + new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + ruleAcc.requestFocusInWindow(); + } }); - ruleAcc.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - int keyCode = e.getKeyCode(); - String combo = ""; - if (e.isControlDown()) { - combo += "Ctrl + "; - } - else { - if (e.isShiftDown()) { - combo += "Shift + "; - } - else { - if (e.isAltDown()) { - combo += "Alt + "; - } - } - } - if (keyCode == KeyEvent.VK_CONTROL || keyCode == KeyEvent.VK_SHIFT || keyCode == KeyEvent.VK_ALT) { - return; + ruleAcc.addKeyListener( + new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + int keyCode = e.getKeyCode(); + String combo = ""; + if (e.isControlDown()) { + combo += "Ctrl + "; + } else { + if (e.isShiftDown()) { + combo += "Shift + "; + } else { + if (e.isAltDown()) { + combo += "Alt + "; } - combo += KeyEvent.getKeyText(keyCode); - ruleAcc.setText(combo); + } } + if (keyCode == KeyEvent.VK_CONTROL + || keyCode == KeyEvent.VK_SHIFT + || keyCode == KeyEvent.VK_ALT) { + return; + } + combo += KeyEvent.getKeyText(keyCode); + ruleAcc.setText(combo); + } }); - ruleRow.add(ruleAcc, BorderLayout.EAST); - - ruleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, ruleRow.getPreferredSize().height)); - return ruleRow; - } - - private JPanel createLeftLabel(String text) { - JPanel labelRow = new JPanel(); - labelRow.setLayout(new BorderLayout()); - JLabel label = new JLabel(text); - label.setFont(MaterialFonts.BOLD); - label.setHorizontalAlignment(JLabel.LEFT); - labelRow.add(label, BorderLayout.WEST); - - labelRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, labelRow.getPreferredSize().height)); - return labelRow; - } - - private JSeparator createLineSeparator() { - JSeparator separator = new JSeparator(); - separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5)); - return separator; + ruleRow.add(ruleAcc, BorderLayout.EAST); + + ruleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, ruleRow.getPreferredSize().height)); + return ruleRow; + } + + private JPanel createLeftLabel(String text) { + JPanel labelRow = new JPanel(); + labelRow.setLayout(new BorderLayout()); + JLabel label = new JLabel(text); + label.setFont(MaterialFonts.BOLD); + label.setHorizontalAlignment(JLabel.LEFT); + labelRow.add(label, BorderLayout.WEST); + + labelRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, labelRow.getPreferredSize().height)); + return labelRow; + } + + private JSeparator createLineSeparator() { + JSeparator separator = new JSeparator(); + separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5)); + return separator; + } + + public void applyPreferences() { + LegupPreferences prefs = LegupPreferences.getInstance(); + prefs.setUserPref(LegupPreferences.WORK_DIRECTORY, workDirectory.getText()); + prefs.setUserPref( + LegupPreferences.START_FULL_SCREEN, Boolean.toString(fullScreen.isSelected())); + prefs.setUserPref(LegupPreferences.AUTO_UPDATE, Boolean.toString(autoUpdate.isSelected())); + prefs.setUserPref(LegupPreferences.DARK_MODE, Boolean.toString(darkMode.isSelected())); + prefs.setUserPref(LegupPreferences.SHOW_MISTAKES, Boolean.toString(showMistakes.isSelected())); + prefs.setUserPref( + LegupPreferences.SHOW_ANNOTATIONS, Boolean.toString(showAnnotations.isSelected())); + prefs.setUserPref( + LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); + prefs.setUserPref( + LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(generateCases.isSelected())); + prefs.setUserPref( + LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(immFeedback.isSelected())); + prefs.setUserPref(LegupPreferences.COLOR_BLIND, Boolean.toString(colorBlind.isSelected())); + + if (rulesFrame != null) { + rulesFrame.getCasePanel().updateRules(); + rulesFrame.getDirectRulePanel().updateRules(); + rulesFrame.getContradictionPanel().updateRules(); } - public void applyPreferences() { - LegupPreferences prefs = LegupPreferences.getInstance(); - prefs.setUserPref(LegupPreferences.WORK_DIRECTORY, workDirectory.getText()); - prefs.setUserPref(LegupPreferences.START_FULL_SCREEN, Boolean.toString(fullScreen.isSelected())); - prefs.setUserPref(LegupPreferences.AUTO_UPDATE, Boolean.toString(autoUpdate.isSelected())); - prefs.setUserPref(LegupPreferences.DARK_MODE, Boolean.toString(darkMode.isSelected())); - prefs.setUserPref(LegupPreferences.SHOW_MISTAKES, Boolean.toString(showMistakes.isSelected())); - prefs.setUserPref(LegupPreferences.SHOW_ANNOTATIONS, Boolean.toString(showAnnotations.isSelected())); - prefs.setUserPref(LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); - prefs.setUserPref(LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(generateCases.isSelected())); - prefs.setUserPref(LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(immFeedback.isSelected())); - prefs.setUserPref(LegupPreferences.COLOR_BLIND, Boolean.toString(colorBlind.isSelected())); - - if(rulesFrame != null) { - rulesFrame.getCasePanel().updateRules(); - rulesFrame.getDirectRulePanel().updateRules(); - rulesFrame.getContradictionPanel().updateRules(); - } - - // toggle dark mode based on updated NIGHT_MODE variable - toggleDarkMode(prefs); - } -} \ No newline at end of file + // toggle dark mode based on updated NIGHT_MODE variable + toggleDarkMode(prefs); + } +} diff --git a/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java b/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java index e83f660e7..99f6b139a 100644 --- a/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java +++ b/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java @@ -17,14 +17,8 @@ import edu.rpi.legup.ui.boardview.BoardView; import edu.rpi.legup.ui.proofeditorui.rulesview.RuleFrame; import edu.rpi.legup.ui.proofeditorui.treeview.TreePanel; -import edu.rpi.legup.ui.proofeditorui.treeview.TreeView; import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; import edu.rpi.legup.user.Submission; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.*; -import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -37,988 +31,1053 @@ import java.net.URL; import java.util.List; import java.util.Objects; +import javax.swing.*; +import javax.swing.border.TitledBorder; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class ProofEditorPanel extends LegupPanel implements IHistoryListener { - private final static Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName()); - private JMenuBar mBar; - private TreePanel treePanel; - private FileDialog fileDialog; - private JFrame frame; - private RuleFrame ruleFrame; - private DynamicView dynamicBoardView; - private JSplitPane topHalfPanel, mainPanel; - private TitledBorder boardBorder; - - private JButton[] toolBarButtons; - private JMenu file; - private JMenuItem newPuzzle, resetPuzzle, saveProofAs, saveProofChange, helpTutorial, preferences, exit; - private JMenu edit; - private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen; - - private JMenu view; - - private JMenu proof; - private JMenuItem add, delete, merge, collapse; - private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback; - - private JMenu about, help; - private JMenuItem helpLegup, aboutLegup; - - private JToolBar toolBar; - private BoardView boardView; - private JFileChooser folderBrowser; - - private LegupUI legupUI; - - public static final int ALLOW_HINTS = 1; - public static final int ALLOW_DEFAPP = 2; - public static final int ALLOW_FULLAI = 4; - public static final int ALLOW_JUST = 8; - public static final int REQ_STEP_JUST = 16; - public static final int IMD_FEEDBACK = 32; - public static final int INTERN_RO = 64; - public static final int AUTO_JUST = 128; - final static int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; - private static final String[] PROFILES = {"No Assistance", "Rigorous Proof", "Casual Proof", "Assisted Proof", "Guided Proof", "Training-Wheels Proof", "No Restrictions"}; - private static final int[] PROF_FLAGS = {0, ALLOW_JUST | REQ_STEP_JUST, ALLOW_JUST, ALLOW_HINTS | ALLOW_JUST | AUTO_JUST, ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST, ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO, ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST}; - private JMenu proofMode = new JMenu("Proof Mode"); - private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length]; - - private static int CONFIG_INDEX = 0; - - protected JMenu ai = new JMenu("AI"); - protected JMenuItem runAI = new JMenuItem("Run AI to completion"); - protected JMenuItem setpAI = new JMenuItem("Run AI one Step"); - protected JMenuItem testAI = new JMenuItem("Test AI!"); - protected JMenuItem hintAI = new JMenuItem("Hint"); - - public ProofEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.fileDialog = fileDialog; - this.frame = frame; - this.legupUI = legupUI; - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(800, 700)); + private static final Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName()); + private JMenuBar mBar; + private TreePanel treePanel; + private FileDialog fileDialog; + private JFrame frame; + private RuleFrame ruleFrame; + private DynamicView dynamicBoardView; + private JSplitPane topHalfPanel, mainPanel; + private TitledBorder boardBorder; + + private JButton[] toolBarButtons; + private JMenu file; + private JMenuItem newPuzzle, + resetPuzzle, + saveProofAs, + saveProofChange, + helpTutorial, + preferences, + exit; + private JMenu edit; + private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen; + + private JMenu view; + + private JMenu proof; + private JMenuItem add, delete, merge, collapse; + private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback; + private JMenu about, help; + private JMenuItem helpLegup, aboutLegup; + + private JToolBar toolBar; + private BoardView boardView; + private JFileChooser folderBrowser; + + private LegupUI legupUI; + + public static final int ALLOW_HINTS = 1; + public static final int ALLOW_DEFAPP = 2; + public static final int ALLOW_FULLAI = 4; + public static final int ALLOW_JUST = 8; + public static final int REQ_STEP_JUST = 16; + public static final int IMD_FEEDBACK = 32; + public static final int INTERN_RO = 64; + public static final int AUTO_JUST = 128; + static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; + private static final String[] PROFILES = { + "No Assistance", + "Rigorous Proof", + "Casual Proof", + "Assisted Proof", + "Guided Proof", + "Training-Wheels Proof", + "No Restrictions" + }; + private static final int[] PROF_FLAGS = { + 0, + ALLOW_JUST | REQ_STEP_JUST, + ALLOW_JUST, + ALLOW_HINTS | ALLOW_JUST | AUTO_JUST, + ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST, + ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO, + ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST + }; + private JMenu proofMode = new JMenu("Proof Mode"); + private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length]; + + private static int CONFIG_INDEX = 0; + + protected JMenu ai = new JMenu("AI"); + protected JMenuItem runAI = new JMenuItem("Run AI to completion"); + protected JMenuItem setpAI = new JMenuItem("Run AI one Step"); + protected JMenuItem testAI = new JMenuItem("Test AI!"); + protected JMenuItem hintAI = new JMenuItem("Hint"); + + public ProofEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.fileDialog = fileDialog; + this.frame = frame; + this.legupUI = legupUI; + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(800, 700)); + } + + @Override + public void makeVisible() { + this.removeAll(); + + setupToolBar(); + setupContent(); + frame.setJMenuBar(getMenuBar()); + } + + public JMenuBar getMenuBar() { + if (mBar != null) return mBar; + mBar = new JMenuBar(); + + file = new JMenu("File"); + newPuzzle = new JMenuItem("Open"); + resetPuzzle = new JMenuItem("Reset Puzzle"); + // genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle generator + saveProofAs = new JMenuItem("Save As"); // create a new file to save + saveProofChange = new JMenuItem("Save"); // save to the current file + preferences = new JMenuItem("Preferences"); + helpTutorial = new JMenuItem("Help"); // jump to web page + exit = new JMenuItem("Exit"); + + edit = new JMenu("Edit"); + undo = new JMenuItem("Undo"); + redo = new JMenuItem("Redo"); + + fitBoardToScreen = new JMenuItem("Fit Board to Screen"); + fitTreeToScreen = new JMenuItem("Fit Tree to Screen"); + + view = new JMenu("View"); + + proof = new JMenu("Proof"); + + String os = LegupUI.getOS(); + + add = new JMenuItem("Add"); + add.addActionListener(a -> treePanel.add()); + if (os.equals("mac")) { + add.setAccelerator( + KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); } - - @Override - public void makeVisible() { - this.removeAll(); - - setupToolBar(); - setupContent(); - frame.setJMenuBar(getMenuBar()); + proof.add(add); + + delete = new JMenuItem("Delete"); + delete.addActionListener(a -> treePanel.delete()); + if (os.equals("mac")) { + delete.setAccelerator( + KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); } - - public JMenuBar getMenuBar() { - if (mBar != null) return mBar; - mBar = new JMenuBar(); - - file = new JMenu("File"); - newPuzzle = new JMenuItem("Open"); - resetPuzzle = new JMenuItem("Reset Puzzle"); -// genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle generator - saveProofAs = new JMenuItem("Save As"); // create a new file to save - saveProofChange = new JMenuItem("Save"); // save to the current file - preferences = new JMenuItem("Preferences"); - helpTutorial = new JMenuItem("Help"); // jump to web page - exit = new JMenuItem("Exit"); - - edit = new JMenu("Edit"); - undo = new JMenuItem("Undo"); - redo = new JMenuItem("Redo"); - - fitBoardToScreen = new JMenuItem("Fit Board to Screen"); - fitTreeToScreen = new JMenuItem("Fit Tree to Screen"); - - view = new JMenu("View"); - - proof = new JMenu("Proof"); - - String os = LegupUI.getOS(); - - add = new JMenuItem("Add"); - add.addActionListener(a -> treePanel.add()); - if (os.equals("mac")) { - add.setAccelerator(KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); - } - proof.add(add); - - delete = new JMenuItem("Delete"); - delete.addActionListener(a -> treePanel.delete()); - if (os.equals("mac")) { - delete.setAccelerator(KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); - } - proof.add(delete); - - merge = new JMenuItem("Merge"); - merge.addActionListener(a -> treePanel.merge()); - if (os.equals("mac")) { - merge.setAccelerator(KeyStroke.getKeyStroke('M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK)); - } - proof.add(merge); - - collapse = new JMenuItem("Collapse"); - collapse.addActionListener(a -> treePanel.collapse()); - if (os.equals("mac")) { - collapse.setAccelerator(KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); - } - collapse.setEnabled(false); - proof.add(collapse); - - allowDefault = new JCheckBoxMenuItem("Allow Default Rule Applications", - LegupPreferences.getInstance().getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES).equalsIgnoreCase(Boolean.toString(true))); - allowDefault.addChangeListener(e -> { - LegupPreferences.getInstance().setUserPref(LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); + proof.add(delete); + + merge = new JMenuItem("Merge"); + merge.addActionListener(a -> treePanel.merge()); + if (os.equals("mac")) { + merge.setAccelerator( + KeyStroke.getKeyStroke('M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK)); + } + proof.add(merge); + + collapse = new JMenuItem("Collapse"); + collapse.addActionListener(a -> treePanel.collapse()); + if (os.equals("mac")) { + collapse.setAccelerator( + KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); + } + collapse.setEnabled(false); + proof.add(collapse); + + allowDefault = + new JCheckBoxMenuItem( + "Allow Default Rule Applications", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES) + .equalsIgnoreCase(Boolean.toString(true))); + allowDefault.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.ALLOW_DEFAULT_RULES, + Boolean.toString(allowDefault.isSelected())); }); - proof.add(allowDefault); - - caseRuleGen = new JCheckBoxMenuItem("Automatically generate cases for CaseRule", - LegupPreferences.getInstance().getUserPref(LegupPreferences.AUTO_GENERATE_CASES).equalsIgnoreCase(Boolean.toString(true))); - caseRuleGen.addChangeListener(e -> { - LegupPreferences.getInstance().setUserPref(LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(caseRuleGen.isSelected())); + proof.add(allowDefault); + + caseRuleGen = + new JCheckBoxMenuItem( + "Automatically generate cases for CaseRule", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) + .equalsIgnoreCase(Boolean.toString(true))); + caseRuleGen.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(caseRuleGen.isSelected())); }); - proof.add(caseRuleGen); - - imdFeedback = new JCheckBoxMenuItem("Provide immediate feedback", - LegupPreferences.getInstance().getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK).equalsIgnoreCase(Boolean.toString(true))); - imdFeedback.addChangeListener(e -> { - LegupPreferences.getInstance().setUserPref(LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(imdFeedback.isSelected())); + proof.add(caseRuleGen); + + imdFeedback = + new JCheckBoxMenuItem( + "Provide immediate feedback", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK) + .equalsIgnoreCase(Boolean.toString(true))); + imdFeedback.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(imdFeedback.isSelected())); }); - proof.add(imdFeedback); - - about = new JMenu("About"); - helpLegup = new JMenuItem("Help Legup"); - aboutLegup = new JMenuItem("About Legup"); - - mBar.add(file); - file.add(newPuzzle); - newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); - if (os.equals("mac")) { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); - } + proof.add(imdFeedback); + + about = new JMenu("About"); + helpLegup = new JMenuItem("Help Legup"); + aboutLegup = new JMenuItem("About Legup"); + + mBar.add(file); + file.add(newPuzzle); + newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); + } - file.add(resetPuzzle); - resetPuzzle.addActionListener(a -> { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle != null) { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeNode rootNode = tree.getRootNode(); - if (rootNode != null) { - int confirmReset = JOptionPane.showConfirmDialog(this, "Reset Puzzle to Root Node?", "Confirm Reset", JOptionPane.YES_NO_OPTION); - if (confirmReset == JOptionPane.YES_OPTION) { - - List children = rootNode.getChildren(); - children.forEach(t -> puzzle.notifyTreeListeners(l -> l.onTreeElementRemoved(t))); - children.forEach(t -> puzzle.notifyBoardListeners(l -> l.onTreeElementChanged(t))); - rootNode.clearChildren(); - final TreeViewSelection selection = new TreeViewSelection(treePanel.getTreeView().getElementView(rootNode)); - puzzle.notifyTreeListeners(l -> l.onTreeSelectionChanged(selection)); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); - GameBoardFacade.getInstance().getHistory().clear(); - } - } + file.add(resetPuzzle); + resetPuzzle.addActionListener( + a -> { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle != null) { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeNode rootNode = tree.getRootNode(); + if (rootNode != null) { + int confirmReset = + JOptionPane.showConfirmDialog( + this, + "Reset Puzzle to Root Node?", + "Confirm Reset", + JOptionPane.YES_NO_OPTION); + if (confirmReset == JOptionPane.YES_OPTION) { + + List children = rootNode.getChildren(); + children.forEach(t -> puzzle.notifyTreeListeners(l -> l.onTreeElementRemoved(t))); + children.forEach(t -> puzzle.notifyBoardListeners(l -> l.onTreeElementChanged(t))); + rootNode.clearChildren(); + final TreeViewSelection selection = + new TreeViewSelection(treePanel.getTreeView().getElementView(rootNode)); + puzzle.notifyTreeListeners(l -> l.onTreeSelectionChanged(selection)); + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged( + selection.getFirstSelection().getTreeElement())); + GameBoardFacade.getInstance().getHistory().clear(); + } } + } }); - if (os.equals("mac")) { - resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK)); - } - file.addSeparator(); - - file.add(saveProofAs); - saveProofAs.addActionListener((ActionEvent) -> saveProofAs()); - + if (os.equals("mac")) { + resetPuzzle.setAccelerator( + KeyStroke.getKeyStroke('R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK)); + } + file.addSeparator(); - //save proof as... - if (os.equals("mac")) { - saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); - } + file.add(saveProofAs); + saveProofAs.addActionListener((ActionEvent) -> saveProofAs()); - // save proof change - if (os.equals("mac")) { - saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); - } + // save proof as... + if (os.equals("mac")) { + saveProofAs.setAccelerator( + KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); + } + // save proof change + if (os.equals("mac")) { + saveProofChange.setAccelerator( + KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + } - file.add(saveProofChange); - saveProofChange.addActionListener((ActionEvent) -> saveProofChange()); - file.addSeparator(); + file.add(saveProofChange); + saveProofChange.addActionListener((ActionEvent) -> saveProofChange()); + file.addSeparator(); - // preference - file.add(preferences); - preferences.addActionListener(a -> { - PreferencesDialog preferencesDialog = PreferencesDialog.CreateDialogForProofEditor(this.frame, this.ruleFrame); + // preference + file.add(preferences); + preferences.addActionListener( + a -> { + PreferencesDialog preferencesDialog = + PreferencesDialog.CreateDialogForProofEditor(this.frame, this.ruleFrame); }); - file.addSeparator(); - - // help function - if (os.equals("mac")) { - helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); - } - file.add(helpTutorial); - - helpTutorial.addActionListener((ActionEvent) -> helpTutorial()); - file.addSeparator(); - - - //exit - file.add(exit); - exit.addActionListener((ActionEvent) -> exitEditor()); - if (os.equals("mac")) { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); - } - mBar.add(edit); - - - edit.add(undo); - undo.addActionListener((ActionEvent) -> - GameBoardFacade.getInstance().getHistory().undo()); - if (os.equals("mac")) { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); - } + file.addSeparator(); + + // help function + if (os.equals("mac")) { + helpTutorial.setAccelerator( + KeyStroke.getKeyStroke('H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); + } + file.add(helpTutorial); + + helpTutorial.addActionListener((ActionEvent) -> helpTutorial()); + file.addSeparator(); + + // exit + file.add(exit); + exit.addActionListener((ActionEvent) -> exitEditor()); + if (os.equals("mac")) { + exit.setAccelerator( + KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); + } + mBar.add(edit); + + edit.add(undo); + undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); + if (os.equals("mac")) { + undo.setAccelerator( + KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + } - edit.add(redo); + edit.add(redo); - // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) - Action redoAction = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - GameBoardFacade.getInstance().getHistory().redo(); - } + // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) + Action redoAction = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + GameBoardFacade.getInstance().getHistory().redo(); + } }; - if (os.equals("mac")) { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW).put( - KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW).put( - KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "redoAction"); - redo.setAccelerator(KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); - } - else { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getActionMap().put("redoAction", redoAction); - - // Button in menu will show CTRL-SHIFT-Z as primary keybind - redo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); - } + if (os.equals("mac")) { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK), + "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "redoAction"); + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); + } else { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), + "redoAction"); + redo.getActionMap().put("redoAction", redoAction); + + // Button in menu will show CTRL-SHIFT-Z as primary keybind + redo.setAccelerator( + KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + } - edit.add(fitBoardToScreen); - fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); + edit.add(fitBoardToScreen); + fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); - edit.add(fitTreeToScreen); - fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen()); + edit.add(fitTreeToScreen); + fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen()); - mBar.add(proof); + mBar.add(proof); - about.add(aboutLegup); - aboutLegup.addActionListener(l -> { - JOptionPane.showMessageDialog(null, "Version: 5.1.0"); + about.add(aboutLegup); + aboutLegup.addActionListener( + l -> { + JOptionPane.showMessageDialog(null, "Version: 5.1.0"); }); - about.add(helpLegup); - helpLegup.addActionListener(l -> { - try { - java.awt.Desktop.getDesktop().browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); - } - catch (IOException e) { - LOGGER.error("Can't open web page"); - } + about.add(helpLegup); + helpLegup.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } }); - mBar.add(about); - - return mBar; - } - - public void exitEditor() { - // Wipes the puzzle entirely as if LEGUP just started - GameBoardFacade.getInstance().clearPuzzle(); - this.legupUI.displayPanel(0); - treePanel = null; - boardView = null; - } - - // File opener - public Object[] promptPuzzle() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - if (facade.getBoard() != null) { - if (noquit("Opening a new puzzle?")) { - return new Object[0]; - } - } - - LegupPreferences preferences = LegupPreferences.getInstance(); - String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); - if (preferences.getSavedPath() != "") { - preferredDirectory = preferences.getSavedPath(); - } - - File preferredDirectoryFile = new File(preferredDirectory); - JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile); - String fileName = null; - File puzzleFile = null; - - fileBrowser.showOpenDialog(this); - fileBrowser.setVisible(true); - fileBrowser.setCurrentDirectory(new File(preferredDirectory)); - fileBrowser.setDialogTitle("Select Proof File"); - fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - fileBrowser.setAcceptAllFileFilterUsed(false); - - File puzzlePath = fileBrowser.getSelectedFile(); - System.out.println(puzzlePath.getAbsolutePath()); - - if (puzzlePath != null) { - fileName = puzzlePath.getAbsolutePath(); - String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator)); - preferences.setSavedPath(lastDirectoryPath); - puzzleFile = puzzlePath; - } - else { - // The attempt to prompt a puzzle ended gracefully (cancel) - return null; - } - - return new Object[]{fileName, puzzleFile}; - } - - public void loadPuzzle() { - Object[] items = promptPuzzle(); - // Return if items == null (cancel) - if (items == null) { - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - loadPuzzle(fileName, puzzleFile); + mBar.add(about); + + return mBar; + } + + public void exitEditor() { + // Wipes the puzzle entirely as if LEGUP just started + GameBoardFacade.getInstance().clearPuzzle(); + this.legupUI.displayPanel(0); + treePanel = null; + boardView = null; + } + + // File opener + public Object[] promptPuzzle() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + if (facade.getBoard() != null) { + if (noquit("Opening a new puzzle?")) { + return new Object[0]; + } } - public void loadPuzzle(String fileName, File puzzleFile) { - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(1); - GameBoardFacade.getInstance().loadPuzzle(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } - catch (InvalidFileFormatException e) { - legupUI.displayPanel(0); - LOGGER.error(e.getMessage()); - if (e.getMessage().contains("Proof Tree construction error: could not find rule by ID")) { // TO DO: make error message not hardcoded - JOptionPane.showMessageDialog(null, "This file runs on an outdated version of Legup\nand is not compatible with the current version.", "Error", JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } - else { - JOptionPane.showMessageDialog(null, "File does not exist or it cannot be read", "Error", JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } - } - } + LegupPreferences preferences = LegupPreferences.getInstance(); + String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); + if (preferences.getSavedPath() != "") { + preferredDirectory = preferences.getSavedPath(); } - /** - * save the proof in the current file - */ - private void direct_save() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - } - catch (ExportFileException e) { - e.printStackTrace(); - } - } + File preferredDirectoryFile = new File(preferredDirectory); + JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile); + String fileName = null; + File puzzleFile = null; + + fileBrowser.showOpenDialog(this); + fileBrowser.setVisible(true); + fileBrowser.setCurrentDirectory(new File(preferredDirectory)); + fileBrowser.setDialogTitle("Select Proof File"); + fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fileBrowser.setAcceptAllFileFilterUsed(false); + + File puzzlePath = fileBrowser.getSelectedFile(); + System.out.println(puzzlePath.getAbsolutePath()); + + if (puzzlePath != null) { + fileName = puzzlePath.getAbsolutePath(); + String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator)); + preferences.setSavedPath(lastDirectoryPath); + puzzleFile = puzzlePath; + } else { + // The attempt to prompt a puzzle ended gracefully (cancel) + return null; } - /** - * Create a new file and save proof to it - */ - private void saveProofAs() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - - fileDialog.setMode(FileDialog.SAVE); - fileDialog.setTitle("Save As"); - String curFileName = GameBoardFacade.getInstance().getCurFileName(); - if (curFileName == null) { - fileDialog.setDirectory(LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); - } - else { - File curFile = new File(curFileName); - fileDialog.setDirectory(curFile.getParent()); - } - fileDialog.setVisible(true); - - String fileName = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - } + return new Object[] {fileName, puzzleFile}; + } - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - } - catch (ExportFileException e) { - e.printStackTrace(); - } - } + public void loadPuzzle() { + Object[] items = promptPuzzle(); + // Return if items == null (cancel) + if (items == null) { + return; } - - // Hyperlink for help button; links to wiki page for tutorials - private void helpTutorial() { - //redirecting to certain help link in wiki - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String puz = puzzle.getName(); - String url; - switch (puz) { - case "LightUp": - url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules"; - break; - case "Nurikabe": - url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules"; - break; - case "TreeTent": - url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules"; - break; - case "Skyscrapers": - url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules"; - break; - case "ShortTruthTable": - url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules"; - break; - default: - url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial"; - } - Runtime rt = Runtime.getRuntime(); - try { - //rt.exec("rundll32 url.dll,FileProtocolHandler "+url); - java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); - } - catch (IOException e) { - e.printStackTrace(); + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + loadPuzzle(fileName, puzzleFile); + } + + public void loadPuzzle(String fileName, File puzzleFile) { + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(1); + GameBoardFacade.getInstance().loadPuzzle(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } catch (InvalidFileFormatException e) { + legupUI.displayPanel(0); + LOGGER.error(e.getMessage()); + if (e.getMessage() + .contains( + "Proof Tree construction error: could not find rule by ID")) { // TO DO: make error + // message not + // hardcoded + JOptionPane.showMessageDialog( + null, + "This file runs on an outdated version of Legup\nand is not compatible with the current version.", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } else { + JOptionPane.showMessageDialog( + null, "File does not exist or it cannot be read", "Error", JOptionPane.ERROR_MESSAGE); + loadPuzzle(); } + } } + } - //add the new function need to implement - public void add_drop() { - // add the mouse event then we can use the new listener to implement and - // we should create a need jbuttom for it to ship the rule we select. - JPanel panel = new JPanel(); - JButton moveing_buttom = new JButton(); - moveing_buttom.setFocusPainted(false); - moveing_buttom.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - //get the selected rule - } - }); - panel.add(moveing_buttom); - + /** save the proof in the current file */ + private void direct_save() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - - - // Quick save proof to the current file with a pop window to show "successfully saved" - private void saveProofChange() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - // Save confirmation - JOptionPane.showMessageDialog(null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE); - } - catch (ExportFileException e) { - e.printStackTrace(); - } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); } - - } - - - //ask to edu.rpi.legup.save current proof - public boolean noquit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - /** - * Sets the main content for the edu.rpi.legup.user interface - */ - protected void setupContent() { -// JPanel consoleBox = new JPanel(new BorderLayout()); - JPanel treeBox = new JPanel(new BorderLayout()); - JPanel ruleBox = new JPanel(new BorderLayout()); - - RuleController ruleController = new RuleController(); - ruleFrame = new RuleFrame(ruleController); - ruleBox.add(ruleFrame, BorderLayout.WEST); - - treePanel = new TreePanel(); - - dynamicBoardView = new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); - TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - JPanel boardPanel = new JPanel(new BorderLayout()); - topHalfPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView); - mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel); - topHalfPanel.setPreferredSize(new Dimension(600, 400)); - mainPanel.setPreferredSize(new Dimension(600, 600)); - - boardPanel.add(mainPanel); - boardPanel.setVisible(true); - boardBorder = BorderFactory.createTitledBorder("Board"); - boardBorder.setTitleJustification(TitledBorder.CENTER); - - ruleBox.add(boardPanel); - treeBox.add(ruleBox); - this.add(treeBox); -// consoleBox.add(treeBox); -// -// getContentPane().add(consoleBox); - -// JPopupPanel popupPanel = new JPopupPanel(); -// setGlassPane(popupPanel); -// popupPanel.setVisible(true); - - mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100); -// frame.pack(); - revalidate(); + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } } + } - private void setupToolBar() { - setToolBarButtons(new JButton[ToolbarName.values().length]); - for (int i = 0; i < ToolbarName.values().length; i++) { - String toolBarName = ToolbarName.values()[i].toString(); - URL resourceLocation = ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); - - // Scale the image icons down to make the buttons smaller - ImageIcon imageIcon = new ImageIcon(resourceLocation); - Image image = imageIcon.getImage(); - imageIcon = new ImageIcon(image.getScaledInstance(this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton button = new JButton(toolBarName, imageIcon); - button.setFocusPainted(false); - getToolBarButtons()[i] = button; - } - - toolBar = new JToolBar(); - toolBar.setFloatable(false); - toolBar.setRollover(true); - - for (int i = 0; i < getToolBarButtons().length; i++) { - for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { - if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { - toolBar.addSeparator(); - } - } - String toolBarName = ToolbarName.values()[i].toString(); - - toolBar.add(getToolBarButtons()[i]); - getToolBarButtons()[i].setToolTipText(toolBarName); - - getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); - getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); - } - -// toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent e) -> promptPuzzle()); -// toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> saveProof()); -// toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> GameBoardFacade.getInstance().getHistory().undo()); -// toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> GameBoardFacade.getInstance().getHistory().redo()); - toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> { - }); - toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener((ActionEvent e) -> checkProof()); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> { - }); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> { - }); - - toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener((ActionEvent e) -> checkProofAll()); - -// toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); -// toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); -// toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true); - - this.add(toolBar, BorderLayout.NORTH); + /** Create a new file and save proof to it */ + private void saveProofAs() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - /** - * Sets the toolbar buttons - * - * @param toolBarButtons toolbar buttons - */ - public void setToolBarButtons(JButton[] toolBarButtons) { - this.toolBarButtons = toolBarButtons; + fileDialog.setMode(FileDialog.SAVE); + fileDialog.setTitle("Save As"); + String curFileName = GameBoardFacade.getInstance().getCurFileName(); + if (curFileName == null) { + fileDialog.setDirectory( + LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); + } else { + File curFile = new File(curFileName); + fileDialog.setDirectory(curFile.getParent()); } + fileDialog.setVisible(true); - /** - * Gets the toolbar buttons - * - * @return toolbar buttons - */ - public JButton[] getToolBarButtons() { - return toolBarButtons; + String fileName = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); } - /** - * Checks the proof for correctness - */ - private void checkProof() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - Tree tree = GameBoardFacade.getInstance().getTree(); - Board board = facade.getBoard(); - Board finalBoard = null; - boolean delayStatus = true; //board.evalDelayStatus(); - - repaintAll(); - - Puzzle puzzle = facade.getPuzzleModule(); - - if (puzzle.isPuzzleComplete()) { - // This is for submission which is not integrated yet - /*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); - if (confirm == JOptionPane.YES_OPTION) { - Submission submission = new Submission(board); - submission.submit(); - }*/ - JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct."); - } - else { - String message = "\nThe game board is not solved."; - JOptionPane.showMessageDialog(null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } } - - private void repaintAll() { - boardView.repaint(); - treePanel.repaint(); + } + + // Hyperlink for help button; links to wiki page for tutorials + private void helpTutorial() { + // redirecting to certain help link in wiki + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - - public void setPuzzleView(Puzzle puzzle) { - this.boardView = puzzle.getBoardView(); - - dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); - this.topHalfPanel.setRightComponent(dynamicBoardView); - this.topHalfPanel.setVisible(true); - String boardType = boardView.getBoard().getClass().getSimpleName(); - boardType = boardType.substring(0, boardType.indexOf("Board")); - TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - this.treePanel.getTreeView().resetView(); - this.treePanel.getTreeView().setTree(puzzle.getTree()); - - puzzle.addTreeListener(treePanel.getTreeView()); - puzzle.addBoardListener(puzzle.getBoardView()); - - ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules()); - ruleFrame.getCasePanel().setRules(puzzle.getCaseRules()); - ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules()); - ruleFrame.getSearchPanel().setSearchBar(puzzle); - - - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); -// toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); - - reloadGui(); + String puz = puzzle.getName(); + String url; + switch (puz) { + case "LightUp": + url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules"; + break; + case "Nurikabe": + url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules"; + break; + case "TreeTent": + url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules"; + break; + case "Skyscrapers": + url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules"; + break; + case "ShortTruthTable": + url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules"; + break; + default: + url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial"; } - - public void reloadGui() { - repaintTree(); + Runtime rt = Runtime.getRuntime(); + try { + // rt.exec("rundll32 url.dll,FileProtocolHandler "+url); + java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); + } catch (IOException e) { + e.printStackTrace(); } - - public void repaintTree() { - treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree()); + } + + // add the new function need to implement + public void add_drop() { + // add the mouse event then we can use the new listener to implement and + // we should create a need jbuttom for it to ship the rule we select. + JPanel panel = new JPanel(); + JButton moveing_buttom = new JButton(); + moveing_buttom.setFocusPainted(false); + moveing_buttom.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // get the selected rule + } + }); + panel.add(moveing_buttom); + } + + // Quick save proof to the current file with a pop window to show "successfully saved" + private void saveProofChange() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - - /** - * Checks the proof for all files - */ - private void checkProofAll() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - - LegupPreferences preferences = LegupPreferences.getInstance(); - File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); - folderBrowser = new JFileChooser(preferredDirectory); - - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - - File folder = folderBrowser.getSelectedFile(); - - // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); - - // Go through student folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - // Write path - String path = folderEntry.getName(); - traverseDir(folderEntry, writer, path); - } - } - catch (IOException ex) { - LOGGER.error(ex.getMessage()); + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); } - JOptionPane.showMessageDialog(null, "Batch grading complete."); + exporter.exportPuzzle(fileName); + // Save confirmation + JOptionPane.showMessageDialog( + null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE); + } catch (ExportFileException e) { + e.printStackTrace(); + } } - - private boolean basicCheckProof(int[][] origCells) { - return false; + } + + // ask to edu.rpi.legup.save current proof + public boolean noquit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + /** Sets the main content for the edu.rpi.legup.user interface */ + protected void setupContent() { + // JPanel consoleBox = new JPanel(new BorderLayout()); + JPanel treeBox = new JPanel(new BorderLayout()); + JPanel ruleBox = new JPanel(new BorderLayout()); + + RuleController ruleController = new RuleController(); + ruleFrame = new RuleFrame(ruleController); + ruleBox.add(ruleFrame, BorderLayout.WEST); + + treePanel = new TreePanel(); + + dynamicBoardView = + new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); + TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + JPanel boardPanel = new JPanel(new BorderLayout()); + topHalfPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView); + mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel); + topHalfPanel.setPreferredSize(new Dimension(600, 400)); + mainPanel.setPreferredSize(new Dimension(600, 600)); + + boardPanel.add(mainPanel); + boardPanel.setVisible(true); + boardBorder = BorderFactory.createTitledBorder("Board"); + boardBorder.setTitleJustification(TitledBorder.CENTER); + + ruleBox.add(boardPanel); + treeBox.add(ruleBox); + this.add(treeBox); + // consoleBox.add(treeBox); + // + // getContentPane().add(consoleBox); + + // JPopupPanel popupPanel = new JPopupPanel(); + // setGlassPane(popupPanel); + // popupPanel.setVisible(true); + + mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100); + // frame.pack(); + revalidate(); + } + + private void setupToolBar() { + setToolBarButtons(new JButton[ToolbarName.values().length]); + for (int i = 0; i < ToolbarName.values().length; i++) { + String toolBarName = ToolbarName.values()[i].toString(); + URL resourceLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); + + // Scale the image icons down to make the buttons smaller + ImageIcon imageIcon = new ImageIcon(resourceLocation); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); + + JButton button = new JButton(toolBarName, imageIcon); + button.setFocusPainted(false); + getToolBarButtons()[i] = button; } - private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { - // Recursively traverse directory - GameBoardFacade facade = GameBoardFacade.getInstance(); + toolBar = new JToolBar(); + toolBar.setFloatable(false); + toolBar.setRollover(true); - // Folder is empty - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,,Ungradeable\n"); - return; + for (int i = 0; i < getToolBarButtons().length; i++) { + for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { + if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { + toolBar.addSeparator(); } + } + String toolBarName = ToolbarName.values()[i].toString(); - // Travese directory, recurse if sub-directory found - // If ungradeable, do not leave a score (0, 1) - for (final File f : Objects.requireNonNull(folder.listFiles())) { - // Recurse - if (f.isDirectory()) { - traverseDir(f, writer, path + "/" + f.getName()); - continue; - } - - // Set path name - writer.append(path).append(","); - - // Load puzzle, run checker - // If wrong file type, ungradeable - String fName = f.getName(); - String fPath = f.getAbsolutePath(); - File puzzleFile = new File(fPath); - if (puzzleFile.exists()) { - // Try to load file. If invalid, note in csv - try { - // Load puzzle, run checker - GameBoardFacade.getInstance().loadPuzzle(fPath); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - - // Write data - writer.append(fName).append(","); - writer.append(puzzle.getName()).append(","); - if (puzzle.isPuzzleComplete()) { - writer.append("1,Solved\n"); - } - else { - writer.append("0,Unsolved\n"); - } - } - catch (InvalidFileFormatException e) { - writer.append(fName).append(",Invalid,,Ungradeable\n"); - } - } - else { - LOGGER.debug("Failed to run sim"); - } - } - } + toolBar.add(getToolBarButtons()[i]); + getToolBarButtons()[i].setToolTipText(toolBarName); - public BoardView getBoardView() { - return boardView; + getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); + getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); } - public DynamicView getDynamicBoardView() { - return dynamicBoardView; + // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent e) -> + // promptPuzzle()); + // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> + // saveProof()); + // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().undo()); + // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().redo()); + toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener((ActionEvent e) -> checkProof()); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); + + toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener( + (ActionEvent e) -> checkProofAll()); + + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true); + + this.add(toolBar, BorderLayout.NORTH); + } + + /** + * Sets the toolbar buttons + * + * @param toolBarButtons toolbar buttons + */ + public void setToolBarButtons(JButton[] toolBarButtons) { + this.toolBarButtons = toolBarButtons; + } + + /** + * Gets the toolbar buttons + * + * @return toolbar buttons + */ + public JButton[] getToolBarButtons() { + return toolBarButtons; + } + + /** Checks the proof for correctness */ + private void checkProof() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + Tree tree = GameBoardFacade.getInstance().getTree(); + Board board = facade.getBoard(); + Board finalBoard = null; + boolean delayStatus = true; // board.evalDelayStatus(); + + repaintAll(); + + Puzzle puzzle = facade.getPuzzleModule(); + + if (puzzle.isPuzzleComplete()) { + // This is for submission which is not integrated yet + /*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); + if (confirm == JOptionPane.YES_OPTION) { + Submission submission = new Submission(board); + submission.submit(); + }*/ + JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct."); + } else { + String message = "\nThe game board is not solved."; + JOptionPane.showMessageDialog(null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE); } + } + + private void repaintAll() { + boardView.repaint(); + treePanel.repaint(); + } + + public void setPuzzleView(Puzzle puzzle) { + this.boardView = puzzle.getBoardView(); + + dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); + this.topHalfPanel.setRightComponent(dynamicBoardView); + this.topHalfPanel.setVisible(true); + String boardType = boardView.getBoard().getClass().getSimpleName(); + boardType = boardType.substring(0, boardType.indexOf("Board")); + TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + this.treePanel.getTreeView().resetView(); + this.treePanel.getTreeView().setTree(puzzle.getTree()); + + puzzle.addTreeListener(treePanel.getTreeView()); + puzzle.addBoardListener(puzzle.getBoardView()); + + ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules()); + ruleFrame.getCasePanel().setRules(puzzle.getCaseRules()); + ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules()); + ruleFrame.getSearchPanel().setSearchBar(puzzle); + + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); + + reloadGui(); + } + + public void reloadGui() { + repaintTree(); + } + + public void repaintTree() { + treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree()); + } + + /** Checks the proof for all files */ + private void checkProofAll() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ - public TreePanel getTreePanel() { - return treePanel; + LegupPreferences preferences = LegupPreferences.getInstance(); + File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); + folderBrowser = new JFileChooser(preferredDirectory); + + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + + File folder = folderBrowser.getSelectedFile(); + + // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); + + // Go through student folders + for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + // Write path + String path = folderEntry.getName(); + traverseDir(folderEntry, writer, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } + JOptionPane.showMessageDialog(null, "Batch grading complete."); + } - /** - * Called when a action is pushed onto the edu.rpi.legup.history stack - * - * @param command action to push onto the stack - */ - @Override - public void onPushChange(ICommand command) { - LOGGER.info("Pushing " + command.getClass().getSimpleName() + " to stack."); - undo.setEnabled(true); -// toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(true); - redo.setEnabled(false); -// toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + private boolean basicCheckProof(int[][] origCells) { + return false; + } - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); - } + private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { + // Recursively traverse directory + GameBoardFacade facade = GameBoardFacade.getInstance(); - /** - * Called when the history is cleared - */ - @Override - public void onClearHistory() { - //undo.setEnabled(false); -// toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - //redo.setEnabled(false); -// toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + // Folder is empty + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,,Ungradeable\n"); + return; } - /** - * Called when an action is redone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - @Override - public void onRedo(boolean isBottom, boolean isTop) { - undo.setEnabled(!isBottom); -// toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); - redo.setEnabled(!isTop); -// toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); - if (isBottom) { - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } - else { - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + // Travese directory, recurse if sub-directory found + // If ungradeable, do not leave a score (0, 1) + for (final File f : Objects.requireNonNull(folder.listFiles())) { + // Recurse + if (f.isDirectory()) { + traverseDir(f, writer, path + "/" + f.getName()); + continue; + } + + // Set path name + writer.append(path).append(","); + + // Load puzzle, run checker + // If wrong file type, ungradeable + String fName = f.getName(); + String fPath = f.getAbsolutePath(); + File puzzleFile = new File(fPath); + if (puzzleFile.exists()) { + // Try to load file. If invalid, note in csv + try { + // Load puzzle, run checker + GameBoardFacade.getInstance().loadPuzzle(fPath); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + + // Write data + writer.append(fName).append(","); + writer.append(puzzle.getName()).append(","); + if (puzzle.isPuzzleComplete()) { + writer.append("1,Solved\n"); + } else { + writer.append("0,Unsolved\n"); + } + } catch (InvalidFileFormatException e) { + writer.append(fName).append(",Invalid,,Ungradeable\n"); } + } else { + LOGGER.debug("Failed to run sim"); + } } - - /** - * Called when an action is undone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - @Override - public void onUndo(boolean isBottom, boolean isTop) { - undo.setEnabled(!isBottom); -// toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); - redo.setEnabled(!isTop); -// toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - if (isBottom) { - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } - else { - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); - } + } + + public BoardView getBoardView() { + return boardView; + } + + public DynamicView getDynamicBoardView() { + return dynamicBoardView; + } + + public TreePanel getTreePanel() { + return treePanel; + } + + /** + * Called when a action is pushed onto the edu.rpi.legup.history stack + * + * @param command action to push onto the stack + */ + @Override + public void onPushChange(ICommand command) { + LOGGER.info("Pushing " + command.getClass().getSimpleName() + " to stack."); + undo.setEnabled(true); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(true); + redo.setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + } + + /** Called when the history is cleared */ + @Override + public void onClearHistory() { + // undo.setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // redo.setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + } + + /** + * Called when an action is redone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + @Override + public void onRedo(boolean isBottom, boolean isTop) { + undo.setEnabled(!isBottom); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); + redo.setEnabled(!isTop); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); + if (isBottom) { + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } else { + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); } - - /** - * Submits the proof file - */ - private void submit() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - Board board = facade.getBoard(); - boolean delayStatus = true; //board.evalDelayStatus(); - repaintAll(); - - Puzzle pm = facade.getPuzzleModule(); - if (pm.isPuzzleComplete() && delayStatus) { - // 0 means yes, 1 means no (Java's fault...) - int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you wish to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); - if (confirm == 0) { - Submission submission = new Submission(board); - submission.submit(); - } - } - else { - JOptionPane.showConfirmDialog(null, "Your proof is incorrect! Are you sure you wish to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); - Submission submit = new Submission(board); - } + } + + /** + * Called when an action is undone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + @Override + public void onUndo(boolean isBottom, boolean isTop) { + undo.setEnabled(!isBottom); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); + redo.setEnabled(!isTop); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + if (isBottom) { + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } else { + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); } - - public void showStatus(String status, boolean error, int timer) { - // TODO: implement + } + + /** Submits the proof file */ + private void submit() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + Board board = facade.getBoard(); + boolean delayStatus = true; // board.evalDelayStatus(); + repaintAll(); + + Puzzle pm = facade.getPuzzleModule(); + if (pm.isPuzzleComplete() && delayStatus) { + // 0 means yes, 1 means no (Java's fault...) + int confirm = + JOptionPane.showConfirmDialog( + null, + "Are you sure you wish to submit?", + "Proof Submission", + JOptionPane.YES_NO_OPTION); + if (confirm == 0) { + Submission submission = new Submission(board); + submission.submit(); + } + } else { + JOptionPane.showConfirmDialog( + null, + "Your proof is incorrect! Are you sure you wish to submit?", + "Proof Submission", + JOptionPane.YES_NO_OPTION); + Submission submit = new Submission(board); } + } - protected void fitTreeViewToScreen() { - this.treePanel.getTreeView().zoomFit(); - } + public void showStatus(String status, boolean error, int timer) { + // TODO: implement + } + + protected void fitTreeViewToScreen() { + this.treePanel.getTreeView().zoomFit(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java b/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java index 2c4f37c85..23b3e728c 100644 --- a/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java +++ b/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java @@ -1,27 +1,19 @@ package edu.rpi.legup.ui; +import static java.lang.System.exit; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.controller.BoardController; import edu.rpi.legup.controller.EditorElementController; -import edu.rpi.legup.controller.ElementController; import edu.rpi.legup.history.ICommand; import edu.rpi.legup.history.IHistoryListener; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.PuzzleExporter; -import edu.rpi.legup.model.gameboard.PuzzleElement; -import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.save.ExportFileException; import edu.rpi.legup.save.InvalidFileFormatException; import edu.rpi.legup.ui.boardview.BoardView; import edu.rpi.legup.ui.puzzleeditorui.elementsview.ElementFrame; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import javax.swing.*; -import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -30,524 +22,539 @@ import java.io.IOException; import java.net.URI; import java.net.URL; -import java.util.List; import java.util.Objects; - -import static java.lang.System.exit; +import javax.swing.*; +import javax.swing.border.TitledBorder; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class PuzzleEditorPanel extends LegupPanel implements IHistoryListener { - private final static Logger LOGGER = LogManager.getLogger(PuzzleEditorPanel.class.getName()); - private JMenu[] menus; - private JMenuItem helpLegup, aboutLegup; - private JMenuBar menuBar; - private JToolBar toolBar; - private JFrame frame; - private JButton[] buttons; + private static final Logger LOGGER = LogManager.getLogger(PuzzleEditorPanel.class.getName()); + private JMenu[] menus; + private JMenuItem helpLegup, aboutLegup; + private JMenuBar menuBar; + private JToolBar toolBar; + private JFrame frame; + private JButton[] buttons; + JSplitPane splitPanel; + private JButton[] toolBarButtons; + private JPanel elementPanel; + private DynamicView dynamicBoardView; + private BoardView boardView; + private TitledBorder boardBorder; + // private JSplitPane splitPanel, topHalfPanel; + private FileDialog fileDialog; + private JMenuItem undo, redo, fitBoardToScreen; + private ElementFrame elementFrame; + private JPanel treePanel; + private LegupUI legupUI; + private EditorElementController editorElementController; + static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; + + public PuzzleEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.fileDialog = fileDialog; + this.frame = frame; + this.legupUI = legupUI; + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(800, 700)); + } + + protected void setupContent() { JSplitPane splitPanel; - private JButton[] toolBarButtons; - private JPanel elementPanel; - private DynamicView dynamicBoardView; - private BoardView boardView; - private TitledBorder boardBorder; - //private JSplitPane splitPanel, topHalfPanel; - private FileDialog fileDialog; - private JMenuItem undo, redo, fitBoardToScreen; - private ElementFrame elementFrame; - private JPanel treePanel; - private LegupUI legupUI; - private EditorElementController editorElementController; - final static int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; - - public PuzzleEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.fileDialog = fileDialog; - this.frame = frame; - this.legupUI = legupUI; - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(800, 700)); + JPanel elementBox = new JPanel(new BorderLayout()); + + editorElementController = new EditorElementController(); + elementFrame = new ElementFrame(editorElementController); + elementBox.add(elementFrame, BorderLayout.WEST); + + dynamicBoardView = + new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); + TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + JPanel boardPanel = new JPanel(new BorderLayout()); + splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, elementFrame, dynamicBoardView); + splitPanel.setPreferredSize(new Dimension(600, 400)); + + boardPanel.add(splitPanel); + boardBorder = BorderFactory.createTitledBorder("Board"); + boardBorder.setTitleJustification(TitledBorder.CENTER); + + elementBox.add(boardPanel); + this.add(elementBox); + + splitPanel.setDividerLocation(splitPanel.getMaximumDividerLocation() + 100); + this.splitPanel = splitPanel; + revalidate(); + } + + public void setMenuBar() { + String os = LegupUI.getOS(); + menuBar = new JMenuBar(); + menus = new JMenu[3]; + + // create menus + + // FILE + menus[0] = new JMenu("File"); + + // file>new + JMenuItem newPuzzle = new JMenuItem("New"); + newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); } - - protected void setupContent() { - JSplitPane splitPanel; - JPanel elementBox = new JPanel(new BorderLayout()); - - editorElementController = new EditorElementController(); - elementFrame = new ElementFrame(editorElementController); - elementBox.add(elementFrame, BorderLayout.WEST); - - dynamicBoardView = new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); - TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - JPanel boardPanel = new JPanel(new BorderLayout()); - splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, elementFrame, dynamicBoardView); - splitPanel.setPreferredSize(new Dimension(600, 400)); - - boardPanel.add(splitPanel); - boardBorder = BorderFactory.createTitledBorder("Board"); - boardBorder.setTitleJustification(TitledBorder.CENTER); - - elementBox.add(boardPanel); - this.add(elementBox); - - splitPanel.setDividerLocation(splitPanel.getMaximumDividerLocation() + 100); - this.splitPanel = splitPanel; - revalidate(); + // file>save + JMenuItem savePuzzle = new JMenuItem("Save As"); + savePuzzle.addActionListener((ActionEvent) -> savePuzzle()); + JMenuItem directSavePuzzle = new JMenuItem("Direct Save Proof "); + directSavePuzzle.addActionListener((ActionEvent) -> direct_save()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); } - public void setMenuBar() { - String os = LegupUI.getOS(); - menuBar = new JMenuBar(); - menus = new JMenu[3]; - - // create menus - - // FILE - menus[0] = new JMenu("File"); - - // file>new - JMenuItem newPuzzle = new JMenuItem("New"); - newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); - if (os.equals("mac")) { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); - } - // file>save - JMenuItem savePuzzle = new JMenuItem("Save As"); - savePuzzle.addActionListener((ActionEvent) -> savePuzzle()); - JMenuItem directSavePuzzle = new JMenuItem("Direct Save Proof "); - directSavePuzzle.addActionListener((ActionEvent) -> direct_save()); - if (os.equals("mac")) { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); - } - - JMenuItem exit = new JMenuItem("Exit"); - exit.addActionListener((ActionEvent) -> exitEditor()); - if (os.equals("mac")) { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); - } - menus[0].add(newPuzzle); - menus[0].add(savePuzzle); - menus[0].add(directSavePuzzle); - menus[0].add(exit); - - // EDIT - menus[1] = new JMenu("Edit"); - // edit>undo - undo = new JMenuItem("Undo"); - // edit>redo - redo = new JMenuItem("Redo"); - fitBoardToScreen = new JMenuItem("Fit Board to Screen"); - - menus[1].add(undo); - undo.addActionListener((ActionEvent) -> - GameBoardFacade.getInstance().getHistory().undo()); - if (os.equals("mac")) { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } - else { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); - } + JMenuItem exit = new JMenuItem("Exit"); + exit.addActionListener((ActionEvent) -> exitEditor()); + if (os.equals("mac")) { + exit.setAccelerator( + KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); + } + menus[0].add(newPuzzle); + menus[0].add(savePuzzle); + menus[0].add(directSavePuzzle); + menus[0].add(exit); + + // EDIT + menus[1] = new JMenu("Edit"); + // edit>undo + undo = new JMenuItem("Undo"); + // edit>redo + redo = new JMenuItem("Redo"); + fitBoardToScreen = new JMenuItem("Fit Board to Screen"); + + menus[1].add(undo); + undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); + if (os.equals("mac")) { + undo.setAccelerator( + KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + } - menus[1].add(redo); + menus[1].add(redo); - // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) - Action redoAction = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - GameBoardFacade.getInstance().getHistory().redo(); - } + // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) + Action redoAction = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + GameBoardFacade.getInstance().getHistory().redo(); + } }; - if (os.equals("mac")) { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW).put( - KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW).put( - KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "redoAction"); - redo.setAccelerator(KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); - } - else { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getActionMap().put("redoAction", redoAction); - - // Button in menu will show CTRL-SHIFT-Z as primary keybind - redo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); - } - + if (os.equals("mac")) { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK), + "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "redoAction"); + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); + } else { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), + "redoAction"); + redo.getActionMap().put("redoAction", redoAction); + + // Button in menu will show CTRL-SHIFT-Z as primary keybind + redo.setAccelerator( + KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + } - menus[1].add(fitBoardToScreen); - fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); - - // HELP - menus[2] = new JMenu("Help"); - helpLegup = new JMenuItem("Help Legup"); - aboutLegup = new JMenuItem("About Legup"); - menus[2].add(helpLegup); - menus[2].add(aboutLegup); - helpLegup.addActionListener(l -> { - try { - java.awt.Desktop.getDesktop().browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); - } - catch (IOException e) { - LOGGER.error("Can't open web page"); - } + menus[1].add(fitBoardToScreen); + fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); + + // HELP + menus[2] = new JMenu("Help"); + helpLegup = new JMenuItem("Help Legup"); + aboutLegup = new JMenuItem("About Legup"); + menus[2].add(helpLegup); + menus[2].add(aboutLegup); + helpLegup.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } }); - menus[2].add(aboutLegup); - aboutLegup.addActionListener(l -> { - JOptionPane.showMessageDialog(null, "Version: 5.1.0"); + menus[2].add(aboutLegup); + aboutLegup.addActionListener( + l -> { + JOptionPane.showMessageDialog(null, "Version: 5.1.0"); }); - // add menus to menubar - for (JMenu menu : menus) { - menuBar.add(menu); - } - frame.setJMenuBar(menuBar); + // add menus to menubar + for (JMenu menu : menus) { + menuBar.add(menu); } - - public void exitEditor() { - // Wipes the puzzle entirely as if LEGUP just started - GameBoardFacade.getInstance().clearPuzzle(); - this.legupUI.displayPanel(0); - treePanel = null; - boardView = null; - } - - @Override - public void makeVisible() { - this.removeAll(); - - setupToolBar(); - setupContent(); - setMenuBar(); + frame.setJMenuBar(menuBar); + } + + public void exitEditor() { + // Wipes the puzzle entirely as if LEGUP just started + GameBoardFacade.getInstance().clearPuzzle(); + this.legupUI.displayPanel(0); + treePanel = null; + boardView = null; + } + + @Override + public void makeVisible() { + this.removeAll(); + + setupToolBar(); + setupContent(); + setMenuBar(); + } + + private void setupToolBar() { + setToolBarButtons(new JButton[ToolbarName.values().length + 1]); + int lastone = 0; + for (int i = 0; i < ToolbarName.values().length - 1; i++) { + String toolBarName = ToolbarName.values()[i].toString(); + URL resourceLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); + + // Scale the image icons down to make the buttons smaller + ImageIcon imageIcon = new ImageIcon(resourceLocation); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); + + JButton button = new JButton(toolBarName, imageIcon); + button.setFocusPainted(false); + getToolBarButtons()[i] = button; + lastone = i; } - private void setupToolBar() { - setToolBarButtons(new JButton[ToolbarName.values().length + 1]); - int lastone = 0; - for (int i = 0; i < ToolbarName.values().length - 1; i++) { - String toolBarName = ToolbarName.values()[i].toString(); - URL resourceLocation = ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); - - // Scale the image icons down to make the buttons smaller - ImageIcon imageIcon = new ImageIcon(resourceLocation); - Image image = imageIcon.getImage(); - imageIcon = new ImageIcon(image.getScaledInstance(this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton button = new JButton(toolBarName, imageIcon); - button.setFocusPainted(false); - getToolBarButtons()[i] = button; - lastone = i; - } - - - URL check_and_save = ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Check.png"); - ImageIcon imageIcon = new ImageIcon(check_and_save); - Image image = imageIcon.getImage(); - imageIcon = new ImageIcon(image.getScaledInstance(this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton checkandsave = new JButton("check and Save", imageIcon); - checkandsave.setFocusPainted(false); - checkandsave.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - //savePuzzle(); - String filename = savePuzzle(); - File puzzlename = new File(filename); - System.out.println(filename); - - - GameBoardFacade.getInstance().getLegupUI().displayPanel(1); - GameBoardFacade.getInstance().getLegupUI().getProofEditor().loadPuzzle(filename, new File(filename)); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzlename.getName()); - } + URL check_and_save = + ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Check.png"); + ImageIcon imageIcon = new ImageIcon(check_and_save); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); + + JButton checkandsave = new JButton("check and Save", imageIcon); + checkandsave.setFocusPainted(false); + checkandsave.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // savePuzzle(); + String filename = savePuzzle(); + File puzzlename = new File(filename); + System.out.println(filename); + + GameBoardFacade.getInstance().getLegupUI().displayPanel(1); + GameBoardFacade.getInstance() + .getLegupUI() + .getProofEditor() + .loadPuzzle(filename, new File(filename)); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzlename.getName()); + } }); - getToolBarButtons()[lastone + 1] = checkandsave; - System.out.println("it is create new file"); - - - toolBar = new JToolBar(); - toolBar.setFloatable(false); - toolBar.setRollover(true); - - for (int i = 0; i < getToolBarButtons().length - 1; i++) { - for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { - if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { - toolBar.addSeparator(); - } - } - String toolBarName = ToolbarName.values()[i].toString(); + getToolBarButtons()[lastone + 1] = checkandsave; + System.out.println("it is create new file"); - toolBar.add(getToolBarButtons()[i]); - getToolBarButtons()[i].setToolTipText(toolBarName); + toolBar = new JToolBar(); + toolBar.setFloatable(false); + toolBar.setRollover(true); - getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); - getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); + for (int i = 0; i < getToolBarButtons().length - 1; i++) { + for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { + if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { + toolBar.addSeparator(); } + } + String toolBarName = ToolbarName.values()[i].toString(); -// toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent e) -> promptPuzzle()); -// toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> saveProof()); -// toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> GameBoardFacade.getInstance().getHistory().undo()); -// toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> GameBoardFacade.getInstance().getHistory().redo()); - toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> { - }); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> { - }); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> { - }); - -// toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); -// toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); -// toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + toolBar.add(getToolBarButtons()[i]); + getToolBarButtons()[i].setToolTipText(toolBarName); - this.add(toolBar, BorderLayout.NORTH); + getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); + getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); } - public void loadPuzzleFromHome(String game, int rows, int columns) throws IllegalArgumentException { - GameBoardFacade facade = GameBoardFacade.getInstance(); - try { - facade.loadPuzzle(game, rows, columns); - } - catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } - catch (RuntimeException e) { - e.printStackTrace(); - LOGGER.error(e.getMessage()); - } + // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent e) -> + // promptPuzzle()); + // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> + // saveProof()); + // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().undo()); + // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().redo()); + toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); + + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + + this.add(toolBar, BorderLayout.NORTH); + } + + public void loadPuzzleFromHome(String game, int rows, int columns) + throws IllegalArgumentException { + GameBoardFacade facade = GameBoardFacade.getInstance(); + try { + facade.loadPuzzle(game, rows, columns); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (RuntimeException e) { + e.printStackTrace(); + LOGGER.error(e.getMessage()); } - - public void loadPuzzleFromHome(String game, String[] statements) { - GameBoardFacade facade = GameBoardFacade.getInstance(); - try { - facade.loadPuzzle(game, statements); - } - catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } - catch (RuntimeException e) { - e.printStackTrace(); - LOGGER.error(e.getMessage()); - } - } - - // File opener - public Object[] promptPuzzle() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - if (facade.getBoard() != null) { - if (noQuit("Opening a new puzzle to edit?")) { - return new Object[0]; - } - } - if (fileDialog == null) { - fileDialog = new FileDialog(this.frame); - } - LegupPreferences preferences = LegupPreferences.getInstance(); - String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); - - fileDialog.setMode(FileDialog.LOAD); - fileDialog.setTitle("Select Puzzle"); - fileDialog.setDirectory(preferredDirectory); - fileDialog.setVisible(true); - String fileName = null; - File puzzleFile = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - puzzleFile = new File(fileName); - } - else { - // The attempt to prompt a puzzle ended gracefully (cancel) - return null; - } - - return new Object[]{fileName, puzzleFile}; + } + + public void loadPuzzleFromHome(String game, String[] statements) { + GameBoardFacade facade = GameBoardFacade.getInstance(); + try { + facade.loadPuzzle(game, statements); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (RuntimeException e) { + e.printStackTrace(); + LOGGER.error(e.getMessage()); } - - public void loadPuzzle() { - Object[] items = promptPuzzle(); - // Return if items == null (cancel) - if (items == null) { - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - loadPuzzle(fileName, puzzleFile); + } + + // File opener + public Object[] promptPuzzle() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + if (facade.getBoard() != null) { + if (noQuit("Opening a new puzzle to edit?")) { + return new Object[0]; + } } - - public void loadPuzzle(String fileName, File puzzleFile) { - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(2); - GameBoardFacade.getInstance().loadPuzzleEditor(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } - catch (InvalidFileFormatException e) { - legupUI.displayPanel(0); - LOGGER.error(e.getMessage()); - JOptionPane.showMessageDialog(null, "File does not exist, cannot be read, or cannot be edited", "Error", JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } - } + if (fileDialog == null) { + fileDialog = new FileDialog(this.frame); } - - public boolean noQuit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; + LegupPreferences preferences = LegupPreferences.getInstance(); + String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); + + fileDialog.setMode(FileDialog.LOAD); + fileDialog.setTitle("Select Puzzle"); + fileDialog.setDirectory(preferredDirectory); + fileDialog.setVisible(true); + String fileName = null; + File puzzleFile = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + puzzleFile = new File(fileName); + } else { + // The attempt to prompt a puzzle ended gracefully (cancel) + return null; } - @Override - public void onPushChange(ICommand command) { + return new Object[] {fileName, puzzleFile}; + } + public void loadPuzzle() { + Object[] items = promptPuzzle(); + // Return if items == null (cancel) + if (items == null) { + return; } - - @Override - public void onUndo(boolean isBottom, boolean isTop) { - + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + loadPuzzle(fileName, puzzleFile); + } + + public void loadPuzzle(String fileName, File puzzleFile) { + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(2); + GameBoardFacade.getInstance().loadPuzzleEditor(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } catch (InvalidFileFormatException e) { + legupUI.displayPanel(0); + LOGGER.error(e.getMessage()); + JOptionPane.showMessageDialog( + null, + "File does not exist, cannot be read, or cannot be edited", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } } - - @Override - public void onRedo(boolean isBottom, boolean isTop) { - + } + + public boolean noQuit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + @Override + public void onPushChange(ICommand command) {} + + @Override + public void onUndo(boolean isBottom, boolean isTop) {} + + @Override + public void onRedo(boolean isBottom, boolean isTop) {} + + @Override + public void onClearHistory() { + // undo.setEnabled(false); + // redo.setEnabled(false); + } + + public BoardView getBoardView() { + return boardView; + } + + public JButton[] getToolBarButtons() { + return toolBarButtons; + } + + public void setToolBarButtons(JButton[] toolBarButtons) { + this.toolBarButtons = toolBarButtons; + } + + private void repaintAll() { + boardView.repaint(); + } + + public void setPuzzleView(Puzzle puzzle) { + this.boardView = puzzle.getBoardView(); + editorElementController.setElementController(boardView.getElementController()); + dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); + if (this.splitPanel != null) { + this.splitPanel.setRightComponent(dynamicBoardView); + this.splitPanel.setVisible(true); } - @Override - public void onClearHistory() { - //undo.setEnabled(false); - //redo.setEnabled(false); - } + TitledBorder titleBoard = + BorderFactory.createTitledBorder(boardView.getClass().getSimpleName()); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); - public BoardView getBoardView() { - return boardView; + puzzle.addBoardListener(puzzle.getBoardView()); + System.out.println("Setting elements"); + if (this.elementFrame != null) { + elementFrame.setElements(puzzle); } - public JButton[] getToolBarButtons() { - return toolBarButtons; - } + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); + } - public void setToolBarButtons(JButton[] toolBarButtons) { - this.toolBarButtons = toolBarButtons; + /** Saves a puzzle */ + private void direct_save() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - - private void repaintAll() { - boardView.repaint(); + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } } + } - public void setPuzzleView(Puzzle puzzle) { - this.boardView = puzzle.getBoardView(); - editorElementController.setElementController(boardView.getElementController()); - dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); - if (this.splitPanel != null) { - this.splitPanel.setRightComponent(dynamicBoardView); - this.splitPanel.setVisible(true); - } - - TitledBorder titleBoard = BorderFactory.createTitledBorder(boardView.getClass().getSimpleName()); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - puzzle.addBoardListener(puzzle.getBoardView()); - System.out.println("Setting elements"); - if (this.elementFrame != null) { - elementFrame.setElements(puzzle); - } - - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); -// toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); + private String savePuzzle() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return ""; } - /** - * Saves a puzzle - */ - - private void direct_save() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - } - catch (ExportFileException e) { - e.printStackTrace(); - } + // for TreeTent, need to check validity before saving + if (Objects.equals(puzzle.getName(), "TreeTent")) { + if (!puzzle.checkValidity()) { + int input = + JOptionPane.showConfirmDialog( + null, "The puzzle you edited is not " + "valid, would you still like to save? "); + if (input != 0) { + return ""; } + } } - private String savePuzzle() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return ""; - } - - // for TreeTent, need to check validity before saving - if (Objects.equals(puzzle.getName(), "TreeTent")) { - if (!puzzle.checkValidity()) { - int input = JOptionPane.showConfirmDialog(null, "The puzzle you edited is not " + - "valid, would you still like to save? "); - if (input != 0) { - return ""; - } - } - } - - if (fileDialog == null) { - fileDialog = new FileDialog(this.frame); - } - - fileDialog.setMode(FileDialog.SAVE); - fileDialog.setTitle("Save Proof"); - String curFileName = GameBoardFacade.getInstance().getCurFileName(); - if (curFileName == null) { - fileDialog.setDirectory(LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); - } - else { - File curFile = new File(curFileName); - fileDialog.setDirectory(curFile.getParent()); - } - fileDialog.setVisible(true); - - String fileName = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - } - - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - } - catch (ExportFileException e) { - e.printStackTrace(); - } - } - return fileName; + if (fileDialog == null) { + fileDialog = new FileDialog(this.frame); } + fileDialog.setMode(FileDialog.SAVE); + fileDialog.setTitle("Save Proof"); + String curFileName = GameBoardFacade.getInstance().getCurFileName(); + if (curFileName == null) { + fileDialog.setDirectory( + LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); + } else { + File curFile = new File(curFileName); + fileDialog.setDirectory(curFile.getParent()); + } + fileDialog.setVisible(true); - public DynamicView getDynamicBoardView() { - return dynamicBoardView; + String fileName = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); } + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } + return fileName; + } + public DynamicView getDynamicBoardView() { + return dynamicBoardView; + } } diff --git a/src/main/java/edu/rpi/legup/ui/ScrollView.java b/src/main/java/edu/rpi/legup/ui/ScrollView.java index 8f9144fda..5d072ebf5 100644 --- a/src/main/java/edu/rpi/legup/ui/ScrollView.java +++ b/src/main/java/edu/rpi/legup/ui/ScrollView.java @@ -1,324 +1,313 @@ package edu.rpi.legup.ui; import edu.rpi.legup.controller.Controller; - import java.awt.*; -import java.lang.Double; - import java.util.TreeSet; import java.util.logging.Logger; - import javax.swing.*; public class ScrollView extends JScrollPane { - private final static Logger LOGGER = Logger.getLogger(ScrollView.class.getName()); - - private static final double minScale = 0.25; - private static final double maxScale = 4.0; - private static final double[] levels = {0.25, 1.0 / 3.0, 0.50, 2.0 / 3.0, 1.0, 2.0, 3.0, 4.0}; - - private Dimension viewSize; - private Dimension zoomSize; - private TreeSet zoomLevels; + private static final Logger LOGGER = Logger.getLogger(ScrollView.class.getName()); - private double scale; + private static final double minScale = 0.25; + private static final double maxScale = 4.0; + private static final double[] levels = {0.25, 1.0 / 3.0, 0.50, 2.0 / 3.0, 1.0, 2.0, 3.0, 4.0}; - private Controller controller; - private ZoomablePane canvas; - private ZoomWidget widget; + private Dimension viewSize; + private Dimension zoomSize; + private TreeSet zoomLevels; - /** - * ScrollView Constructor - creates a ScrollView object using - * the controller handle the ui events - * - * @param controller controller that handles the ui events - */ - public ScrollView(Controller controller) { - super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS); + private double scale; - viewSize = new Dimension(); - zoomSize = new Dimension(); - scale = 1.0; + private Controller controller; + private ZoomablePane canvas; + private ZoomWidget widget; - this.canvas = new ZoomablePane(this); + /** + * ScrollView Constructor - creates a ScrollView object using the controller handle the ui events + * + * @param controller controller that handles the ui events + */ + public ScrollView(Controller controller) { + super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS); - viewport.setView(canvas); + viewSize = new Dimension(); + zoomSize = new Dimension(); + scale = 1.0; - zoomLevels = new TreeSet<>(); - for (Double level : levels) { - zoomLevels.add(level); - } + this.canvas = new ZoomablePane(this); - widget = new ZoomWidget(this); - setCorner(JScrollPane.LOWER_RIGHT_CORNER, widget); + viewport.setView(canvas); - setWheelScrollingEnabled(false); - - this.controller = controller; - controller.setViewer(this); - canvas.addMouseMotionListener(controller); - canvas.addMouseListener(controller); - viewport.addMouseWheelListener(controller); - viewport.addMouseListener(controller); - viewport.addMouseMotionListener(controller); + zoomLevels = new TreeSet<>(); + for (Double level : levels) { + zoomLevels.add(level); } - /** - * Creates a customized viewport for the scroll pane - * - * @return viewport for the scroll pane - */ - @Override - protected JViewport createViewport() { - return new JViewport() { - @Override - protected LayoutManager createLayoutManager() { - return new ViewportLayout() { - @Override - public void layoutContainer(Container parent) { - Point point = viewport.getViewPosition(); - // determine the maximum x and y view positions - int mx = canvas.getWidth() - viewport.getWidth(); - int my = canvas.getHeight() - viewport.getHeight(); - // obey edge boundaries - if (point.x < 0) { - point.x = 0; - } - if (point.x > mx) { - point.x = mx; - } - if (point.y < 0) { - point.y = 0; - } - if (point.y > my) { - point.y = my; - } - // center margins - if (mx < 0) { - point.x = mx / 2; - } - if (my < 0) { - point.y = my / 2; - } - viewport.setViewPosition(point); - } - }; + widget = new ZoomWidget(this); + setCorner(JScrollPane.LOWER_RIGHT_CORNER, widget); + + setWheelScrollingEnabled(false); + + this.controller = controller; + controller.setViewer(this); + canvas.addMouseMotionListener(controller); + canvas.addMouseListener(controller); + viewport.addMouseWheelListener(controller); + viewport.addMouseListener(controller); + viewport.addMouseMotionListener(controller); + } + + /** + * Creates a customized viewport for the scroll pane + * + * @return viewport for the scroll pane + */ + @Override + protected JViewport createViewport() { + return new JViewport() { + @Override + protected LayoutManager createLayoutManager() { + return new ViewportLayout() { + @Override + public void layoutContainer(Container parent) { + Point point = viewport.getViewPosition(); + // determine the maximum x and y view positions + int mx = canvas.getWidth() - viewport.getWidth(); + int my = canvas.getHeight() - viewport.getHeight(); + // obey edge boundaries + if (point.x < 0) { + point.x = 0; } - }; - } - - /** - * Updates zoomSize and view viewSize with the new scale - */ - private void updateSize() { - zoomSize.setSize((int) (viewSize.width * scale), (int) (viewSize.height * scale)); - viewport.setViewSize(zoomSize); - } - - /** - * Updates the viewport position - * - * @param point point to set the viewport to - * @param magnification magnification to set the viewport to - */ - public void updatePosition(Point point, double magnification) { - Point position = viewport.getViewPosition(); - position.x = (int) ((double) (point.x + position.x) * magnification - point.x + 0.0); - position.y = (int) ((double) (point.y + position.y) * magnification - point.y + 0.0); - viewport.setViewPosition(position); - } - - /** - * Zooms in or out on a position within the dynamicView - * - * @param n level of zoom - n less than 0 is zoom in, n greater than 0 is zoom out - * @param point position to zoom in on - */ - public void zoom(int n, Point point) { - // if no Point is given, keep current center - if (point == null) { - point = new Point(viewport.getWidth() / 2 + viewport.getX(), viewport.getHeight() / 2 + viewport.getY()); - } - // magnification level - double mag = (double) n * 1.05; - // zoom in - if (n < 0) { - mag = -mag; - // check zoom bounds - if (scale * mag > maxScale) { - mag = maxScale / scale; + if (point.x > mx) { + point.x = mx; } - // update - scale *= mag; - updateSize(); - updatePosition(point, mag); - // zoom out - } - else { - mag = 1 / mag; - // check zoom bounds - if (scale * mag < minScale) { - mag = minScale / scale; + if (point.y < 0) { + point.y = 0; } - // update - scale *= mag; - updatePosition(point, mag); - updateSize(); - } - // update the scrollpane and subclass - revalidate(); - } - - public void zoomTo(double newScale) { - // check zoom bounds - if (newScale < minScale) { - newScale = minScale; - } - if (newScale > maxScale) { - newScale = maxScale; - } - if (newScale == scale) { - return; - } - // calculate the newScale and center point - double mag = newScale / scale; - Point p = new Point(viewport.getWidth() / 2 + viewport.getX(), - viewport.getHeight() / 2 + viewport.getY()); - - // set scale directly - scale = newScale; - // zoom in - if (mag > 1.0) { - updateSize(); - updatePosition(p, mag); - // zoom out - } - else { - updatePosition(p, mag); - updateSize(); - } - // update the scrollpane and subclass - revalidate(); - } - - /** - * Get the ideal zoom based on the viewSize - */ - public void zoomFit() { - if (viewport.getWidth() != 0 && viewport.getHeight() != 0) { - double fitWidth = (viewport.getWidth() - 8.0) / viewSize.width; - double fitHeight = (viewport.getHeight() - 8.0) / viewSize.height; - - zoomTo(Math.min(fitWidth, fitHeight)); - } + if (point.y > my) { + point.y = my; + } + // center margins + if (mx < 0) { + point.x = mx / 2; + } + if (my < 0) { + point.y = my / 2; + } + viewport.setViewPosition(point); + } + }; + } + }; + } + + /** Updates zoomSize and view viewSize with the new scale */ + private void updateSize() { + zoomSize.setSize((int) (viewSize.width * scale), (int) (viewSize.height * scale)); + viewport.setViewSize(zoomSize); + } + + /** + * Updates the viewport position + * + * @param point point to set the viewport to + * @param magnification magnification to set the viewport to + */ + public void updatePosition(Point point, double magnification) { + Point position = viewport.getViewPosition(); + position.x = (int) ((double) (point.x + position.x) * magnification - point.x + 0.0); + position.y = (int) ((double) (point.y + position.y) * magnification - point.y + 0.0); + viewport.setViewPosition(position); + } + + /** + * Zooms in or out on a position within the dynamicView + * + * @param n level of zoom - n less than 0 is zoom in, n greater than 0 is zoom out + * @param point position to zoom in on + */ + public void zoom(int n, Point point) { + // if no Point is given, keep current center + if (point == null) { + point = + new Point( + viewport.getWidth() / 2 + viewport.getX(), + viewport.getHeight() / 2 + viewport.getY()); } - - /** - * Zooms in to the next zoom level - */ - public void zoomIn() { - // find the next valid zoom level - Double newScale = zoomLevels.higher(scale); - if (newScale != null) { - zoomTo(newScale); - } + // magnification level + double mag = (double) n * 1.05; + // zoom in + if (n < 0) { + mag = -mag; + // check zoom bounds + if (scale * mag > maxScale) { + mag = maxScale / scale; + } + // update + scale *= mag; + updateSize(); + updatePosition(point, mag); + // zoom out + } else { + mag = 1 / mag; + // check zoom bounds + if (scale * mag < minScale) { + mag = minScale / scale; + } + // update + scale *= mag; + updatePosition(point, mag); + updateSize(); } - - /** - * Zooms out to the previous zoom level - */ - public void zoomOut() { - // find the next valid zoom level - Double newScale = zoomLevels.lower(scale); - if (newScale != null) { - zoomTo(newScale); - } + // update the scrollpane and subclass + revalidate(); + } + + public void zoomTo(double newScale) { + // check zoom bounds + if (newScale < minScale) { + newScale = minScale; } - - /** - * Converts canvas coordinates to draw coordinates - * - * @param point canvas coordinate - * @return draw coordinate as Point - */ - public Point getActualPoint(Point point) { - return new Point((int) (point.x / scale), (int) (point.y / scale)); + if (newScale > maxScale) { + newScale = maxScale; } - - /** - * Gets the zoom amount - * - * @return zoom scale - */ - public int getZoom() { - return (int) (scale * 100.0); + if (newScale == scale) { + return; } - - /** - * Gets the scale for the dynamic dynamicView - * - * @return scale of the dynamic dynamicView - */ - public double getScale() { - return scale; - } - - /** - * Sets the background of the viewport - * - * @param c color of the background - */ - public void setBackground(Color c) { - viewport.setBackground(c); - } - - /** - * Gets the dimension of the viewport - * - * @return dimension of the viewport - */ - public Dimension getSize() { - return viewSize; + // calculate the newScale and center point + double mag = newScale / scale; + Point p = + new Point( + viewport.getWidth() / 2 + viewport.getX(), viewport.getHeight() / 2 + viewport.getY()); + + // set scale directly + scale = newScale; + // zoom in + if (mag > 1.0) { + updateSize(); + updatePosition(p, mag); + // zoom out + } else { + updatePosition(p, mag); + updateSize(); } + // update the scrollpane and subclass + revalidate(); + } - /** - * Sets the dimension of the viewport - * - * @param size new dimension of the viewport - */ - public void setSize(Dimension size) { - this.viewSize = size; - updateSize(); - } + /** Get the ideal zoom based on the viewSize */ + public void zoomFit() { + if (viewport.getWidth() != 0 && viewport.getHeight() != 0) { + double fitWidth = (viewport.getWidth() - 8.0) / viewSize.width; + double fitHeight = (viewport.getHeight() - 8.0) / viewSize.height; - public ZoomablePane getCanvas() { - return canvas; + zoomTo(Math.min(fitWidth, fitHeight)); } - - /** - * Draws the ScrollView - * - * @param graphics2D Graphics2D object used for drawing - */ - protected void draw(Graphics2D graphics2D) { - graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); - canvas.paint(graphics2D); + } + + /** Zooms in to the next zoom level */ + public void zoomIn() { + // find the next valid zoom level + Double newScale = zoomLevels.higher(scale); + if (newScale != null) { + zoomTo(newScale); } - - /** - * Scroll up or down on the ScrollView - * - * @param mag The magnitude for scroll up - * positive is scroll up, negative is scroll down, - * recommend to use getWheelRotation() as the mag - */ - public void scroll(int mag) { - Point point = super.viewport.getViewPosition(); - // the point changing speed changes with the scale - point.y += mag * getZoom() / 20; - viewport.setViewPosition(point); - updateSize(); - revalidate(); + } + + /** Zooms out to the previous zoom level */ + public void zoomOut() { + // find the next valid zoom level + Double newScale = zoomLevels.lower(scale); + if (newScale != null) { + zoomTo(newScale); } + } + + /** + * Converts canvas coordinates to draw coordinates + * + * @param point canvas coordinate + * @return draw coordinate as Point + */ + public Point getActualPoint(Point point) { + return new Point((int) (point.x / scale), (int) (point.y / scale)); + } + + /** + * Gets the zoom amount + * + * @return zoom scale + */ + public int getZoom() { + return (int) (scale * 100.0); + } + + /** + * Gets the scale for the dynamic dynamicView + * + * @return scale of the dynamic dynamicView + */ + public double getScale() { + return scale; + } + + /** + * Sets the background of the viewport + * + * @param c color of the background + */ + public void setBackground(Color c) { + viewport.setBackground(c); + } + + /** + * Gets the dimension of the viewport + * + * @return dimension of the viewport + */ + public Dimension getSize() { + return viewSize; + } + + /** + * Sets the dimension of the viewport + * + * @param size new dimension of the viewport + */ + public void setSize(Dimension size) { + this.viewSize = size; + updateSize(); + } + + public ZoomablePane getCanvas() { + return canvas; + } + + /** + * Draws the ScrollView + * + * @param graphics2D Graphics2D object used for drawing + */ + protected void draw(Graphics2D graphics2D) { + graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics2D.setRenderingHint( + RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + canvas.paint(graphics2D); + } + + /** + * Scroll up or down on the ScrollView + * + * @param mag The magnitude for scroll up positive is scroll up, negative is scroll down, + * recommend to use getWheelRotation() as the mag + */ + public void scroll(int mag) { + Point point = super.viewport.getViewPosition(); + // the point changing speed changes with the scale + point.y += mag * getZoom() / 20; + viewport.setViewPosition(point); + updateSize(); + revalidate(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ToolbarName.java b/src/main/java/edu/rpi/legup/ui/ToolbarName.java index 3df635b05..1e0cbe7fb 100644 --- a/src/main/java/edu/rpi/legup/ui/ToolbarName.java +++ b/src/main/java/edu/rpi/legup/ui/ToolbarName.java @@ -1,26 +1,30 @@ package edu.rpi.legup.ui; public enum ToolbarName { - HINT, CHECK, SUBMIT, DIRECTIONS, CHECK_ALL; + HINT, + CHECK, + SUBMIT, + DIRECTIONS, + CHECK_ALL; - /** - * Gets the String representation of the ToolbarName enum - * - * @return String representing the enum - */ - public String toString() { - String str = super.toString(); - str = str.replace("_", " "); - str = str.toLowerCase(); - str = str.substring(0, 1).toUpperCase() + str.substring(1); - for (int i = 0; i < str.length(); i++) { - if (str.charAt(i) == ' ') { - str = str.substring(0, i + 1) + - str.substring(i + 1, i + 2).toUpperCase() + - str.substring(i + 2); - } - } - return str; + /** + * Gets the String representation of the ToolbarName enum + * + * @return String representing the enum + */ + public String toString() { + String str = super.toString(); + str = str.replace("_", " "); + str = str.toLowerCase(); + str = str.substring(0, 1).toUpperCase() + str.substring(1); + for (int i = 0; i < str.length(); i++) { + if (str.charAt(i) == ' ') { + str = + str.substring(0, i + 1) + + str.substring(i + 1, i + 2).toUpperCase() + + str.substring(i + 2); + } } - + return str; + } } diff --git a/src/main/java/edu/rpi/legup/ui/WrapLayout.java b/src/main/java/edu/rpi/legup/ui/WrapLayout.java index c37eb02f4..6251d6f70 100644 --- a/src/main/java/edu/rpi/legup/ui/WrapLayout.java +++ b/src/main/java/edu/rpi/legup/ui/WrapLayout.java @@ -1,174 +1,166 @@ package edu.rpi.legup.ui; +import java.awt.*; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; -import java.awt.*; -/** - * FlowLayout subclass that fully supports wrapping of components. - */ +/** FlowLayout subclass that fully supports wrapping of components. */ public class WrapLayout extends FlowLayout { - private Dimension preferredLayoutSize; - - /** - * Constructs a new WrapLayout with a left - * alignment and a default 5-unit horizontal and vertical gap. - */ - public WrapLayout() { - super(LEFT); - } - - /** - * Constructs a new FlowLayout with the specified - * alignment and a default 5-unit horizontal and vertical gap. - * The value of the alignment argument must be one of - * WrapLayout, WrapLayout, - * or WrapLayout. - * - * @param align the alignment value - */ - public WrapLayout(int align) { - super(align); - } - - /** - * Creates a new flow layout manager with the indicated alignment - * and the indicated horizontal and vertical gaps. - *

- * The value of the alignment argument must be one of - * WrapLayout, WrapLayout, - * or WrapLayout. - * - * @param align the alignment value - * @param hgap the horizontal gap between components - * @param vgap the vertical gap between components - */ - public WrapLayout(int align, int hgap, int vgap) { - super(align, hgap, vgap); - } - - /** - * Returns the preferred dimensions for this layout given the - * visible components in the specified target container. - * - * @param target the component which needs to be laid out - * @return the preferred dimensions to lay out the - * subcomponents of the specified container - */ - @Override - public Dimension preferredLayoutSize(Container target) { - return layoutSize(target, true); - } - - /** - * Returns the minimum dimensions needed to layout the visible - * components contained in the specified target container. - * - * @param target the component which needs to be laid out - * @return the minimum dimensions to lay out the - * subcomponents of the specified container - */ - @Override - public Dimension minimumLayoutSize(Container target) { - Dimension minimum = layoutSize(target, false); - minimum.width -= (getHgap() + 1); - return minimum; - } - - /** - * Returns the minimum or preferred dimension needed to layout the target - * container. - * - * @param target target to get layout dimension for - * @param preferred should preferred dimension be calculated - * @return the dimension to layout the target container - */ - private Dimension layoutSize(Container target, boolean preferred) { - synchronized (target.getTreeLock()) { - // Each row must fit with the width allocated to the containter. - // When the container width = 0, the preferred width of the container - // has not yet been calculated so lets ask for the maximum. - - int targetWidth = target.getSize().width; - - if (targetWidth == 0) { - targetWidth = Integer.MAX_VALUE; - } - - int hgap = getHgap(); - int vgap = getVgap(); - Insets insets = target.getInsets(); - int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); - int maxWidth = targetWidth - horizontalInsetsAndGap; - - // Fit components into the allowed width - - Dimension dim = new Dimension(0, 0); - int rowWidth = 0; - int rowHeight = 0; - - int nmembers = target.getComponentCount(); - - for (int i = 0; i < nmembers; i++) { - Component m = target.getComponent(i); - - if (m.isVisible()) { - Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); - - // Can't add the component to current row. Start a new row. - - if (rowWidth + d.width > maxWidth) { - addRow(dim, rowWidth, rowHeight); - rowWidth = 0; - rowHeight = 0; - } + private Dimension preferredLayoutSize; + + /** + * Constructs a new WrapLayout with a left alignment and a default 5-unit horizontal + * and vertical gap. + */ + public WrapLayout() { + super(LEFT); + } + + /** + * Constructs a new FlowLayout with the specified alignment and a default 5-unit + * horizontal and vertical gap. The value of the alignment argument must be one of + * WrapLayout, WrapLayout, or WrapLayout. + * + * @param align the alignment value + */ + public WrapLayout(int align) { + super(align); + } + + /** + * Creates a new flow layout manager with the indicated alignment and the indicated horizontal and + * vertical gaps. + * + *

The value of the alignment argument must be one of WrapLayout, WrapLayout + * , or WrapLayout. + * + * @param align the alignment value + * @param hgap the horizontal gap between components + * @param vgap the vertical gap between components + */ + public WrapLayout(int align, int hgap, int vgap) { + super(align, hgap, vgap); + } + + /** + * Returns the preferred dimensions for this layout given the visible components in the specified + * target container. + * + * @param target the component which needs to be laid out + * @return the preferred dimensions to lay out the subcomponents of the specified container + */ + @Override + public Dimension preferredLayoutSize(Container target) { + return layoutSize(target, true); + } + + /** + * Returns the minimum dimensions needed to layout the visible components contained in the + * specified target container. + * + * @param target the component which needs to be laid out + * @return the minimum dimensions to lay out the subcomponents of the specified container + */ + @Override + public Dimension minimumLayoutSize(Container target) { + Dimension minimum = layoutSize(target, false); + minimum.width -= (getHgap() + 1); + return minimum; + } + + /** + * Returns the minimum or preferred dimension needed to layout the target container. + * + * @param target target to get layout dimension for + * @param preferred should preferred dimension be calculated + * @return the dimension to layout the target container + */ + private Dimension layoutSize(Container target, boolean preferred) { + synchronized (target.getTreeLock()) { + // Each row must fit with the width allocated to the containter. + // When the container width = 0, the preferred width of the container + // has not yet been calculated so lets ask for the maximum. + + int targetWidth = target.getSize().width; + + if (targetWidth == 0) { + targetWidth = Integer.MAX_VALUE; + } + + int hgap = getHgap(); + int vgap = getVgap(); + Insets insets = target.getInsets(); + int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); + int maxWidth = targetWidth - horizontalInsetsAndGap; + + // Fit components into the allowed width + + Dimension dim = new Dimension(0, 0); + int rowWidth = 0; + int rowHeight = 0; + + int nmembers = target.getComponentCount(); + + for (int i = 0; i < nmembers; i++) { + Component m = target.getComponent(i); + + if (m.isVisible()) { + Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); + + // Can't add the component to current row. Start a new row. + + if (rowWidth + d.width > maxWidth) { + addRow(dim, rowWidth, rowHeight); + rowWidth = 0; + rowHeight = 0; + } - // Add a horizontal gap for all components after the first + // Add a horizontal gap for all components after the first - if (rowWidth != 0) { - rowWidth += hgap; - } + if (rowWidth != 0) { + rowWidth += hgap; + } - rowWidth += d.width; - rowHeight = Math.max(rowHeight, d.height); - } - } + rowWidth += d.width; + rowHeight = Math.max(rowHeight, d.height); + } + } - addRow(dim, rowWidth, rowHeight); + addRow(dim, rowWidth, rowHeight); - dim.width += horizontalInsetsAndGap; - dim.height += insets.top + insets.bottom + vgap * 2; + dim.width += horizontalInsetsAndGap; + dim.height += insets.top + insets.bottom + vgap * 2; - // When using a scroll pane or the DecoratedLookAndFeel we need to - // make sure the preferred dimension is less than the dimension of the - // target containter so shrinking the container dimension works - // correctly. Removing the horizontal gap is an easy way to do this. + // When using a scroll pane or the DecoratedLookAndFeel we need to + // make sure the preferred dimension is less than the dimension of the + // target containter so shrinking the container dimension works + // correctly. Removing the horizontal gap is an easy way to do this. - Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); + Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); - if (scrollPane != null) { - dim.width -= (hgap + 1); - } + if (scrollPane != null) { + dim.width -= (hgap + 1); + } - return dim; - } + return dim; } - - /** - * A new row has been completed. Use the dimensions of this row - * to update the preferred dimension for the container. - * - * @param dim update the width and height when appropriate - * @param rowWidth the width of the row to add - * @param rowHeight the height of the row to add - */ - private void addRow(Dimension dim, int rowWidth, int rowHeight) { - dim.width = Math.max(dim.width, rowWidth); - - if (dim.height > 0) { - dim.height += getVgap(); - } - - dim.height += rowHeight; + } + + /** + * A new row has been completed. Use the dimensions of this row to update the preferred dimension + * for the container. + * + * @param dim update the width and height when appropriate + * @param rowWidth the width of the row to add + * @param rowHeight the height of the row to add + */ + private void addRow(Dimension dim, int rowWidth, int rowHeight) { + dim.width = Math.max(dim.width, rowWidth); + + if (dim.height > 0) { + dim.height += getVgap(); } -} \ No newline at end of file + + dim.height += rowHeight; + } +} diff --git a/src/main/java/edu/rpi/legup/ui/ZoomWidget.java b/src/main/java/edu/rpi/legup/ui/ZoomWidget.java index 1e423c346..0afe0c2d1 100644 --- a/src/main/java/edu/rpi/legup/ui/ZoomWidget.java +++ b/src/main/java/edu/rpi/legup/ui/ZoomWidget.java @@ -2,58 +2,55 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; - +import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.JSlider; import javax.swing.SwingConstants; -import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; -import javax.swing.ImageIcon; - +import javax.swing.event.ChangeListener; public class ZoomWidget extends JLabel { - private ScrollView parent; - private PopupSlider palette = new PopupSlider(); - private MouseAdapter open = new MouseAdapter() { + private ScrollView parent; + private PopupSlider palette = new PopupSlider(); + private MouseAdapter open = + new MouseAdapter() { public void mouseClicked(MouseEvent e) { - palette.slider.setValue(parent.getZoom()); - palette.show(e.getComponent(), 0, 0); + palette.slider.setValue(parent.getZoom()); + palette.show(e.getComponent(), 0, 0); } - }; - - /** - * ZoomWidget Constructor creates a zoom widget for a ScrollView object - * - * @param parent dynamicView to which to the ZoomWidget is applied to - */ - public ZoomWidget(ScrollView parent) { - super(new ImageIcon("zoom.png")); - this.parent = parent; - addMouseListener(open); + }; + + /** + * ZoomWidget Constructor creates a zoom widget for a ScrollView object + * + * @param parent dynamicView to which to the ZoomWidget is applied to + */ + public ZoomWidget(ScrollView parent) { + super(new ImageIcon("zoom.png")); + this.parent = parent; + addMouseListener(open); + } + + /** */ + private class PopupSlider extends JPopupMenu implements ChangeListener { + private static final long serialVersionUID = 8225019381200459814L; + + private JSlider slider; + + public PopupSlider() { + slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 200); + slider.setMajorTickSpacing(25); + slider.setPaintTicks(true); + + add(slider); + slider.addChangeListener(this); } - /** - * - */ - private class PopupSlider extends JPopupMenu implements ChangeListener { - private static final long serialVersionUID = 8225019381200459814L; - - private JSlider slider; - - public PopupSlider() { - slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 200); - slider.setMajorTickSpacing(25); - slider.setPaintTicks(true); - - add(slider); - slider.addChangeListener(this); - } - - public void stateChanged(ChangeEvent e) { - if (slider.getValueIsAdjusting()) { - parent.zoomTo((double) slider.getValue() / 100.0); - } - } + public void stateChanged(ChangeEvent e) { + if (slider.getValueIsAdjusting()) { + parent.zoomTo((double) slider.getValue() / 100.0); + } } + } } diff --git a/src/main/java/edu/rpi/legup/ui/ZoomablePane.java b/src/main/java/edu/rpi/legup/ui/ZoomablePane.java index 86cfd866f..121047448 100644 --- a/src/main/java/edu/rpi/legup/ui/ZoomablePane.java +++ b/src/main/java/edu/rpi/legup/ui/ZoomablePane.java @@ -1,40 +1,40 @@ package edu.rpi.legup.ui; -import javax.swing.*; +import java.awt.AWTEvent; import java.awt.Graphics; import java.awt.Graphics2D; -import java.awt.AWTEvent; +import javax.swing.*; public class ZoomablePane extends JLayeredPane { - private ScrollView viewer; + private ScrollView viewer; - /** - * ZoomablePane Constructor creates scalable JComponent - * - * @param viewer dynamic dynamicView - */ - public ZoomablePane(ScrollView viewer) { - this.viewer = viewer; - } + /** + * ZoomablePane Constructor creates scalable JComponent + * + * @param viewer dynamic dynamicView + */ + public ZoomablePane(ScrollView viewer) { + this.viewer = viewer; + } - /** - * Paints the JComponents - * - * @param graphics graphics object used to paint the JComponent - */ - public void paint(Graphics graphics) { - Graphics2D graphics2D = (Graphics2D) graphics; - graphics2D.scale(viewer.getScale(), viewer.getScale()); - viewer.draw(graphics2D); - } + /** + * Paints the JComponents + * + * @param graphics graphics object used to paint the JComponent + */ + public void paint(Graphics graphics) { + Graphics2D graphics2D = (Graphics2D) graphics; + graphics2D.scale(viewer.getScale(), viewer.getScale()); + viewer.draw(graphics2D); + } - /** - * Processes an event and sends it to the dynamicView - * - * @param e AWTEvent to process - */ - protected void processEvent(AWTEvent e) { - viewer.dispatchEvent(e); - super.processEvent(e); - } + /** + * Processes an event and sends it to the dynamicView + * + * @param e AWTEvent to process + */ + protected void processEvent(AWTEvent e) { + viewer.dispatchEvent(e); + super.processEvent(e); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java b/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java index 602672a9e..f917ef9b0 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java @@ -8,203 +8,201 @@ import edu.rpi.legup.model.observer.IBoardListener; import edu.rpi.legup.model.tree.TreeElement; import edu.rpi.legup.ui.ScrollView; - import java.awt.*; import java.util.ArrayList; public abstract class BoardView extends ScrollView implements IBoardListener { - protected TreeElement treeElement; - protected Board board; - protected ArrayList elementViews; - protected ElementController elementController; - protected ElementSelection selection; - - - /** - * BoardView Constructor creates a view for the board object using the controller handle the ui events - * - * @param boardController controller that handles the ui events - * @param elementController controller that handles the ui events - */ - public BoardView(BoardController boardController, ElementController elementController) { - super(boardController); - this.treeElement = null; - this.board = null; - this.elementViews = new ArrayList<>(); - this.elementController = elementController; - this.selection = new ElementSelection(); - - elementController.setBoardView(this); - addMouseListener(elementController); - addMouseMotionListener(elementController); - addKeyListener(elementController); - } - - /** - * Initializes the initial dimension of the viewport for the BoardView - */ - public abstract void initSize(); - - /** - * Gets the dimension of the board view - * - * @return dimension of the board view - */ - protected abstract Dimension getProperSize(); - - /** - * Gets the ElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return ElementView at the specified index - */ - public abstract ElementView getElement(int index); - - /** - * Sets the ElementView list - * - * @param elements ElementView list - */ - public void setElementViews(ArrayList elements) { - elementViews = elements; - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - public ElementView getElement(Point point) { - Point scaledPoint = new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - return null; - } - - /** - * Gets the ElementSelection for this BoardView - * - * @return the ElementSelection - */ - public ElementSelection getSelection() { - return selection; - } - - /** - * Gets the board associated with this view - * - * @return board - */ - public Board getBoard() { - return board; - } - - /** - * Sets the board associated with this view - * - * @param board board - */ - public void setBoard(Board board) { - if (this.board != board) { - this.board = board; - - if (board instanceof CaseBoard) { - setCasePickable(); - } - else { - for (ElementView elementView : elementViews) { - elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); - elementView.setShowCasePicker(false); - } - } - } - } - - protected void setCasePickable() { - CaseBoard caseBoard = (CaseBoard) board; - Board baseBoard = caseBoard.getBaseBoard(); - + protected TreeElement treeElement; + protected Board board; + protected ArrayList elementViews; + protected ElementController elementController; + protected ElementSelection selection; + + /** + * BoardView Constructor creates a view for the board object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + * @param elementController controller that handles the ui events + */ + public BoardView(BoardController boardController, ElementController elementController) { + super(boardController); + this.treeElement = null; + this.board = null; + this.elementViews = new ArrayList<>(); + this.elementController = elementController; + this.selection = new ElementSelection(); + + elementController.setBoardView(this); + addMouseListener(elementController); + addMouseMotionListener(elementController); + addKeyListener(elementController); + } + + /** Initializes the initial dimension of the viewport for the BoardView */ + public abstract void initSize(); + + /** + * Gets the dimension of the board view + * + * @return dimension of the board view + */ + protected abstract Dimension getProperSize(); + + /** + * Gets the ElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return ElementView at the specified index + */ + public abstract ElementView getElement(int index); + + /** + * Sets the ElementView list + * + * @param elements ElementView list + */ + public void setElementViews(ArrayList elements) { + elementViews = elements; + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + public ElementView getElement(Point point) { + Point scaledPoint = + new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + return null; + } + + /** + * Gets the ElementSelection for this BoardView + * + * @return the ElementSelection + */ + public ElementSelection getSelection() { + return selection; + } + + /** + * Gets the board associated with this view + * + * @return board + */ + public Board getBoard() { + return board; + } + + /** + * Sets the board associated with this view + * + * @param board board + */ + public void setBoard(Board board) { + if (this.board != board) { + this.board = board; + + if (board instanceof CaseBoard) { + setCasePickable(); + } else { for (ElementView elementView : elementViews) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); - elementView.setPuzzleElement(puzzleElement); - elementView.setShowCasePicker(true); - elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); + elementView.setShowCasePicker(false); } - } - - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - this.treeElement = treeElement; - setBoard(treeElement.getBoard()); - repaint(); - } - - /** - * Called when the a case board has been added to the view. - * - * @param caseBoard case board to be added - */ - @Override - public void onCaseBoardAdded(CaseBoard caseBoard) { - setBoard(caseBoard); - repaint(); - } - - public TreeElement getTreeElement() { - return this.treeElement; - } - - /** - * Gets the amount of edu.rpi.legup.puzzle elements for this board - * - * @return the amount of edu.rpi.legup.puzzle elements for this board - */ - public int getElementCount() { - return elementViews.size(); - } - - /** - * Gets the PuzzleElements associated with the BoardView - * - * @return list of PuzzleElements - */ - public ArrayList getElementViews() { - return elementViews; - } - - public ElementController getElementController() { - return elementController; - } - - @Override - public void draw(Graphics2D graphics2D) { - drawBoard(graphics2D); - } - - public void drawBoard(Graphics2D graphics2D) { - for (ElementView element : elementViews) { - element.draw(graphics2D); - } - } - - /** - * Called when the board puzzleElement changed - * - * @param puzzleElement puzzleElement of the puzzleElement that changed - */ - @Override - public void onBoardDataChanged(PuzzleElement puzzleElement) { - repaint(); - } - - public abstract DataSelectionView getSelectionPopupMenu(); + } + } + } + + protected void setCasePickable() { + CaseBoard caseBoard = (CaseBoard) board; + Board baseBoard = caseBoard.getBaseBoard(); + + for (ElementView elementView : elementViews) { + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); + elementView.setPuzzleElement(puzzleElement); + elementView.setShowCasePicker(true); + elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + } + + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + this.treeElement = treeElement; + setBoard(treeElement.getBoard()); + repaint(); + } + + /** + * Called when the a case board has been added to the view. + * + * @param caseBoard case board to be added + */ + @Override + public void onCaseBoardAdded(CaseBoard caseBoard) { + setBoard(caseBoard); + repaint(); + } + + public TreeElement getTreeElement() { + return this.treeElement; + } + + /** + * Gets the amount of edu.rpi.legup.puzzle elements for this board + * + * @return the amount of edu.rpi.legup.puzzle elements for this board + */ + public int getElementCount() { + return elementViews.size(); + } + + /** + * Gets the PuzzleElements associated with the BoardView + * + * @return list of PuzzleElements + */ + public ArrayList getElementViews() { + return elementViews; + } + + public ElementController getElementController() { + return elementController; + } + + @Override + public void draw(Graphics2D graphics2D) { + drawBoard(graphics2D); + } + + public void drawBoard(Graphics2D graphics2D) { + for (ElementView element : elementViews) { + element.draw(graphics2D); + } + } + + /** + * Called when the board puzzleElement changed + * + * @param puzzleElement puzzleElement of the puzzleElement that changed + */ + @Override + public void onBoardDataChanged(PuzzleElement puzzleElement) { + repaint(); + } + + public abstract DataSelectionView getSelectionPopupMenu(); } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java b/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java index 8257fd47c..3c6e78f5d 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java @@ -1,15 +1,14 @@ package edu.rpi.legup.ui.boardview; import edu.rpi.legup.controller.ElementController; - +import java.awt.*; import javax.swing.*; import javax.swing.border.BevelBorder; -import java.awt.*; public class DataSelectionView extends JPopupMenu { - public DataSelectionView(ElementController controller) { - setBackground(Color.GRAY); - setBorder(new BevelBorder(BevelBorder.RAISED)); - } + public DataSelectionView(ElementController controller) { + setBackground(Color.GRAY); + setBorder(new BevelBorder(BevelBorder.RAISED)); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java b/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java index d8f88f979..cce569af3 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java @@ -4,72 +4,71 @@ import java.util.ArrayList; public class ElementSelection { - private ArrayList selection; - private ElementView hover; - private Point mousePoint; + private ArrayList selection; + private ElementView hover; + private Point mousePoint; - public ElementSelection() { - this.selection = new ArrayList<>(); - this.hover = null; - this.mousePoint = null; - } + public ElementSelection() { + this.selection = new ArrayList<>(); + this.hover = null; + this.mousePoint = null; + } - public ArrayList getSelection() { - return selection; - } + public ArrayList getSelection() { + return selection; + } - public ElementView getFirstSelection() { - return selection.size() == 0 ? null : selection.get(0); - } + public ElementView getFirstSelection() { + return selection.size() == 0 ? null : selection.get(0); + } - public void toggleSelection(ElementView elementView) { - if (selection.contains(elementView)) { - selection.remove(elementView); - elementView.setSelected(false); - } - else { - selection.add(elementView); - elementView.setSelected(true); - } + public void toggleSelection(ElementView elementView) { + if (selection.contains(elementView)) { + selection.remove(elementView); + elementView.setSelected(false); + } else { + selection.add(elementView); + elementView.setSelected(true); } + } - public void newSelection(ElementView elementView) { - clearSelection(); - selection.add(elementView); - elementView.setSelected(true); - } + public void newSelection(ElementView elementView) { + clearSelection(); + selection.add(elementView); + elementView.setSelected(true); + } - public void clearSelection() { - for (ElementView elementView : selection) { - elementView.setSelected(false); - } - selection.clear(); + public void clearSelection() { + for (ElementView elementView : selection) { + elementView.setSelected(false); } + selection.clear(); + } - public ElementView getHover() { - return hover; - } + public ElementView getHover() { + return hover; + } - public void newHover(ElementView newHovered) { - newHovered.setHover(true); - if (hover != null) { - hover.setHover(false); - } - hover = newHovered; + public void newHover(ElementView newHovered) { + newHovered.setHover(true); + if (hover != null) { + hover.setHover(false); } + hover = newHovered; + } - public void clearHover() { - if (hover != null) { - hover.setHover(false); - hover = null; - } + public void clearHover() { + if (hover != null) { + hover.setHover(false); + hover = null; } + } - public Point getMousePoint() { - return mousePoint; - } + public Point getMousePoint() { + return mousePoint; + } - public void setMousePoint(Point point) { - this.mousePoint = point; - } + public void setMousePoint(Point point) { + this.mousePoint = point; + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java b/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java index 008c1a5f5..6cca76bcd 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java @@ -1,329 +1,340 @@ package edu.rpi.legup.ui.boardview; import edu.rpi.legup.model.gameboard.PuzzleElement; - -import javax.swing.*; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; +import javax.swing.*; public abstract class ElementView implements Shape { - protected int index; - protected Point location; - protected Dimension size; - protected PuzzleElement puzzleElement; - private Color hoverColor; - private Color modifiedColor; - private Color caseColor; - private Color invalidColor; - private boolean showCasePicker; - private boolean isCaseRulePickable; - private boolean isHover; - private boolean isSelected; - - /** - * ElementView Constructor creates a puzzleElement view - * - * @param puzzleElement puzzleElement to which the view uses to draw - */ - public ElementView(PuzzleElement puzzleElement) { - this.puzzleElement = puzzleElement; - this.hoverColor = new Color(0x79, 0x86, 0xCB, 255); - this.modifiedColor = new Color(0x64, 0xDD, 0x17, 255); - this.caseColor = new Color(0x1A, 0x23, 0x7E, 200); - this.invalidColor = new Color(0xf4, 0x43, 0x36, 200); - this.isHover = false; - this.isSelected = false; - this.isCaseRulePickable = false; - } - - /** - * Determines if the specified point is within the ElementView - * - * @param point point to check - * @return true if the point is within the ElementView, false otherwise - */ - public boolean isWithinBounds(Point point) { - return point.x >= location.x && point.x <= location.x + size.width && - point.y >= location.y && point.y <= location.y + size.height; - } - - /** - * Draws the puzzle element on the screen - * - * @param graphics2D graphics2D object used for drawing - */ - public void draw(Graphics2D graphics2D) { - drawElement(graphics2D); - if (puzzleElement.isGiven()) { - drawGiven(graphics2D); - } - if (puzzleElement.isModified()) { - drawModified(graphics2D); - } - if (showCasePicker && isCaseRulePickable) { - drawCase(graphics2D); - } - if (isHover) { - drawHover(graphics2D); - } - } - - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.draw(new Rectangle2D.Double(location.x + 0.5f, location.y + 0.5f, size.width - 2, size.height - 2)); - - graphics2D.setColor(Color.BLACK); - FontMetrics metrics = graphics2D.getFontMetrics(graphics2D.getFont()); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } - - public void drawGiven(Graphics2D graphics2D) { - - } - - public void drawHover(Graphics2D graphics2D) { - graphics2D.setColor(hoverColor); - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.draw(new Rectangle2D.Double(location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public void drawModified(Graphics2D graphics2D) { - graphics2D.setColor(puzzleElement.isValid() ? modifiedColor : invalidColor); - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.draw(new Rectangle2D.Double(location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public void drawCase(Graphics2D graphics2D) { - graphics2D.setColor(caseColor); - graphics2D.fill(new Rectangle2D.Double(location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public BufferedImage getImage() { - BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics2D = image.createGraphics(); - drawElement(graphics2D); - graphics2D.dispose(); - return image; - } - - /** - * Gets the index of the ElementView - * - * @return index of the ElementView - */ - public int getIndex() { - return index; - } - - /** - * Sets the index of the ElementView - * - * @param index index of the ElementView - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Gets the location of the ElementView - * - * @return location of the ElementView - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the ElementView - * - * @param location location of the ElementView - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Gets the dimension of the ElementView - * - * @return dimension of the ElementView - */ - public Dimension getSize() { - return size; - } - - /** - * Sets the dimension of the ElementView - * - * @param size dimension of the ElementView - */ - public void setSize(Dimension size) { - this.size = size; - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - public PuzzleElement getPuzzleElement() { - return puzzleElement; - } - - /** - * Sets the PuzzleElement associated with this view - * - * @param data PuzzleElement associated with this view - */ - public void setPuzzleElement(PuzzleElement data) { - this.puzzleElement = data; - } - - public boolean isShowCasePicker() { - return showCasePicker; - } - - public void setShowCasePicker(boolean showCasePicker) { - this.showCasePicker = showCasePicker; - } - - /** - * Gets the isCaseRulePickable field to determine if this ElementView - * should be highlighted in some way to indicate if it can be chosen by - * the CaseRule - * - * @return true if the ElementView can be chosen for the CaseRule, false otherwise - */ - public boolean isCaseRulePickable() { - return isCaseRulePickable; - } - - /** - * Sets the isCaseRulePickable field to determine if this ElementView - * should be highlighted in some way to indicate if it can be chosen by - * the CaseRule - * - * @param isCaseRulePickable true if the ElementView can be chosen for the CaseRule, false otherwise - */ - public void setCaseRulePickable(boolean isCaseRulePickable) { - this.isCaseRulePickable = isCaseRulePickable; - } - - /** - * Gets the high-light color - * - * @return high-light color - */ - public Color getHoverColor() { - return hoverColor; - } - - /** - * Sets the high-light color - * - * @param hoverColor high-light color - */ - public void setHoverColor(Color hoverColor) { - this.hoverColor = hoverColor; - } - - /** - * Gets whether the puzzleElement is currently being hovered over - * - * @return true if the puzzleElement is currently being hover over, false otherwise - */ - public boolean isHover() { - return isHover; - } - - /** - * Sets whether the puzzleElement is being hover over - * - * @param hover true if the puzzleElement is correctly being hover over, false otherwise - */ - public void setHover(boolean hover) { - isHover = hover; - } - - /** - * Gets whether the puzzleElement is being selected - * - * @return tue if the puzzleElement is currently selected, false otherwise - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets whether the puzzleElement is being selected - * - * @param selected tue if the puzzleElement is currently selected, false otherwise - */ - public void setSelected(boolean selected) { - isSelected = selected; - } - - public JMenuItem getSelectionMenuItem() { - JMenuItem item = new JMenuItem(puzzleElement.getData() + ""); - return item; - } - - @Override - public boolean contains(double x, double y) { - return x >= location.x && x <= location.x + size.width && - y >= location.y && y <= location.y + size.height; - } - - @Override - public boolean contains(Point2D point) { - return contains(point.getX(), point.getY()); - } - - @Override - public boolean intersects(double x, double y, double width, double height) { - return (x + width >= location.x && x <= location.x + size.width) || - (y + height >= location.y && y <= location.y + size.height); - } - - @Override - public boolean intersects(Rectangle2D rectangle2D) { - return intersects(rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); - } - - @Override - public boolean contains(double x, double y, double width, double height) { - return (x + width >= location.x && x <= location.x + size.width) && - (y + height >= location.y && y <= location.y + size.height); - } - - @Override - public boolean contains(Rectangle2D rectangle2D) { - return contains(rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at); - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at, flatness); - } - - @Override - public Rectangle getBounds() { - return new Rectangle(location.x, location.y, size.width, size.height); - } - - @Override - public Rectangle2D getBounds2D() { - return new Rectangle(location.x, location.y, size.width, size.height); - } + protected int index; + protected Point location; + protected Dimension size; + protected PuzzleElement puzzleElement; + private Color hoverColor; + private Color modifiedColor; + private Color caseColor; + private Color invalidColor; + private boolean showCasePicker; + private boolean isCaseRulePickable; + private boolean isHover; + private boolean isSelected; + + /** + * ElementView Constructor creates a puzzleElement view + * + * @param puzzleElement puzzleElement to which the view uses to draw + */ + public ElementView(PuzzleElement puzzleElement) { + this.puzzleElement = puzzleElement; + this.hoverColor = new Color(0x79, 0x86, 0xCB, 255); + this.modifiedColor = new Color(0x64, 0xDD, 0x17, 255); + this.caseColor = new Color(0x1A, 0x23, 0x7E, 200); + this.invalidColor = new Color(0xf4, 0x43, 0x36, 200); + this.isHover = false; + this.isSelected = false; + this.isCaseRulePickable = false; + } + + /** + * Determines if the specified point is within the ElementView + * + * @param point point to check + * @return true if the point is within the ElementView, false otherwise + */ + public boolean isWithinBounds(Point point) { + return point.x >= location.x + && point.x <= location.x + size.width + && point.y >= location.y + && point.y <= location.y + size.height; + } + + /** + * Draws the puzzle element on the screen + * + * @param graphics2D graphics2D object used for drawing + */ + public void draw(Graphics2D graphics2D) { + drawElement(graphics2D); + if (puzzleElement.isGiven()) { + drawGiven(graphics2D); + } + if (puzzleElement.isModified()) { + drawModified(graphics2D); + } + if (showCasePicker && isCaseRulePickable) { + drawCase(graphics2D); + } + if (isHover) { + drawHover(graphics2D); + } + } + + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 2, size.height - 2)); + + graphics2D.setColor(Color.BLACK); + FontMetrics metrics = graphics2D.getFontMetrics(graphics2D.getFont()); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } + + public void drawGiven(Graphics2D graphics2D) {} + + public void drawHover(Graphics2D graphics2D) { + graphics2D.setColor(hoverColor); + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public void drawModified(Graphics2D graphics2D) { + graphics2D.setColor(puzzleElement.isValid() ? modifiedColor : invalidColor); + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public void drawCase(Graphics2D graphics2D) { + graphics2D.setColor(caseColor); + graphics2D.fill( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public BufferedImage getImage() { + BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics2D = image.createGraphics(); + drawElement(graphics2D); + graphics2D.dispose(); + return image; + } + + /** + * Gets the index of the ElementView + * + * @return index of the ElementView + */ + public int getIndex() { + return index; + } + + /** + * Sets the index of the ElementView + * + * @param index index of the ElementView + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Gets the location of the ElementView + * + * @return location of the ElementView + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the ElementView + * + * @param location location of the ElementView + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Gets the dimension of the ElementView + * + * @return dimension of the ElementView + */ + public Dimension getSize() { + return size; + } + + /** + * Sets the dimension of the ElementView + * + * @param size dimension of the ElementView + */ + public void setSize(Dimension size) { + this.size = size; + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + public PuzzleElement getPuzzleElement() { + return puzzleElement; + } + + /** + * Sets the PuzzleElement associated with this view + * + * @param data PuzzleElement associated with this view + */ + public void setPuzzleElement(PuzzleElement data) { + this.puzzleElement = data; + } + + public boolean isShowCasePicker() { + return showCasePicker; + } + + public void setShowCasePicker(boolean showCasePicker) { + this.showCasePicker = showCasePicker; + } + + /** + * Gets the isCaseRulePickable field to determine if this ElementView should be highlighted in + * some way to indicate if it can be chosen by the CaseRule + * + * @return true if the ElementView can be chosen for the CaseRule, false otherwise + */ + public boolean isCaseRulePickable() { + return isCaseRulePickable; + } + + /** + * Sets the isCaseRulePickable field to determine if this ElementView should be highlighted in + * some way to indicate if it can be chosen by the CaseRule + * + * @param isCaseRulePickable true if the ElementView can be chosen for the CaseRule, false + * otherwise + */ + public void setCaseRulePickable(boolean isCaseRulePickable) { + this.isCaseRulePickable = isCaseRulePickable; + } + + /** + * Gets the high-light color + * + * @return high-light color + */ + public Color getHoverColor() { + return hoverColor; + } + + /** + * Sets the high-light color + * + * @param hoverColor high-light color + */ + public void setHoverColor(Color hoverColor) { + this.hoverColor = hoverColor; + } + + /** + * Gets whether the puzzleElement is currently being hovered over + * + * @return true if the puzzleElement is currently being hover over, false otherwise + */ + public boolean isHover() { + return isHover; + } + + /** + * Sets whether the puzzleElement is being hover over + * + * @param hover true if the puzzleElement is correctly being hover over, false otherwise + */ + public void setHover(boolean hover) { + isHover = hover; + } + + /** + * Gets whether the puzzleElement is being selected + * + * @return tue if the puzzleElement is currently selected, false otherwise + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets whether the puzzleElement is being selected + * + * @param selected tue if the puzzleElement is currently selected, false otherwise + */ + public void setSelected(boolean selected) { + isSelected = selected; + } + + public JMenuItem getSelectionMenuItem() { + JMenuItem item = new JMenuItem(puzzleElement.getData() + ""); + return item; + } + + @Override + public boolean contains(double x, double y) { + return x >= location.x + && x <= location.x + size.width + && y >= location.y + && y <= location.y + size.height; + } + + @Override + public boolean contains(Point2D point) { + return contains(point.getX(), point.getY()); + } + + @Override + public boolean intersects(double x, double y, double width, double height) { + return (x + width >= location.x && x <= location.x + size.width) + || (y + height >= location.y && y <= location.y + size.height); + } + + @Override + public boolean intersects(Rectangle2D rectangle2D) { + return intersects( + rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); + } + + @Override + public boolean contains(double x, double y, double width, double height) { + return (x + width >= location.x && x <= location.x + size.width) + && (y + height >= location.y && y <= location.y + size.height); + } + + @Override + public boolean contains(Rectangle2D rectangle2D) { + return contains( + rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at); + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return new Rectangle(location.x, location.y, size.width, size.height) + .getPathIterator(at, flatness); + } + + @Override + public Rectangle getBounds() { + return new Rectangle(location.x, location.y, size.width, size.height); + } + + @Override + public Rectangle2D getBounds2D() { + return new Rectangle(location.x, location.y, size.width, size.height); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java b/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java index 5fdacc6b0..34f41b60d 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java @@ -2,87 +2,84 @@ import edu.rpi.legup.controller.BoardController; import edu.rpi.legup.controller.ElementController; - import java.awt.Color; import java.awt.Dimension; public class GridBoardView extends BoardView { - protected Dimension gridSize; - protected Dimension elementSize; + protected Dimension gridSize; + protected Dimension elementSize; - /** - * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui events - * - * @param boardController controller that handles the ui events - * @param gridSize dimension of the grid - * @param elementController controller that handles the ui events - */ - public GridBoardView(BoardController boardController, ElementController elementController, Dimension gridSize) { - this(boardController, elementController); - this.gridSize = gridSize; - this.elementSize = new Dimension(30, 30); - initSize(); - } + /** + * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + * @param gridSize dimension of the grid + * @param elementController controller that handles the ui events + */ + public GridBoardView( + BoardController boardController, ElementController elementController, Dimension gridSize) { + this(boardController, elementController); + this.gridSize = gridSize; + this.elementSize = new Dimension(30, 30); + initSize(); + } - /** - * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui events - * - * @param boardController controller that handles the ui events - */ - private GridBoardView(BoardController boardController, ElementController elementController) { - super(boardController, elementController); - setBackground(new Color(0xE0E0E0)); - } + /** + * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + */ + private GridBoardView(BoardController boardController, ElementController elementController) { + super(boardController, elementController); + setBackground(new Color(0xE0E0E0)); + } - /** - * Gets the GridElementView from the puzzleElement index or - * null if out of bounds - * - * @param index index of the ElementView - * @return GridElementView at the specified index - */ - public GridElementView getElement(int index) { - if (index < elementViews.size()) { - return (GridElementView) elementViews.get(index); - } - return null; + /** + * Gets the GridElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return GridElementView at the specified index + */ + public GridElementView getElement(int index) { + if (index < elementViews.size()) { + return (GridElementView) elementViews.get(index); } + return null; + } - public GridElementView getElement(int xIndex, int yIndex) { - if (xIndex < gridSize.width && yIndex < gridSize.height) { - return (GridElementView) elementViews.get(yIndex * gridSize.width + xIndex); - } - return null; + public GridElementView getElement(int xIndex, int yIndex) { + if (xIndex < gridSize.width && yIndex < gridSize.height) { + return (GridElementView) elementViews.get(yIndex * gridSize.width + xIndex); } + return null; + } - /** - * Initializes the initial dimension of the viewport for the GridBoardView - */ - @Override - public void initSize() { - setSize(getProperSize()); - zoomFit(); - } + /** Initializes the initial dimension of the viewport for the GridBoardView */ + @Override + public void initSize() { + setSize(getProperSize()); + zoomFit(); + } - /** - * Helper method to determine the proper dimension of the grid view - * - * @return proper dimension of the grid view - */ - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = gridSize.width * elementSize.width; - boardViewSize.height = gridSize.height * elementSize.height; - return boardViewSize; - } + /** + * Helper method to determine the proper dimension of the grid view + * + * @return proper dimension of the grid view + */ + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = gridSize.width * elementSize.width; + boardViewSize.height = gridSize.height * elementSize.height; + return boardViewSize; + } - public DataSelectionView getSelectionPopupMenu() { - return null; - } - - public Dimension getElementSize() { - return this.elementSize; - } + public DataSelectionView getSelectionPopupMenu() { + return null; + } + public Dimension getElementSize() { + return this.elementSize; + } } - diff --git a/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java b/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java index 440b3a693..4a3d84261 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java @@ -3,7 +3,7 @@ import edu.rpi.legup.model.gameboard.GridCell; public class GridElementView extends ElementView { - public GridElementView(GridCell cell) { - super(cell); - } + public GridElementView(GridCell cell) { + super(cell); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java b/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java index 1ce5033c7..ee8060e3c 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java @@ -1,32 +1,31 @@ package edu.rpi.legup.ui.boardview; import edu.rpi.legup.model.gameboard.PuzzleElement; - import javax.swing.*; public class SelectionItemView extends JMenuItem { - private PuzzleElement data; - - public SelectionItemView(PuzzleElement data, Icon icon) { - super(icon); - this.data = data; - } - - public SelectionItemView(PuzzleElement data, String display) { - super(display); - this.data = data; - } - - public SelectionItemView(PuzzleElement data, int display) { - super(String.valueOf(display)); - this.data = data; - } - - public SelectionItemView(PuzzleElement data) { - this(data, (Integer) data.getData()); - } - - public PuzzleElement getData() { - return data; - } + private PuzzleElement data; + + public SelectionItemView(PuzzleElement data, Icon icon) { + super(icon); + this.data = data; + } + + public SelectionItemView(PuzzleElement data, String display) { + super(display); + this.data = data; + } + + public SelectionItemView(PuzzleElement data, int display) { + super(String.valueOf(display)); + this.data = data; + } + + public SelectionItemView(PuzzleElement data) { + this(data, (Integer) data.getData()); + } + + public PuzzleElement getData() { + return data; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java index 84804e1a0..613822c14 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java @@ -5,343 +5,339 @@ import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialColors; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialFonts; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialImages; - +import java.awt.*; import javax.swing.*; import javax.swing.plaf.basic.BasicLookAndFeel; -import java.awt.*; public class LegupLookAndFeel extends BasicLookAndFeel { - /** - * Return a short string that identifies this look and feel, e.g. - * "CDE/Motif". This string should be appropriate for a menu item. - * Distinct look and feels should have different names, e.g. - * a subclass of MotifLookAndFeel that changes the way a few components - * are rendered should be called "CDE/Motif My Way"; something - * that would be useful to a user trying to select a L&F from a list - * of names. - * - * @return short identifier for the look and feel - */ - @Override - public String getName() { - return "Legup"; - } - - /** - * Return a string that identifies this look and feel. This string - * will be used by applications/services that want to recognize - * well known look and feel implementations. Presently - * the well known names are "Motif", "Windows", "Mac", "Metal". Note - * that a LookAndFeel derived from a well known superclass - * that doesn't make any fundamental changes to the look or feel - * shouldn't override this method. - * - * @return identifier for the look and feel - */ - @Override - public String getID() { - return "Legup Look and Feel"; - } - - /** - * Return a one line description of this look and feel implementation, - * e.g. "The CDE/Motif Look and Feel". This string is intended for - * the user, e.g. in the title of a window or in a ToolTip message. - * - * @return short description for the look and feel - */ - @Override - public String getDescription() { - return "Material design look and feel for Legup"; - } - - /** - * If the underlying platform has a "native" look and feel, and - * this is an implementation of it, return {@code true}. For - * example, when the underlying platform is Solaris running CDE - * a CDE/Motif look and feel implementation would return {@code - * true}. - * - * @return {@code true} if this look and feel represents the underlying - * platform look and feel - */ - @Override - public boolean isNativeLookAndFeel() { - return true; - } - - /** - * Return {@code true} if the underlying platform supports and or permits - * this look and feel. This method returns {@code false} if the look - * and feel depends on special resources or legal agreements that - * aren't defined for the current platform. - * - * @return {@code true} if this is a supported look and feel - * @see UIManager#setLookAndFeel - */ - @Override - public boolean isSupportedLookAndFeel() { - return true; - } - - /** - * Initializes the look and feel. While this method is public, - * it should only be invoked by the {@code UIManager} when a - * look and feel is installed as the current look and feel. This - * method is invoked before the {@code UIManager} invokes - * {@code getDefaults}. This method is intended to perform any - * initialization for the look and feel. Subclasses - * should do any one-time setup they need here, rather than - * in a static initializer, because look and feel class objects - * may be loaded just to discover that {@code isSupportedLookAndFeel()} - * returns {@code false}. - * - * @see #uninitialize - * @see UIManager#setLookAndFeel - */ - @Override - public void initialize() { - super.initialize(); - } - - /** - * Populates {@code table} with mappings from {@code uiClassID} to the - * fully qualified name of the ui class. The value for a - * particular {@code uiClassID} is {@code - * "javax.swing.plaf.basic.Basic + uiClassID"}. For example, the - * value for the {@code uiClassID} {@code TreeUI} is {@code - * "javax.swing.plaf.basic.BasicTreeUI"}. - * - * @param table the {@code UIDefaults} instance the entries are - * added to - * @throws NullPointerException if {@code table} is {@code null} - * @see LookAndFeel - * @see #getDefaults - */ - @Override - protected void initClassDefaults(UIDefaults table) { - super.initClassDefaults(table); - - table.put("ButtonUI", MaterialButtonUI.class.getCanonicalName()); - table.put("TextFieldUI", MaterialTextFieldUI.class.getCanonicalName()); - table.put("PasswordFieldUI", MaterialPasswordFieldUI.class.getCanonicalName()); - table.put("TableUI", MaterialTableUI.class.getCanonicalName()); - table.put("TableHeaderUI", MaterialTableHeaderUI.class.getCanonicalName()); - table.put("TreeUI", MaterialTreeUI.class.getCanonicalName()); - table.put("SpinnerUI", MaterialSpinnerUI.class.getCanonicalName()); - table.put("PanelUI", MaterialPanelUI.class.getCanonicalName()); - table.put("LabelUI", MaterialLabelUI.class.getCanonicalName()); - table.put("MenuItemUI", MaterialMenuItemUI.class.getCanonicalName()); -// table.put ("MenuBarUI", .class.getCanonicalName()); - table.put("MenuUI", MaterialMenuUI.class.getCanonicalName()); - table.put("CheckBoxUI", MaterialCheckBoxUI.class.getCanonicalName()); - table.put("RadioButtonUI", MaterialRadioButtonUI.class.getCanonicalName()); - table.put("TabbedPaneUI", MaterialTabbedPaneUI.class.getCanonicalName()); - table.put("ToggleButtonUI", MaterialToggleButtonUI.class.getCanonicalName()); - table.put("ScrollBarUI", MaterialScrollBarUI.class.getCanonicalName()); - table.put("ComboBoxUI", MaterialComboBoxUI.class.getCanonicalName()); - table.put("PopupMenuUI", MaterialPopupMenuUI.class.getCanonicalName()); - table.put("ToolBarUI", MaterialToolBarUI.class.getCanonicalName()); - table.put("SliderUI", MaterialSliderUI.class.getCanonicalName()); - table.put("ProgressBarUI", MaterialProgressBarUI.class.getCanonicalName()); - table.put("RadioButtonMenuItemUI", MaterialRadioButtonMenuItemUI.class.getCanonicalName()); - table.put("CheckBoxMenuItemUI", MaterialCheckBoxMenuItemUI.class.getCanonicalName()); - table.put("TextPaneUI", MaterialTextPaneUI.class.getCanonicalName()); - table.put("EditorPaneUI", MaterialEditorPaneUI.class.getCanonicalName()); - table.put("SeparatorUI", MaterialSeparatorUI.class.getCanonicalName()); - table.put("FileChooserUI", MaterialFileChooserUI.class.getCanonicalName()); - table.put("ToolTipUI", MaterialToolTipUI.class.getCanonicalName()); - table.put("SplitPaneUI", MaterialSplitPaneUI.class.getCanonicalName()); -// table.put ("ColorChooserUI", ); - } - - @Override - protected void initComponentDefaults(UIDefaults table) { - super.initComponentDefaults(table); - - table.put("Button.highlight", MaterialColors.GRAY_300); - table.put("Button.opaque", false); - table.put("Button.border", BorderFactory.createEmptyBorder(7, 17, 7, 17)); - table.put("Button.background", MaterialColors.GRAY_200); - table.put("Button.foreground", Color.BLACK); - table.put("Button.font", MaterialFonts.MEDIUM); - - table.put("CheckBox.font", MaterialFonts.REGULAR); - table.put("CheckBox.background", Color.WHITE); - table.put("CheckBox.foreground", Color.BLACK); - table.put("CheckBox.icon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); - table.put("CheckBox.selectedIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); - - table.put("ComboBox.font", MaterialFonts.REGULAR); - table.put("ComboBox.background", Color.WHITE); - table.put("ComboBox.foreground", Color.BLACK); - table.put("ComboBox.border", BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(0, 5, 0, 0))); - table.put("ComboBox.buttonBackground", MaterialColors.GRAY_300); - table.put("ComboBox.selectionBackground", Color.WHITE); - table.put("ComboBox.selectionForeground", Color.BLACK); - table.put("ComboBox.selectedInDropDownBackground", MaterialColors.GRAY_200); - - table.put("Label.font", MaterialFonts.REGULAR); - table.put("Label.background", Color.WHITE); - table.put("Label.foreground", Color.BLACK); - table.put("Label.border", BorderFactory.createEmptyBorder()); - - table.put("Menu.font", MaterialFonts.BOLD); - table.put("Menu.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("Menu.background", Color.WHITE); - table.put("Menu.foreground", Color.BLACK); - table.put("Menu.opaque", true); - table.put("Menu.selectionBackground", MaterialColors.GRAY_200); - table.put("Menu.selectionForeground", Color.BLACK); - table.put("Menu.disabledForeground", new Color(0, 0, 0, 100)); - table.put("Menu.menuPopupOffsetY", 3); - - table.put("MenuBar.font", MaterialFonts.BOLD); - table.put("MenuBar.background", Color.WHITE); - table.put("MenuBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); - table.put("MenuBar.foreground", Color.BLACK); - - table.put("MenuItem.disabledForeground", new Color(0, 0, 0, 100)); - table.put("MenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("MenuItem.selectionForeground", Color.BLACK); - table.put("MenuItem.font", MaterialFonts.MEDIUM); - table.put("MenuItem.background", Color.WHITE); - table.put("MenuItem.foreground", Color.BLACK); - table.put("MenuItem.border", BorderFactory.createEmptyBorder(5, 0, 5, 0)); - - table.put("OptionPane.background", Color.WHITE); - table.put("OptionPane.border", MaterialBorders.DEFAULT_SHADOW_BORDER); - table.put("OptionPane.font", MaterialFonts.REGULAR); - - table.put("Panel.font", MaterialFonts.REGULAR); - table.put("Panel.background", Color.WHITE); - table.put("Panel.border", BorderFactory.createEmptyBorder()); - - table.put("PopupMenu.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("PopupMenu.background", Color.WHITE); - table.put("PopupMenu.foreground", Color.BLACK); - - table.put("RadioButton.font", MaterialFonts.REGULAR); - table.put("RadioButton.background", Color.WHITE); - table.put("RadioButton.foreground", Color.BLACK); - table.put("RadioButton.icon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); - table.put("RadioButton.selectedIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); - - table.put("Spinner.font", MaterialFonts.REGULAR); - table.put("Spinner.background", Color.WHITE); - table.put("Spinner.foreground", Color.BLACK); - table.put("Spinner.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("Spinner.arrowButtonBackground", MaterialColors.GRAY_200); - table.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); - - table.put("ScrollBar.font", MaterialFonts.REGULAR); - table.put("ScrollBar.track", MaterialColors.GRAY_200); - table.put("ScrollBar.thumb", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbDarkShadow", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbHighlight", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbShadow", MaterialColors.GRAY_300); - table.put("ScrollBar.arrowButtonBackground", MaterialColors.GRAY_300); - table.put("ScrollBar.arrowButtonBorder", BorderFactory.createEmptyBorder()); - - table.put("ScrollPane.background", Color.WHITE); - table.put("ScrollPane.border", BorderFactory.createEmptyBorder()); - table.put("ScrollPane.font", MaterialFonts.REGULAR); - - table.put("Slider.font", MaterialFonts.REGULAR); - table.put("Slider.background", Color.WHITE); - table.put("Slider.foreground", MaterialColors.GRAY_700); - table.put("Slider.trackColor", Color.BLACK); -// table.put ("Slider.border", BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder (5, 5, 5, 5))); - - table.put("SplitPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("SplitPane.background", Color.WHITE); - table.put("SplitPane.dividerSize", 10); - table.put("SplitPaneDivider.border", MaterialBorders.LIGHT_SHADOW_BORDER); - - table.put("TabbedPane.font", MaterialFonts.REGULAR); - table.put("TabbedPane.background", Color.WHITE); - table.put("TabbedPane.foreground", Color.BLACK); - table.put("TabbedPane.border", BorderFactory.createEmptyBorder()); - table.put("TabbedPane.shadow", null); - table.put("TabbedPane.darkShadow", null); - table.put("TabbedPane.highlight", MaterialColors.GRAY_200); - table.put("TabbedPane.borderHighlightColor", MaterialColors.GRAY_300); - - table.put("Table.selectionBackground", MaterialColors.GRAY_100); - table.put("Table.selectionForeground", Color.BLACK); - table.put("Table.background", Color.WHITE); - table.put("Table.font", MaterialFonts.REGULAR); - table.put("Table.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("Table.gridColor", MaterialColors.GRAY_200); - table.put("TableHeader.background", MaterialColors.GRAY_200); - table.put("TableHeader.font", MaterialFonts.BOLD); - table.put("TableHeader.cellBorder", BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(5, 5, 5, 5))); - - table.put("TextArea.background", MaterialColors.GRAY_200); - table.put("TextArea.border", BorderFactory.createEmptyBorder()); - table.put("TextArea.foreground", Color.BLACK); - - table.put("ToggleButton.border", BorderFactory.createEmptyBorder()); - table.put("ToggleButton.font", MaterialFonts.REGULAR); - table.put("ToggleButton.background", Color.WHITE); - table.put("ToggleButton.foreground", Color.BLACK); - table.put("ToggleButton.icon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_OFF)); - table.put("ToggleButton.selectedIcon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_ON)); - - table.put("ToolBar.font", MaterialFonts.REGULAR); - table.put("ToolBar.background", Color.WHITE); - table.put("ToolBar.foreground", Color.BLACK); - table.put("ToolBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); - table.put("ToolBar.dockingBackground", MaterialColors.LIGHT_GREEN_A100); - table.put("ToolBar.floatingBackground", MaterialColors.GRAY_200); - - table.put("Tree.font", MaterialFonts.REGULAR); - table.put("Tree.selectionForeground", Color.BLACK); - table.put("Tree.foreground", Color.BLACK); - table.put("Tree.selectionBackground", MaterialColors.GRAY_200); - table.put("Tree.background", Color.WHITE); - table.put("Tree.closedIcon", new ImageIcon(MaterialImages.RIGHT_ARROW)); - table.put("Tree.openIcon", new ImageIcon(MaterialImages.DOWN_ARROW)); - table.put("Tree.selectionBorderColor", null); - - table.put("RadioButtonMenuItem.foreground", Color.BLACK); - table.put("RadioButtonMenuItem.selectionForeground", Color.BLACK); - //If it changes the background of the menuitem it must change this too, irrespective of its setting - table.put("RadioButtonMenuItem.background", UIManager.getColor("MenuItem.background")); - table.put("RadioButtonMenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("RadioButtonMenuItem.checkIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); - table.put("RadioButtonMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); - - //If it changes the background of the menuitem it must change this too, irrespective of its setting - table.put("CheckBoxMenuItem.background", UIManager.getColor("MenuItem.background")); - table.put("CheckBoxMenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("CheckBoxMenuItem.foreground", Color.BLACK); - table.put("CheckBoxMenuItem.selectionForeground", Color.BLACK); - table.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("CheckBoxMenuItem.checkIcon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); - table.put("CheckBoxMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); - - table.put("TextPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("TextPane.background", MaterialColors.GRAY_50); - table.put("TextPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); - table.put("TextPane.inactiveForeground", MaterialColors.GRAY_500); - table.put("TextPane.font", MaterialFonts.REGULAR); - - table.put("EditorPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("EditorPane.background", MaterialColors.GRAY_50); - table.put("EditorPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); - table.put("EditorPane.inactiveForeground", MaterialColors.GRAY_500); - table.put("EditorPane.font", MaterialFonts.REGULAR); - - table.put("Separator.background", MaterialColors.GRAY_300); - table.put("Separator.foreground", MaterialColors.GRAY_300); - - table.put("ToolTip.background", MaterialColors.GRAY_500); - table.put("ToolTip.foreground", MaterialColors.GRAY_50); - table.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - - table.put("ColorChooser.background", MaterialColors.WHITE); - table.put("ColorChooser.foreground", MaterialColors.BLACK); - } + /** + * Return a short string that identifies this look and feel, e.g. "CDE/Motif". This string should + * be appropriate for a menu item. Distinct look and feels should have different names, e.g. a + * subclass of MotifLookAndFeel that changes the way a few components are rendered should be + * called "CDE/Motif My Way"; something that would be useful to a user trying to select a L&F + * from a list of names. + * + * @return short identifier for the look and feel + */ + @Override + public String getName() { + return "Legup"; + } + + /** + * Return a string that identifies this look and feel. This string will be used by + * applications/services that want to recognize well known look and feel implementations. + * Presently the well known names are "Motif", "Windows", "Mac", "Metal". Note that a LookAndFeel + * derived from a well known superclass that doesn't make any fundamental changes to the look or + * feel shouldn't override this method. + * + * @return identifier for the look and feel + */ + @Override + public String getID() { + return "Legup Look and Feel"; + } + + /** + * Return a one line description of this look and feel implementation, e.g. "The CDE/Motif Look + * and Feel". This string is intended for the user, e.g. in the title of a window or in a ToolTip + * message. + * + * @return short description for the look and feel + */ + @Override + public String getDescription() { + return "Material design look and feel for Legup"; + } + + /** + * If the underlying platform has a "native" look and feel, and this is an implementation of it, + * return {@code true}. For example, when the underlying platform is Solaris running CDE a + * CDE/Motif look and feel implementation would return {@code true}. + * + * @return {@code true} if this look and feel represents the underlying platform look and feel + */ + @Override + public boolean isNativeLookAndFeel() { + return true; + } + + /** + * Return {@code true} if the underlying platform supports and or permits this look and feel. This + * method returns {@code false} if the look and feel depends on special resources or legal + * agreements that aren't defined for the current platform. + * + * @return {@code true} if this is a supported look and feel + * @see UIManager#setLookAndFeel + */ + @Override + public boolean isSupportedLookAndFeel() { + return true; + } + + /** + * Initializes the look and feel. While this method is public, it should only be invoked by the + * {@code UIManager} when a look and feel is installed as the current look and feel. This method + * is invoked before the {@code UIManager} invokes {@code getDefaults}. This method is intended to + * perform any initialization for the look and feel. Subclasses should do any one-time setup they + * need here, rather than in a static initializer, because look and feel class objects may be + * loaded just to discover that {@code isSupportedLookAndFeel()} returns {@code false}. + * + * @see #uninitialize + * @see UIManager#setLookAndFeel + */ + @Override + public void initialize() { + super.initialize(); + } + + /** + * Populates {@code table} with mappings from {@code uiClassID} to the fully qualified name of the + * ui class. The value for a particular {@code uiClassID} is {@code "javax.swing.plaf.basic.Basic + * + uiClassID"}. For example, the value for the {@code uiClassID} {@code TreeUI} is {@code + * "javax.swing.plaf.basic.BasicTreeUI"}. + * + * @param table the {@code UIDefaults} instance the entries are added to + * @throws NullPointerException if {@code table} is {@code null} + * @see LookAndFeel + * @see #getDefaults + */ + @Override + protected void initClassDefaults(UIDefaults table) { + super.initClassDefaults(table); + + table.put("ButtonUI", MaterialButtonUI.class.getCanonicalName()); + table.put("TextFieldUI", MaterialTextFieldUI.class.getCanonicalName()); + table.put("PasswordFieldUI", MaterialPasswordFieldUI.class.getCanonicalName()); + table.put("TableUI", MaterialTableUI.class.getCanonicalName()); + table.put("TableHeaderUI", MaterialTableHeaderUI.class.getCanonicalName()); + table.put("TreeUI", MaterialTreeUI.class.getCanonicalName()); + table.put("SpinnerUI", MaterialSpinnerUI.class.getCanonicalName()); + table.put("PanelUI", MaterialPanelUI.class.getCanonicalName()); + table.put("LabelUI", MaterialLabelUI.class.getCanonicalName()); + table.put("MenuItemUI", MaterialMenuItemUI.class.getCanonicalName()); + // table.put ("MenuBarUI", .class.getCanonicalName()); + table.put("MenuUI", MaterialMenuUI.class.getCanonicalName()); + table.put("CheckBoxUI", MaterialCheckBoxUI.class.getCanonicalName()); + table.put("RadioButtonUI", MaterialRadioButtonUI.class.getCanonicalName()); + table.put("TabbedPaneUI", MaterialTabbedPaneUI.class.getCanonicalName()); + table.put("ToggleButtonUI", MaterialToggleButtonUI.class.getCanonicalName()); + table.put("ScrollBarUI", MaterialScrollBarUI.class.getCanonicalName()); + table.put("ComboBoxUI", MaterialComboBoxUI.class.getCanonicalName()); + table.put("PopupMenuUI", MaterialPopupMenuUI.class.getCanonicalName()); + table.put("ToolBarUI", MaterialToolBarUI.class.getCanonicalName()); + table.put("SliderUI", MaterialSliderUI.class.getCanonicalName()); + table.put("ProgressBarUI", MaterialProgressBarUI.class.getCanonicalName()); + table.put("RadioButtonMenuItemUI", MaterialRadioButtonMenuItemUI.class.getCanonicalName()); + table.put("CheckBoxMenuItemUI", MaterialCheckBoxMenuItemUI.class.getCanonicalName()); + table.put("TextPaneUI", MaterialTextPaneUI.class.getCanonicalName()); + table.put("EditorPaneUI", MaterialEditorPaneUI.class.getCanonicalName()); + table.put("SeparatorUI", MaterialSeparatorUI.class.getCanonicalName()); + table.put("FileChooserUI", MaterialFileChooserUI.class.getCanonicalName()); + table.put("ToolTipUI", MaterialToolTipUI.class.getCanonicalName()); + table.put("SplitPaneUI", MaterialSplitPaneUI.class.getCanonicalName()); + // table.put ("ColorChooserUI", ); + } + + @Override + protected void initComponentDefaults(UIDefaults table) { + super.initComponentDefaults(table); + + table.put("Button.highlight", MaterialColors.GRAY_300); + table.put("Button.opaque", false); + table.put("Button.border", BorderFactory.createEmptyBorder(7, 17, 7, 17)); + table.put("Button.background", MaterialColors.GRAY_200); + table.put("Button.foreground", Color.BLACK); + table.put("Button.font", MaterialFonts.MEDIUM); + + table.put("CheckBox.font", MaterialFonts.REGULAR); + table.put("CheckBox.background", Color.WHITE); + table.put("CheckBox.foreground", Color.BLACK); + table.put("CheckBox.icon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); + table.put("CheckBox.selectedIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); + + table.put("ComboBox.font", MaterialFonts.REGULAR); + table.put("ComboBox.background", Color.WHITE); + table.put("ComboBox.foreground", Color.BLACK); + table.put( + "ComboBox.border", + BorderFactory.createCompoundBorder( + MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(0, 5, 0, 0))); + table.put("ComboBox.buttonBackground", MaterialColors.GRAY_300); + table.put("ComboBox.selectionBackground", Color.WHITE); + table.put("ComboBox.selectionForeground", Color.BLACK); + table.put("ComboBox.selectedInDropDownBackground", MaterialColors.GRAY_200); + + table.put("Label.font", MaterialFonts.REGULAR); + table.put("Label.background", Color.WHITE); + table.put("Label.foreground", Color.BLACK); + table.put("Label.border", BorderFactory.createEmptyBorder()); + + table.put("Menu.font", MaterialFonts.BOLD); + table.put("Menu.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("Menu.background", Color.WHITE); + table.put("Menu.foreground", Color.BLACK); + table.put("Menu.opaque", true); + table.put("Menu.selectionBackground", MaterialColors.GRAY_200); + table.put("Menu.selectionForeground", Color.BLACK); + table.put("Menu.disabledForeground", new Color(0, 0, 0, 100)); + table.put("Menu.menuPopupOffsetY", 3); + + table.put("MenuBar.font", MaterialFonts.BOLD); + table.put("MenuBar.background", Color.WHITE); + table.put("MenuBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); + table.put("MenuBar.foreground", Color.BLACK); + + table.put("MenuItem.disabledForeground", new Color(0, 0, 0, 100)); + table.put("MenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("MenuItem.selectionForeground", Color.BLACK); + table.put("MenuItem.font", MaterialFonts.MEDIUM); + table.put("MenuItem.background", Color.WHITE); + table.put("MenuItem.foreground", Color.BLACK); + table.put("MenuItem.border", BorderFactory.createEmptyBorder(5, 0, 5, 0)); + + table.put("OptionPane.background", Color.WHITE); + table.put("OptionPane.border", MaterialBorders.DEFAULT_SHADOW_BORDER); + table.put("OptionPane.font", MaterialFonts.REGULAR); + + table.put("Panel.font", MaterialFonts.REGULAR); + table.put("Panel.background", Color.WHITE); + table.put("Panel.border", BorderFactory.createEmptyBorder()); + + table.put("PopupMenu.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("PopupMenu.background", Color.WHITE); + table.put("PopupMenu.foreground", Color.BLACK); + + table.put("RadioButton.font", MaterialFonts.REGULAR); + table.put("RadioButton.background", Color.WHITE); + table.put("RadioButton.foreground", Color.BLACK); + table.put("RadioButton.icon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); + table.put("RadioButton.selectedIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); + + table.put("Spinner.font", MaterialFonts.REGULAR); + table.put("Spinner.background", Color.WHITE); + table.put("Spinner.foreground", Color.BLACK); + table.put("Spinner.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("Spinner.arrowButtonBackground", MaterialColors.GRAY_200); + table.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); + + table.put("ScrollBar.font", MaterialFonts.REGULAR); + table.put("ScrollBar.track", MaterialColors.GRAY_200); + table.put("ScrollBar.thumb", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbDarkShadow", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbHighlight", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbShadow", MaterialColors.GRAY_300); + table.put("ScrollBar.arrowButtonBackground", MaterialColors.GRAY_300); + table.put("ScrollBar.arrowButtonBorder", BorderFactory.createEmptyBorder()); + + table.put("ScrollPane.background", Color.WHITE); + table.put("ScrollPane.border", BorderFactory.createEmptyBorder()); + table.put("ScrollPane.font", MaterialFonts.REGULAR); + + table.put("Slider.font", MaterialFonts.REGULAR); + table.put("Slider.background", Color.WHITE); + table.put("Slider.foreground", MaterialColors.GRAY_700); + table.put("Slider.trackColor", Color.BLACK); + // table.put ("Slider.border", + // BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, + // BorderFactory.createEmptyBorder (5, 5, 5, 5))); + + table.put("SplitPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("SplitPane.background", Color.WHITE); + table.put("SplitPane.dividerSize", 10); + table.put("SplitPaneDivider.border", MaterialBorders.LIGHT_SHADOW_BORDER); + + table.put("TabbedPane.font", MaterialFonts.REGULAR); + table.put("TabbedPane.background", Color.WHITE); + table.put("TabbedPane.foreground", Color.BLACK); + table.put("TabbedPane.border", BorderFactory.createEmptyBorder()); + table.put("TabbedPane.shadow", null); + table.put("TabbedPane.darkShadow", null); + table.put("TabbedPane.highlight", MaterialColors.GRAY_200); + table.put("TabbedPane.borderHighlightColor", MaterialColors.GRAY_300); + + table.put("Table.selectionBackground", MaterialColors.GRAY_100); + table.put("Table.selectionForeground", Color.BLACK); + table.put("Table.background", Color.WHITE); + table.put("Table.font", MaterialFonts.REGULAR); + table.put("Table.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("Table.gridColor", MaterialColors.GRAY_200); + table.put("TableHeader.background", MaterialColors.GRAY_200); + table.put("TableHeader.font", MaterialFonts.BOLD); + table.put( + "TableHeader.cellBorder", + BorderFactory.createCompoundBorder( + MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(5, 5, 5, 5))); + + table.put("TextArea.background", MaterialColors.GRAY_200); + table.put("TextArea.border", BorderFactory.createEmptyBorder()); + table.put("TextArea.foreground", Color.BLACK); + + table.put("ToggleButton.border", BorderFactory.createEmptyBorder()); + table.put("ToggleButton.font", MaterialFonts.REGULAR); + table.put("ToggleButton.background", Color.WHITE); + table.put("ToggleButton.foreground", Color.BLACK); + table.put("ToggleButton.icon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_OFF)); + table.put("ToggleButton.selectedIcon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_ON)); + + table.put("ToolBar.font", MaterialFonts.REGULAR); + table.put("ToolBar.background", Color.WHITE); + table.put("ToolBar.foreground", Color.BLACK); + table.put("ToolBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); + table.put("ToolBar.dockingBackground", MaterialColors.LIGHT_GREEN_A100); + table.put("ToolBar.floatingBackground", MaterialColors.GRAY_200); + + table.put("Tree.font", MaterialFonts.REGULAR); + table.put("Tree.selectionForeground", Color.BLACK); + table.put("Tree.foreground", Color.BLACK); + table.put("Tree.selectionBackground", MaterialColors.GRAY_200); + table.put("Tree.background", Color.WHITE); + table.put("Tree.closedIcon", new ImageIcon(MaterialImages.RIGHT_ARROW)); + table.put("Tree.openIcon", new ImageIcon(MaterialImages.DOWN_ARROW)); + table.put("Tree.selectionBorderColor", null); + + table.put("RadioButtonMenuItem.foreground", Color.BLACK); + table.put("RadioButtonMenuItem.selectionForeground", Color.BLACK); + // If it changes the background of the menuitem it must change this too, irrespective of its + // setting + table.put("RadioButtonMenuItem.background", UIManager.getColor("MenuItem.background")); + table.put("RadioButtonMenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("RadioButtonMenuItem.checkIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); + table.put( + "RadioButtonMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); + + // If it changes the background of the menuitem it must change this too, irrespective of its + // setting + table.put("CheckBoxMenuItem.background", UIManager.getColor("MenuItem.background")); + table.put("CheckBoxMenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("CheckBoxMenuItem.foreground", Color.BLACK); + table.put("CheckBoxMenuItem.selectionForeground", Color.BLACK); + table.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("CheckBoxMenuItem.checkIcon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); + table.put( + "CheckBoxMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); + + table.put("TextPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("TextPane.background", MaterialColors.GRAY_50); + table.put("TextPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); + table.put("TextPane.inactiveForeground", MaterialColors.GRAY_500); + table.put("TextPane.font", MaterialFonts.REGULAR); + + table.put("EditorPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("EditorPane.background", MaterialColors.GRAY_50); + table.put("EditorPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); + table.put("EditorPane.inactiveForeground", MaterialColors.GRAY_500); + table.put("EditorPane.font", MaterialFonts.REGULAR); + + table.put("Separator.background", MaterialColors.GRAY_300); + table.put("Separator.foreground", MaterialColors.GRAY_300); + + table.put("ToolTip.background", MaterialColors.GRAY_500); + table.put("ToolTip.foreground", MaterialColors.GRAY_50); + table.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + table.put("ColorChooser.background", MaterialColors.WHITE); + table.put("ColorChooser.foreground", MaterialColors.BLACK); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java index fe82238ab..a0fdc487a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java @@ -1,18 +1,17 @@ package edu.rpi.legup.ui.lookandfeel.animation; -import javax.swing.JComponent; import java.awt.Color; +import javax.swing.JComponent; public class MaterialUIMovement { - private MaterialUIMovement() { - } + private MaterialUIMovement() {} - public static void add(JComponent c, Color fadeTo, int steps, int interval) { - new MaterialUITimer(c, fadeTo, steps, interval); - } + public static void add(JComponent c, Color fadeTo, int steps, int interval) { + new MaterialUITimer(c, fadeTo, steps, interval); + } - public static void add(JComponent c, Color fadeTo) { - add(c, fadeTo, 5, 1000 / 30); - } + public static void add(JComponent c, Color fadeTo) { + add(c, fadeTo, 5, 1000 / 30); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java index b5b3bbd76..b5ca8415f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java @@ -1,113 +1,108 @@ package edu.rpi.legup.ui.lookandfeel.animation; -import javax.swing.JComponent; -import javax.swing.Timer; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; +import javax.swing.JComponent; +import javax.swing.Timer; public class MaterialUITimer implements MouseListener, ActionListener { - private Color from, to; - private boolean forward; - private int alpha, steps; - private int[] forwardDeltas, backwardDeltas; - - private JComponent component; - private Timer timer; - - protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { - this.from = component.getBackground(); - this.to = to; - - this.forwardDeltas = new int[4]; - this.backwardDeltas = new int[4]; - - forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; - forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; - forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; - forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; - - backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; - backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; - backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; - backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; - - this.steps = steps; - - this.component = component; - this.component.addMouseListener(this); - timer = new Timer(interval, this); - } - - private Color nextColor() { - int rValue = from.getRed() - alpha * forwardDeltas[0]; - int gValue = from.getGreen() - alpha * forwardDeltas[1]; - int bValue = from.getBlue() - alpha * forwardDeltas[2]; - int aValue = from.getAlpha() - alpha * forwardDeltas[3]; - - return new Color(rValue, gValue, bValue, aValue); - } - - private Color previousColor() { - int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; - int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; - int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; - int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; - - return new Color(rValue, gValue, bValue, aValue); - } - - @Override - public void mousePressed(MouseEvent me) { - alpha = steps - 1; - forward = false; - timer.start(); - - alpha = 0; - forward = true; - timer.start(); - } - - @Override - public void mouseReleased(MouseEvent me) { - - } - - @Override - public void mouseClicked(MouseEvent me) { - - } - - @Override - public void mouseExited(MouseEvent me) { - alpha = steps - 1; - forward = false; - timer.start(); - } - - @Override - public void mouseEntered(MouseEvent me) { - alpha = 0; - forward = true; - timer.start(); + private Color from, to; + private boolean forward; + private int alpha, steps; + private int[] forwardDeltas, backwardDeltas; + + private JComponent component; + private Timer timer; + + protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { + this.from = component.getBackground(); + this.to = to; + + this.forwardDeltas = new int[4]; + this.backwardDeltas = new int[4]; + + forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; + forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; + forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; + forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; + + backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; + backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; + backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; + backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; + + this.steps = steps; + + this.component = component; + this.component.addMouseListener(this); + timer = new Timer(interval, this); + } + + private Color nextColor() { + int rValue = from.getRed() - alpha * forwardDeltas[0]; + int gValue = from.getGreen() - alpha * forwardDeltas[1]; + int bValue = from.getBlue() - alpha * forwardDeltas[2]; + int aValue = from.getAlpha() - alpha * forwardDeltas[3]; + + return new Color(rValue, gValue, bValue, aValue); + } + + private Color previousColor() { + int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; + int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; + int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; + int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; + + return new Color(rValue, gValue, bValue, aValue); + } + + @Override + public void mousePressed(MouseEvent me) { + alpha = steps - 1; + forward = false; + timer.start(); + + alpha = 0; + forward = true; + timer.start(); + } + + @Override + public void mouseReleased(MouseEvent me) {} + + @Override + public void mouseClicked(MouseEvent me) {} + + @Override + public void mouseExited(MouseEvent me) { + alpha = steps - 1; + forward = false; + timer.start(); + } + + @Override + public void mouseEntered(MouseEvent me) { + alpha = 0; + forward = true; + timer.start(); + } + + @Override + public void actionPerformed(ActionEvent ae) { + if (forward) { + component.setBackground(nextColor()); + ++alpha; + } else { + component.setBackground(previousColor()); + --alpha; } - @Override - public void actionPerformed(ActionEvent ae) { - if (forward) { - component.setBackground(nextColor()); - ++alpha; - } - else { - component.setBackground(previousColor()); - --alpha; - } - - if (alpha == steps + 1 || alpha == -1) { - timer.stop(); - } + if (alpha == steps + 1 || alpha == -1) { + timer.stop(); } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java index fe23536d3..5fbc8c1aa 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java @@ -3,43 +3,42 @@ import edu.rpi.legup.ui.lookandfeel.animation.MaterialUIMovement; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialColors; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.AbstractButton; import javax.swing.JComponent; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicButtonUI; -import java.awt.Graphics; public class MaterialButtonUI extends BasicButtonUI { - public static ComponentUI createUI(final JComponent c) { - return new MaterialButtonUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - AbstractButton button = (AbstractButton) c; - MaterialUIMovement.add(c, MaterialColors.GRAY_300); - button.setOpaque(UIManager.getBoolean("Button.opaque")); - button.setBorder(UIManager.getBorder("Button.border")); - button.setBackground(UIManager.getColor("Button.background")); - button.setForeground(UIManager.getColor("Button.foreground")); - button.setFont(UIManager.getFont("Button.font")); - } - - @Override - public void paint(Graphics g, JComponent c) { - AbstractButton b = (AbstractButton) c; - g = MaterialDrawingUtils.getAliasedGraphics(g); - paintBackground(g, b); - super.paint(g, c); - } - - private void paintBackground(Graphics g, JComponent c) { - g.setColor(c.getBackground()); - g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 7, 7); - } -} \ No newline at end of file + public static ComponentUI createUI(final JComponent c) { + return new MaterialButtonUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + AbstractButton button = (AbstractButton) c; + MaterialUIMovement.add(c, MaterialColors.GRAY_300); + button.setOpaque(UIManager.getBoolean("Button.opaque")); + button.setBorder(UIManager.getBorder("Button.border")); + button.setBackground(UIManager.getColor("Button.background")); + button.setForeground(UIManager.getColor("Button.foreground")); + button.setFont(UIManager.getFont("Button.font")); + } + + @Override + public void paint(Graphics g, JComponent c) { + AbstractButton b = (AbstractButton) c; + g = MaterialDrawingUtils.getAliasedGraphics(g); + paintBackground(g, b); + super.paint(g, c); + } + + private void paintBackground(Graphics g, JComponent c) { + g.setColor(c.getBackground()); + g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 7, 7); + } +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java index e5068a8ed..18870c571 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java @@ -1,43 +1,62 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Color; +import java.awt.Graphics; import javax.swing.Icon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicCheckBoxMenuItemUI; -import java.awt.Color; -import java.awt.Graphics; /** * @author https://github.com/vincenzopalazzo */ - public class MaterialCheckBoxMenuItemUI extends BasicCheckBoxMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialCheckBoxMenuItemUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } - - @Override - protected void paintMenuItem(Graphics g, JComponent c, Icon checkIcon, Icon arrowIcon, Color background, Color foreground, int defaultTextIconGap) { - JCheckBoxMenuItem checkBoxMenuItem = (JCheckBoxMenuItem) c; - if (checkBoxMenuItem.isSelected()) { - super.paintMenuItem(MaterialDrawingUtils.getAliasedGraphics(g), checkBoxMenuItem, UIManager.getIcon("CheckBoxMenuItem.selectedCheckIcon"), arrowIcon, background, foreground, defaultTextIconGap); - return; - } - super.paintMenuItem(MaterialDrawingUtils.getAliasedGraphics(g), checkBoxMenuItem, UIManager.getIcon("CheckBoxMenuItem.checkIcon"), arrowIcon, background, foreground, defaultTextIconGap); + public static ComponentUI createUI(JComponent c) { + return new MaterialCheckBoxMenuItemUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } + + @Override + protected void paintMenuItem( + Graphics g, + JComponent c, + Icon checkIcon, + Icon arrowIcon, + Color background, + Color foreground, + int defaultTextIconGap) { + JCheckBoxMenuItem checkBoxMenuItem = (JCheckBoxMenuItem) c; + if (checkBoxMenuItem.isSelected()) { + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + checkBoxMenuItem, + UIManager.getIcon("CheckBoxMenuItem.selectedCheckIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + return; } + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + checkBoxMenuItem, + UIManager.getIcon("CheckBoxMenuItem.checkIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java index a85e9079e..e851617f9 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java @@ -1,35 +1,34 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicCheckBoxUI; -import java.awt.Graphics; -//TODO cambio colore icone combo box +// TODO cambio colore icone combo box public class MaterialCheckBoxUI extends BasicCheckBoxUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialCheckBoxUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialCheckBoxUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JCheckBox checkBox = (JCheckBox) c; - checkBox.setFont(UIManager.getFont("CheckBox.font")); - checkBox.setBackground(UIManager.getColor("CheckBox.background")); - checkBox.setForeground(UIManager.getColor("CheckBox.foreground")); - checkBox.setIcon(UIManager.getIcon("CheckBox.icon")); - checkBox.setSelectedIcon(UIManager.getIcon("CheckBox.selectedIcon")); - } + JCheckBox checkBox = (JCheckBox) c; + checkBox.setFont(UIManager.getFont("CheckBox.font")); + checkBox.setBackground(UIManager.getColor("CheckBox.background")); + checkBox.setForeground(UIManager.getColor("CheckBox.foreground")); + checkBox.setIcon(UIManager.getIcon("CheckBox.icon")); + checkBox.setSelectedIcon(UIManager.getIcon("CheckBox.selectedIcon")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java index d6df89d44..e8e0957e1 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java @@ -1,24 +1,28 @@ package edu.rpi.legup.ui.lookandfeel.components; +import java.awt.Component; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.UIManager; import javax.swing.plaf.basic.BasicComboBoxRenderer; -import java.awt.Component; public class MaterialComboBoxRenderer extends BasicComboBoxRenderer { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JComponent component = (JComponent) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + @Override + public Component getListCellRendererComponent( + JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JComponent component = + (JComponent) + super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - component.setForeground(UIManager.getColor("ComboBox.foreground")); - component.setBackground(isSelected || cellHasFocus ? - UIManager.getColor("ComboBox.selectedInDropDownBackground") : - UIManager.getColor("ComboBox.background")); + component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + component.setForeground(UIManager.getColor("ComboBox.foreground")); + component.setBackground( + isSelected || cellHasFocus + ? UIManager.getColor("ComboBox.selectedInDropDownBackground") + : UIManager.getColor("ComboBox.background")); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java index f9d6fa090..3cd934502 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java @@ -1,7 +1,7 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; @@ -12,47 +12,45 @@ import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.plaf.basic.BasicComboBoxUI; -import java.awt.Graphics; public class MaterialComboBoxUI extends BasicComboBoxUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialComboBoxUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JComboBox comboBox = (JComboBox) c; - comboBox.setFont(UIManager.getFont("ComboBox.font")); - comboBox.setBackground(UIManager.getColor("ComboBox.background")); - comboBox.setForeground(UIManager.getColor("ComboBox.foreground")); - comboBox.setBorder(UIManager.getBorder("ComboBox.border")); - comboBox.setLightWeightPopupEnabled(true); - comboBox.setRenderer(new MaterialComboBoxRenderer()); - } - - @Override - protected JButton createArrowButton() { - Icon icon = UIManager.getIcon("ComboBox.buttonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } - else { - button = new BasicArrowButton(SwingConstants.SOUTH); - } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ComboBox.buttonBackground")); - button.setBorder(BorderFactory.createEmptyBorder()); - - return button; - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + public static ComponentUI createUI(JComponent c) { + return new MaterialComboBoxUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JComboBox comboBox = (JComboBox) c; + comboBox.setFont(UIManager.getFont("ComboBox.font")); + comboBox.setBackground(UIManager.getColor("ComboBox.background")); + comboBox.setForeground(UIManager.getColor("ComboBox.foreground")); + comboBox.setBorder(UIManager.getBorder("ComboBox.border")); + comboBox.setLightWeightPopupEnabled(true); + comboBox.setRenderer(new MaterialComboBoxRenderer()); + } + + @Override + protected JButton createArrowButton() { + Icon icon = UIManager.getIcon("ComboBox.buttonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.SOUTH); } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ComboBox.buttonBackground")); + button.setBorder(BorderFactory.createEmptyBorder()); + + return button; + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java index 92d6770e0..df165a608 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java @@ -7,15 +7,14 @@ /** * @author https://github.com/vincenzopalazzo */ - public class MaterialEditorPaneUI extends BasicEditorPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialEditorPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialEditorPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java index 9a4ffc9d4..ffcca1064 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java @@ -2,58 +2,57 @@ import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialImages; - +import java.awt.Graphics; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.metal.MetalFileChooserUI; -import java.awt.Graphics; public class MaterialFileChooserUI extends MetalFileChooserUI { - public MaterialFileChooserUI(JFileChooser fileChooser) { - super(fileChooser); - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialFileChooserUI((JFileChooser) c); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - JFileChooser fileChooser = (JFileChooser) c; - MaterialFileChooserUI ui = (MaterialFileChooserUI) fileChooser.getUI(); - - ui.uninstallIcons(fileChooser); - ui.uninstallComponents(fileChooser); - ui.clearIconCache(); - - ui.computerIcon = new ImageIcon(MaterialImages.COMPUTER); - ui.directoryIcon = new ImageIcon(MaterialImages.FOLDER); - ui.fileIcon = new ImageIcon(MaterialImages.FILE); - ui.floppyDriveIcon = new ImageIcon(MaterialImages.FLOPPY_DRIVE); - ui.hardDriveIcon = new ImageIcon(MaterialImages.HARD_DRIVE); - - ui.homeFolderIcon = new ImageIcon(MaterialImages.HOME); - ui.listViewIcon = new ImageIcon(MaterialImages.LIST); - ui.detailsViewIcon = new ImageIcon(MaterialImages.DETAILS); - ui.newFolderIcon = new ImageIcon(MaterialImages.NEW_FOLDER); - ui.upFolderIcon = new ImageIcon(MaterialImages.BACK_ARROW); - - ui.openButtonText = "OPEN"; - ui.cancelButtonText = "CANCEL"; - ui.helpButtonText = "HELP"; - ui.saveButtonText = "SAVE"; - ui.directoryOpenButtonText = "OPEN"; - ui.updateButtonText = "UPDATE"; - - ui.installComponents(fileChooser); - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + public MaterialFileChooserUI(JFileChooser fileChooser) { + super(fileChooser); + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialFileChooserUI((JFileChooser) c); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + JFileChooser fileChooser = (JFileChooser) c; + MaterialFileChooserUI ui = (MaterialFileChooserUI) fileChooser.getUI(); + + ui.uninstallIcons(fileChooser); + ui.uninstallComponents(fileChooser); + ui.clearIconCache(); + + ui.computerIcon = new ImageIcon(MaterialImages.COMPUTER); + ui.directoryIcon = new ImageIcon(MaterialImages.FOLDER); + ui.fileIcon = new ImageIcon(MaterialImages.FILE); + ui.floppyDriveIcon = new ImageIcon(MaterialImages.FLOPPY_DRIVE); + ui.hardDriveIcon = new ImageIcon(MaterialImages.HARD_DRIVE); + + ui.homeFolderIcon = new ImageIcon(MaterialImages.HOME); + ui.listViewIcon = new ImageIcon(MaterialImages.LIST); + ui.detailsViewIcon = new ImageIcon(MaterialImages.DETAILS); + ui.newFolderIcon = new ImageIcon(MaterialImages.NEW_FOLDER); + ui.upFolderIcon = new ImageIcon(MaterialImages.BACK_ARROW); + + ui.openButtonText = "OPEN"; + ui.cancelButtonText = "CANCEL"; + ui.helpButtonText = "HELP"; + ui.saveButtonText = "SAVE"; + ui.directoryOpenButtonText = "OPEN"; + ui.updateButtonText = "UPDATE"; + + ui.installComponents(fileChooser); + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java index e06509a82..de43761a9 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java @@ -1,34 +1,33 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicLabelUI; -import java.awt.Graphics; public class MaterialLabelUI extends BasicLabelUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialLabelUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialLabelUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JLabel label = (JLabel) c; - label.setOpaque(true); - label.setFont(UIManager.getFont("Label.font")); - label.setBackground(UIManager.getColor("Label.background")); - label.setForeground(UIManager.getColor("Label.foreground")); - label.setBorder(UIManager.getBorder("Label.border")); - } + JLabel label = (JLabel) c; + label.setOpaque(true); + label.setFont(UIManager.getFont("Label.font")); + label.setBackground(UIManager.getColor("Label.background")); + label.setForeground(UIManager.getColor("Label.foreground")); + label.setBorder(UIManager.getBorder("Label.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java index 8d5625559..decb5908d 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java @@ -1,33 +1,32 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JMenuBar; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicMenuBarUI; -import java.awt.Graphics; public class MaterialMenuBarUI extends BasicMenuBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenuBar menuBar = (JMenuBar) c; - menuBar.setFont(UIManager.getFont("MenuBar.font")); - menuBar.setBackground(UIManager.getColor("MenuBar.background")); - menuBar.setBorder(UIManager.getBorder("MenuBar.border")); - menuBar.setForeground(UIManager.getColor("MenuBar.foreground")); - } + JMenuBar menuBar = (JMenuBar) c; + menuBar.setFont(UIManager.getFont("MenuBar.font")); + menuBar.setBackground(UIManager.getColor("MenuBar.background")); + menuBar.setBorder(UIManager.getBorder("MenuBar.border")); + menuBar.setForeground(UIManager.getColor("MenuBar.foreground")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java index d7a23d1a3..32b537bd1 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java @@ -1,36 +1,35 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicMenuItemUI; -import java.awt.Graphics; public class MaterialMenuItemUI extends BasicMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenuItem menuItem = (JMenuItem) c; - menuItem.setFont(UIManager.getFont("MenuItem.font")); - menuItem.setBackground(UIManager.getColor("MenuItem.background")); - menuItem.setForeground(UIManager.getColor("MenuItem.foreground")); - menuItem.setHorizontalAlignment(SwingConstants.LEFT); - menuItem.setVerticalAlignment(SwingConstants.CENTER); - menuItem.setBorder(UIManager.getBorder("MenuItem.border")); - } + JMenuItem menuItem = (JMenuItem) c; + menuItem.setFont(UIManager.getFont("MenuItem.font")); + menuItem.setBackground(UIManager.getColor("MenuItem.background")); + menuItem.setForeground(UIManager.getColor("MenuItem.foreground")); + menuItem.setHorizontalAlignment(SwingConstants.LEFT); + menuItem.setVerticalAlignment(SwingConstants.CENTER); + menuItem.setBorder(UIManager.getBorder("MenuItem.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java index 7461cbea0..d45c3f37f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java @@ -1,34 +1,33 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicMenuUI; -import java.awt.Graphics; public class MaterialMenuUI extends BasicMenuUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenu menu = (JMenu) c; - menu.setFont(UIManager.getFont("Menu.font")); - menu.setBorder(UIManager.getBorder("Menu.border")); - menu.setBackground(UIManager.getColor("Menu.background")); - menu.setForeground(UIManager.getColor("Menu.foreground")); - menu.setOpaque(UIManager.getBoolean("Menu.opaque")); - } + JMenu menu = (JMenu) c; + menu.setFont(UIManager.getFont("Menu.font")); + menu.setBorder(UIManager.getBorder("Menu.border")); + menu.setBackground(UIManager.getColor("Menu.background")); + menu.setForeground(UIManager.getColor("Menu.foreground")); + menu.setOpaque(UIManager.getBoolean("Menu.opaque")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java index cf786be3f..005d439d6 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java @@ -1,33 +1,32 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicPanelUI; -import java.awt.Graphics; public class MaterialPanelUI extends BasicPanelUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialPanelUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialPanelUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JPanel panel = (JPanel) c; - panel.setOpaque(true); - panel.setFont(UIManager.getFont("Panel.font")); - panel.setBackground(UIManager.getColor("Panel.background")); - panel.setBorder(UIManager.getBorder("Panel.border")); - } + JPanel panel = (JPanel) c; + panel.setOpaque(true); + panel.setFont(UIManager.getFont("Panel.font")); + panel.setBackground(UIManager.getColor("Panel.background")); + panel.setBorder(UIManager.getBorder("Panel.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java index 61aa84fc7..4ba2910cd 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java @@ -2,18 +2,6 @@ import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialColors; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JPasswordField; -import javax.swing.KeyStroke; -import javax.swing.plaf.ComponentUI; -import javax.swing.plaf.basic.BasicPasswordFieldUI; -import javax.swing.text.Element; -import javax.swing.text.PasswordView; -import javax.swing.text.View; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; @@ -26,170 +14,196 @@ import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.BorderFactory; +import javax.swing.JComponent; +import javax.swing.JPasswordField; +import javax.swing.KeyStroke; +import javax.swing.plaf.ComponentUI; +import javax.swing.plaf.basic.BasicPasswordFieldUI; +import javax.swing.text.Element; +import javax.swing.text.PasswordView; +import javax.swing.text.View; -public class MaterialPasswordFieldUI extends BasicPasswordFieldUI implements FocusListener, PropertyChangeListener { - - private Color focusedBackground; - private Color unfocusedBackground; - private Color focusedSelectionBackground; - private Color unfocusedSelectionBackground; - - public static ComponentUI createUI(JComponent c) { - return new MaterialPasswordFieldUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JPasswordField passwordField = (JPasswordField) c; - passwordField.setOpaque(false); - passwordField.setBorder(BorderFactory.createEmptyBorder(5, 2, 10, 0)); - passwordField.setBackground(MaterialColors.LIGHT_BLUE_400); - - this.focusedBackground = passwordField.getBackground(); - this.unfocusedBackground = MaterialColors.GRAY_200; - - this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); - this.unfocusedSelectionBackground = unfocusedBackground; - } - - @Override - protected void installListeners() { - getComponent().addFocusListener(this); - getComponent().addPropertyChangeListener(this); - } - - @Override - protected void installKeyboardActions() { - super.installKeyboardActions(); - - Action selectAll = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().selectAll(); - } +public class MaterialPasswordFieldUI extends BasicPasswordFieldUI + implements FocusListener, PropertyChangeListener { + + private Color focusedBackground; + private Color unfocusedBackground; + private Color focusedSelectionBackground; + private Color unfocusedSelectionBackground; + + public static ComponentUI createUI(JComponent c) { + return new MaterialPasswordFieldUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JPasswordField passwordField = (JPasswordField) c; + passwordField.setOpaque(false); + passwordField.setBorder(BorderFactory.createEmptyBorder(5, 2, 10, 0)); + passwordField.setBackground(MaterialColors.LIGHT_BLUE_400); + + this.focusedBackground = passwordField.getBackground(); + this.unfocusedBackground = MaterialColors.GRAY_200; + + this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); + this.unfocusedSelectionBackground = unfocusedBackground; + } + + @Override + protected void installListeners() { + getComponent().addFocusListener(this); + getComponent().addPropertyChangeListener(this); + } + + @Override + protected void installKeyboardActions() { + super.installKeyboardActions(); + + Action selectAll = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().selectAll(); + } }; - Action delete = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (getComponent().getSelectedText() == null) { - int pos = getComponent().getCaretPosition() - 1; - - if (pos >= 0) { - getComponent().select(pos, pos + 1); - getComponent().replaceSelection(""); - } - } - else { - getComponent().replaceSelection(""); - } + Action delete = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (getComponent().getSelectedText() == null) { + int pos = getComponent().getCaretPosition() - 1; + + if (pos >= 0) { + getComponent().select(pos, pos + 1); + getComponent().replaceSelection(""); + } + } else { + getComponent().replaceSelection(""); } + } }; - Action left = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); - } + Action left = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); + } }; - Action right = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().setCaretPosition(Math.min(getComponent().getText().length(), getComponent().getCaretPosition() + 1)); - } + Action right = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.min( + getComponent().getText().length(), getComponent().getCaretPosition() + 1)); + } }; - // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to getMenuShortcutKeyMaskEx() - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "selectAll"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); - - getComponent().getActionMap().put("selectAll", selectAll); - getComponent().getActionMap().put("delete", delete); - getComponent().getActionMap().put("left", left); - getComponent().getActionMap().put("right", right); - } - - @Override - public void paintSafely(Graphics g) { - JPasswordField c = (JPasswordField) getComponent(); - g = MaterialDrawingUtils.getAliasedGraphics(g); - - if (getComponent().hasFocus()) { - c.setBackground(focusedBackground); - c.setSelectionColor(focusedSelectionBackground); - } - else { - c.setBackground(unfocusedBackground); - c.setSelectionColor(unfocusedSelectionBackground); - } - - int x = getComponent().getInsets().left; - int y = getComponent().getInsets().top; - int w = getComponent().getWidth() - getComponent().getInsets().left - getComponent().getInsets().right; - - g.setColor(c.getBackground()); - g.fillRect(x, c.getHeight() - y, w, 2); - - super.paintSafely(g); + // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to getMenuShortcutKeyMaskEx() + getComponent() + .getInputMap() + .put( + KeyStroke.getKeyStroke( + KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "selectAll"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); + + getComponent().getActionMap().put("selectAll", selectAll); + getComponent().getActionMap().put("delete", delete); + getComponent().getActionMap().put("left", left); + getComponent().getActionMap().put("right", right); + } + + @Override + public void paintSafely(Graphics g) { + JPasswordField c = (JPasswordField) getComponent(); + g = MaterialDrawingUtils.getAliasedGraphics(g); + + if (getComponent().hasFocus()) { + c.setBackground(focusedBackground); + c.setSelectionColor(focusedSelectionBackground); + } else { + c.setBackground(unfocusedBackground); + c.setSelectionColor(unfocusedSelectionBackground); } - @Override - public void paintBackground(Graphics g) { - super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); + int x = getComponent().getInsets().left; + int y = getComponent().getInsets().top; + int w = + getComponent().getWidth() + - getComponent().getInsets().left + - getComponent().getInsets().right; + + g.setColor(c.getBackground()); + g.fillRect(x, c.getHeight() - y, w, 2); + + super.paintSafely(g); + } + + @Override + public void paintBackground(Graphics g) { + super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); + } + + @Override + public void focusGained(FocusEvent e) { + e.getComponent().setBackground(focusedBackground); + } + + @Override + public void focusLost(FocusEvent e) { + e.getComponent().setBackground(unfocusedBackground); + } + + @Override + public void propertyChange(PropertyChangeEvent pce) { + if (pce.getPropertyName().equals("background")) { + Color newColor = (Color) pce.getNewValue(); + + if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { + this.focusedBackground = (Color) pce.getNewValue(); + this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); + } } + } - @Override - public void focusGained(FocusEvent e) { - e.getComponent().setBackground(focusedBackground); - } - - @Override - public void focusLost(FocusEvent e) { - e.getComponent().setBackground(unfocusedBackground); - } + @Override + public View create(Element elem) { + return new MaterialPasswordView(elem); + } - @Override - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName().equals("background")) { - Color newColor = (Color) pce.getNewValue(); + private static class MaterialPasswordView extends PasswordView { - if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { - this.focusedBackground = (Color) pce.getNewValue(); - this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); - } - } + private MaterialPasswordView(Element elem) { + super(elem); } + // depreciated in Java 9 and above - replace method with float drawEchoCharacter(Graphics2D g, + // float x, float y, char c) @Override - public View create(Element elem) { - return new MaterialPasswordView(elem); - } - - private static class MaterialPasswordView extends PasswordView { - - private MaterialPasswordView(Element elem) { - super(elem); - } - - // depreciated in Java 9 and above - replace method with float drawEchoCharacter(Graphics2D g, float x, float y, char c) - @Override - protected int drawEchoCharacter(Graphics g, int x, int y, char c) { - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + protected int drawEchoCharacter(Graphics g, int x, int y, char c) { + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - FontMetrics fm = g2.getFontMetrics(); - int r = fm.charWidth(c) - 2; + FontMetrics fm = g2.getFontMetrics(); + int r = fm.charWidth(c) - 2; - g2.setPaint(Color.BLACK); - g2.fillOval(x + 1, y + 5 - fm.getAscent(), r, r); - g2.dispose(); + g2.setPaint(Color.BLACK); + g2.fillOval(x + 1, y + 5 - fm.getAscent(), r, r); + g2.dispose(); - return x + fm.charWidth(c); - } + return x + fm.charWidth(c); } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java index 3fdb79961..a864e9a41 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java @@ -1,32 +1,31 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicPopupMenuUI; -import java.awt.Graphics; public class MaterialPopupMenuUI extends BasicPopupMenuUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialPopupMenuUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialPopupMenuUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JPopupMenu popupMenu = (JPopupMenu) c; - popupMenu.setBorder(UIManager.getBorder("PopupMenu.border")); - popupMenu.setBackground(UIManager.getColor("PopupMenu.background")); - popupMenu.setForeground(UIManager.getColor("PopupMenu.foreground")); - } + JPopupMenu popupMenu = (JPopupMenu) c; + popupMenu.setBorder(UIManager.getBorder("PopupMenu.border")); + popupMenu.setBackground(UIManager.getColor("PopupMenu.background")); + popupMenu.setForeground(UIManager.getColor("PopupMenu.foreground")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java index 111b7ef92..062204e11 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java @@ -3,36 +3,33 @@ import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialBorders; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialColors; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JProgressBar; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicProgressBarUI; -import java.awt.Graphics; /** * @author https://github.com/vincenzopalazzo */ - public class MaterialProgressBarUI extends BasicProgressBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialProgressBarUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); + public static ComponentUI createUI(JComponent c) { + return new MaterialProgressBarUI(); + } - JProgressBar progressBar = (JProgressBar) c; - progressBar.setBorder(MaterialBorders.LIGHT_LINE_BORDER); - progressBar.setBackground(MaterialColors.GRAY_200); - progressBar.setForeground(MaterialColors.LIGHT_BLUE_400); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + JProgressBar progressBar = (JProgressBar) c; + progressBar.setBorder(MaterialBorders.LIGHT_LINE_BORDER); + progressBar.setBackground(MaterialColors.GRAY_200); + progressBar.setForeground(MaterialColors.LIGHT_BLUE_400); + } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java index d08e52f05..92aa97726 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java @@ -1,46 +1,65 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Color; +import java.awt.Graphics; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JRadioButtonMenuItem; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicRadioButtonMenuItemUI; -import java.awt.Color; -import java.awt.Graphics; /** * @author https://github.com/vincenzopalazzo */ - public class MaterialRadioButtonMenuItemUI extends BasicRadioButtonMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialRadioButtonMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialRadioButtonMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; - //j.setBackground(MaterialColors.WHITE); - j.setBorder(UIManager.getBorder("MenuItem.border")); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; + // j.setBackground(MaterialColors.WHITE); + j.setBorder(UIManager.getBorder("MenuItem.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintMenuItem(Graphics g, JComponent c, Icon checkIcon, Icon arrowIcon, Color background, Color foreground, int defaultTextIconGap) { - JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; - if (j.isSelected()) { - super.paintMenuItem(MaterialDrawingUtils.getAliasedGraphics(g), c, UIManager.getIcon("RadioButtonMenuItem.selectedCheckIcon"), arrowIcon, background, foreground, defaultTextIconGap); - return; - } - super.paintMenuItem(MaterialDrawingUtils.getAliasedGraphics(g), c, UIManager.getIcon("RadioButtonMenuItem.checkIcon"), arrowIcon, background, foreground, defaultTextIconGap); + @Override + protected void paintMenuItem( + Graphics g, + JComponent c, + Icon checkIcon, + Icon arrowIcon, + Color background, + Color foreground, + int defaultTextIconGap) { + JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; + if (j.isSelected()) { + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + c, + UIManager.getIcon("RadioButtonMenuItem.selectedCheckIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + return; } + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + c, + UIManager.getIcon("RadioButtonMenuItem.checkIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java index 047270369..517d9086d 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java @@ -1,38 +1,37 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JRadioButton; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicRadioButtonUI; -import java.awt.Graphics; /* * Contributed by https://github.com/downToHell * */ -//TODO cambio colore del radio button. +// TODO cambio colore del radio button. public class MaterialRadioButtonUI extends BasicRadioButtonUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialRadioButtonUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialRadioButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JRadioButton radioButton = (JRadioButton) c; - radioButton.setFont(UIManager.getFont("RadioButton.font")); - radioButton.setBackground(UIManager.getColor("RadioButton.background")); - radioButton.setForeground(UIManager.getColor("RadioButton.foreground")); - radioButton.setIcon(UIManager.getIcon("RadioButton.icon")); - radioButton.setSelectedIcon(UIManager.getIcon("RadioButton.selectedIcon")); - } + JRadioButton radioButton = (JRadioButton) c; + radioButton.setFont(UIManager.getFont("RadioButton.font")); + radioButton.setBackground(UIManager.getColor("RadioButton.background")); + radioButton.setForeground(UIManager.getColor("RadioButton.foreground")); + radioButton.setIcon(UIManager.getIcon("RadioButton.icon")); + radioButton.setSelectedIcon(UIManager.getIcon("RadioButton.selectedIcon")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } -} \ No newline at end of file + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java index 4bf5bbb0f..c433ddf92 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java @@ -1,7 +1,7 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JScrollBar; @@ -9,7 +9,6 @@ import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.plaf.basic.BasicScrollBarUI; -import java.awt.Graphics; /* * Contributed by https://github.com/downToHell @@ -17,49 +16,49 @@ public class MaterialScrollBarUI extends BasicScrollBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialScrollBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialScrollBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JScrollBar scrollBar = (JScrollBar) c; - scrollBar.setFont(UIManager.getFont("ScrollBar.font")); - trackColor = UIManager.getColor("ScrollBar.track"); - thumbColor = UIManager.getColor("ScrollBar.thumb"); - thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); - thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); - thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); - } + JScrollBar scrollBar = (JScrollBar) c; + scrollBar.setFont(UIManager.getFont("ScrollBar.font")); + trackColor = UIManager.getColor("ScrollBar.track"); + thumbColor = UIManager.getColor("ScrollBar.thumb"); + thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); + thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); + thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected JButton createDecreaseButton(int orientation) { - JButton button = new BasicArrowButton(orientation); + @Override + protected JButton createDecreaseButton(int orientation) { + JButton button = new BasicArrowButton(orientation); - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); - return button; - } + return button; + } - @Override - protected JButton createIncreaseButton(int orientation) { - JButton button = new BasicArrowButton(orientation); + @Override + protected JButton createIncreaseButton(int orientation) { + JButton button = new BasicArrowButton(orientation); - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); - return button; - } -} \ No newline at end of file + return button; + } +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java index 05cd5b60e..36ee98b90 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java @@ -1,25 +1,24 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicSeparatorUI; -import java.awt.Graphics; public class MaterialSeparatorUI extends BasicSeparatorUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialSeparatorUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialSeparatorUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java index ab9d75484..3195c05e0 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java @@ -2,127 +2,142 @@ import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialColors; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Dimension; +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JSlider; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicSliderUI; -import java.awt.Dimension; -import java.awt.Graphics; -//TODO cambio grafica slider +// TODO cambio grafica slider public class MaterialSliderUI extends BasicSliderUI { - private static final int NORMAL_THUMB_RADIUS = 6; - private static final int DRAG_THUMB_RADIUS = 10; - private static final Dimension THUMB_SIZE = new Dimension(DRAG_THUMB_RADIUS * 2, DRAG_THUMB_RADIUS * 2); - - public MaterialSliderUI(JSlider slider) { - super(slider); - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialSliderUI((JSlider) c); - } - - private static void drawCircle(Graphics g, int x, int y, int radius) { - g.fillOval(x - radius, y - radius, radius * 2, radius * 2); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JSlider slider = (JSlider) c; - slider.setFont(UIManager.getFont("Slider.font")); - slider.setBackground(UIManager.getColor("Slider.background")); - slider.setForeground(UIManager.getColor("Slider.foreground")); - slider.setBorder(UIManager.getBorder("Slider.border")); - } - - @Override - public Dimension getThumbSize() { - return THUMB_SIZE; - } - - @Override - public void paintThumb(Graphics g) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - - int cx = thumbRect.x + thumbRect.width / 2; - int cy = thumbRect.y + thumbRect.height / 2; - - if (isDragging()) { - g.setColor(MaterialColors.bleach(slider.getForeground(), 0.5f)); - drawCircle(g, cx, cy, DRAG_THUMB_RADIUS); - } - - g.setColor(slider.getForeground()); - drawCircle(g, cx, cy, NORMAL_THUMB_RADIUS); - - // need to redraw loaded part of progress line - Line loaded = getTrack(true); - g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + private static final int NORMAL_THUMB_RADIUS = 6; + private static final int DRAG_THUMB_RADIUS = 10; + private static final Dimension THUMB_SIZE = + new Dimension(DRAG_THUMB_RADIUS * 2, DRAG_THUMB_RADIUS * 2); + + public MaterialSliderUI(JSlider slider) { + super(slider); + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialSliderUI((JSlider) c); + } + + private static void drawCircle(Graphics g, int x, int y, int radius) { + g.fillOval(x - radius, y - radius, radius * 2, radius * 2); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JSlider slider = (JSlider) c; + slider.setFont(UIManager.getFont("Slider.font")); + slider.setBackground(UIManager.getColor("Slider.background")); + slider.setForeground(UIManager.getColor("Slider.foreground")); + slider.setBorder(UIManager.getBorder("Slider.border")); + } + + @Override + public Dimension getThumbSize() { + return THUMB_SIZE; + } + + @Override + public void paintThumb(Graphics g) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + + int cx = thumbRect.x + thumbRect.width / 2; + int cy = thumbRect.y + thumbRect.height / 2; + + if (isDragging()) { + g.setColor(MaterialColors.bleach(slider.getForeground(), 0.5f)); + drawCircle(g, cx, cy, DRAG_THUMB_RADIUS); } - @Override - public void paintTrack(Graphics g) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - - g.setColor(UIManager.getColor("Slider.trackColor")); - Line unloaded = getTrack(false); - g.drawLine(unloaded.x1, unloaded.y1, unloaded.x2, unloaded.y2); - - g.setColor(slider.getForeground()); - Line loaded = getTrack(true); - g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); - } - - private Line getTrack(boolean loaded) { - if (slider.getOrientation() == JSlider.HORIZONTAL) { - Line left = new Line(trackRect.x, thumbRect.y + thumbRect.height / 2, thumbRect.x + thumbRect.width / 2, thumbRect.y + thumbRect.height / 2); - Line right = new Line(thumbRect.x + thumbRect.width / 2, thumbRect.y + thumbRect.height / 2, trackRect.x + trackRect.width, thumbRect.y + thumbRect.height / 2); - - if (loaded) { - return slider.getInverted() ? right : left; - } - else { - return slider.getInverted() ? left : right; - } - } - else { - Line top = new Line(thumbRect.x + thumbRect.width / 2, trackRect.y, thumbRect.x + thumbRect.width / 2, thumbRect.y + thumbRect.height / 2); - Line bottom = new Line(thumbRect.x + thumbRect.width / 2, thumbRect.y + thumbRect.height / 2, thumbRect.x + thumbRect.width / 2, trackRect.y + trackRect.height); - - if (loaded) { - return slider.getInverted() ? top : bottom; - } - else { - return slider.getInverted() ? bottom : top; - } - } + g.setColor(slider.getForeground()); + drawCircle(g, cx, cy, NORMAL_THUMB_RADIUS); + + // need to redraw loaded part of progress line + Line loaded = getTrack(true); + g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + } + + @Override + public void paintTrack(Graphics g) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + + g.setColor(UIManager.getColor("Slider.trackColor")); + Line unloaded = getTrack(false); + g.drawLine(unloaded.x1, unloaded.y1, unloaded.x2, unloaded.y2); + + g.setColor(slider.getForeground()); + Line loaded = getTrack(true); + g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + } + + private Line getTrack(boolean loaded) { + if (slider.getOrientation() == JSlider.HORIZONTAL) { + Line left = + new Line( + trackRect.x, + thumbRect.y + thumbRect.height / 2, + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2); + Line right = + new Line( + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2, + trackRect.x + trackRect.width, + thumbRect.y + thumbRect.height / 2); + + if (loaded) { + return slider.getInverted() ? right : left; + } else { + return slider.getInverted() ? left : right; + } + } else { + Line top = + new Line( + thumbRect.x + thumbRect.width / 2, + trackRect.y, + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2); + Line bottom = + new Line( + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2, + thumbRect.x + thumbRect.width / 2, + trackRect.y + trackRect.height); + + if (loaded) { + return slider.getInverted() ? top : bottom; + } else { + return slider.getInverted() ? bottom : top; + } } + } - @Override - public void paintFocus(Graphics g) { + @Override + public void paintFocus(Graphics g) {} - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - private static class Line { + private static class Line { - int x1, y1, x2, y2; + int x1, y1, x2, y2; - Line(int x1, int y1, int x2, int y2) { - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - } + Line(int x1, int y1, int x2, int y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java index 0a74c9d99..71428661a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java @@ -1,7 +1,8 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Component; +import java.awt.Graphics; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; @@ -11,75 +12,71 @@ import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.plaf.basic.BasicSpinnerUI; -import java.awt.Component; -import java.awt.Graphics; public class MaterialSpinnerUI extends BasicSpinnerUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialSpinnerUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialSpinnerUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JSpinner spinner = (JSpinner) c; - spinner.setOpaque(false); - spinner.setFont(UIManager.getFont("Spinner.font")); - spinner.setBackground(UIManager.getColor("Spinner.background")); - spinner.setForeground(UIManager.getColor("Spinner.foreground")); - spinner.setBorder(UIManager.getBorder("Spinner.border")); - } + JSpinner spinner = (JSpinner) c; + spinner.setOpaque(false); + spinner.setFont(UIManager.getFont("Spinner.font")); + spinner.setBackground(UIManager.getColor("Spinner.background")); + spinner.setForeground(UIManager.getColor("Spinner.foreground")); + spinner.setBorder(UIManager.getBorder("Spinner.border")); + } - @Override - protected JComponent createEditor() { - JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) super.createEditor(); - editor.getTextField().setUI(new MaterialTextFieldUI(false)); + @Override + protected JComponent createEditor() { + JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) super.createEditor(); + editor.getTextField().setUI(new MaterialTextFieldUI(false)); - return editor; - } + return editor; + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected Component createNextButton() { - Icon icon = UIManager.getIcon("Spinner.nextButtonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } - else { - button = new BasicArrowButton(SwingConstants.NORTH); - } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); - installNextButtonListeners(button); - - return button; + @Override + protected Component createNextButton() { + Icon icon = UIManager.getIcon("Spinner.nextButtonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.NORTH); } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); + installNextButtonListeners(button); - @Override - protected Component createPreviousButton() { - Icon icon = UIManager.getIcon("Spinner.previousButtonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } - else { - button = new BasicArrowButton(SwingConstants.SOUTH); - } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); - installPreviousButtonListeners(button); + return button; + } - return button; + @Override + protected Component createPreviousButton() { + Icon icon = UIManager.getIcon("Spinner.previousButtonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.SOUTH); } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); + installPreviousButtonListeners(button); + + return button; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java index 23d798644..c33ea201a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java @@ -4,20 +4,20 @@ import javax.swing.plaf.basic.BasicSplitPaneUI; public class MaterialSplitPaneDivider extends BasicSplitPaneDivider { - public MaterialSplitPaneDivider(BasicSplitPaneUI ui) { - super(ui); -// oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, -// "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); -// oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, -// "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); -// centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), -// ui, "SplitPane.centerOneTouchButtons", true); -// setLayout(new DividerLayout()); -// setBasicSplitPaneUI(ui); -// orientation = splitPane.getOrientation(); -// setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? -// Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : -// Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); -// setBackground(UIManager.getColor("SplitPane.background")); - } + public MaterialSplitPaneDivider(BasicSplitPaneUI ui) { + super(ui); + // oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, + // "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); + // oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, + // "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); + // centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), + // ui, "SplitPane.centerOneTouchButtons", true); + // setLayout(new DividerLayout()); + // setBasicSplitPaneUI(ui); + // orientation = splitPane.getOrientation(); + // setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? + // Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : + // Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); + // setBackground(UIManager.getColor("SplitPane.background")); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java index 90bd79b5e..d95f3f766 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java @@ -4,24 +4,24 @@ import javax.swing.plaf.basic.BasicSplitPaneUI; public class MaterialSplitPaneUI extends BasicSplitPaneUI { - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JSplitPane splitPane = (JSplitPane) c; - splitPane.setOpaque(false); - splitPane.setBorder(UIManager.getBorder("SplitPane.border")); - splitPane.setBackground(UIManager.getColor("SplitPane.background")); - splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); - } + JSplitPane splitPane = (JSplitPane) c; + splitPane.setOpaque(false); + splitPane.setBorder(UIManager.getBorder("SplitPane.border")); + splitPane.setBackground(UIManager.getColor("SplitPane.background")); + splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); + } -// /** -// * Creates the default divider. -// * -// * @return the default divider -// */ -// @Override -// public BasicSplitPaneDivider createDefaultDivider() { -// return new MaterialSplitPaneDivider(this); -// } + // /** + // * Creates the default divider. + // * + // * @return the default divider + // */ + // @Override + // public BasicSplitPaneDivider createDefaultDivider() { + // return new MaterialSplitPaneDivider(this); + // } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java index 0441cca35..bcc6d68f4 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java @@ -1,62 +1,82 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; +import java.awt.Rectangle; import javax.swing.JComponent; import javax.swing.JTabbedPane; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicTabbedPaneUI; -import java.awt.Graphics; -import java.awt.Rectangle; public class MaterialTabbedPaneUI extends BasicTabbedPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTabbedPaneUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTabbedPane tabbedPane = (JTabbedPane) c; - tabbedPane.setOpaque(false); - tabbedPane.setFont(UIManager.getFont("TabbedPane.font")); - tabbedPane.setBackground(UIManager.getColor("TabbedPane.background")); - tabbedPane.setForeground(UIManager.getColor("TabbedPane.foreground")); - tabbedPane.setBorder(UIManager.getBorder("TabbedPane.border")); - - darkShadow = UIManager.getColor("TabbedPane.darkShadow"); - shadow = UIManager.getColor("TabbedPane.shadow"); - lightHighlight = UIManager.getColor("TabbedPane.highlight"); - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } - - @Override - protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { - g.setColor(isSelected ? lightHighlight : tabPane.getBackground()); - g.fillRect(x, y, w, h); - } - - @Override - protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { - g.setColor(UIManager.getColor("TabbedPane.borderHighlightColor")); - g.drawRect(x, y, w, h); - } - - @Override - protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { - // do nothing - } - - @Override - protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) { - // for some reason tabs aren't painted properly by paint() - super.paintTab(MaterialDrawingUtils.getAliasedGraphics(g), tabPlacement, rects, tabIndex, iconRect, textRect); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTabbedPaneUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTabbedPane tabbedPane = (JTabbedPane) c; + tabbedPane.setOpaque(false); + tabbedPane.setFont(UIManager.getFont("TabbedPane.font")); + tabbedPane.setBackground(UIManager.getColor("TabbedPane.background")); + tabbedPane.setForeground(UIManager.getColor("TabbedPane.foreground")); + tabbedPane.setBorder(UIManager.getBorder("TabbedPane.border")); + + darkShadow = UIManager.getColor("TabbedPane.darkShadow"); + shadow = UIManager.getColor("TabbedPane.shadow"); + lightHighlight = UIManager.getColor("TabbedPane.highlight"); + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } + + @Override + protected void paintTabBackground( + Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { + g.setColor(isSelected ? lightHighlight : tabPane.getBackground()); + g.fillRect(x, y, w, h); + } + + @Override + protected void paintTabBorder( + Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { + g.setColor(UIManager.getColor("TabbedPane.borderHighlightColor")); + g.drawRect(x, y, w, h); + } + + @Override + protected void paintFocusIndicator( + Graphics g, + int tabPlacement, + Rectangle[] rects, + int tabIndex, + Rectangle iconRect, + Rectangle textRect, + boolean isSelected) { + // do nothing + } + + @Override + protected void paintTab( + Graphics g, + int tabPlacement, + Rectangle[] rects, + int tabIndex, + Rectangle iconRect, + Rectangle textRect) { + // for some reason tabs aren't painted properly by paint() + super.paintTab( + MaterialDrawingUtils.getAliasedGraphics(g), + tabPlacement, + rects, + tabIndex, + iconRect, + textRect); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java index 329102fbe..3f8cdc80b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java @@ -1,28 +1,31 @@ package edu.rpi.legup.ui.lookandfeel.components; +import java.awt.Component; import javax.swing.DefaultCellEditor; import javax.swing.JTable; import javax.swing.JTextField; -import java.awt.Component; public class MaterialTableCellEditor extends DefaultCellEditor { - public MaterialTableCellEditor() { - super(init()); - } + public MaterialTableCellEditor() { + super(init()); + } - private static JTextField init() { - JTextField textField = new JTextField(); - textField.setUI(new MaterialTextFieldUI(false)); + private static JTextField init() { + JTextField textField = new JTextField(); + textField.setUI(new MaterialTextFieldUI(false)); - return textField; - } + return textField; + } - @Override - public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { - JTextField textField = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, rowIndex, vColIndex); - textField.setText(value.toString()); + @Override + public Component getTableCellEditorComponent( + JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { + JTextField textField = + (JTextField) + super.getTableCellEditorComponent(table, value, isSelected, rowIndex, vColIndex); + textField.setText(value.toString()); - return textField; - } + return textField; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java index 86c76e005..2dd33246a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java @@ -1,24 +1,27 @@ package edu.rpi.legup.ui.lookandfeel.components; +import java.awt.Component; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Component; public class MaterialTableCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - JComponent component = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JComponent component = + (JComponent) + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - // hides yellow selection highlight - component.setBorder(BorderFactory.createEmptyBorder()); + // hides yellow selection highlight + component.setBorder(BorderFactory.createEmptyBorder()); - this.setHorizontalAlignment(SwingConstants.CENTER); - this.setVerticalAlignment(SwingConstants.CENTER); + this.setHorizontalAlignment(SwingConstants.CENTER); + this.setVerticalAlignment(SwingConstants.CENTER); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java index 2cdfb0fa9..458b8062a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java @@ -1,24 +1,27 @@ package edu.rpi.legup.ui.lookandfeel.components; +import java.awt.Component; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Component; public class MaterialTableHeaderCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - JComponent component = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - component.setBorder(UIManager.getBorder("TableHeader.cellBorder")); - component.setFont(UIManager.getFont("TableHeader.font")); - component.setBackground(UIManager.getColor("TableHeader.background")); + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JComponent component = + (JComponent) + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + component.setBorder(UIManager.getBorder("TableHeader.cellBorder")); + component.setFont(UIManager.getFont("TableHeader.font")); + component.setBackground(UIManager.getColor("TableHeader.background")); - this.setHorizontalAlignment(SwingConstants.CENTER); - this.setVerticalAlignment(SwingConstants.CENTER); + this.setHorizontalAlignment(SwingConstants.CENTER); + this.setVerticalAlignment(SwingConstants.CENTER); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java index 82144615b..e039aba97 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java @@ -1,29 +1,28 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicTableHeaderUI; import javax.swing.table.JTableHeader; -import java.awt.Graphics; public class MaterialTableHeaderUI extends BasicTableHeaderUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTableHeaderUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTableHeaderUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JTableHeader header = (JTableHeader) c; - header.setDefaultRenderer(new MaterialTableHeaderCellRenderer()); - } + JTableHeader header = (JTableHeader) c; + header.setDefaultRenderer(new MaterialTableHeaderCellRenderer()); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java index dc0b82a34..af3d7fbc5 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java @@ -1,48 +1,46 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicTableUI; -import java.awt.Graphics; public class MaterialTableUI extends BasicTableUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTableUI(); + public static ComponentUI createUI(JComponent c) { + return new MaterialTableUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTable table = (JTable) c; + table.setOpaque(false); + table.setSelectionForeground(UIManager.getColor("Table.selectionForeground")); + table.setBackground(UIManager.getColor("Table.background")); + table.setFont(UIManager.getFont("Table.font")); + table.setBorder(UIManager.getBorder("Table.border")); + table.setGridColor(UIManager.getColor("Table.gridColor")); + table.setSelectionBackground(UIManager.getColor("Table.selectionBackground")); + + table.getTableHeader().setResizingAllowed(true); + int rowHeight = UIManager.getInt("Table.rowHeight"); + if (rowHeight > 0) { + table.setRowHeight(rowHeight); + } else { + table.setRowHeight(table.getRowHeight() + 25); } - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTable table = (JTable) c; - table.setOpaque(false); - table.setSelectionForeground(UIManager.getColor("Table.selectionForeground")); - table.setBackground(UIManager.getColor("Table.background")); - table.setFont(UIManager.getFont("Table.font")); - table.setBorder(UIManager.getBorder("Table.border")); - table.setGridColor(UIManager.getColor("Table.gridColor")); - table.setSelectionBackground(UIManager.getColor("Table.selectionBackground")); - - table.getTableHeader().setResizingAllowed(true); - int rowHeight = UIManager.getInt("Table.rowHeight"); - if (rowHeight > 0) { - table.setRowHeight(rowHeight); - } - else { - table.setRowHeight(table.getRowHeight() + 25); - } - - table.setDefaultRenderer(Object.class, new MaterialTableCellRenderer()); - table.setDefaultEditor(Object.class, new MaterialTableCellEditor()); - } + table.setDefaultRenderer(Object.class, new MaterialTableCellRenderer()); + table.setDefaultEditor(Object.class, new MaterialTableCellEditor()); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java index 019c4b047..002d3a0be 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java @@ -3,15 +3,6 @@ import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialColors; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialFonts; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.plaf.ComponentUI; -import javax.swing.plaf.basic.BasicTextFieldUI; import java.awt.Color; import java.awt.Graphics; import java.awt.Toolkit; @@ -21,175 +12,198 @@ import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.BorderFactory; +import javax.swing.JComponent; +import javax.swing.JTextField; +import javax.swing.KeyStroke; +import javax.swing.plaf.ComponentUI; +import javax.swing.plaf.basic.BasicTextFieldUI; - -public class MaterialTextFieldUI extends BasicTextFieldUI implements FocusListener, PropertyChangeListener { - - private Color focusedBackground; - private Color unfocusedBackground; - private Color focusedSelectionBackground; - private Color unfocusedSelectionBackground; - private boolean drawLine; - - public MaterialTextFieldUI() { - this(true); - } - - public MaterialTextFieldUI(boolean drawLine) { - super(); - this.drawLine = drawLine; - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialTextFieldUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTextField textField = (JTextField) c; - textField.setOpaque(false); - textField.setBorder(drawLine ? - BorderFactory.createEmptyBorder(5, 2, 10, 0) : - BorderFactory.createEmptyBorder(2, 2, 2, 2)); - - textField.setBackground(MaterialColors.LIGHT_BLUE_400); - textField.setFont(MaterialFonts.REGULAR); - - this.focusedBackground = textField.getBackground(); - this.unfocusedBackground = MaterialColors.GRAY_200; - - this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); - this.unfocusedSelectionBackground = unfocusedBackground; - } - - @Override - protected void installListeners() { - super.installListeners(); - getComponent().addFocusListener(this); - getComponent().addPropertyChangeListener(this); - } - - @Override - protected void installKeyboardActions() { - super.installKeyboardActions(); - - Action selectAll = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().selectAll(); - } +public class MaterialTextFieldUI extends BasicTextFieldUI + implements FocusListener, PropertyChangeListener { + + private Color focusedBackground; + private Color unfocusedBackground; + private Color focusedSelectionBackground; + private Color unfocusedSelectionBackground; + private boolean drawLine; + + public MaterialTextFieldUI() { + this(true); + } + + public MaterialTextFieldUI(boolean drawLine) { + super(); + this.drawLine = drawLine; + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialTextFieldUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTextField textField = (JTextField) c; + textField.setOpaque(false); + textField.setBorder( + drawLine + ? BorderFactory.createEmptyBorder(5, 2, 10, 0) + : BorderFactory.createEmptyBorder(2, 2, 2, 2)); + + textField.setBackground(MaterialColors.LIGHT_BLUE_400); + textField.setFont(MaterialFonts.REGULAR); + + this.focusedBackground = textField.getBackground(); + this.unfocusedBackground = MaterialColors.GRAY_200; + + this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); + this.unfocusedSelectionBackground = unfocusedBackground; + } + + @Override + protected void installListeners() { + super.installListeners(); + getComponent().addFocusListener(this); + getComponent().addPropertyChangeListener(this); + } + + @Override + protected void installKeyboardActions() { + super.installKeyboardActions(); + + Action selectAll = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().selectAll(); + } }; - Action delete = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (getComponent().getSelectedText() == null) { - int pos = getComponent().getCaretPosition() - 1; - - if (pos >= 0) { - getComponent().select(pos, pos + 1); - getComponent().replaceSelection(""); - } - } - else { - getComponent().replaceSelection(""); - } + Action delete = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (getComponent().getSelectedText() == null) { + int pos = getComponent().getCaretPosition() - 1; + + if (pos >= 0) { + getComponent().select(pos, pos + 1); + getComponent().replaceSelection(""); + } + } else { + getComponent().replaceSelection(""); } + } }; - Action left = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); - } + Action left = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); + } }; - Action right = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().setCaretPosition(Math.min(getComponent().getText().length(), getComponent().getCaretPosition() + 1)); - } + Action right = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.min( + getComponent().getText().length(), getComponent().getCaretPosition() + 1)); + } }; - Action enter = new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - ((JTextField) getComponent()).postActionEvent(); - } + Action enter = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + ((JTextField) getComponent()).postActionEvent(); + } }; - // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to getMenuShortcutKeyMaskEx() - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "selectAll"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); - - getComponent().getActionMap().put("selectAll", selectAll); - getComponent().getActionMap().put("delete", delete); - getComponent().getActionMap().put("left", left); - getComponent().getActionMap().put("right", right); - getComponent().getActionMap().put("enter", enter); + // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to getMenuShortcutKeyMaskEx() + getComponent() + .getInputMap() + .put( + KeyStroke.getKeyStroke( + KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "selectAll"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); + + getComponent().getActionMap().put("selectAll", selectAll); + getComponent().getActionMap().put("delete", delete); + getComponent().getActionMap().put("left", left); + getComponent().getActionMap().put("right", right); + getComponent().getActionMap().put("enter", enter); + } + + @Override + public void paintSafely(Graphics g) { + JTextField c = (JTextField) getComponent(); + g = MaterialDrawingUtils.getAliasedGraphics(g); + + Color lineColor; + + if (getComponent().hasFocus()) { + lineColor = focusedBackground; + c.setSelectionColor(focusedSelectionBackground); + } else { + lineColor = unfocusedBackground; + c.setSelectionColor(unfocusedSelectionBackground); } - @Override - public void paintSafely(Graphics g) { - JTextField c = (JTextField) getComponent(); - g = MaterialDrawingUtils.getAliasedGraphics(g); - - Color lineColor; - - if (getComponent().hasFocus()) { - lineColor = focusedBackground; - c.setSelectionColor(focusedSelectionBackground); - } - else { - lineColor = unfocusedBackground; - c.setSelectionColor(unfocusedSelectionBackground); - } - - g.setColor(lineColor); - getComponent().setBackground(lineColor); + g.setColor(lineColor); + getComponent().setBackground(lineColor); - if (drawLine) { - int x = getComponent().getInsets().left; - int y = getComponent().getInsets().top; - int w = getComponent().getWidth() - getComponent().getInsets().left - getComponent().getInsets().right; + if (drawLine) { + int x = getComponent().getInsets().left; + int y = getComponent().getInsets().top; + int w = + getComponent().getWidth() + - getComponent().getInsets().left + - getComponent().getInsets().right; - g.fillRect(x, c.getHeight() - y, w, 2); - } - - super.paintSafely(g); + g.fillRect(x, c.getHeight() - y, w, 2); } - @Override - public void paintBackground(final Graphics g) { - super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); - } + super.paintSafely(g); + } - @Override - public void focusGained(FocusEvent e) { - e.getComponent().setBackground(focusedBackground); - } + @Override + public void paintBackground(final Graphics g) { + super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); + } - @Override - public void focusLost(FocusEvent e) { - e.getComponent().setBackground(unfocusedBackground); - } + @Override + public void focusGained(FocusEvent e) { + e.getComponent().setBackground(focusedBackground); + } - @Override - public void propertyChange(PropertyChangeEvent pce) { - super.propertyChange(pce); + @Override + public void focusLost(FocusEvent e) { + e.getComponent().setBackground(unfocusedBackground); + } - if (pce.getPropertyName().equals("background")) { - Color newColor = (Color) pce.getNewValue(); + @Override + public void propertyChange(PropertyChangeEvent pce) { + super.propertyChange(pce); - if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { - this.focusedBackground = (Color) pce.getNewValue(); - this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); - } - } + if (pce.getPropertyName().equals("background")) { + Color newColor = (Color) pce.getNewValue(); + + if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { + this.focusedBackground = (Color) pce.getNewValue(); + this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); + } } -} \ No newline at end of file + } +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java index 2adea67b2..61fba8d33 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java @@ -7,15 +7,14 @@ /** * @author https://github.com/vincenzopalazzo */ - public class MaterialTextPaneUI extends BasicTextPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTextPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTextPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java index 928b2e688..42786abba 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java @@ -1,38 +1,37 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JToggleButton; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicToggleButtonUI; -import java.awt.Graphics; public class MaterialToggleButtonUI extends BasicToggleButtonUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToggleButtonUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToggleButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JToggleButton toggleButton = (JToggleButton) c; - toggleButton.setBorder(UIManager.getBorder("ToggleButton.border")); - toggleButton.setFont(UIManager.getFont("ToggleButton.font")); - toggleButton.setBackground(UIManager.getColor("ToggleButton.background")); - toggleButton.setForeground(UIManager.getColor("ToggleButton.foreground")); + JToggleButton toggleButton = (JToggleButton) c; + toggleButton.setBorder(UIManager.getBorder("ToggleButton.border")); + toggleButton.setFont(UIManager.getFont("ToggleButton.font")); + toggleButton.setBackground(UIManager.getColor("ToggleButton.background")); + toggleButton.setForeground(UIManager.getColor("ToggleButton.foreground")); - if (toggleButton.getIcon() == null && toggleButton.getSelectedIcon() == null) { - toggleButton.setIcon(UIManager.getIcon("ToggleButton.icon")); - toggleButton.setSelectedIcon(UIManager.getIcon("ToggleButton.selectedIcon")); - } + if (toggleButton.getIcon() == null && toggleButton.getSelectedIcon() == null) { + toggleButton.setIcon(UIManager.getIcon("ToggleButton.icon")); + toggleButton.setSelectedIcon(UIManager.getIcon("ToggleButton.selectedIcon")); } + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java index d95d52455..58a752c59 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java @@ -1,38 +1,37 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JToolBar; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicToolBarUI; -import java.awt.Graphics; public class MaterialToolBarUI extends BasicToolBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToolBarUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - JToolBar toolBar = (JToolBar) c; - - toolBar.setFont(UIManager.getFont("ToolBar.font")); - toolBar.setBackground(UIManager.getColor("ToolBar.background")); - toolBar.setForeground(UIManager.getColor("ToolBar.foreground")); - toolBar.setBorder(UIManager.getBorder("ToolBar.border")); - - this.dockingBorderColor = null; - this.floatingBorderColor = null; - this.dockingColor = UIManager.getColor("ToolBar.dockingBackground"); - this.floatingColor = UIManager.getColor("ToolBar.floatingBackground"); - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToolBarUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + JToolBar toolBar = (JToolBar) c; + + toolBar.setFont(UIManager.getFont("ToolBar.font")); + toolBar.setBackground(UIManager.getColor("ToolBar.background")); + toolBar.setForeground(UIManager.getColor("ToolBar.foreground")); + toolBar.setBorder(UIManager.getBorder("ToolBar.border")); + + this.dockingBorderColor = null; + this.floatingBorderColor = null; + this.dockingColor = UIManager.getColor("ToolBar.dockingBackground"); + this.floatingColor = UIManager.getColor("ToolBar.floatingBackground"); + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java index adbd78925..2b023c920 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java @@ -1,25 +1,24 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.*; import javax.swing.*; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicToolTipUI; -import java.awt.*; public class MaterialToolTipUI extends BasicToolTipUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToolTipUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToolTipUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java index 6ac2230f4..6565ca731 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java @@ -1,50 +1,53 @@ package edu.rpi.legup.ui.lookandfeel.components; +import java.awt.Component; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellEditor; -import java.awt.Component; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; public class MaterialTreeCellEditor extends DefaultTreeCellEditor { - private JTextField textField; - - public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { - super(tree, renderer); - init(); - } - - public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { - super(tree, renderer, editor); - init(); - } - - private void init() { - textField = new JTextField(); - textField.setUI(new MaterialTextFieldUI()); - - textField.addKeyListener(new KeyAdapter() { - @Override - public void keyTyped(KeyEvent e) { - if (e.getKeyChar() == KeyEvent.VK_ENTER) { - stopCellEditing(); - } + private JTextField textField; + + public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { + super(tree, renderer); + init(); + } + + public MaterialTreeCellEditor( + JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { + super(tree, renderer, editor); + init(); + } + + private void init() { + textField = new JTextField(); + textField.setUI(new MaterialTextFieldUI()); + + textField.addKeyListener( + new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + if (e.getKeyChar() == KeyEvent.VK_ENTER) { + stopCellEditing(); } + } }); - } - - @Override - public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { - textField.setText(value.toString()); - return textField; - } - - @Override - public Object getCellEditorValue() { - return textField.getText(); - } + } + + @Override + public Component getTreeCellEditorComponent( + JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { + textField.setText(value.toString()); + return textField; + } + + @Override + public Object getCellEditorValue() { + return textField.getText(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java index f9ddcbf45..f4e85bba2 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java @@ -1,36 +1,45 @@ package edu.rpi.legup.ui.lookandfeel.components; +import java.awt.Component; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.tree.DefaultTreeCellRenderer; -import java.awt.Component; public class MaterialTreeCellRenderer extends DefaultTreeCellRenderer { - public MaterialTreeCellRenderer() { - setTextSelectionColor(UIManager.getColor("Tree.selectionForeground")); - setTextNonSelectionColor(UIManager.getColor("Tree.foreground")); - - setBackgroundSelectionColor(UIManager.getColor("Tree.selectionBackground")); - setBackgroundNonSelectionColor(UIManager.getColor("Tree.background")); - - setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor")); - - setClosedIcon(UIManager.getIcon("Tree.closedIcon")); - setOpenIcon(UIManager.getIcon("Tree.openIcon")); - setLeafIcon(null); - - - setFont(UIManager.getFont("Tree.font")); - } - - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row, boolean hasFocus) { - JComponent component = (JComponent) super.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, hasFocus); - component.setBorder(BorderFactory.createEmptyBorder(5, 2, 5, 2)); - - return component; - } + public MaterialTreeCellRenderer() { + setTextSelectionColor(UIManager.getColor("Tree.selectionForeground")); + setTextNonSelectionColor(UIManager.getColor("Tree.foreground")); + + setBackgroundSelectionColor(UIManager.getColor("Tree.selectionBackground")); + setBackgroundNonSelectionColor(UIManager.getColor("Tree.background")); + + setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor")); + + setClosedIcon(UIManager.getIcon("Tree.closedIcon")); + setOpenIcon(UIManager.getIcon("Tree.openIcon")); + setLeafIcon(null); + + setFont(UIManager.getFont("Tree.font")); + } + + @Override + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean isSelected, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + JComponent component = + (JComponent) + super.getTreeCellRendererComponent( + tree, value, isSelected, expanded, leaf, row, hasFocus); + component.setBorder(BorderFactory.createEmptyBorder(5, 2, 5, 2)); + + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java index b1b9839bd..f21b0dfaa 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java @@ -1,7 +1,7 @@ package edu.rpi.legup.ui.lookandfeel.components; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialDrawingUtils; - +import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JTree; import javax.swing.UIManager; @@ -9,37 +9,36 @@ import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeCellEditor; -import java.awt.Graphics; public class MaterialTreeUI extends BasicTreeUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTreeUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTreeUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - JTree tree = (JTree) c; + @Override + public void installUI(JComponent c) { + super.installUI(c); + JTree tree = (JTree) c; - DefaultTreeCellRenderer renderer = new MaterialTreeCellRenderer(); - TreeCellEditor editor = new MaterialTreeCellEditor(tree, renderer); + DefaultTreeCellRenderer renderer = new MaterialTreeCellRenderer(); + TreeCellEditor editor = new MaterialTreeCellEditor(tree, renderer); - tree.setCellRenderer(renderer); - tree.setCellEditor(editor); + tree.setCellRenderer(renderer); + tree.setCellEditor(editor); - tree.setFont(UIManager.getFont("Tree.font")); - tree.setRowHeight(0); - tree.setInvokesStopCellEditing(true); + tree.setFont(UIManager.getFont("Tree.font")); + tree.setRowHeight(0); + tree.setInvokesStopCellEditing(true); - MaterialTreeUI ui = (MaterialTreeUI) tree.getUI(); - ui.setLeftChildIndent(10); - ui.setRightChildIndent(10); - } + MaterialTreeUI ui = (MaterialTreeUI) tree.getUI(); + ui.setLeftChildIndent(10); + ui.setRightChildIndent(10); + } - @Override - public void paint(Graphics g, JComponent c) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - super.paint(g, c); - } -} \ No newline at end of file + @Override + public void paint(Graphics g, JComponent c) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + super.paint(g, c); + } +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java index 2543b8664..61eb3c433 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java @@ -1,8 +1,5 @@ package edu.rpi.legup.ui.lookandfeel.materialdesign; -import javax.swing.UIManager; -import javax.swing.border.AbstractBorder; -import javax.swing.border.Border; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; @@ -18,333 +15,403 @@ import java.awt.image.Kernel; import java.util.HashMap; import java.util.Map; +import javax.swing.UIManager; +import javax.swing.border.AbstractBorder; +import javax.swing.border.Border; /** - * Implements a DropShadow for components. In general, the mdlaf.shadows.DropShadowBorder will - * work with any rectangular components that do not have a default border installed - * as part of the look and feel, or otherwise. For example, mdlaf.shadows.DropShadowBorder works - * wonderfully with JPanel, but horribly with JComboBox. + * Implements a DropShadow for components. In general, the mdlaf.shadows.DropShadowBorder will work + * with any rectangular components that do not have a default border installed as part of the look + * and feel, or otherwise. For example, mdlaf.shadows.DropShadowBorder works wonderfully with + * JPanel, but horribly with JComboBox. * * @author rbair */ public class DropShadowBorder extends AbstractBorder implements Border { - private static final Map> CACHE - = new HashMap>(); - private Color lineColor; - private int lineWidth; - private int shadowSize; - private float shadowOpacity; - private int cornerSize; - private boolean showTopShadow; - private boolean showLeftShadow; - private boolean showBottomShadow; - private boolean showRightShadow; - - public DropShadowBorder() { - this(UIManager.getColor("Control"), 1, 5); - } - - public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) { - this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true); - } - - public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) { - this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true); - } - - public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize, - float shadowOpacity, int cornerSize, boolean showTopShadow, - boolean showLeftShadow, boolean showBottomShadow, boolean showRightShadow) { - this.lineColor = lineColor; - this.lineWidth = lineWidth; - this.shadowSize = shadowSize; - this.shadowOpacity = shadowOpacity; - this.cornerSize = cornerSize; - this.showTopShadow = showTopShadow; - this.showLeftShadow = showLeftShadow; - this.showBottomShadow = showBottomShadow; - this.showRightShadow = showRightShadow; - } - - /** - * + private static final Map> CACHE = + new HashMap>(); + private Color lineColor; + private int lineWidth; + private int shadowSize; + private float shadowOpacity; + private int cornerSize; + private boolean showTopShadow; + private boolean showLeftShadow; + private boolean showBottomShadow; + private boolean showRightShadow; + + public DropShadowBorder() { + this(UIManager.getColor("Control"), 1, 5); + } + + public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) { + this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true); + } + + public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) { + this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true); + } + + public DropShadowBorder( + Color lineColor, + int lineWidth, + int shadowSize, + float shadowOpacity, + int cornerSize, + boolean showTopShadow, + boolean showLeftShadow, + boolean showBottomShadow, + boolean showRightShadow) { + this.lineColor = lineColor; + this.lineWidth = lineWidth; + this.shadowSize = shadowSize; + this.shadowOpacity = shadowOpacity; + this.cornerSize = cornerSize; + this.showTopShadow = showTopShadow; + this.showLeftShadow = showLeftShadow; + this.showBottomShadow = showBottomShadow; + this.showRightShadow = showRightShadow; + } + + /** */ + public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { + /* + * 1) Get images for this border + * 2) Paint the images for each side of the border that should be painted */ - public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { - /* - * 1) Get images for this border - * 2) Paint the images for each side of the border that should be painted - */ - Map images = getImages(null); - - //compute the edges of the components -- not including the border - //Insets borderInsets = getBorderInsets (c); - // int leftEdge = x + borderInsets.left - lineWidth; - // int rightEdge = x + width - borderInsets.right; - // int topEdge = y + borderInsets.top - lineWidth; - // int bottomEdge = y + height - borderInsets.bottom; - Graphics2D g2 = (Graphics2D) graphics; - g2.setColor(lineColor); - - //The location and size of the shadows depends on which shadows are being - //drawn. For instance, if the left & bottom shadows are being drawn, then - //the left shadows extends all the way down to the corner, a corner is drawn, - //and then the bottom shadows begins at the corner. If, however, only the - //bottom shadows is drawn, then the bottom-left corner is drawn to the - //right of the corner, and the bottom shadows is somewhat shorter than before. - - Point topLeftShadowPoint = null; - if (showLeftShadow || showTopShadow) { - topLeftShadowPoint = new Point(); - if (showLeftShadow && !showTopShadow) { - topLeftShadowPoint.setLocation(x, y + shadowSize); - } - else { - if (showLeftShadow && showTopShadow) { - topLeftShadowPoint.setLocation(x, y); - } - else { - if (!showLeftShadow && showTopShadow) { - topLeftShadowPoint.setLocation(x + shadowSize, y); - } - } - } - } - - Point bottomLeftShadowPoint = null; - if (showLeftShadow || showBottomShadow) { - bottomLeftShadowPoint = new Point(); - if (showLeftShadow && !showBottomShadow) { - bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); - } - else { - if (showLeftShadow && showBottomShadow) { - bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); - } - else { - if (!showLeftShadow && showBottomShadow) { - bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); - } - } - } - } - - Point bottomRightShadowPoint = null; - if (showRightShadow || showBottomShadow) { - bottomRightShadowPoint = new Point(); - if (showRightShadow && !showBottomShadow) { - bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize - shadowSize); - } - else { - if (showRightShadow && showBottomShadow) { - bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); - } - else { - if (!showRightShadow && showBottomShadow) { - bottomRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y + height - shadowSize); - } - } - } - } - - Point topRightShadowPoint = null; - if (showRightShadow || showTopShadow) { - topRightShadowPoint = new Point(); - if (showRightShadow && !showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize); - } - else { - if (showRightShadow && showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize, y); - } - else { - if (!showRightShadow && showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); - } - } - } - } - - if (showLeftShadow) { - Rectangle leftShadowRect = new Rectangle(x, (int) (topLeftShadowPoint.getY() + shadowSize), shadowSize, (int) (bottomLeftShadowPoint.getY() - topLeftShadowPoint.getY() - shadowSize)); - g2.drawImage(images.get(Position.LEFT).getScaledInstance(leftShadowRect.width, leftShadowRect.height, Image.SCALE_FAST), leftShadowRect.x, leftShadowRect.y, null); - } - - if (showBottomShadow) { - Rectangle bottomShadowRect = new Rectangle((int) (bottomLeftShadowPoint.getX() + shadowSize), y + height - shadowSize, (int) (bottomRightShadowPoint.getX() - bottomLeftShadowPoint.getX() - shadowSize), shadowSize); - g2.drawImage(images.get(Position.BOTTOM).getScaledInstance(bottomShadowRect.width, bottomShadowRect.height, Image.SCALE_FAST), bottomShadowRect.x, bottomShadowRect.y, null); - } - - if (showRightShadow) { - Rectangle rightShadowRect = new Rectangle(x + width - shadowSize, (int) (topRightShadowPoint.getY() + shadowSize), shadowSize, (int) (bottomRightShadowPoint.getY() - topRightShadowPoint.getY() - shadowSize)); - g2.drawImage(images.get(Position.RIGHT).getScaledInstance(rightShadowRect.width, rightShadowRect.height, Image.SCALE_FAST), rightShadowRect.x, rightShadowRect.y, null); - } - - if (showTopShadow) { - Rectangle topShadowRect = new Rectangle((int) topLeftShadowPoint.getX() + shadowSize, y, (int) (topRightShadowPoint.getX() - topLeftShadowPoint.getX() - shadowSize), shadowSize); - g2.drawImage(images.get(Position.TOP).getScaledInstance(topShadowRect.width, topShadowRect.height, Image.SCALE_FAST), topShadowRect.x, topShadowRect.y, null); - } - - if (showLeftShadow || showTopShadow) { - g2.drawImage(images.get(Position.TOP_LEFT), null, (int) topLeftShadowPoint.getX(), (int) topLeftShadowPoint.getY()); - } - if (showLeftShadow || showBottomShadow) { - g2.drawImage(images.get(Position.BOTTOM_LEFT), null, (int) bottomLeftShadowPoint.getX(), (int) bottomLeftShadowPoint.getY()); - } - if (showRightShadow || showBottomShadow) { - g2.drawImage(images.get(Position.BOTTOM_RIGHT), null, (int) bottomRightShadowPoint.getX(), (int) bottomRightShadowPoint.getY()); - } - if (showRightShadow || showTopShadow) { - g2.drawImage(images.get(Position.TOP_RIGHT), null, (int) topRightShadowPoint.getX(), (int) topRightShadowPoint.getY()); + Map images = getImages(null); + + // compute the edges of the components -- not including the border + // Insets borderInsets = getBorderInsets (c); + // int leftEdge = x + borderInsets.left - lineWidth; + // int rightEdge = x + width - borderInsets.right; + // int topEdge = y + borderInsets.top - lineWidth; + // int bottomEdge = y + height - borderInsets.bottom; + Graphics2D g2 = (Graphics2D) graphics; + g2.setColor(lineColor); + + // The location and size of the shadows depends on which shadows are being + // drawn. For instance, if the left & bottom shadows are being drawn, then + // the left shadows extends all the way down to the corner, a corner is drawn, + // and then the bottom shadows begins at the corner. If, however, only the + // bottom shadows is drawn, then the bottom-left corner is drawn to the + // right of the corner, and the bottom shadows is somewhat shorter than before. + + Point topLeftShadowPoint = null; + if (showLeftShadow || showTopShadow) { + topLeftShadowPoint = new Point(); + if (showLeftShadow && !showTopShadow) { + topLeftShadowPoint.setLocation(x, y + shadowSize); + } else { + if (showLeftShadow && showTopShadow) { + topLeftShadowPoint.setLocation(x, y); + } else { + if (!showLeftShadow && showTopShadow) { + topLeftShadowPoint.setLocation(x + shadowSize, y); + } } + } } - private Map getImages(Graphics2D g2) { - //first, check to see if an image for this size has already been rendered - //if so, use the cache. Else, draw and save - Map images = CACHE.get(shadowSize); - if (images == null) { - images = new HashMap(); - - /* - * Do draw a drop shadows, I have to: - * 1) Create a rounded rectangle - * 2) Create a BufferedImage to draw the rounded rect in - * 3) Translate the graphics for the image, so that the rectangle - * is centered in the drawn space. The border around the rectangle - * needs to be shadowWidth wide, so that there is space for the - * shadows to be drawn. - * 4) Draw the rounded rect as black, with an opacity of 50% - * 5) Create the BLUR_KERNEL - * 6) Blur the image - * 7) copy off the corners, sides, etc into images to be used for - * drawing the Border - */ - int rectWidth = cornerSize + 1; - RoundRectangle2D rect = new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); - int imageWidth = rectWidth + shadowSize * 2; - BufferedImage image = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); - Graphics2D buffer = (Graphics2D) image.getGraphics(); - buffer.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - buffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - buffer.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - buffer.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); - buffer.translate(shadowSize, shadowSize); - buffer.fill(rect); - float blurry = 1.0f / (float) (shadowSize * shadowSize);//1.0f / (float)(shadowSize * shadowSize); - float[] blurKernel = new float[shadowSize * shadowSize]; - for (int i = 0; i < blurKernel.length; i++) { - blurKernel[i] = blurry; - } - ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); - BufferedImage targetImage = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); - ((Graphics2D) targetImage.getGraphics()).drawImage(image, blur, -(shadowSize / 2), -(shadowSize / 2)); - - int x = 1; - int y = 1; - int w = shadowSize; - int h = shadowSize; - images.put(Position.TOP_LEFT, targetImage.getSubimage(x, y, w, h)); - x = 1; - y = h; - w = shadowSize; - h = 1; - images.put(Position.LEFT, targetImage.getSubimage(x, y, w, h)); - x = 1; - y = rectWidth; - w = shadowSize; - h = shadowSize; - images.put(Position.BOTTOM_LEFT, targetImage.getSubimage(x, y, w, h)); - x = cornerSize + 1; - y = rectWidth; - w = 1; - h = shadowSize; - images.put(Position.BOTTOM, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = x; - w = shadowSize; - h = shadowSize; - images.put(Position.BOTTOM_RIGHT, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = cornerSize + 1; - w = shadowSize; - h = 1; - images.put(Position.RIGHT, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = 1; - w = shadowSize; - h = shadowSize; - images.put(Position.TOP_RIGHT, targetImage.getSubimage(x, y, w, h)); - x = shadowSize; - y = 1; - w = 1; - h = shadowSize; - images.put(Position.TOP, targetImage.getSubimage(x, y, w, h)); - - buffer.dispose(); - image.flush(); + Point bottomLeftShadowPoint = null; + if (showLeftShadow || showBottomShadow) { + bottomLeftShadowPoint = new Point(); + if (showLeftShadow && !showBottomShadow) { + bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); + } else { + if (showLeftShadow && showBottomShadow) { + bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); + } else { + if (!showLeftShadow && showBottomShadow) { + bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); + } } - return images; + } } - /** - * - */ - public Insets getBorderInsets(Component c) { - int top = 4 + (showTopShadow ? lineWidth + shadowSize : lineWidth); - int left = 4 + (showLeftShadow ? lineWidth + shadowSize : lineWidth); - int bottom = 4 + (showBottomShadow ? lineWidth + shadowSize : lineWidth); - int right = 4 + (showRightShadow ? lineWidth + shadowSize : lineWidth); - - return new Insets(top, left, bottom, right); - } - - /** - * - */ - public boolean isBorderOpaque() { - return true; + Point bottomRightShadowPoint = null; + if (showRightShadow || showBottomShadow) { + bottomRightShadowPoint = new Point(); + if (showRightShadow && !showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize, y + height - shadowSize - shadowSize); + } else { + if (showRightShadow && showBottomShadow) { + bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); + } else { + if (!showRightShadow && showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize - shadowSize, y + height - shadowSize); + } + } + } } - public boolean isShowTopShadow() { - return showTopShadow; + Point topRightShadowPoint = null; + if (showRightShadow || showTopShadow) { + topRightShadowPoint = new Point(); + if (showRightShadow && !showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize); + } else { + if (showRightShadow && showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize, y); + } else { + if (!showRightShadow && showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); + } + } + } } - public boolean isShowLeftShadow() { - return showLeftShadow; + if (showLeftShadow) { + Rectangle leftShadowRect = + new Rectangle( + x, + (int) (topLeftShadowPoint.getY() + shadowSize), + shadowSize, + (int) (bottomLeftShadowPoint.getY() - topLeftShadowPoint.getY() - shadowSize)); + g2.drawImage( + images + .get(Position.LEFT) + .getScaledInstance(leftShadowRect.width, leftShadowRect.height, Image.SCALE_FAST), + leftShadowRect.x, + leftShadowRect.y, + null); } - public boolean isShowRightShadow() { - return showRightShadow; + if (showBottomShadow) { + Rectangle bottomShadowRect = + new Rectangle( + (int) (bottomLeftShadowPoint.getX() + shadowSize), + y + height - shadowSize, + (int) (bottomRightShadowPoint.getX() - bottomLeftShadowPoint.getX() - shadowSize), + shadowSize); + g2.drawImage( + images + .get(Position.BOTTOM) + .getScaledInstance(bottomShadowRect.width, bottomShadowRect.height, Image.SCALE_FAST), + bottomShadowRect.x, + bottomShadowRect.y, + null); } - public boolean isShowBottomShadow() { - return showBottomShadow; + if (showRightShadow) { + Rectangle rightShadowRect = + new Rectangle( + x + width - shadowSize, + (int) (topRightShadowPoint.getY() + shadowSize), + shadowSize, + (int) (bottomRightShadowPoint.getY() - topRightShadowPoint.getY() - shadowSize)); + g2.drawImage( + images + .get(Position.RIGHT) + .getScaledInstance(rightShadowRect.width, rightShadowRect.height, Image.SCALE_FAST), + rightShadowRect.x, + rightShadowRect.y, + null); } - public int getLineWidth() { - return lineWidth; + if (showTopShadow) { + Rectangle topShadowRect = + new Rectangle( + (int) topLeftShadowPoint.getX() + shadowSize, + y, + (int) (topRightShadowPoint.getX() - topLeftShadowPoint.getX() - shadowSize), + shadowSize); + g2.drawImage( + images + .get(Position.TOP) + .getScaledInstance(topShadowRect.width, topShadowRect.height, Image.SCALE_FAST), + topShadowRect.x, + topShadowRect.y, + null); } - public Color getLineColor() { - return lineColor; + if (showLeftShadow || showTopShadow) { + g2.drawImage( + images.get(Position.TOP_LEFT), + null, + (int) topLeftShadowPoint.getX(), + (int) topLeftShadowPoint.getY()); } - - public int getShadowSize() { - return shadowSize; + if (showLeftShadow || showBottomShadow) { + g2.drawImage( + images.get(Position.BOTTOM_LEFT), + null, + (int) bottomLeftShadowPoint.getX(), + (int) bottomLeftShadowPoint.getY()); } - - public float getShadowOpacity() { - return shadowOpacity; + if (showRightShadow || showBottomShadow) { + g2.drawImage( + images.get(Position.BOTTOM_RIGHT), + null, + (int) bottomRightShadowPoint.getX(), + (int) bottomRightShadowPoint.getY()); } - - public int getCornerSize() { - return cornerSize; + if (showRightShadow || showTopShadow) { + g2.drawImage( + images.get(Position.TOP_RIGHT), + null, + (int) topRightShadowPoint.getX(), + (int) topRightShadowPoint.getY()); } - - private enum Position { - TOP, TOP_LEFT, LEFT, BOTTOM_LEFT, - BOTTOM, BOTTOM_RIGHT, RIGHT, TOP_RIGHT + } + + private Map getImages(Graphics2D g2) { + // first, check to see if an image for this size has already been rendered + // if so, use the cache. Else, draw and save + Map images = CACHE.get(shadowSize); + if (images == null) { + images = new HashMap(); + + /* + * Do draw a drop shadows, I have to: + * 1) Create a rounded rectangle + * 2) Create a BufferedImage to draw the rounded rect in + * 3) Translate the graphics for the image, so that the rectangle + * is centered in the drawn space. The border around the rectangle + * needs to be shadowWidth wide, so that there is space for the + * shadows to be drawn. + * 4) Draw the rounded rect as black, with an opacity of 50% + * 5) Create the BLUR_KERNEL + * 6) Blur the image + * 7) copy off the corners, sides, etc into images to be used for + * drawing the Border + */ + int rectWidth = cornerSize + 1; + RoundRectangle2D rect = + new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); + int imageWidth = rectWidth + shadowSize * 2; + BufferedImage image = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); + Graphics2D buffer = (Graphics2D) image.getGraphics(); + buffer.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + buffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + buffer.setRenderingHint( + RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + buffer.setRenderingHint( + RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); + buffer.translate(shadowSize, shadowSize); + buffer.fill(rect); + float blurry = + 1.0f / (float) (shadowSize * shadowSize); // 1.0f / (float)(shadowSize * shadowSize); + float[] blurKernel = new float[shadowSize * shadowSize]; + for (int i = 0; i < blurKernel.length; i++) { + blurKernel[i] = blurry; + } + ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); + BufferedImage targetImage = + new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); + ((Graphics2D) targetImage.getGraphics()) + .drawImage(image, blur, -(shadowSize / 2), -(shadowSize / 2)); + + int x = 1; + int y = 1; + int w = shadowSize; + int h = shadowSize; + images.put(Position.TOP_LEFT, targetImage.getSubimage(x, y, w, h)); + x = 1; + y = h; + w = shadowSize; + h = 1; + images.put(Position.LEFT, targetImage.getSubimage(x, y, w, h)); + x = 1; + y = rectWidth; + w = shadowSize; + h = shadowSize; + images.put(Position.BOTTOM_LEFT, targetImage.getSubimage(x, y, w, h)); + x = cornerSize + 1; + y = rectWidth; + w = 1; + h = shadowSize; + images.put(Position.BOTTOM, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = x; + w = shadowSize; + h = shadowSize; + images.put(Position.BOTTOM_RIGHT, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = cornerSize + 1; + w = shadowSize; + h = 1; + images.put(Position.RIGHT, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = 1; + w = shadowSize; + h = shadowSize; + images.put(Position.TOP_RIGHT, targetImage.getSubimage(x, y, w, h)); + x = shadowSize; + y = 1; + w = 1; + h = shadowSize; + images.put(Position.TOP, targetImage.getSubimage(x, y, w, h)); + + buffer.dispose(); + image.flush(); } -} \ No newline at end of file + return images; + } + + /** */ + public Insets getBorderInsets(Component c) { + int top = 4 + (showTopShadow ? lineWidth + shadowSize : lineWidth); + int left = 4 + (showLeftShadow ? lineWidth + shadowSize : lineWidth); + int bottom = 4 + (showBottomShadow ? lineWidth + shadowSize : lineWidth); + int right = 4 + (showRightShadow ? lineWidth + shadowSize : lineWidth); + + return new Insets(top, left, bottom, right); + } + + /** */ + public boolean isBorderOpaque() { + return true; + } + + public boolean isShowTopShadow() { + return showTopShadow; + } + + public boolean isShowLeftShadow() { + return showLeftShadow; + } + + public boolean isShowRightShadow() { + return showRightShadow; + } + + public boolean isShowBottomShadow() { + return showBottomShadow; + } + + public int getLineWidth() { + return lineWidth; + } + + public Color getLineColor() { + return lineColor; + } + + public int getShadowSize() { + return shadowSize; + } + + public float getShadowOpacity() { + return shadowOpacity; + } + + public int getCornerSize() { + return cornerSize; + } + + private enum Position { + TOP, + TOP_LEFT, + LEFT, + BOTTOM_LEFT, + BOTTOM, + BOTTOM_RIGHT, + RIGHT, + TOP_RIGHT + } +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java index c78d20e34..049ce78af 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java @@ -1,17 +1,20 @@ package edu.rpi.legup.ui.lookandfeel.materialdesign; +import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.border.Border; -import java.awt.Color; public class MaterialBorders { - public static final Border LIGHT_LINE_BORDER = BorderFactory.createLineBorder(MaterialColors.GRAY_200, 1); - public static final Border THICK_LINE_BORDER = BorderFactory.createLineBorder(MaterialColors.GRAY_200, 2); + public static final Border LIGHT_LINE_BORDER = + BorderFactory.createLineBorder(MaterialColors.GRAY_200, 1); + public static final Border THICK_LINE_BORDER = + BorderFactory.createLineBorder(MaterialColors.GRAY_200, 2); - public static final Border LIGHT_SHADOW_BORDER = new DropShadowBorder(Color.BLACK, 0, 4, 0.3f, 12, true, true, true, true); - public static final Border DEFAULT_SHADOW_BORDER = new DropShadowBorder(Color.BLACK, 5, 5, 0.3f, 12, true, true, true, true); + public static final Border LIGHT_SHADOW_BORDER = + new DropShadowBorder(Color.BLACK, 0, 4, 0.3f, 12, true, true, true, true); + public static final Border DEFAULT_SHADOW_BORDER = + new DropShadowBorder(Color.BLACK, 5, 5, 0.3f, 12, true, true, true, true); - private MaterialBorders() { - } -} \ No newline at end of file + private MaterialBorders() {} +} diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java index 30229b936..f9678d403 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java @@ -3,271 +3,270 @@ import java.awt.*; public class MaterialColors { - public static final Color RED_50 = new Color(255, 235, 238); - public static final Color RED_100 = new Color(255, 205, 210); - public static final Color RED_200 = new Color(239, 154, 154); - public static final Color RED_300 = new Color(229, 115, 115); - public static final Color RED_400 = new Color(239, 83, 80); - public static final Color RED_500 = new Color(244, 67, 54); - public static final Color RED_600 = new Color(229, 57, 53); - public static final Color RED_700 = new Color(211, 47, 47); - public static final Color RED_800 = new Color(198, 40, 40); - public static final Color RED_900 = new Color(183, 28, 28); - public static final Color RED_A100 = new Color(255, 138, 128); - public static final Color RED_A200 = new Color(255, 82, 82); - public static final Color RED_A400 = new Color(255, 23, 68); - public static final Color RED_A700 = new Color(213, 0, 0); - public static final Color PINK_50 = new Color(252, 228, 236); - public static final Color PINK_100 = new Color(248, 187, 208); - public static final Color PINK_200 = new Color(244, 143, 177); - public static final Color PINK_300 = new Color(240, 98, 146); - public static final Color PINK_400 = new Color(236, 64, 122); - public static final Color PINK_500 = new Color(233, 30, 99); - public static final Color PINK_600 = new Color(216, 27, 96); - public static final Color PINK_700 = new Color(194, 24, 91); - public static final Color PINK_800 = new Color(173, 20, 87); - public static final Color PINK_900 = new Color(136, 14, 79); - public static final Color PINK_A100 = new Color(255, 128, 171); - public static final Color PINK_A200 = new Color(255, 64, 129); - public static final Color PINK_A400 = new Color(245, 0, 87); - public static final Color PINK_A700 = new Color(197, 17, 98); - public static final Color PURPLE_50 = new Color(243, 229, 245); - public static final Color PURPLE_100 = new Color(225, 190, 231); - public static final Color PURPLE_200 = new Color(206, 147, 216); - public static final Color PURPLE_300 = new Color(186, 104, 200); - public static final Color PURPLE_400 = new Color(171, 71, 188); - public static final Color PURPLE_500 = new Color(156, 39, 176); - public static final Color PURPLE_600 = new Color(142, 36, 170); - public static final Color PURPLE_700 = new Color(123, 31, 162); - public static final Color PURPLE_800 = new Color(106, 27, 154); - public static final Color PURPLE_900 = new Color(74, 20, 140); - public static final Color PURPLE_A100 = new Color(234, 128, 252); - public static final Color PURPLE_A200 = new Color(224, 64, 251); - public static final Color PURPLE_A400 = new Color(213, 0, 249); - public static final Color PURPLE_A700 = new Color(170, 0, 255); - public static final Color DEEP_PURPLE_50 = new Color(237, 231, 246); - public static final Color DEEP_PURPLE_100 = new Color(209, 196, 233); - public static final Color DEEP_PURPLE_200 = new Color(179, 157, 219); - public static final Color DEEP_PURPLE_300 = new Color(149, 117, 205); - public static final Color DEEP_PURPLE_400 = new Color(126, 87, 194); - public static final Color DEEP_PURPLE_500 = new Color(103, 58, 183); - public static final Color DEEP_PURPLE_600 = new Color(94, 53, 177); - public static final Color DEEP_PURPLE_700 = new Color(81, 45, 168); - public static final Color DEEP_PURPLE_800 = new Color(69, 39, 160); - public static final Color DEEP_PURPLE_900 = new Color(49, 27, 146); - public static final Color DEEP_PURPLE_A100 = new Color(179, 136, 255); - public static final Color DEEP_PURPLE_A200 = new Color(124, 77, 255); - public static final Color DEEP_PURPLE_A400 = new Color(101, 31, 255); - public static final Color DEEP_PURPLE_A700 = new Color(98, 0, 234); - public static final Color INDIGO_50 = new Color(232, 234, 246); - public static final Color INDIGO_100 = new Color(197, 202, 233); - public static final Color INDIGO_200 = new Color(159, 168, 218); - public static final Color INDIGO_300 = new Color(121, 134, 203); - public static final Color INDIGO_400 = new Color(92, 107, 192); - public static final Color INDIGO_500 = new Color(63, 81, 181); - public static final Color INDIGO_600 = new Color(57, 73, 171); - public static final Color INDIGO_700 = new Color(48, 63, 159); - public static final Color INDIGO_800 = new Color(40, 53, 147); - public static final Color INDIGO_900 = new Color(26, 35, 126); - public static final Color INDIGO_A100 = new Color(140, 158, 255); - public static final Color INDIGO_A200 = new Color(83, 109, 254); - public static final Color INDIGO_A400 = new Color(61, 90, 254); - public static final Color INDIGO_A700 = new Color(48, 79, 254); - public static final Color BLUE_50 = new Color(227, 242, 253); - public static final Color BLUE_100 = new Color(187, 222, 251); - public static final Color BLUE_200 = new Color(144, 202, 249); - public static final Color BLUE_300 = new Color(100, 181, 246); - public static final Color BLUE_400 = new Color(66, 165, 245); - public static final Color BLUE_500 = new Color(33, 150, 243); - public static final Color BLUE_600 = new Color(30, 136, 229); - public static final Color BLUE_700 = new Color(25, 118, 210); - public static final Color BLUE_800 = new Color(21, 101, 192); - public static final Color BLUE_900 = new Color(13, 71, 161); - public static final Color BLUE_A100 = new Color(130, 177, 255); - public static final Color BLUE_A200 = new Color(68, 138, 255); - public static final Color BLUE_A400 = new Color(41, 121, 255); - public static final Color BLUE_A700 = new Color(41, 98, 255); - public static final Color LIGHT_BLUE_50 = new Color(225, 245, 254); - public static final Color LIGHT_BLUE_100 = new Color(179, 229, 252); - public static final Color LIGHT_BLUE_200 = new Color(129, 212, 250); - public static final Color LIGHT_BLUE_300 = new Color(79, 195, 247); - public static final Color LIGHT_BLUE_400 = new Color(41, 182, 246); - public static final Color LIGHT_BLUE_500 = new Color(3, 169, 244); - public static final Color LIGHT_BLUE_600 = new Color(3, 155, 229); - public static final Color LIGHT_BLUE_700 = new Color(2, 136, 209); - public static final Color LIGHT_BLUE_800 = new Color(2, 119, 189); - public static final Color LIGHT_BLUE_900 = new Color(1, 87, 155); - public static final Color LIGHT_BLUE_A100 = new Color(128, 216, 255); - public static final Color LIGHT_BLUE_A200 = new Color(64, 196, 255); - public static final Color LIGHT_BLUE_A400 = new Color(0, 176, 255); - public static final Color LIGHT_BLUE_A700 = new Color(0, 145, 234); - public static final Color CYAN_50 = new Color(224, 247, 250); - public static final Color CYAN_100 = new Color(178, 235, 242); - public static final Color CYAN_200 = new Color(128, 222, 234); - public static final Color CYAN_300 = new Color(77, 208, 225); - public static final Color CYAN_400 = new Color(38, 198, 218); - public static final Color CYAN_500 = new Color(0, 188, 212); - public static final Color CYAN_600 = new Color(0, 172, 193); - public static final Color CYAN_700 = new Color(0, 151, 167); - public static final Color CYAN_800 = new Color(0, 131, 143); - public static final Color CYAN_900 = new Color(0, 96, 100); - public static final Color CYAN_A100 = new Color(132, 255, 255); - public static final Color CYAN_A200 = new Color(24, 255, 255); - public static final Color CYAN_A400 = new Color(0, 229, 255); - public static final Color CYAN_A700 = new Color(0, 184, 212); - public static final Color TEAL_50 = new Color(224, 242, 241); - public static final Color TEAL_100 = new Color(178, 223, 219); - public static final Color TEAL_200 = new Color(128, 203, 196); - public static final Color TEAL_300 = new Color(77, 182, 172); - public static final Color TEAL_400 = new Color(38, 166, 154); - public static final Color TEAL_500 = new Color(0, 150, 136); - public static final Color TEAL_600 = new Color(0, 137, 123); - public static final Color TEAL_700 = new Color(0, 121, 107); - public static final Color TEAL_800 = new Color(0, 105, 92); - public static final Color TEAL_900 = new Color(0, 77, 64); - public static final Color TEAL_A100 = new Color(167, 255, 235); - public static final Color TEAL_A200 = new Color(100, 255, 218); - public static final Color TEAL_A400 = new Color(29, 233, 182); - public static final Color TEAL_A700 = new Color(0, 191, 165); - public static final Color GREEN_50 = new Color(232, 245, 233); - public static final Color GREEN_100 = new Color(200, 230, 201); - public static final Color GREEN_200 = new Color(165, 214, 167); - public static final Color GREEN_300 = new Color(129, 199, 132); - public static final Color GREEN_400 = new Color(102, 187, 106); - public static final Color GREEN_500 = new Color(76, 175, 80); - public static final Color GREEN_600 = new Color(67, 160, 71); - public static final Color GREEN_700 = new Color(56, 142, 60); - public static final Color GREEN_800 = new Color(46, 125, 50); - public static final Color GREEN_900 = new Color(27, 94, 32); - public static final Color GREEN_A100 = new Color(185, 246, 202); - public static final Color GREEN_A200 = new Color(105, 240, 174); - public static final Color GREEN_A400 = new Color(0, 230, 118); - public static final Color GREEN_A700 = new Color(0, 200, 83); - public static final Color LIGHT_GREEN_50 = new Color(241, 248, 233); - public static final Color LIGHT_GREEN_100 = new Color(220, 237, 200); - public static final Color LIGHT_GREEN_200 = new Color(197, 225, 165); - public static final Color LIGHT_GREEN_300 = new Color(174, 213, 129); - public static final Color LIGHT_GREEN_400 = new Color(156, 204, 101); - public static final Color LIGHT_GREEN_500 = new Color(139, 195, 74); - public static final Color LIGHT_GREEN_600 = new Color(124, 179, 66); - public static final Color LIGHT_GREEN_700 = new Color(104, 159, 56); - public static final Color LIGHT_GREEN_800 = new Color(85, 139, 47); - public static final Color LIGHT_GREEN_900 = new Color(51, 105, 30); - public static final Color LIGHT_GREEN_A100 = new Color(204, 255, 144); - public static final Color LIGHT_GREEN_A200 = new Color(178, 255, 89); - public static final Color LIGHT_GREEN_A400 = new Color(118, 255, 3); - public static final Color LIGHT_GREEN_A700 = new Color(100, 221, 23); - public static final Color LIME_50 = new Color(249, 251, 231); - public static final Color LIME_100 = new Color(240, 244, 195); - public static final Color LIME_200 = new Color(230, 238, 156); - public static final Color LIME_300 = new Color(220, 231, 117); - public static final Color LIME_400 = new Color(212, 225, 87); - public static final Color LIME_500 = new Color(205, 220, 57); - public static final Color LIME_600 = new Color(192, 202, 51); - public static final Color LIME_700 = new Color(175, 180, 43); - public static final Color LIME_800 = new Color(158, 157, 36); - public static final Color LIME_900 = new Color(130, 119, 23); - public static final Color LIME_A100 = new Color(244, 255, 129); - public static final Color LIME_A200 = new Color(238, 255, 65); - public static final Color LIME_A400 = new Color(198, 255, 0); - public static final Color LIME_A700 = new Color(174, 234, 0); - public static final Color YELLOW_50 = new Color(255, 253, 231); - public static final Color YELLOW_100 = new Color(255, 249, 196); - public static final Color YELLOW_200 = new Color(255, 245, 157); - public static final Color YELLOW_300 = new Color(255, 241, 118); - public static final Color YELLOW_400 = new Color(255, 238, 88); - public static final Color YELLOW_500 = new Color(255, 235, 59); - public static final Color YELLOW_600 = new Color(253, 216, 53); - public static final Color YELLOW_700 = new Color(251, 192, 45); - public static final Color YELLOW_800 = new Color(249, 168, 37); - public static final Color YELLOW_900 = new Color(245, 127, 23); - public static final Color YELLOW_A100 = new Color(255, 255, 141); - public static final Color YELLOW_A200 = new Color(255, 255, 0); - public static final Color YELLOW_A400 = new Color(255, 234, 0); - public static final Color YELLOW_A700 = new Color(255, 214, 0); - public static final Color AMBER_50 = new Color(255, 248, 225); - public static final Color AMBER_100 = new Color(255, 236, 179); - public static final Color AMBER_200 = new Color(255, 224, 130); - public static final Color AMBER_300 = new Color(255, 213, 79); - public static final Color AMBER_400 = new Color(255, 202, 40); - public static final Color AMBER_500 = new Color(255, 193, 7); - public static final Color AMBER_600 = new Color(255, 179, 0); - public static final Color AMBER_700 = new Color(255, 160, 0); - public static final Color AMBER_800 = new Color(255, 143, 0); - public static final Color AMBER_900 = new Color(255, 111, 0); - public static final Color AMBER_A100 = new Color(255, 229, 127); - public static final Color AMBER_A200 = new Color(255, 215, 64); - public static final Color AMBER_A400 = new Color(255, 196, 0); - public static final Color AMBER_A700 = new Color(255, 171, 0); - public static final Color ORANGE_50 = new Color(255, 243, 224); - public static final Color ORANGE_100 = new Color(255, 224, 178); - public static final Color ORANGE_200 = new Color(255, 204, 128); - public static final Color ORANGE_300 = new Color(255, 183, 77); - public static final Color ORANGE_400 = new Color(255, 167, 38); - public static final Color ORANGE_500 = new Color(255, 152, 0); - public static final Color ORANGE_600 = new Color(251, 140, 0); - public static final Color ORANGE_700 = new Color(245, 124, 0); - public static final Color ORANGE_800 = new Color(239, 108, 0); - public static final Color ORANGE_900 = new Color(230, 81, 0); - public static final Color ORANGE_A100 = new Color(255, 209, 128); - public static final Color ORANGE_A200 = new Color(255, 171, 64); - public static final Color ORANGE_A400 = new Color(255, 145, 0); - public static final Color ORANGE_A700 = new Color(255, 109, 0); - public static final Color DEEP_ORANGE_50 = new Color(251, 233, 231); - public static final Color DEEP_ORANGE_100 = new Color(255, 204, 188); - public static final Color DEEP_ORANGE_200 = new Color(255, 171, 145); - public static final Color DEEP_ORANGE_300 = new Color(255, 138, 101); - public static final Color DEEP_ORANGE_400 = new Color(255, 112, 67); - public static final Color DEEP_ORANGE_500 = new Color(255, 87, 34); - public static final Color DEEP_ORANGE_600 = new Color(244, 81, 30); - public static final Color DEEP_ORANGE_700 = new Color(230, 74, 25); - public static final Color DEEP_ORANGE_800 = new Color(216, 67, 21); - public static final Color DEEP_ORANGE_900 = new Color(191, 54, 12); - public static final Color DEEP_ORANGE_A100 = new Color(255, 158, 128); - public static final Color DEEP_ORANGE_A200 = new Color(255, 110, 64); - public static final Color DEEP_ORANGE_A400 = new Color(255, 61, 0); - public static final Color DEEP_ORANGE_A700 = new Color(221, 44, 0); - public static final Color BROWN_50 = new Color(239, 235, 233); - public static final Color BROWN_100 = new Color(215, 204, 200); - public static final Color BROWN_200 = new Color(188, 170, 164); - public static final Color BROWN_300 = new Color(161, 136, 127); - public static final Color BROWN_400 = new Color(141, 110, 99); - public static final Color BROWN_500 = new Color(121, 85, 72); - public static final Color BROWN_600 = new Color(109, 76, 65); - public static final Color BROWN_700 = new Color(93, 64, 55); - public static final Color BROWN_800 = new Color(78, 52, 46); - public static final Color BROWN_900 = new Color(62, 39, 35); - public static final Color GRAY_50 = new Color(250, 250, 250); - public static final Color GRAY_100 = new Color(245, 245, 245); - public static final Color GRAY_200 = new Color(238, 238, 238); - public static final Color GRAY_300 = new Color(224, 224, 224); - public static final Color GRAY_400 = new Color(189, 189, 189); - public static final Color GRAY_500 = new Color(158, 158, 158); - public static final Color GRAY_600 = new Color(117, 117, 117); - public static final Color GRAY_700 = new Color(97, 97, 97); - public static final Color GRAY_800 = new Color(66, 66, 66); - public static final Color GRAY_900 = new Color(33, 33, 33); - public static final Color BLUE_GRAY_50 = new Color(236, 239, 241); - public static final Color BLUE_GRAY_100 = new Color(207, 216, 220); - public static final Color BLUE_GRAY_200 = new Color(176, 190, 197); - public static final Color BLUE_GRAY_300 = new Color(144, 164, 174); - public static final Color BLUE_GRAY_400 = new Color(120, 144, 156); - public static final Color BLUE_GRAY_500 = new Color(96, 125, 139); - public static final Color BLUE_GRAY_600 = new Color(84, 110, 122); - public static final Color BLUE_GRAY_700 = new Color(69, 90, 100); - public static final Color BLUE_GRAY_800 = new Color(55, 71, 79); - public static final Color BLUE_GRAY_900 = new Color(38, 50, 56); - public static final Color BLACK = new Color(0, 0, 0); - public static final Color WHITE = new Color(255, 255, 255); - public static final Color TRANSPARENT = new Color(0, 0, 0, 255); + public static final Color RED_50 = new Color(255, 235, 238); + public static final Color RED_100 = new Color(255, 205, 210); + public static final Color RED_200 = new Color(239, 154, 154); + public static final Color RED_300 = new Color(229, 115, 115); + public static final Color RED_400 = new Color(239, 83, 80); + public static final Color RED_500 = new Color(244, 67, 54); + public static final Color RED_600 = new Color(229, 57, 53); + public static final Color RED_700 = new Color(211, 47, 47); + public static final Color RED_800 = new Color(198, 40, 40); + public static final Color RED_900 = new Color(183, 28, 28); + public static final Color RED_A100 = new Color(255, 138, 128); + public static final Color RED_A200 = new Color(255, 82, 82); + public static final Color RED_A400 = new Color(255, 23, 68); + public static final Color RED_A700 = new Color(213, 0, 0); + public static final Color PINK_50 = new Color(252, 228, 236); + public static final Color PINK_100 = new Color(248, 187, 208); + public static final Color PINK_200 = new Color(244, 143, 177); + public static final Color PINK_300 = new Color(240, 98, 146); + public static final Color PINK_400 = new Color(236, 64, 122); + public static final Color PINK_500 = new Color(233, 30, 99); + public static final Color PINK_600 = new Color(216, 27, 96); + public static final Color PINK_700 = new Color(194, 24, 91); + public static final Color PINK_800 = new Color(173, 20, 87); + public static final Color PINK_900 = new Color(136, 14, 79); + public static final Color PINK_A100 = new Color(255, 128, 171); + public static final Color PINK_A200 = new Color(255, 64, 129); + public static final Color PINK_A400 = new Color(245, 0, 87); + public static final Color PINK_A700 = new Color(197, 17, 98); + public static final Color PURPLE_50 = new Color(243, 229, 245); + public static final Color PURPLE_100 = new Color(225, 190, 231); + public static final Color PURPLE_200 = new Color(206, 147, 216); + public static final Color PURPLE_300 = new Color(186, 104, 200); + public static final Color PURPLE_400 = new Color(171, 71, 188); + public static final Color PURPLE_500 = new Color(156, 39, 176); + public static final Color PURPLE_600 = new Color(142, 36, 170); + public static final Color PURPLE_700 = new Color(123, 31, 162); + public static final Color PURPLE_800 = new Color(106, 27, 154); + public static final Color PURPLE_900 = new Color(74, 20, 140); + public static final Color PURPLE_A100 = new Color(234, 128, 252); + public static final Color PURPLE_A200 = new Color(224, 64, 251); + public static final Color PURPLE_A400 = new Color(213, 0, 249); + public static final Color PURPLE_A700 = new Color(170, 0, 255); + public static final Color DEEP_PURPLE_50 = new Color(237, 231, 246); + public static final Color DEEP_PURPLE_100 = new Color(209, 196, 233); + public static final Color DEEP_PURPLE_200 = new Color(179, 157, 219); + public static final Color DEEP_PURPLE_300 = new Color(149, 117, 205); + public static final Color DEEP_PURPLE_400 = new Color(126, 87, 194); + public static final Color DEEP_PURPLE_500 = new Color(103, 58, 183); + public static final Color DEEP_PURPLE_600 = new Color(94, 53, 177); + public static final Color DEEP_PURPLE_700 = new Color(81, 45, 168); + public static final Color DEEP_PURPLE_800 = new Color(69, 39, 160); + public static final Color DEEP_PURPLE_900 = new Color(49, 27, 146); + public static final Color DEEP_PURPLE_A100 = new Color(179, 136, 255); + public static final Color DEEP_PURPLE_A200 = new Color(124, 77, 255); + public static final Color DEEP_PURPLE_A400 = new Color(101, 31, 255); + public static final Color DEEP_PURPLE_A700 = new Color(98, 0, 234); + public static final Color INDIGO_50 = new Color(232, 234, 246); + public static final Color INDIGO_100 = new Color(197, 202, 233); + public static final Color INDIGO_200 = new Color(159, 168, 218); + public static final Color INDIGO_300 = new Color(121, 134, 203); + public static final Color INDIGO_400 = new Color(92, 107, 192); + public static final Color INDIGO_500 = new Color(63, 81, 181); + public static final Color INDIGO_600 = new Color(57, 73, 171); + public static final Color INDIGO_700 = new Color(48, 63, 159); + public static final Color INDIGO_800 = new Color(40, 53, 147); + public static final Color INDIGO_900 = new Color(26, 35, 126); + public static final Color INDIGO_A100 = new Color(140, 158, 255); + public static final Color INDIGO_A200 = new Color(83, 109, 254); + public static final Color INDIGO_A400 = new Color(61, 90, 254); + public static final Color INDIGO_A700 = new Color(48, 79, 254); + public static final Color BLUE_50 = new Color(227, 242, 253); + public static final Color BLUE_100 = new Color(187, 222, 251); + public static final Color BLUE_200 = new Color(144, 202, 249); + public static final Color BLUE_300 = new Color(100, 181, 246); + public static final Color BLUE_400 = new Color(66, 165, 245); + public static final Color BLUE_500 = new Color(33, 150, 243); + public static final Color BLUE_600 = new Color(30, 136, 229); + public static final Color BLUE_700 = new Color(25, 118, 210); + public static final Color BLUE_800 = new Color(21, 101, 192); + public static final Color BLUE_900 = new Color(13, 71, 161); + public static final Color BLUE_A100 = new Color(130, 177, 255); + public static final Color BLUE_A200 = new Color(68, 138, 255); + public static final Color BLUE_A400 = new Color(41, 121, 255); + public static final Color BLUE_A700 = new Color(41, 98, 255); + public static final Color LIGHT_BLUE_50 = new Color(225, 245, 254); + public static final Color LIGHT_BLUE_100 = new Color(179, 229, 252); + public static final Color LIGHT_BLUE_200 = new Color(129, 212, 250); + public static final Color LIGHT_BLUE_300 = new Color(79, 195, 247); + public static final Color LIGHT_BLUE_400 = new Color(41, 182, 246); + public static final Color LIGHT_BLUE_500 = new Color(3, 169, 244); + public static final Color LIGHT_BLUE_600 = new Color(3, 155, 229); + public static final Color LIGHT_BLUE_700 = new Color(2, 136, 209); + public static final Color LIGHT_BLUE_800 = new Color(2, 119, 189); + public static final Color LIGHT_BLUE_900 = new Color(1, 87, 155); + public static final Color LIGHT_BLUE_A100 = new Color(128, 216, 255); + public static final Color LIGHT_BLUE_A200 = new Color(64, 196, 255); + public static final Color LIGHT_BLUE_A400 = new Color(0, 176, 255); + public static final Color LIGHT_BLUE_A700 = new Color(0, 145, 234); + public static final Color CYAN_50 = new Color(224, 247, 250); + public static final Color CYAN_100 = new Color(178, 235, 242); + public static final Color CYAN_200 = new Color(128, 222, 234); + public static final Color CYAN_300 = new Color(77, 208, 225); + public static final Color CYAN_400 = new Color(38, 198, 218); + public static final Color CYAN_500 = new Color(0, 188, 212); + public static final Color CYAN_600 = new Color(0, 172, 193); + public static final Color CYAN_700 = new Color(0, 151, 167); + public static final Color CYAN_800 = new Color(0, 131, 143); + public static final Color CYAN_900 = new Color(0, 96, 100); + public static final Color CYAN_A100 = new Color(132, 255, 255); + public static final Color CYAN_A200 = new Color(24, 255, 255); + public static final Color CYAN_A400 = new Color(0, 229, 255); + public static final Color CYAN_A700 = new Color(0, 184, 212); + public static final Color TEAL_50 = new Color(224, 242, 241); + public static final Color TEAL_100 = new Color(178, 223, 219); + public static final Color TEAL_200 = new Color(128, 203, 196); + public static final Color TEAL_300 = new Color(77, 182, 172); + public static final Color TEAL_400 = new Color(38, 166, 154); + public static final Color TEAL_500 = new Color(0, 150, 136); + public static final Color TEAL_600 = new Color(0, 137, 123); + public static final Color TEAL_700 = new Color(0, 121, 107); + public static final Color TEAL_800 = new Color(0, 105, 92); + public static final Color TEAL_900 = new Color(0, 77, 64); + public static final Color TEAL_A100 = new Color(167, 255, 235); + public static final Color TEAL_A200 = new Color(100, 255, 218); + public static final Color TEAL_A400 = new Color(29, 233, 182); + public static final Color TEAL_A700 = new Color(0, 191, 165); + public static final Color GREEN_50 = new Color(232, 245, 233); + public static final Color GREEN_100 = new Color(200, 230, 201); + public static final Color GREEN_200 = new Color(165, 214, 167); + public static final Color GREEN_300 = new Color(129, 199, 132); + public static final Color GREEN_400 = new Color(102, 187, 106); + public static final Color GREEN_500 = new Color(76, 175, 80); + public static final Color GREEN_600 = new Color(67, 160, 71); + public static final Color GREEN_700 = new Color(56, 142, 60); + public static final Color GREEN_800 = new Color(46, 125, 50); + public static final Color GREEN_900 = new Color(27, 94, 32); + public static final Color GREEN_A100 = new Color(185, 246, 202); + public static final Color GREEN_A200 = new Color(105, 240, 174); + public static final Color GREEN_A400 = new Color(0, 230, 118); + public static final Color GREEN_A700 = new Color(0, 200, 83); + public static final Color LIGHT_GREEN_50 = new Color(241, 248, 233); + public static final Color LIGHT_GREEN_100 = new Color(220, 237, 200); + public static final Color LIGHT_GREEN_200 = new Color(197, 225, 165); + public static final Color LIGHT_GREEN_300 = new Color(174, 213, 129); + public static final Color LIGHT_GREEN_400 = new Color(156, 204, 101); + public static final Color LIGHT_GREEN_500 = new Color(139, 195, 74); + public static final Color LIGHT_GREEN_600 = new Color(124, 179, 66); + public static final Color LIGHT_GREEN_700 = new Color(104, 159, 56); + public static final Color LIGHT_GREEN_800 = new Color(85, 139, 47); + public static final Color LIGHT_GREEN_900 = new Color(51, 105, 30); + public static final Color LIGHT_GREEN_A100 = new Color(204, 255, 144); + public static final Color LIGHT_GREEN_A200 = new Color(178, 255, 89); + public static final Color LIGHT_GREEN_A400 = new Color(118, 255, 3); + public static final Color LIGHT_GREEN_A700 = new Color(100, 221, 23); + public static final Color LIME_50 = new Color(249, 251, 231); + public static final Color LIME_100 = new Color(240, 244, 195); + public static final Color LIME_200 = new Color(230, 238, 156); + public static final Color LIME_300 = new Color(220, 231, 117); + public static final Color LIME_400 = new Color(212, 225, 87); + public static final Color LIME_500 = new Color(205, 220, 57); + public static final Color LIME_600 = new Color(192, 202, 51); + public static final Color LIME_700 = new Color(175, 180, 43); + public static final Color LIME_800 = new Color(158, 157, 36); + public static final Color LIME_900 = new Color(130, 119, 23); + public static final Color LIME_A100 = new Color(244, 255, 129); + public static final Color LIME_A200 = new Color(238, 255, 65); + public static final Color LIME_A400 = new Color(198, 255, 0); + public static final Color LIME_A700 = new Color(174, 234, 0); + public static final Color YELLOW_50 = new Color(255, 253, 231); + public static final Color YELLOW_100 = new Color(255, 249, 196); + public static final Color YELLOW_200 = new Color(255, 245, 157); + public static final Color YELLOW_300 = new Color(255, 241, 118); + public static final Color YELLOW_400 = new Color(255, 238, 88); + public static final Color YELLOW_500 = new Color(255, 235, 59); + public static final Color YELLOW_600 = new Color(253, 216, 53); + public static final Color YELLOW_700 = new Color(251, 192, 45); + public static final Color YELLOW_800 = new Color(249, 168, 37); + public static final Color YELLOW_900 = new Color(245, 127, 23); + public static final Color YELLOW_A100 = new Color(255, 255, 141); + public static final Color YELLOW_A200 = new Color(255, 255, 0); + public static final Color YELLOW_A400 = new Color(255, 234, 0); + public static final Color YELLOW_A700 = new Color(255, 214, 0); + public static final Color AMBER_50 = new Color(255, 248, 225); + public static final Color AMBER_100 = new Color(255, 236, 179); + public static final Color AMBER_200 = new Color(255, 224, 130); + public static final Color AMBER_300 = new Color(255, 213, 79); + public static final Color AMBER_400 = new Color(255, 202, 40); + public static final Color AMBER_500 = new Color(255, 193, 7); + public static final Color AMBER_600 = new Color(255, 179, 0); + public static final Color AMBER_700 = new Color(255, 160, 0); + public static final Color AMBER_800 = new Color(255, 143, 0); + public static final Color AMBER_900 = new Color(255, 111, 0); + public static final Color AMBER_A100 = new Color(255, 229, 127); + public static final Color AMBER_A200 = new Color(255, 215, 64); + public static final Color AMBER_A400 = new Color(255, 196, 0); + public static final Color AMBER_A700 = new Color(255, 171, 0); + public static final Color ORANGE_50 = new Color(255, 243, 224); + public static final Color ORANGE_100 = new Color(255, 224, 178); + public static final Color ORANGE_200 = new Color(255, 204, 128); + public static final Color ORANGE_300 = new Color(255, 183, 77); + public static final Color ORANGE_400 = new Color(255, 167, 38); + public static final Color ORANGE_500 = new Color(255, 152, 0); + public static final Color ORANGE_600 = new Color(251, 140, 0); + public static final Color ORANGE_700 = new Color(245, 124, 0); + public static final Color ORANGE_800 = new Color(239, 108, 0); + public static final Color ORANGE_900 = new Color(230, 81, 0); + public static final Color ORANGE_A100 = new Color(255, 209, 128); + public static final Color ORANGE_A200 = new Color(255, 171, 64); + public static final Color ORANGE_A400 = new Color(255, 145, 0); + public static final Color ORANGE_A700 = new Color(255, 109, 0); + public static final Color DEEP_ORANGE_50 = new Color(251, 233, 231); + public static final Color DEEP_ORANGE_100 = new Color(255, 204, 188); + public static final Color DEEP_ORANGE_200 = new Color(255, 171, 145); + public static final Color DEEP_ORANGE_300 = new Color(255, 138, 101); + public static final Color DEEP_ORANGE_400 = new Color(255, 112, 67); + public static final Color DEEP_ORANGE_500 = new Color(255, 87, 34); + public static final Color DEEP_ORANGE_600 = new Color(244, 81, 30); + public static final Color DEEP_ORANGE_700 = new Color(230, 74, 25); + public static final Color DEEP_ORANGE_800 = new Color(216, 67, 21); + public static final Color DEEP_ORANGE_900 = new Color(191, 54, 12); + public static final Color DEEP_ORANGE_A100 = new Color(255, 158, 128); + public static final Color DEEP_ORANGE_A200 = new Color(255, 110, 64); + public static final Color DEEP_ORANGE_A400 = new Color(255, 61, 0); + public static final Color DEEP_ORANGE_A700 = new Color(221, 44, 0); + public static final Color BROWN_50 = new Color(239, 235, 233); + public static final Color BROWN_100 = new Color(215, 204, 200); + public static final Color BROWN_200 = new Color(188, 170, 164); + public static final Color BROWN_300 = new Color(161, 136, 127); + public static final Color BROWN_400 = new Color(141, 110, 99); + public static final Color BROWN_500 = new Color(121, 85, 72); + public static final Color BROWN_600 = new Color(109, 76, 65); + public static final Color BROWN_700 = new Color(93, 64, 55); + public static final Color BROWN_800 = new Color(78, 52, 46); + public static final Color BROWN_900 = new Color(62, 39, 35); + public static final Color GRAY_50 = new Color(250, 250, 250); + public static final Color GRAY_100 = new Color(245, 245, 245); + public static final Color GRAY_200 = new Color(238, 238, 238); + public static final Color GRAY_300 = new Color(224, 224, 224); + public static final Color GRAY_400 = new Color(189, 189, 189); + public static final Color GRAY_500 = new Color(158, 158, 158); + public static final Color GRAY_600 = new Color(117, 117, 117); + public static final Color GRAY_700 = new Color(97, 97, 97); + public static final Color GRAY_800 = new Color(66, 66, 66); + public static final Color GRAY_900 = new Color(33, 33, 33); + public static final Color BLUE_GRAY_50 = new Color(236, 239, 241); + public static final Color BLUE_GRAY_100 = new Color(207, 216, 220); + public static final Color BLUE_GRAY_200 = new Color(176, 190, 197); + public static final Color BLUE_GRAY_300 = new Color(144, 164, 174); + public static final Color BLUE_GRAY_400 = new Color(120, 144, 156); + public static final Color BLUE_GRAY_500 = new Color(96, 125, 139); + public static final Color BLUE_GRAY_600 = new Color(84, 110, 122); + public static final Color BLUE_GRAY_700 = new Color(69, 90, 100); + public static final Color BLUE_GRAY_800 = new Color(55, 71, 79); + public static final Color BLUE_GRAY_900 = new Color(38, 50, 56); + public static final Color BLACK = new Color(0, 0, 0); + public static final Color WHITE = new Color(255, 255, 255); + public static final Color TRANSPARENT = new Color(0, 0, 0, 255); - private MaterialColors() { - } + private MaterialColors() {} - public static Color bleach(Color color, float amount) { - int red = (int) ((color.getRed() * (1 - amount) / 255 + amount) * 255); - int green = (int) ((color.getGreen() * (1 - amount) / 255 + amount) * 255); - int blue = (int) ((color.getBlue() * (1 - amount) / 255 + amount) * 255); - return new Color(red, green, blue); - } + public static Color bleach(Color color, float amount) { + int red = (int) ((color.getRed() * (1 - amount) / 255 + amount) * 255); + int green = (int) ((color.getGreen() * (1 - amount) / 255 + amount) * 255); + int blue = (int) ((color.getBlue() * (1 - amount) / 255 + amount) * 255); + return new Color(red, green, blue); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java index fbc330faf..30c4fdeda 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java @@ -8,26 +8,28 @@ public class MaterialDrawingUtils { - static { - System.setProperty("awt.useSystemAAFontSettings", "on"); - System.setProperty("swing.aatext", "true"); - System.setProperty("sun.java2d.xrender", "true"); - } + static { + System.setProperty("awt.useSystemAAFontSettings", "on"); + System.setProperty("swing.aatext", "true"); + System.setProperty("sun.java2d.xrender", "true"); + } - public static Graphics getAliasedGraphics(Graphics g) { - Map hints = (Map) Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); - if (hints != null) { - hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + public static Graphics getAliasedGraphics(Graphics g) { + Map hints = + (Map) + Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); + if (hints != null) { + hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - Graphics2D g2d = (Graphics2D) g; - g2d.addRenderingHints(hints); + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(hints); - //g2d.addRenderingHints (new RenderingHints (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); - return g2d; - } - else { - // Desktop hints not supported on this platform - return g; - } + // g2d.addRenderingHints (new RenderingHints (RenderingHints.KEY_ANTIALIASING, + // RenderingHints.VALUE_ANTIALIAS_ON)); + return g2d; + } else { + // Desktop hints not supported on this platform + return g; } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java index 9bbc4e884..cb6a79f86 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java @@ -1,6 +1,5 @@ package edu.rpi.legup.ui.lookandfeel.materialdesign; - import java.awt.*; import java.awt.font.TextAttribute; import java.io.IOException; @@ -10,47 +9,51 @@ public class MaterialFonts { - private static final Map fontSettings = new HashMap<>(); - - public static final Font BLACK = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Black.ttf"); - public static final Font BLACK_ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BlackItalic.ttf"); - public static final Font BOLD = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Bold.ttf"); - public static final Font BOLD_ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BoldItalic.ttf"); - public static final Font ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Italic.ttf"); - public static final Font LIGHT = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Light.ttf"); - public static final Font LIGHT_ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-LightItalic.ttf"); - public static final Font MEDIUM = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Medium.ttf"); - public static final Font MEDIUM_ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-MediumItalic.ttf"); - public static final Font REGULAR = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf"); - public static final Font THIN = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Thin.ttf"); - public static final Font THIN_ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-ThinItalic.ttf"); - - private static Font loadFont(String fontPath) { - if (fontSettings.isEmpty()) { - fontSettings.put(TextAttribute.SIZE, 14f); - fontSettings.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); - } - - try (InputStream inputStream = MaterialFonts.class.getResourceAsStream(fontPath)) { - return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(fontSettings); - } - catch (IOException | FontFormatException e) { - e.printStackTrace(); - throw new RuntimeException("Font " + fontPath + " wasn't loaded"); - } + private static final Map fontSettings = new HashMap<>(); + + public static final Font BLACK = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Black.ttf"); + public static final Font BLACK_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BlackItalic.ttf"); + public static final Font BOLD = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Bold.ttf"); + public static final Font BOLD_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BoldItalic.ttf"); + public static final Font ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Italic.ttf"); + public static final Font LIGHT = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Light.ttf"); + public static final Font LIGHT_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-LightItalic.ttf"); + public static final Font MEDIUM = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Medium.ttf"); + public static final Font MEDIUM_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-MediumItalic.ttf"); + public static final Font REGULAR = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf"); + public static final Font THIN = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Thin.ttf"); + public static final Font THIN_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-ThinItalic.ttf"); + + private static Font loadFont(String fontPath) { + if (fontSettings.isEmpty()) { + fontSettings.put(TextAttribute.SIZE, 14f); + fontSettings.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); } - public static Font getRegularFont(float size) { - final Map map = new HashMap<>(); - map.put(TextAttribute.SIZE, size); - map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); - - try (InputStream inputStream = MaterialFonts.class.getResourceAsStream("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf")) { - return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(map); - } - catch (IOException | FontFormatException e) { - e.printStackTrace(); - throw new RuntimeException("Font regular wasn't loaded"); - } + try (InputStream inputStream = MaterialFonts.class.getResourceAsStream(fontPath)) { + return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(fontSettings); + } catch (IOException | FontFormatException e) { + e.printStackTrace(); + throw new RuntimeException("Font " + fontPath + " wasn't loaded"); + } + } + + public static Font getRegularFont(float size) { + final Map map = new HashMap<>(); + map.put(TextAttribute.SIZE, size); + map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + + try (InputStream inputStream = + MaterialFonts.class.getResourceAsStream("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf")) { + return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(map); + } catch (IOException | FontFormatException e) { + e.printStackTrace(); + throw new RuntimeException("Font regular wasn't loaded"); } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java index dabf2139d..93abff7a2 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java @@ -1,43 +1,47 @@ package edu.rpi.legup.ui.lookandfeel.materialdesign; -import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; +import javax.imageio.ImageIO; public class MaterialImages { - public static final BufferedImage RIGHT_ARROW = loadImg("/edu/rpi/legup/imgs/right_arrow.png"); - public static final BufferedImage DOWN_ARROW = loadImg("/edu/rpi/legup/imgs/down_arrow.png"); - public static final BufferedImage UP_ARROW = loadImg("/edu/rpi/legup/imgs/up_arrow.png"); - public static final BufferedImage PAINTED_CHECKED_BOX = loadImg("/edu/rpi/legup/imgs/painted_checked_box.png"); - public static final BufferedImage OUTLINED_CHECKED_BOX = loadImg("/edu/rpi/legup/imgs/outlined_checked_box.png"); - public static final BufferedImage UNCHECKED_BOX = loadImg("/edu/rpi/legup/imgs/unchecked_box.png"); - public static final BufferedImage RADIO_BUTTON_ON = loadImg("/edu/rpi/legup/imgs/radio_button_on.png"); - public static final BufferedImage RADIO_BUTTON_OFF = loadImg("/edu/rpi/legup/imgs/radio_button_off.png"); - public static final BufferedImage TOGGLE_BUTTON_ON = loadImg("/edu/rpi/legup/imgs/toggle_on.png"); - public static final BufferedImage TOGGLE_BUTTON_OFF = loadImg("/edu/rpi/legup/imgs/toggle_off.png"); - public static final BufferedImage BACK_ARROW = loadImg("/edu/rpi/legup/imgs/back_arrow.png"); - public static final BufferedImage COMPUTER = loadImg("/edu/rpi/legup/imgs/computer.png"); - public static final BufferedImage FILE = loadImg("/edu/rpi/legup/imgs/file.png"); - public static final BufferedImage FLOPPY_DRIVE = loadImg("/edu/rpi/legup/imgs/floppy_drive.png"); - public static final BufferedImage FOLDER = loadImg("/edu/rpi/legup/imgs/folder.png"); - public static final BufferedImage HARD_DRIVE = loadImg("/edu/rpi/legup/imgs/hard_drive.png"); - public static final BufferedImage HOME = loadImg("/edu/rpi/legup/imgs/home.png"); - public static final BufferedImage LIST = loadImg("/edu/rpi/legup/imgs/list.png"); - public static final BufferedImage NEW_FOLDER = loadImg("/edu/rpi/legup/imgs/new_folder.png"); - public static final BufferedImage DETAILS = loadImg("/edu/rpi/legup/imgs/details.png"); + public static final BufferedImage RIGHT_ARROW = loadImg("/edu/rpi/legup/imgs/right_arrow.png"); + public static final BufferedImage DOWN_ARROW = loadImg("/edu/rpi/legup/imgs/down_arrow.png"); + public static final BufferedImage UP_ARROW = loadImg("/edu/rpi/legup/imgs/up_arrow.png"); + public static final BufferedImage PAINTED_CHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/painted_checked_box.png"); + public static final BufferedImage OUTLINED_CHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/outlined_checked_box.png"); + public static final BufferedImage UNCHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/unchecked_box.png"); + public static final BufferedImage RADIO_BUTTON_ON = + loadImg("/edu/rpi/legup/imgs/radio_button_on.png"); + public static final BufferedImage RADIO_BUTTON_OFF = + loadImg("/edu/rpi/legup/imgs/radio_button_off.png"); + public static final BufferedImage TOGGLE_BUTTON_ON = loadImg("/edu/rpi/legup/imgs/toggle_on.png"); + public static final BufferedImage TOGGLE_BUTTON_OFF = + loadImg("/edu/rpi/legup/imgs/toggle_off.png"); + public static final BufferedImage BACK_ARROW = loadImg("/edu/rpi/legup/imgs/back_arrow.png"); + public static final BufferedImage COMPUTER = loadImg("/edu/rpi/legup/imgs/computer.png"); + public static final BufferedImage FILE = loadImg("/edu/rpi/legup/imgs/file.png"); + public static final BufferedImage FLOPPY_DRIVE = loadImg("/edu/rpi/legup/imgs/floppy_drive.png"); + public static final BufferedImage FOLDER = loadImg("/edu/rpi/legup/imgs/folder.png"); + public static final BufferedImage HARD_DRIVE = loadImg("/edu/rpi/legup/imgs/hard_drive.png"); + public static final BufferedImage HOME = loadImg("/edu/rpi/legup/imgs/home.png"); + public static final BufferedImage LIST = loadImg("/edu/rpi/legup/imgs/list.png"); + public static final BufferedImage NEW_FOLDER = loadImg("/edu/rpi/legup/imgs/new_folder.png"); + public static final BufferedImage DETAILS = loadImg("/edu/rpi/legup/imgs/details.png"); - private MaterialImages() { - } + private MaterialImages() {} - private static BufferedImage loadImg(String imgPath) { - try (InputStream inputStream = MaterialImages.class.getResourceAsStream(imgPath)) { - return ImageIO.read(inputStream); - } - catch (IOException e) { - e.printStackTrace(); - throw new RuntimeException("Image " + imgPath + " wasn't loaded"); - } + private static BufferedImage loadImg(String imgPath) { + try (InputStream inputStream = MaterialImages.class.getResourceAsStream(imgPath)) { + return ImageIO.read(inputStream); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Image " + imgPath + " wasn't loaded"); } + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java index 5f22ac62c..c3c70db31 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java @@ -3,15 +3,18 @@ import javax.swing.ImageIcon; public class CaseRulePanel extends RulePanel { - /** - * CaseRulePanel Constructor creates a CaseRulePanel - * - * @param ruleFrame rule frame that this CaseRulePanel is contained in - */ - CaseRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = new ImageIcon(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Case Rules.gif")); - this.name = "Case Rules"; - this.toolTip = "Case Rules"; - } -} \ No newline at end of file + /** + * CaseRulePanel Constructor creates a CaseRulePanel + * + * @param ruleFrame rule frame that this CaseRulePanel is contained in + */ + CaseRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Case Rules.gif")); + this.name = "Case Rules"; + this.toolTip = "Case Rules"; + } +} diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java index 276583a99..1e7d6066c 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java @@ -1,22 +1,21 @@ package edu.rpi.legup.ui.proofeditorui.rulesview; import edu.rpi.legup.ui.WrapLayout; - -import javax.swing.*; import java.awt.*; +import javax.swing.*; public class CaseRuleSelectionView extends JPanel { - public CaseRuleSelectionView(RuleButton ruleButton) { - setLayout(new WrapLayout()); - Button button1 = new Button(ruleButton.getX() + ", " + ruleButton.getY()); - button1.setSize(50, 50); - Button button2 = new Button("How"); - button2.setSize(50, 50); + public CaseRuleSelectionView(RuleButton ruleButton) { + setLayout(new WrapLayout()); + Button button1 = new Button(ruleButton.getX() + ", " + ruleButton.getY()); + button1.setSize(50, 50); + Button button2 = new Button("How"); + button2.setSize(50, 50); - add(button1); - add(button2); + add(button1); + add(button2); - revalidate(); - } + revalidate(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java index 908ffc49b..5f5fb6aaf 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java @@ -3,15 +3,18 @@ import javax.swing.*; public class ContradictionRulePanel extends RulePanel { - /** - * ContradictionRulePanel Constructor creates a ContradictionRulePanel - * - * @param ruleFrame rule frame that this ContradictionRulePanel is contained in - */ - ContradictionRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = new ImageIcon(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Contradictions.gif")); - this.name = "Contradiction Rules"; - this.toolTip = "Contradiction Rules"; - } + /** + * ContradictionRulePanel Constructor creates a ContradictionRulePanel + * + * @param ruleFrame rule frame that this ContradictionRulePanel is contained in + */ + ContradictionRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Contradictions.gif")); + this.name = "Contradiction Rules"; + this.toolTip = "Contradiction Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java index 2f165b55d..a89811a64 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java @@ -1,22 +1,24 @@ package edu.rpi.legup.ui.proofeditorui.rulesview; +import javax.swing.ImageIcon; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import javax.swing.ImageIcon; - public class DirectRulePanel extends RulePanel { - private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); - /** - * DirectRulePanel Constructor creates a basic rule panel - * - * @param ruleFrame rule frame that this basic rule panel is contained in - */ - DirectRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = new ImageIcon(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Direct Rules"; - this.toolTip = "Direct Rules"; - } -} \ No newline at end of file + /** + * DirectRulePanel Constructor creates a basic rule panel + * + * @param ruleFrame rule frame that this basic rule panel is contained in + */ + DirectRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Direct Rules"; + this.toolTip = "Direct Rules"; + } +} diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java index 30545f413..6100b6964 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java @@ -1,38 +1,39 @@ package edu.rpi.legup.ui.proofeditorui.rulesview; import edu.rpi.legup.model.rules.Rule; - import javax.swing.*; public class RuleButton extends JButton { - private Rule rule; + private Rule rule; - /** - * RuleButton Constructor - creates a button for a rule - * - * @param rule rule to create the button - */ - RuleButton(Rule rule) { - super(rule.getRuleName(), rule.getImageIcon()); // display rules' name under rule when load the icon - this.rule = rule; - this.setFocusPainted(false); - } + /** + * RuleButton Constructor - creates a button for a rule + * + * @param rule rule to create the button + */ + RuleButton(Rule rule) { + super( + rule.getRuleName(), + rule.getImageIcon()); // display rules' name under rule when load the icon + this.rule = rule; + this.setFocusPainted(false); + } - /** - * Gets the Rule from this button - * - * @return Rule from this button - */ - public Rule getRule() { - return rule; - } + /** + * Gets the Rule from this button + * + * @return Rule from this button + */ + public Rule getRule() { + return rule; + } - /** - * Sets the Rule for this button - * - * @param rule Rule for this button - */ - void setRule(Rule rule) { - this.rule = rule; - } + /** + * Sets the Rule for this button + * + * @param rule Rule for this button + */ + void setRule(Rule rule) { + this.rule = rule; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java index 0fe03d476..2f31f24dc 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java @@ -5,176 +5,171 @@ import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.rules.Rule; import edu.rpi.legup.ui.lookandfeel.components.MaterialTabbedPaneUI; - import java.awt.BorderLayout; import java.awt.Dimension; - import javax.swing.*; - import javax.swing.border.TitledBorder; public class RuleFrame extends JPanel { - private static final String checkBox = " \u2714 "; - private static final String xBox = " \u2718 "; - private static final String htmlHead = ""; - private static final String htmlTail = ""; + private static final String checkBox = " \u2714 "; + private static final String xBox = " \u2718 "; + private static final String htmlHead = ""; + private static final String htmlTail = ""; - private DirectRulePanel DirectRulePanel; - private ContradictionRulePanel contradictionPanel; - private CaseRulePanel casePanel; + private DirectRulePanel DirectRulePanel; + private ContradictionRulePanel contradictionPanel; + private CaseRulePanel casePanel; - private SearchBarPanel searchPanel; + private SearchBarPanel searchPanel; - private JTabbedPane tabbedPane; - private JLabel status; - private ButtonGroup buttonGroup; + private JTabbedPane tabbedPane; + private JLabel status; + private ButtonGroup buttonGroup; - private RuleController controller; + private RuleController controller; - public RuleFrame(RuleController controller) { + public RuleFrame(RuleController controller) { - MaterialTabbedPaneUI tabOverride = new MaterialTabbedPaneUI() { - //this prevents the tabs from moving around when you select them - @Override - protected boolean shouldRotateTabRuns(int i) { - return false; - } + MaterialTabbedPaneUI tabOverride = + new MaterialTabbedPaneUI() { + // this prevents the tabs from moving around when you select them + @Override + protected boolean shouldRotateTabRuns(int i) { + return false; + } }; - this.controller = controller; - - this.tabbedPane = new JTabbedPane(); - this.tabbedPane.setUI(tabOverride); - this.status = new JLabel(); - this.buttonGroup = new ButtonGroup(); - - DirectRulePanel = new DirectRulePanel(this); - JScrollPane newbrp = new JScrollPane(DirectRulePanel); - newbrp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(DirectRulePanel.getName(), DirectRulePanel.getIcon(), newbrp, DirectRulePanel.getToolTip()); - - casePanel = new CaseRulePanel(this); - JScrollPane newcp = new JScrollPane(casePanel); - newcp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(casePanel.name, casePanel.icon, newcp, casePanel.toolTip); - - contradictionPanel = new ContradictionRulePanel(this); - JScrollPane newp = new JScrollPane(contradictionPanel); - newp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(contradictionPanel.name, contradictionPanel.icon, newp, contradictionPanel.toolTip); - - searchPanel = new SearchBarPanel(this); - JScrollPane newsp = new JScrollPane(searchPanel); - newsp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(searchPanel.name, searchPanel.icon, newsp, searchPanel.toolTip); - - setLayout(new BorderLayout()); - setMinimumSize(new Dimension(250, 256)); - setPreferredSize(new Dimension(355, 256)); - - add(tabbedPane); - add(status, BorderLayout.SOUTH); - - TitledBorder title = BorderFactory.createTitledBorder("Rules"); - title.setTitleJustification(TitledBorder.CENTER); - setBorder(title); - } - - /** - * Gets the button group for the rule frame - * - * @return button group - */ - public ButtonGroup getButtonGroup() { - return buttonGroup; - } - - public void setSelectionByRule(Rule rule) { - DirectRulePanel.setSelectionByRule(rule); - casePanel.setSelectionByRule(rule); - contradictionPanel.setSelectionByRule(rule); - } - - /** - * Reset the rules button and status string - */ - public void resetRuleButtons() { - resetStatus(); - } - - /** - * Reset the status label to the empty string - */ - public void resetStatus() { - //((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().updateStatus(); - } - - /** - * Resets the dimension of the rule frame - */ - public void resetSize() { - int buttonWidth = ((RulePanel) tabbedPane.getSelectedComponent()).getRuleButtons()[0].getWidth(); - this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); - } - - /** - * Set the status label to a value. Use resetStatus to clear it. - * - * @param check true iff we want a check box, if false we'll have a red x box - * @param text the text we're setting the label to display - */ - public void setStatus(boolean check, String text) { - String box = (check ? checkBox : xBox); - //status.setText(htmlHead + box + text + htmlTail); - //((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().getStatus().setText(htmlHead + box + text + htmlTail); - } - - /** - * Sets all the rules for the rule frame - * - * @param puzzle edu.rpi.legup.puzzle game - */ - public void setRules(Puzzle puzzle) { - DirectRulePanel.setRules(puzzle.getDirectRules()); - contradictionPanel.setRules(puzzle.getContradictionRules()); - casePanel.setRules(puzzle.getCaseRules()); - } - - /** - * Board puzzleElement has changed - * - * @param board board state - */ - public void boardDataChanged(Board board) { - this.resetStatus(); - } - - /** - * Gets the RuleController for this RuleFrame - * - * @return rule controller - */ - public RuleController getController() { - return controller; - } - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - public DirectRulePanel getDirectRulePanel() { - return DirectRulePanel; - } - - public CaseRulePanel getCasePanel() { - return casePanel; - } - - public ContradictionRulePanel getContradictionPanel() { - return contradictionPanel; - } - - public SearchBarPanel getSearchPanel() { - return searchPanel; - } + this.controller = controller; + + this.tabbedPane = new JTabbedPane(); + this.tabbedPane.setUI(tabOverride); + this.status = new JLabel(); + this.buttonGroup = new ButtonGroup(); + + DirectRulePanel = new DirectRulePanel(this); + JScrollPane newbrp = new JScrollPane(DirectRulePanel); + newbrp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab( + DirectRulePanel.getName(), DirectRulePanel.getIcon(), newbrp, DirectRulePanel.getToolTip()); + + casePanel = new CaseRulePanel(this); + JScrollPane newcp = new JScrollPane(casePanel); + newcp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab(casePanel.name, casePanel.icon, newcp, casePanel.toolTip); + + contradictionPanel = new ContradictionRulePanel(this); + JScrollPane newp = new JScrollPane(contradictionPanel); + newp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab( + contradictionPanel.name, contradictionPanel.icon, newp, contradictionPanel.toolTip); + + searchPanel = new SearchBarPanel(this); + JScrollPane newsp = new JScrollPane(searchPanel); + newsp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab(searchPanel.name, searchPanel.icon, newsp, searchPanel.toolTip); + + setLayout(new BorderLayout()); + setMinimumSize(new Dimension(250, 256)); + setPreferredSize(new Dimension(355, 256)); + + add(tabbedPane); + add(status, BorderLayout.SOUTH); + + TitledBorder title = BorderFactory.createTitledBorder("Rules"); + title.setTitleJustification(TitledBorder.CENTER); + setBorder(title); + } + + /** + * Gets the button group for the rule frame + * + * @return button group + */ + public ButtonGroup getButtonGroup() { + return buttonGroup; + } + + public void setSelectionByRule(Rule rule) { + DirectRulePanel.setSelectionByRule(rule); + casePanel.setSelectionByRule(rule); + contradictionPanel.setSelectionByRule(rule); + } + + /** Reset the rules button and status string */ + public void resetRuleButtons() { + resetStatus(); + } + + /** Reset the status label to the empty string */ + public void resetStatus() { + // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().updateStatus(); + } + + /** Resets the dimension of the rule frame */ + public void resetSize() { + int buttonWidth = + ((RulePanel) tabbedPane.getSelectedComponent()).getRuleButtons()[0].getWidth(); + this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); + } + + /** + * Set the status label to a value. Use resetStatus to clear it. + * + * @param check true iff we want a check box, if false we'll have a red x box + * @param text the text we're setting the label to display + */ + public void setStatus(boolean check, String text) { + String box = (check ? checkBox : xBox); + // status.setText(htmlHead + box + text + htmlTail); + // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().getStatus().setText(htmlHead + box + text + htmlTail); + } + + /** + * Sets all the rules for the rule frame + * + * @param puzzle edu.rpi.legup.puzzle game + */ + public void setRules(Puzzle puzzle) { + DirectRulePanel.setRules(puzzle.getDirectRules()); + contradictionPanel.setRules(puzzle.getContradictionRules()); + casePanel.setRules(puzzle.getCaseRules()); + } + + /** + * Board puzzleElement has changed + * + * @param board board state + */ + public void boardDataChanged(Board board) { + this.resetStatus(); + } + + /** + * Gets the RuleController for this RuleFrame + * + * @return rule controller + */ + public RuleController getController() { + return controller; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public DirectRulePanel getDirectRulePanel() { + return DirectRulePanel; + } + + public CaseRulePanel getCasePanel() { + return casePanel; + } + + public ContradictionRulePanel getContradictionPanel() { + return contradictionPanel; + } + + public SearchBarPanel getSearchPanel() { + return searchPanel; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java index f11fee5b4..50bd8a110 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java @@ -3,342 +3,343 @@ import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.model.rules.Rule; import edu.rpi.legup.ui.WrapLayout; - -import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.List; +import javax.swing.*; public abstract class RulePanel extends JPanel { - protected ImageIcon icon; - protected String name; - protected String toolTip; - - protected RuleButton[] ruleButtons; - protected JPanel searchBarPanel; - JTextField textField; - protected RuleFrame ruleFrame; - protected List rules; - - /** - * RulePanel Constructor creates a RulePanel - * - * @param ruleFrame rule frame that this RulePanel is contained in - */ - public RulePanel(RuleFrame ruleFrame) { - this.ruleFrame = ruleFrame; - this.rules = new ArrayList<>(); - setLayout(new WrapLayout()); + protected ImageIcon icon; + protected String name; + protected String toolTip; + + protected RuleButton[] ruleButtons; + protected JPanel searchBarPanel; + JTextField textField; + protected RuleFrame ruleFrame; + protected List rules; + + /** + * RulePanel Constructor creates a RulePanel + * + * @param ruleFrame rule frame that this RulePanel is contained in + */ + public RulePanel(RuleFrame ruleFrame) { + this.ruleFrame = ruleFrame; + this.rules = new ArrayList<>(); + setLayout(new WrapLayout()); + } + + /** + * Gets the rule rule buttons + * + * @return rule ruleButtons + */ + public RuleButton[] getRuleButtons() { + return ruleButtons; + } + + /** + * Sets the rules for this rule panel + * + * @param rules list of the rules + */ + public void setRules(List rules) { + this.rules = rules; + clearButtons(); + + ruleButtons = new RuleButton[rules.size()]; + + for (int i = 0; i < rules.size(); i++) { + Rule rule = rules.get(i); + + ruleButtons[i] = new RuleButton(rule); + ruleButtons[i].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[i].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[i].setVerticalTextPosition(JButton.BOTTOM); + + ruleFrame.getButtonGroup().add(ruleButtons[i]); + ruleButtons[i].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); // showing description + ruleButtons[i].addActionListener(ruleFrame.getController()); + add(ruleButtons[i]); } + revalidate(); + } - /** - * Gets the rule rule buttons - * - * @return rule ruleButtons - */ - public RuleButton[] getRuleButtons() { - return ruleButtons; + public void updateRules() { + for (Rule rule : rules) { + rule.loadImage(); } - - /** - * Sets the rules for this rule panel - * - * @param rules list of the rules - */ - public void setRules(List rules) { - this.rules = rules; - clearButtons(); - - ruleButtons = new RuleButton[rules.size()]; - - for (int i = 0; i < rules.size(); i++) { - Rule rule = rules.get(i); - - ruleButtons[i] = new RuleButton(rule); - ruleButtons[i].setPreferredSize(new Dimension(150, 150));// adjust the size of each RuleButton - ruleButtons[i].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[i].setVerticalTextPosition(JButton.BOTTOM); - - ruleFrame.getButtonGroup().add(ruleButtons[i]); - ruleButtons[i].setToolTipText(rule.getRuleName() + ": " + rule.getDescription()); // showing description - ruleButtons[i].addActionListener(ruleFrame.getController()); - add(ruleButtons[i]); - + setRules(rules); + } + + /** + * Search a certain rule in all the puzzles and set it for the searchBarPanel + * + * @param puzzle puzzle where the rule is being searched for + * @param ruleName rule that is being compared to each puzzle + *

This function is the searching algorithm for "public void setSearchBar(Puzzle + * allPuzzle)" (below) + *

It takes two param Puzzle puzzle and String ruleName puzzle contains rules, this + * function will compare each rule of puzzle with ruleName, to find exact same, similar rules, + * or all the rules with same start letter (if input is a signal letter) + */ + public void searchForRule(Puzzle puzzle, String ruleName) { + + List> allrules = new ArrayList>(3); + allrules.add(0, puzzle.getDirectRules()); + allrules.add(1, puzzle.getCaseRules()); + allrules.add(2, puzzle.getContradictionRules()); + + ruleButtons = new RuleButton[100]; + int similarfound = 0; + + for (int i = 0; i < allrules.size(); i++) { + for (int j = 0; j < allrules.get(i).size(); j++) { + Rule rule = allrules.get(i).get(j); + if ((ruleName).equals(rule.getRuleName().toUpperCase())) { + + ruleButtons[0] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[0]); + + ruleButtons[0].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[0].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[0].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[0].setToolTipText(rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[0].addActionListener(ruleFrame.getController()); + add(ruleButtons[0]); + revalidate(); + return; + + } else { + if (similarityCheck(ruleName, rule.getRuleName().toUpperCase()) > 0.2) { + ruleButtons[similarfound] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); + + ruleButtons[similarfound].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[similarfound].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[similarfound].addActionListener(ruleFrame.getController()); + add(ruleButtons[similarfound]); + similarfound += 1; + revalidate(); + } else { + if ((ruleName.charAt(0)) == (rule.getRuleName().toUpperCase()).charAt(0)) { + ruleButtons[similarfound] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); + + ruleButtons[similarfound].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[similarfound].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[similarfound].addActionListener(ruleFrame.getController()); + add(ruleButtons[similarfound]); + similarfound += 1; + revalidate(); + } + } } - revalidate(); + } } - public void updateRules() { - for (Rule rule : rules){ - rule.loadImage(); - } - setRules(rules); + if (ruleButtons[0] == null) { + JOptionPane.showMessageDialog( + null, "Please input the correct rule name", "Confirm", JOptionPane.INFORMATION_MESSAGE); } - - - /** - * Search a certain rule in all the puzzles and set it for the searchBarPanel - * - * @param puzzle puzzle where the rule is being searched for - * @param ruleName rule that is being compared to each puzzle - * - * This function is the searching algorithm for "public void setSearchBar(Puzzle allPuzzle)" (below) - * - * It takes two param Puzzle puzzle and String ruleName - * puzzle contains rules, this function will compare each rule of puzzle with ruleName, - * to find exact same, similar rules, or all the rules with same start letter (if input is a signal letter) - */ - public void searchForRule(Puzzle puzzle, String ruleName) { - - List> allrules = new ArrayList>(3); - allrules.add(0, puzzle.getDirectRules()); - allrules.add(1, puzzle.getCaseRules()); - allrules.add(2, puzzle.getContradictionRules()); - - ruleButtons = new RuleButton[100]; - int similarfound = 0; - - - for (int i = 0; i < allrules.size(); i++) { - for (int j = 0; j < allrules.get(i).size(); j++) { - Rule rule = allrules.get(i).get(j); - if ((ruleName).equals(rule.getRuleName().toUpperCase())) { - - ruleButtons[0] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[0]); - - ruleButtons[0].setPreferredSize(new Dimension(150, 150));// adjust the size of each RuleButton - ruleButtons[0].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[0].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[0].setToolTipText(rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[0].addActionListener(ruleFrame.getController()); - add(ruleButtons[0]); - revalidate(); - return; - - } - else { - if (similarityCheck(ruleName, rule.getRuleName().toUpperCase()) > 0.2) { - ruleButtons[similarfound] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); - - ruleButtons[similarfound].setPreferredSize(new Dimension(150, 150));// adjust the size of each RuleButton - ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[similarfound].setToolTipText(rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[similarfound].addActionListener(ruleFrame.getController()); - add(ruleButtons[similarfound]); - similarfound += 1; - revalidate(); - } - else { - if ((ruleName.charAt(0)) == (rule.getRuleName().toUpperCase()).charAt(0)) { - ruleButtons[similarfound] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); - - ruleButtons[similarfound].setPreferredSize(new Dimension(150, 150));// adjust the size of each RuleButton - ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[similarfound].setToolTipText(rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[similarfound].addActionListener(ruleFrame.getController()); - add(ruleButtons[similarfound]); - similarfound += 1; - revalidate(); - } - } - } - } - } - - if (ruleButtons[0] == null) { - JOptionPane.showMessageDialog(null, "Please input the correct rule name", "Confirm", JOptionPane.INFORMATION_MESSAGE); - } + } + + /** + * Calculates the similarity (a number within 0 and 1) between two strings. This function will + * take two para String s1 and String s2, which s1 is the user's input and s2 is the compared + * really rule name + * + * @param s1 user's input + * @param s2 the compared really rule name + * @return a similarity degree between 0 and 1 similarityCheck will use a helper function to + * calculate a similarity degree(from 0 to 1). closer to 0 means less similar, and closer to 1 + * means more similar. + */ + public static double similarityCheck(String s1, String s2) { + String longer = s1, shorter = s2; + if (s1.length() < s2.length()) { // longer should always have greater length + longer = s2; + shorter = s1; } - - /** - * Calculates the similarity (a number within 0 and 1) between two strings. - * This function will take two para String s1 and String s2, which s1 is the user's input - * and s2 is the compared really rule name - * @param s1 user's input - * @param s2 the compared really rule name - * @return a similarity degree between 0 and 1 - * similarityCheck will use a helper function to calculate a similarity degree(from 0 to 1). - * closer to 0 means less similar, and closer to 1 means more similar. - */ - public static double similarityCheck(String s1, String s2) { - String longer = s1, shorter = s2; - if (s1.length() < s2.length()) { // longer should always have greater length - longer = s2; - shorter = s1; - } - int longerLength = longer.length(); - if (longerLength == 0) { - return 1.0; /* both strings are zero length */ - } - return (longerLength - editDistance(longer, shorter)) / (double) longerLength; + int longerLength = longer.length(); + if (longerLength == 0) { + return 1.0; /* both strings are zero length */ } - - /** - * Help function for similarityCheck(); - * @param s1 user's input - * @param s2 the compared really rule name - * @return a similarity degree between 0 and 1 - */ - public static int editDistance(String s1, String s2) { - s1 = s1.toLowerCase(); - s2 = s2.toLowerCase(); - - int[] costs = new int[s2.length() + 1]; - for (int i = 0; i <= s1.length(); i++) { - int lastValue = i; - for (int j = 0; j <= s2.length(); j++) { - if (i == 0) { - costs[j] = j; - } - else { - if (j > 0) { - int newValue = costs[j - 1]; - if (s1.charAt(i - 1) != s2.charAt(j - 1)) { - newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; - } - costs[j - 1] = lastValue; - lastValue = newValue; - } - } - } - if (i > 0) { - costs[s2.length()] = lastValue; + return (longerLength - editDistance(longer, shorter)) / (double) longerLength; + } + + /** + * Help function for similarityCheck(); + * + * @param s1 user's input + * @param s2 the compared really rule name + * @return a similarity degree between 0 and 1 + */ + public static int editDistance(String s1, String s2) { + s1 = s1.toLowerCase(); + s2 = s2.toLowerCase(); + + int[] costs = new int[s2.length() + 1]; + for (int i = 0; i <= s1.length(); i++) { + int lastValue = i; + for (int j = 0; j <= s2.length(); j++) { + if (i == 0) { + costs[j] = j; + } else { + if (j > 0) { + int newValue = costs[j - 1]; + if (s1.charAt(i - 1) != s2.charAt(j - 1)) { + newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; } + costs[j - 1] = lastValue; + lastValue = newValue; + } } - return costs[s2.length()]; + } + if (i > 0) { + costs[s2.length()] = lastValue; + } } - - /** - * Sets the search bar for SearchBarPanel - * search bar allows user to input a name to get relative rules - * once a name is entered and click ok will load (a/several) rule icon, - * which has all the functions just as other rule icons. - * @param allPuzzle name of rule input - */ - public void setSearchBar(Puzzle allPuzzle) { - - searchBarPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 6, 6)); - - textField=new JTextField(); - ruleFrame.addComponentListener(new ComponentAdapter() { - public void componentResized(ComponentEvent componentEvent) { - Component c= componentEvent.getComponent(); - textField.setColumns((8+(c.getWidth()-250)/10)-1); - } + return costs[s2.length()]; + } + + /** + * Sets the search bar for SearchBarPanel search bar allows user to input a name to get relative + * rules once a name is entered and click ok will load (a/several) rule icon, which has all the + * functions just as other rule icons. + * + * @param allPuzzle name of rule input + */ + public void setSearchBar(Puzzle allPuzzle) { + + searchBarPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 6, 6)); + + textField = new JTextField(); + ruleFrame.addComponentListener( + new ComponentAdapter() { + public void componentResized(ComponentEvent componentEvent) { + Component c = componentEvent.getComponent(); + textField.setColumns((8 + (c.getWidth() - 250) / 10) - 1); + } }); - add(searchBarPanel); - JLabel findLabel = new JLabel("Search:"); - searchBarPanel.add(findLabel); - searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); - searchBarPanel.add(textField); - searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); - JButton findButton = new JButton("Go"); - ActionListener action = new ActionListener() { - @Override - public void actionPerformed(ActionEvent event) { - if (ruleButtons != null) { - for (int i = 0; i != ruleButtons.length; i++) { - if (ruleButtons[i] == null) { - continue; - } - ruleButtons[i].removeActionListener(ruleFrame.getController()); - } - } - String inputRule = textField.getText().toUpperCase().trim(); - - if (!inputRule.isEmpty()) { - if (ruleButtons != null) { - - for (int x = 0; x < ruleButtons.length; ++x) { - if (ruleButtons[x] == null) { - continue; - } - remove(ruleButtons[x]); - } - } - searchForRule(allPuzzle, inputRule); - } - else { - JOptionPane.showMessageDialog(null, "Please give a name", "Confirm", JOptionPane.INFORMATION_MESSAGE); + add(searchBarPanel); + JLabel findLabel = new JLabel("Search:"); + searchBarPanel.add(findLabel); + searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); + searchBarPanel.add(textField); + searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); + JButton findButton = new JButton("Go"); + ActionListener action = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + if (ruleButtons != null) { + for (int i = 0; i != ruleButtons.length; i++) { + if (ruleButtons[i] == null) { + continue; } - + ruleButtons[i].removeActionListener(ruleFrame.getController()); + } } - }; - textField.addActionListener(action); - findButton.addActionListener(action); - searchBarPanel.add(findButton); - } + String inputRule = textField.getText().toUpperCase().trim(); - /** - * Sets the selection by the specified rule - * - * @param rule rule to set the selection to - */ - public void setSelectionByRule(Rule rule) { - if (ruleButtons != null) { - for (int i = 0; i < ruleButtons.length; i++) { - if (rules.get(i).equals(rule)) { - ruleButtons[i].setSelected(true); - break; - } - } - } - } + if (!inputRule.isEmpty()) { + if (ruleButtons != null) { - /** - * Clears the rule buttons off this panel - */ - protected void clearButtons() { - if (ruleButtons != null) { - removeAll(); - for (int x = 0; x < ruleButtons.length; ++x) { - ruleButtons[x].removeActionListener(ruleFrame.getController()); + for (int x = 0; x < ruleButtons.length; ++x) { + if (ruleButtons[x] == null) { + continue; + } + remove(ruleButtons[x]); + } + } + searchForRule(allPuzzle, inputRule); + } else { + JOptionPane.showMessageDialog( + null, "Please give a name", "Confirm", JOptionPane.INFORMATION_MESSAGE); } + } + }; + textField.addActionListener(action); + findButton.addActionListener(action); + searchBarPanel.add(findButton); + } + + /** + * Sets the selection by the specified rule + * + * @param rule rule to set the selection to + */ + public void setSelectionByRule(Rule rule) { + if (ruleButtons != null) { + for (int i = 0; i < ruleButtons.length; i++) { + if (rules.get(i).equals(rule)) { + ruleButtons[i].setSelected(true); + break; } + } } - - /** - * Gets the rules associated with this panel - * - * @return the rules - */ - public List getRules() { - return rules; - } - - public ImageIcon getIcon() { - return icon; - } - - public void setIcon(ImageIcon icon) { - this.icon = icon; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getToolTip() { - return toolTip; - } - - public void setToolTip(String toolTip) { - this.toolTip = toolTip; + } + + /** Clears the rule buttons off this panel */ + protected void clearButtons() { + if (ruleButtons != null) { + removeAll(); + for (int x = 0; x < ruleButtons.length; ++x) { + ruleButtons[x].removeActionListener(ruleFrame.getController()); + } } -} \ No newline at end of file + } + + /** + * Gets the rules associated with this panel + * + * @return the rules + */ + public List getRules() { + return rules; + } + + public ImageIcon getIcon() { + return icon; + } + + public void setIcon(ImageIcon icon) { + this.icon = icon; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + public String getToolTip() { + return toolTip; + } + + public void setToolTip(String toolTip) { + this.toolTip = toolTip; + } +} diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java index ff8a5d259..b0dddc2c7 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java @@ -3,17 +3,19 @@ import javax.swing.*; public class SearchBarPanel extends RulePanel { - /** - * SearchBarPanel Constructor creates a SearchBarPanel - * - * @param ruleFrame rule frame that this SearchBarPanel is contained in - *

- * This class is used to create a panel named "search bar" - */ - SearchBarPanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = new ImageIcon(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Zoom In.png")); - this.name = "Search Rules"; - this.toolTip = "Search Rules"; - } + /** + * SearchBarPanel Constructor creates a SearchBarPanel + * + * @param ruleFrame rule frame that this SearchBarPanel is contained in + *

This class is used to create a panel named "search bar" + */ + SearchBarPanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Zoom In.png")); + this.name = "Search Rules"; + this.toolTip = "Search Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java index 676992654..00b8ec0bb 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java @@ -2,173 +2,172 @@ import edu.rpi.legup.model.tree.TreeElement; import edu.rpi.legup.model.tree.TreeElementType; - import java.awt.*; public abstract class TreeElementView implements Shape { - protected TreeElement treeElement; - protected double span; - protected int depth; - protected boolean isSelected; - protected boolean isHover; - protected TreeElementType type; - protected boolean isVisible; - protected boolean isCollapsed; - - /** - * TreeElementView Constructor creates a tree puzzleElement view - * - * @param type tree puzzleElement type - * @param treeElement tree puzzleElement puzzleElement associated with this view - */ - protected TreeElementView(TreeElementType type, TreeElement treeElement) { - this.type = type; - this.treeElement = treeElement; - this.isSelected = false; - this.isHover = false; - this.isVisible = true; - } - - /** - * Draws the tree puzzleElement view - * - * @param graphics2D graphics2D object used to draw the tree puzzleElement view - */ - public abstract void draw(Graphics2D graphics2D); - - /** - * Gets the span for the sub tree rooted at this view - * - * @return span bounded y span - */ - public double getSpan() { - return span; - } - - /** - * Sets the span for the sub tree rooted at this view. - * - * @param span bounded y span - */ - public void setSpan(double span) { - this.span = span; - } - - /** - * Gets the depth of this tree puzzleElement in the tree - * - * @return depth of this tree puzzleElement - */ - public int getDepth() { - return depth; - } - - /** - * Sets the depth of this tree puzzleElement in the tree - * - * @param depth depth of this tree puzzleElement - */ - public void setDepth(int depth) { - this.depth = depth; - } - - /** - * Gets the tree puzzleElement type for this view - * - * @return tree puzzleElement type - */ - public TreeElementType getType() { - return type; - } - - /** - * Gets the tree puzzleElement associated with this view - * - * @return tree puzzleElement associated with this view - */ - public TreeElement getTreeElement() { - return treeElement; - } - - /** - * Sets the tree puzzleElement associated with this view - * - * @param treeElement tree puzzleElement associated with this view - */ - public void setTreeElement(TreeElement treeElement) { - this.treeElement = treeElement; - } - - /** - * Gets the mouse selection - * - * @return mouse selection - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets the mouse selection - * - * @param isSelected mouse selection - */ - public void setSelected(boolean isSelected) { - this.isSelected = isSelected; - } - - /** - * Gets the mouse hover - * - * @return mouse hover - */ - public boolean isHover() { - return isHover; - } - - /** - * Sets the mouse hover - * - * @param isHovered mouse hover - */ - public void setHover(boolean isHovered) { - this.isHover = isHovered; - } - - /** - * Gets the visibility of the tree puzzleElement. - * Tells the TreeView whether or not to draw the tree puzzleElement - * - * @return visibility of the tree puzzleElement - */ - public boolean isVisible() { - return isVisible; - } - - /** - * Sets the visibility of the tree puzzleElement - * - * @param isVisible visibility of the tree puzzleElement - */ - public void setVisible(boolean isVisible) { - this.isVisible = isVisible; - } - - /** - * Is this tree node view collapsed in the view - * - * @return true if the node is collapsed, false otherwise - */ - public boolean isCollapsed() { - return isCollapsed; - } - - /** - * Sets the tree node view collapsed field - * - * @param isCollapsed true if the node is collapsed, false otherwise - */ - public void setCollapsed(boolean isCollapsed) { - this.isCollapsed = isCollapsed; - } + protected TreeElement treeElement; + protected double span; + protected int depth; + protected boolean isSelected; + protected boolean isHover; + protected TreeElementType type; + protected boolean isVisible; + protected boolean isCollapsed; + + /** + * TreeElementView Constructor creates a tree puzzleElement view + * + * @param type tree puzzleElement type + * @param treeElement tree puzzleElement puzzleElement associated with this view + */ + protected TreeElementView(TreeElementType type, TreeElement treeElement) { + this.type = type; + this.treeElement = treeElement; + this.isSelected = false; + this.isHover = false; + this.isVisible = true; + } + + /** + * Draws the tree puzzleElement view + * + * @param graphics2D graphics2D object used to draw the tree puzzleElement view + */ + public abstract void draw(Graphics2D graphics2D); + + /** + * Gets the span for the sub tree rooted at this view + * + * @return span bounded y span + */ + public double getSpan() { + return span; + } + + /** + * Sets the span for the sub tree rooted at this view. + * + * @param span bounded y span + */ + public void setSpan(double span) { + this.span = span; + } + + /** + * Gets the depth of this tree puzzleElement in the tree + * + * @return depth of this tree puzzleElement + */ + public int getDepth() { + return depth; + } + + /** + * Sets the depth of this tree puzzleElement in the tree + * + * @param depth depth of this tree puzzleElement + */ + public void setDepth(int depth) { + this.depth = depth; + } + + /** + * Gets the tree puzzleElement type for this view + * + * @return tree puzzleElement type + */ + public TreeElementType getType() { + return type; + } + + /** + * Gets the tree puzzleElement associated with this view + * + * @return tree puzzleElement associated with this view + */ + public TreeElement getTreeElement() { + return treeElement; + } + + /** + * Sets the tree puzzleElement associated with this view + * + * @param treeElement tree puzzleElement associated with this view + */ + public void setTreeElement(TreeElement treeElement) { + this.treeElement = treeElement; + } + + /** + * Gets the mouse selection + * + * @return mouse selection + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets the mouse selection + * + * @param isSelected mouse selection + */ + public void setSelected(boolean isSelected) { + this.isSelected = isSelected; + } + + /** + * Gets the mouse hover + * + * @return mouse hover + */ + public boolean isHover() { + return isHover; + } + + /** + * Sets the mouse hover + * + * @param isHovered mouse hover + */ + public void setHover(boolean isHovered) { + this.isHover = isHovered; + } + + /** + * Gets the visibility of the tree puzzleElement. Tells the TreeView whether or not to draw the + * tree puzzleElement + * + * @return visibility of the tree puzzleElement + */ + public boolean isVisible() { + return isVisible; + } + + /** + * Sets the visibility of the tree puzzleElement + * + * @param isVisible visibility of the tree puzzleElement + */ + public void setVisible(boolean isVisible) { + this.isVisible = isVisible; + } + + /** + * Is this tree node view collapsed in the view + * + * @return true if the node is collapsed, false otherwise + */ + public boolean isCollapsed() { + return isCollapsed; + } + + /** + * Sets the tree node view collapsed field + * + * @param isCollapsed true if the node is collapsed, false otherwise + */ + public void setCollapsed(boolean isCollapsed) { + this.isCollapsed = isCollapsed; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java index 2fce4d2d1..dbb4dfcb4 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java @@ -3,291 +3,290 @@ import edu.rpi.legup.model.rules.RuleType; import edu.rpi.legup.model.tree.TreeElementType; import edu.rpi.legup.model.tree.TreeNode; - import java.awt.*; import java.awt.geom.*; import java.util.ArrayList; public class TreeNodeView extends TreeElementView { - static final int RADIUS = 25; - static final int DIAMETER = 2 * RADIUS; - - private static final Stroke MAIN_STROKE = new BasicStroke(3); - private static final Stroke SELECTION_STROKE = new BasicStroke(2); - - private static final Color NODE_COLOR_ROOT = new Color(100, 100, 100); - private static final Color NODE_MINOR_COLOR_ROOT = new Color(75, 75, 75); - - private static final Color NODE_COLOR_DEFAULT = new Color(0xFFEB3B); - private static final Color NODE_MINOR_COLOR_DEFAULT = new Color(216, 197, 52); - - private static final Color NODE_COLOR_CONTRADICTION = new Color(178, 10, 16); - private static final Color NODE_MINOR_COLOR_CONTRADICTION = new Color(119, 13, 16); - - private static final Color OUTLINE_COLOR = new Color(0x212121); - private static final Color SELECTION_COLOR = new Color(0x1E88E5); - private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); - - private static final Color HOVER_COLOR = new Color(0x90CAF9); - private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); - - - private Point location; - - private TreeTransitionView parentView; - private ArrayList childrenViews; - - private boolean isCollapsed; - private boolean isContradictoryState; - - /** - * TreeNodeView Constructor creates a node for display - * - * @param treeNode treeElement associated with this transition - */ - public TreeNodeView(TreeNode treeNode) { - super(TreeElementType.NODE, treeNode); - this.treeElement = treeNode; - this.location = new Point(); - this.parentView = null; - this.childrenViews = new ArrayList<>(); - this.isCollapsed = false; - this.isContradictoryState = false; - this.isVisible = true; - } - - /** - * Draws the TreeNodeView - * - * @param graphics2D graphics2D used for drawing - */ - public void draw(Graphics2D graphics2D) { - if (isVisible() && treeElement != null) { - if (getTreeElement().getParent() != null && - getTreeElement().getParent().isJustified() && - getTreeElement().getParent().getRule().getRuleType() == RuleType.CONTRADICTION) { - isContradictoryState = true; - graphics2D.setColor(NODE_COLOR_CONTRADICTION); - graphics2D.drawLine(location.x - RADIUS, location.y - RADIUS, location.x + RADIUS, location.y + RADIUS); - graphics2D.drawLine(location.x + RADIUS, location.y - RADIUS, location.x - RADIUS, location.y + RADIUS); - } - else { - isContradictoryState = false; - graphics2D.setStroke(MAIN_STROKE); - boolean isContraBranch = getTreeElement().isContradictoryBranch(); - - if (isSelected) { - graphics2D.setColor(SELECTION_COLOR); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_SELECTION_COLOR); - graphics2D.drawOval(location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); - } - else { - if (isHover) { - graphics2D.setColor(HOVER_COLOR); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_HOVER_COLOR); - graphics2D.drawOval(location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); - } - else { - graphics2D.setColor(isContraBranch ? NODE_COLOR_CONTRADICTION : NODE_COLOR_DEFAULT); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - } - } - } + static final int RADIUS = 25; + static final int DIAMETER = 2 * RADIUS; + + private static final Stroke MAIN_STROKE = new BasicStroke(3); + private static final Stroke SELECTION_STROKE = new BasicStroke(2); + + private static final Color NODE_COLOR_ROOT = new Color(100, 100, 100); + private static final Color NODE_MINOR_COLOR_ROOT = new Color(75, 75, 75); + + private static final Color NODE_COLOR_DEFAULT = new Color(0xFFEB3B); + private static final Color NODE_MINOR_COLOR_DEFAULT = new Color(216, 197, 52); + + private static final Color NODE_COLOR_CONTRADICTION = new Color(178, 10, 16); + private static final Color NODE_MINOR_COLOR_CONTRADICTION = new Color(119, 13, 16); + + private static final Color OUTLINE_COLOR = new Color(0x212121); + private static final Color SELECTION_COLOR = new Color(0x1E88E5); + private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); + + private static final Color HOVER_COLOR = new Color(0x90CAF9); + private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); + + private Point location; + + private TreeTransitionView parentView; + private ArrayList childrenViews; + + private boolean isCollapsed; + private boolean isContradictoryState; + + /** + * TreeNodeView Constructor creates a node for display + * + * @param treeNode treeElement associated with this transition + */ + public TreeNodeView(TreeNode treeNode) { + super(TreeElementType.NODE, treeNode); + this.treeElement = treeNode; + this.location = new Point(); + this.parentView = null; + this.childrenViews = new ArrayList<>(); + this.isCollapsed = false; + this.isContradictoryState = false; + this.isVisible = true; + } + + /** + * Draws the TreeNodeView + * + * @param graphics2D graphics2D used for drawing + */ + public void draw(Graphics2D graphics2D) { + if (isVisible() && treeElement != null) { + if (getTreeElement().getParent() != null + && getTreeElement().getParent().isJustified() + && getTreeElement().getParent().getRule().getRuleType() == RuleType.CONTRADICTION) { + isContradictoryState = true; + graphics2D.setColor(NODE_COLOR_CONTRADICTION); + graphics2D.drawLine( + location.x - RADIUS, location.y - RADIUS, location.x + RADIUS, location.y + RADIUS); + graphics2D.drawLine( + location.x + RADIUS, location.y - RADIUS, location.x - RADIUS, location.y + RADIUS); + } else { + isContradictoryState = false; + graphics2D.setStroke(MAIN_STROKE); + boolean isContraBranch = getTreeElement().isContradictoryBranch(); + + if (isSelected) { + graphics2D.setColor(SELECTION_COLOR); + graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_SELECTION_COLOR); + graphics2D.drawOval( + location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); + } else { + if (isHover) { + graphics2D.setColor(HOVER_COLOR); + graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_HOVER_COLOR); + graphics2D.drawOval( + location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); + } else { + graphics2D.setColor(isContraBranch ? NODE_COLOR_CONTRADICTION : NODE_COLOR_DEFAULT); + graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + } } + } } - - public boolean isContradictoryState() { - return isContradictoryState; - } - - /** - * Gets the list of children views associated with this tree node - * - * @return list of children views for this tree node - */ - public ArrayList getChildrenViews() { - return childrenViews; - } - - /** - * Sets the list of children views associated with this tree node - * - * @param childrenViews list of children views for this tree node - */ - public void setChildrenViews(ArrayList childrenViews) { - this.childrenViews = childrenViews; - } - - /** - * Adds a TreeTransitionView to the list of children views - * - * @param nodeView TreeTransitionView to add to the list of children views - */ - public void addChildrenView(TreeTransitionView nodeView) { - childrenViews.add(nodeView); - } - - /** - * Removes a TreeTransitionView from the list of children views - * - * @param nodeView TreeTransitionView to remove from the list of children views - */ - public void removeChildrenView(TreeTransitionView nodeView) { - childrenViews.remove(nodeView); - } - - /** - * Sets the parent tree transition view - * - * @param parentView parent tree transition view - */ - public void setParentView(TreeTransitionView parentView) { - this.parentView = parentView; - } - - /** - * Gets the parent tree transition view - * - * @return parent tree transition view - */ - public TreeTransitionView getParentView() { - return parentView; - } - - /** - * Gets the tree node associated with this view - * - * @return tree node - */ - public TreeNode getTreeElement() { - return (TreeNode) treeElement; - } - - /** - * Gets the location of the tree node - * - * @return location of the tree node - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the tree node - * - * @param location location of the tree node - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Gets the x location of the tree node - * - * @return x location - */ - public int getX() { - return location.x; - } - - /** - * Sets the x location of the tree node - * - * @param x x location - */ - public void setX(int x) { - location.x = x; - } - - /** - * Gets the y location of the tree node - * - * @return y location - */ - public int getY() { - return location.y; - } - - /** - * Sets the y location of the tree node - * - * @param y y location - */ - public void setY(int y) { - location.y = y; - } - - /** - * Gets the radius of the tree node - * - * @return radius - */ - public int getRadius() { - return RADIUS; - } - - @Override - public Rectangle getBounds() { - return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); - } - - @Override - public Rectangle2D getBounds2D() { - return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); - } - - @Override - public boolean contains(double x, double y) { - return Math.sqrt(Math.pow(x - location.x, 2) + Math.pow(y - location.y, 2)) <= RADIUS; - } - - @Override - public boolean contains(Point2D p) { - return contains(p.getX(), p.getY()); - } - - @Override - public boolean intersects(double x, double y, double w, double h) { - return false; - } - - @Override - public boolean intersects(Rectangle2D r) { - return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); - } - - @Override - public boolean contains(double x, double y, double w, double h) { - return false; - } - - @Override - public boolean contains(Rectangle2D r) { - return false; - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return null; - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return null; - } -} \ No newline at end of file + } + + public boolean isContradictoryState() { + return isContradictoryState; + } + + /** + * Gets the list of children views associated with this tree node + * + * @return list of children views for this tree node + */ + public ArrayList getChildrenViews() { + return childrenViews; + } + + /** + * Sets the list of children views associated with this tree node + * + * @param childrenViews list of children views for this tree node + */ + public void setChildrenViews(ArrayList childrenViews) { + this.childrenViews = childrenViews; + } + + /** + * Adds a TreeTransitionView to the list of children views + * + * @param nodeView TreeTransitionView to add to the list of children views + */ + public void addChildrenView(TreeTransitionView nodeView) { + childrenViews.add(nodeView); + } + + /** + * Removes a TreeTransitionView from the list of children views + * + * @param nodeView TreeTransitionView to remove from the list of children views + */ + public void removeChildrenView(TreeTransitionView nodeView) { + childrenViews.remove(nodeView); + } + + /** + * Sets the parent tree transition view + * + * @param parentView parent tree transition view + */ + public void setParentView(TreeTransitionView parentView) { + this.parentView = parentView; + } + + /** + * Gets the parent tree transition view + * + * @return parent tree transition view + */ + public TreeTransitionView getParentView() { + return parentView; + } + + /** + * Gets the tree node associated with this view + * + * @return tree node + */ + public TreeNode getTreeElement() { + return (TreeNode) treeElement; + } + + /** + * Gets the location of the tree node + * + * @return location of the tree node + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the tree node + * + * @param location location of the tree node + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Gets the x location of the tree node + * + * @return x location + */ + public int getX() { + return location.x; + } + + /** + * Sets the x location of the tree node + * + * @param x x location + */ + public void setX(int x) { + location.x = x; + } + + /** + * Gets the y location of the tree node + * + * @return y location + */ + public int getY() { + return location.y; + } + + /** + * Sets the y location of the tree node + * + * @param y y location + */ + public void setY(int y) { + location.y = y; + } + + /** + * Gets the radius of the tree node + * + * @return radius + */ + public int getRadius() { + return RADIUS; + } + + @Override + public Rectangle getBounds() { + return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); + } + + @Override + public Rectangle2D getBounds2D() { + return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); + } + + @Override + public boolean contains(double x, double y) { + return Math.sqrt(Math.pow(x - location.x, 2) + Math.pow(y - location.y, 2)) <= RADIUS; + } + + @Override + public boolean contains(Point2D p) { + return contains(p.getX(), p.getY()); + } + + @Override + public boolean intersects(double x, double y, double w, double h) { + return false; + } + + @Override + public boolean intersects(Rectangle2D r) { + return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); + } + + @Override + public boolean contains(double x, double y, double w, double h) { + return false; + } + + @Override + public boolean contains(Rectangle2D r) { + return false; + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return null; + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return null; + } +} diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java index ac7accaee..f73ab02fe 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java @@ -10,138 +10,131 @@ import edu.rpi.legup.model.tree.Tree; import edu.rpi.legup.ui.DynamicView; import edu.rpi.legup.ui.DynamicViewType; -import edu.rpi.legup.ui.LegupUI; import edu.rpi.legup.ui.lookandfeel.materialdesign.MaterialFonts; - import java.awt.*; - +import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; - -import javax.swing.BorderFactory; import javax.swing.border.TitledBorder; public class TreePanel extends JPanel { - public boolean modifiedSinceSave = false; - public boolean modifiedSinceUndoPush = false; - public int updateStatusTimer = 0; + public boolean modifiedSinceSave = false; + public boolean modifiedSinceUndoPush = false; + public int updateStatusTimer = 0; - private JPanel main; - private TreeView treeView; - private TreeToolbarPanel toolbar; - // private LegupUI legupUI; + private JPanel main; + private TreeView treeView; + private TreeToolbarPanel toolbar; + // private LegupUI legupUI; - private JLabel status; + private JLabel status; - public TreePanel(/*LegupUI legupUI*/) { - //this.legupUI = legupUI; + public TreePanel(/*LegupUI legupUI*/ ) { + // this.legupUI = legupUI; - main = new JPanel(); + main = new JPanel(); - main.setLayout(new BorderLayout()); + main.setLayout(new BorderLayout()); - TreeController treeController = new TreeController(); - treeView = new TreeView(treeController); - treeController.setViewer(treeView); + TreeController treeController = new TreeController(); + treeView = new TreeView(treeController); + treeController.setViewer(treeView); - toolbar = new TreeToolbarPanel(this); + toolbar = new TreeToolbarPanel(this); - DynamicView dynamicTreeView = new DynamicView(treeView, DynamicViewType.PROOF_TREE); - main.add(dynamicTreeView, BorderLayout.CENTER); - dynamicTreeView.add(toolbar, BorderLayout.WEST); + DynamicView dynamicTreeView = new DynamicView(treeView, DynamicViewType.PROOF_TREE); + main.add(dynamicTreeView, BorderLayout.CENTER); + dynamicTreeView.add(toolbar, BorderLayout.WEST); - status = new JLabel(); - status.setPreferredSize(new Dimension(150, 15)); - dynamicTreeView.getZoomWrapper().add(status, BorderLayout.CENTER); + status = new JLabel(); + status.setPreferredSize(new Dimension(150, 15)); + dynamicTreeView.getZoomWrapper().add(status, BorderLayout.CENTER); - TitledBorder title = BorderFactory.createTitledBorder("Proof Tree"); - title.setTitleJustification(TitledBorder.CENTER); - main.setBorder(title); + TitledBorder title = BorderFactory.createTitledBorder("Proof Tree"); + title.setTitleJustification(TitledBorder.CENTER); + main.setBorder(title); - setLayout(new BorderLayout()); - add(main); + setLayout(new BorderLayout()); + add(main); - updateStatusTimer = 0; - } + updateStatusTimer = 0; + } - public void repaintTreeView(Tree tree) { - treeView.updateTreeView(tree); - } + public void repaintTreeView(Tree tree) { + treeView.updateTreeView(tree); + } - public void boardDataChanged(Board board) { - modifiedSinceSave = true; - modifiedSinceUndoPush = true; - updateStatus(); - //colorTransitions(); - } - - public void updateStatus() { - updateStatusTimer = ((updateStatusTimer - 1) > 0) ? (updateStatusTimer - 1) : 0; - if (updateStatusTimer > 0) { - return; - } - this.status.setText(""); - } + public void boardDataChanged(Board board) { + modifiedSinceSave = true; + modifiedSinceUndoPush = true; + updateStatus(); + // colorTransitions(); + } - public void updateStatus(String statusString) { - status.setForeground(Color.BLACK); - status.setFont(MaterialFonts.REGULAR); - status.setText(statusString); + public void updateStatus() { + updateStatusTimer = ((updateStatusTimer - 1) > 0) ? (updateStatusTimer - 1) : 0; + if (updateStatusTimer > 0) { + return; } - - public void updateError(String error) { - status.setForeground(Color.RED); - status.setFont(MaterialFonts.ITALIC); - status.setText(error); + this.status.setText(""); + } + + public void updateStatus(String statusString) { + status.setForeground(Color.BLACK); + status.setFont(MaterialFonts.REGULAR); + status.setText(statusString); + } + + public void updateError(String error) { + status.setForeground(Color.RED); + status.setFont(MaterialFonts.ITALIC); + status.setText(error); + } + + public TreeView getTreeView() { + return treeView; + } + + public void add() { + TreeViewSelection selection = treeView.getSelection(); + + AddTreeElementCommand add = new AddTreeElementCommand(selection); + if (add.canExecute()) { + add.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(add); + } else { + updateError(add.getError()); } + } - public TreeView getTreeView() { - return treeView; - } + public void delete() { + TreeViewSelection selection = treeView.getSelection(); - public void add() { - TreeViewSelection selection = treeView.getSelection(); - - AddTreeElementCommand add = new AddTreeElementCommand(selection); - if (add.canExecute()) { - add.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(add); - } - else { - updateError(add.getError()); - } + DeleteTreeElementCommand del = new DeleteTreeElementCommand(selection); + if (del.canExecute()) { + del.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(del); + } else { + updateError(del.getError()); } + } - public void delete() { - TreeViewSelection selection = treeView.getSelection(); - - DeleteTreeElementCommand del = new DeleteTreeElementCommand(selection); - if (del.canExecute()) { - del.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(del); - } - else { - updateError(del.getError()); - } - } + public void merge() { + TreeViewSelection selection = treeView.getSelection(); - public void merge() { - TreeViewSelection selection = treeView.getSelection(); - - ICommand merge = new MergeCommand(selection); - if (merge.canExecute()) { - merge.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(merge); - } - else { - updateError(merge.getError()); - } + ICommand merge = new MergeCommand(selection); + if (merge.canExecute()) { + merge.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(merge); + } else { + updateError(merge.getError()); } + } - public void collapse() { - TreeViewSelection selection = treeView.getSelection(); - for (TreeElementView view : selection.getSelectedViews()) { - view.setCollapsed(!view.isCollapsed()); - } + public void collapse() { + TreeViewSelection selection = treeView.getSelection(); + for (TreeElementView view : selection.getSelectedViews()) { + view.setCollapsed(!view.isCollapsed()); } + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java index c2f40e21a..45bf518b2 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java @@ -1,22 +1,22 @@ package edu.rpi.legup.ui.proofeditorui.treeview; -import javax.swing.*; import java.awt.Dimension; +import javax.swing.*; public class TreeToolBarButton extends JButton { - private TreeToolBarName name; - private final Dimension MINIMUM_DIMENSION = new Dimension(60, 60); + private TreeToolBarName name; + private final Dimension MINIMUM_DIMENSION = new Dimension(60, 60); - public TreeToolBarButton(ImageIcon imageIcon, TreeToolBarName name) { - super(imageIcon); - this.name = name; - this.setSize(MINIMUM_DIMENSION.width, MINIMUM_DIMENSION.height); - this.setMinimumSize(this.MINIMUM_DIMENSION); - this.setFocusPainted(false); - } + public TreeToolBarButton(ImageIcon imageIcon, TreeToolBarName name) { + super(imageIcon); + this.name = name; + this.setSize(MINIMUM_DIMENSION.width, MINIMUM_DIMENSION.height); + this.setMinimumSize(this.MINIMUM_DIMENSION); + this.setFocusPainted(false); + } - public TreeToolBarName getToolBarName() { - return name; - } + public TreeToolBarName getToolBarName() { + return name; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java index dd8a37c15..d1a009b7e 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java @@ -1,5 +1,8 @@ package edu.rpi.legup.ui.proofeditorui.treeview; public enum TreeToolBarName { - ADD_CHILD, DEL_CHILD, MERGE, COLLAPSE + ADD_CHILD, + DEL_CHILD, + MERGE, + COLLAPSE } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java index 332fd64a0..3923de25b 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java @@ -1,41 +1,53 @@ package edu.rpi.legup.ui.proofeditorui.treeview; -import javax.swing.*; import java.awt.*; +import javax.swing.*; public class TreeToolbarPanel extends JPanel { - private TreePanel treePanel; - private TreeToolBarButton addChild, delChild, merge, collapse; - - /** - * TreeToolbarPanel Constructor - creates the tree tool mBar panel - * @param treePanel treePanel input - */ - public TreeToolbarPanel(TreePanel treePanel) { - this.treePanel = treePanel; - this.setLayout(new GridLayout(4, 1, 0, 2)); - - - addChild = new TreeToolBarButton(new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/AddChild.png")), TreeToolBarName.ADD_CHILD); - delChild = new TreeToolBarButton(new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/DelChild.png")), TreeToolBarName.DEL_CHILD); - merge = new TreeToolBarButton(new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Merge.png")), TreeToolBarName.MERGE); - collapse = new TreeToolBarButton(new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Collapse.png")), TreeToolBarName.COLLAPSE); - - add(addChild); - addChild.addActionListener(a -> treePanel.add()); - addChild.setToolTipText("Add tree element"); - - add(delChild); - delChild.addActionListener(a -> treePanel.delete()); - delChild.setToolTipText("Remove selected tree elements"); - - add(merge); - merge.addActionListener(a -> treePanel.merge()); - merge.setToolTipText("Merge selected tree nodes"); - - add(collapse); - collapse.addActionListener(a -> treePanel.collapse()); - collapse.setToolTipText("Collapse nodes"); - collapse.setEnabled(false); - } -} \ No newline at end of file + private TreePanel treePanel; + private TreeToolBarButton addChild, delChild, merge, collapse; + + /** + * TreeToolbarPanel Constructor - creates the tree tool mBar panel + * + * @param treePanel treePanel input + */ + public TreeToolbarPanel(TreePanel treePanel) { + this.treePanel = treePanel; + this.setLayout(new GridLayout(4, 1, 0, 2)); + + addChild = + new TreeToolBarButton( + new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/AddChild.png")), + TreeToolBarName.ADD_CHILD); + delChild = + new TreeToolBarButton( + new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/DelChild.png")), + TreeToolBarName.DEL_CHILD); + merge = + new TreeToolBarButton( + new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Merge.png")), + TreeToolBarName.MERGE); + collapse = + new TreeToolBarButton( + new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Collapse.png")), + TreeToolBarName.COLLAPSE); + + add(addChild); + addChild.addActionListener(a -> treePanel.add()); + addChild.setToolTipText("Add tree element"); + + add(delChild); + delChild.addActionListener(a -> treePanel.delete()); + delChild.setToolTipText("Remove selected tree elements"); + + add(merge); + merge.addActionListener(a -> treePanel.merge()); + merge.setToolTipText("Merge selected tree nodes"); + + add(collapse); + collapse.addActionListener(a -> treePanel.collapse()); + collapse.setToolTipText("Collapse nodes"); + collapse.setEnabled(false); + } +} diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java index 749af0c79..652514be6 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java @@ -1,358 +1,354 @@ package edu.rpi.legup.ui.proofeditorui.treeview; +import static java.lang.Math.*; + +import edu.rpi.legup.app.LegupPreferences; import edu.rpi.legup.model.tree.TreeElementType; import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.app.LegupPreferences; - import java.awt.*; import java.awt.geom.*; -import java.util.List; import java.util.ArrayList; - -import static java.lang.Math.*; +import java.util.List; public class TreeTransitionView extends TreeElementView { - static final int RADIUS = 25; - static final int DIAMETER = 2 * RADIUS; - static final int GAP = 5; - - private static final Stroke MAIN_STROKE = new BasicStroke(3); - private static final Stroke SELECTION_STROKE = new BasicStroke(2); - - private static final Color OUTLINE_COLOR = Color.BLACK; - private static final Color CORRECT_COLOR = Color.GREEN; - private static final Color INCORRECT_COLOR = Color.RED; - private static final Color DEFAULT_COLOR = Color.GRAY; - private static final Color X_COLOR = Color.RED; - - private static final Color CORRECT_COLOR_COLORBLIND = new Color(0, 0, 255); - private static final Color INCORRECT_COLOR_COLORBLIND = new Color(255, 0, 0); - - private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); - - private static final Color HOVER_COLOR = new Color(0x90CAF9); - private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); - - private TreeNodeView childView; - private ArrayList parentViews; - private Polygon arrowhead; - - private List lineStartPoints; - private Point lineEndPoint; - - private Point endPoint; - - /** - * TreeTransitionView Constructor creates a transition arrow for display - * - * @param transition tree transition associated with this view - */ - public TreeTransitionView(TreeTransition transition) { - super(TreeElementType.TRANSITION, transition); - this.parentViews = new ArrayList<>(); - this.isCollapsed = false; - this.endPoint = new Point(); - this.lineStartPoints = new ArrayList<>(); - this.lineEndPoint = new Point(); - } - - /** - * TreeTransitionView Constructor creates a transition arrow for display - * - * @param transition tree transition associated with this view - * @param parentView TreeNodeView of the parent associated with this transition - */ - public TreeTransitionView(TreeTransition transition, TreeNodeView parentView) { - this(transition); - this.parentViews.add(parentView); - this.lineStartPoints.add(new Point()); + static final int RADIUS = 25; + static final int DIAMETER = 2 * RADIUS; + static final int GAP = 5; + + private static final Stroke MAIN_STROKE = new BasicStroke(3); + private static final Stroke SELECTION_STROKE = new BasicStroke(2); + + private static final Color OUTLINE_COLOR = Color.BLACK; + private static final Color CORRECT_COLOR = Color.GREEN; + private static final Color INCORRECT_COLOR = Color.RED; + private static final Color DEFAULT_COLOR = Color.GRAY; + private static final Color X_COLOR = Color.RED; + + private static final Color CORRECT_COLOR_COLORBLIND = new Color(0, 0, 255); + private static final Color INCORRECT_COLOR_COLORBLIND = new Color(255, 0, 0); + + private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); + + private static final Color HOVER_COLOR = new Color(0x90CAF9); + private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); + + private TreeNodeView childView; + private ArrayList parentViews; + private Polygon arrowhead; + + private List lineStartPoints; + private Point lineEndPoint; + + private Point endPoint; + + /** + * TreeTransitionView Constructor creates a transition arrow for display + * + * @param transition tree transition associated with this view + */ + public TreeTransitionView(TreeTransition transition) { + super(TreeElementType.TRANSITION, transition); + this.parentViews = new ArrayList<>(); + this.isCollapsed = false; + this.endPoint = new Point(); + this.lineStartPoints = new ArrayList<>(); + this.lineEndPoint = new Point(); + } + + /** + * TreeTransitionView Constructor creates a transition arrow for display + * + * @param transition tree transition associated with this view + * @param parentView TreeNodeView of the parent associated with this transition + */ + public TreeTransitionView(TreeTransition transition, TreeNodeView parentView) { + this(transition); + this.parentViews.add(parentView); + this.lineStartPoints.add(new Point()); + } + + /** + * Draws the TreeTransitionView + * + * @param graphics2D graphics2D used for drawing + */ + public void draw(Graphics2D graphics2D) { + arrowhead = createTransitionTriangle(RADIUS); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.setStroke(MAIN_STROKE); + + for (Point lineStartPoint : lineStartPoints) { + CubicCurve2D c = new CubicCurve2D.Double(); + double ctrlx1 = lineEndPoint.x - 25; + double ctrly1 = lineStartPoint.y; + double ctrlx2 = lineEndPoint.x - 25; + double ctrly2 = lineEndPoint.y; + + c.setCurve( + lineStartPoint.x, + lineStartPoint.y, + ctrlx1, + ctrly1, + ctrlx2, + ctrly2, + lineEndPoint.x, + lineEndPoint.y); + graphics2D.draw(c); } - /** - * Draws the TreeTransitionView - * - * @param graphics2D graphics2D used for drawing - */ - public void draw(Graphics2D graphics2D) { - arrowhead = createTransitionTriangle(RADIUS); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.setStroke(MAIN_STROKE); - - for (Point lineStartPoint : lineStartPoints) { - CubicCurve2D c = new CubicCurve2D.Double(); - double ctrlx1 = lineEndPoint.x - 25; - double ctrly1 = lineStartPoint.y; - double ctrlx2 = lineEndPoint.x - 25; - double ctrly2 = lineEndPoint.y; - - c.setCurve(lineStartPoint.x, lineStartPoint.y, ctrlx1, - ctrly1, ctrlx2, ctrly2, lineEndPoint.x, lineEndPoint.y); - graphics2D.draw(c); + LegupPreferences prefs = LegupPreferences.getInstance(); + boolean colorBlind = prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true"); + + if (isSelected) { + Color c = DEFAULT_COLOR; + if (getTreeElement().isJustified()) { + if (getTreeElement().isCorrect()) { + if (colorBlind) { + c = CORRECT_COLOR_COLORBLIND; + } else { + c = CORRECT_COLOR; + } + } else { + if (colorBlind) { + c = INCORRECT_COLOR_COLORBLIND; + } else { + c = INCORRECT_COLOR; + } } + } + graphics2D.setColor(c); - LegupPreferences prefs = LegupPreferences.getInstance(); - boolean colorBlind = prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true"); - - if (isSelected) { - Color c = DEFAULT_COLOR; - if (getTreeElement().isJustified()) { - if (getTreeElement().isCorrect()) { - if (colorBlind) { - c = CORRECT_COLOR_COLORBLIND; - } - else { - c = CORRECT_COLOR; - } - } - else { - if (colorBlind) { - c = INCORRECT_COLOR_COLORBLIND; - } - else { - c = INCORRECT_COLOR; - } - } - } - graphics2D.setColor(c); - - graphics2D.fillPolygon(arrowhead); + graphics2D.fillPolygon(arrowhead); - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); - Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); - selection_triangle.translate(7, 0); + Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); + selection_triangle.translate(7, 0); - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_SELECTION_COLOR); - graphics2D.drawPolygon(selection_triangle); - } - else { - if (isHover) { - graphics2D.setColor(HOVER_COLOR); - graphics2D.fillPolygon(arrowhead); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); - - Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); - selection_triangle.translate(7, 0); + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_SELECTION_COLOR); + graphics2D.drawPolygon(selection_triangle); + } else { + if (isHover) { + graphics2D.setColor(HOVER_COLOR); + graphics2D.fillPolygon(arrowhead); - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_HOVER_COLOR); - graphics2D.drawPolygon(selection_triangle); + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); + + Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); + selection_triangle.translate(7, 0); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_HOVER_COLOR); + graphics2D.drawPolygon(selection_triangle); + } else { + Color c = DEFAULT_COLOR; + if (getTreeElement().isJustified()) { + if (getTreeElement().isCorrect()) { + if (colorBlind) { + c = CORRECT_COLOR_COLORBLIND; + } else { + c = CORRECT_COLOR; } - else { - Color c = DEFAULT_COLOR; - if (getTreeElement().isJustified()) { - if (getTreeElement().isCorrect()) { - if (colorBlind) { - c = CORRECT_COLOR_COLORBLIND; - } - else { - c = CORRECT_COLOR; - } - } - else { - if (colorBlind) { - c = INCORRECT_COLOR_COLORBLIND; - } - else { - c = INCORRECT_COLOR; - } - } - } - graphics2D.setColor(c); - graphics2D.fillPolygon(arrowhead); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); + } else { + if (colorBlind) { + c = INCORRECT_COLOR_COLORBLIND; + } else { + c = INCORRECT_COLOR; } + } } - } - - /** - * Constructs the arrowhead shape from the start and end points - */ - private Polygon createTransitionTriangle(int radius) { - double thetaArrow = Math.toRadians(30); - - int point1X = endPoint.x; - int point1Y = endPoint.y; - - int point2X = point1X - radius; - int point2Y = point1Y + (int) Math.round(radius / (2 * cos(thetaArrow))); - - int point3X = point1X - radius; - int point3Y = point1Y - (int) Math.round(radius / (2 * cos(thetaArrow))); - - lineEndPoint.x = point2X; - lineEndPoint.y = (point3Y - point2Y) / 2 + point2Y; - - Polygon tri = new Polygon(); - tri.addPoint(point1X, point1Y); - tri.addPoint(point2X, point2Y); - tri.addPoint(point3X, point3Y); - - return tri; - } - - /** - * Gets the TreeElement associated with this view - * - * @return the TreeElement associated with this view - */ - public TreeTransition getTreeElement() { - return (TreeTransition) treeElement; - } - - /** - * Gets the TreeNodeView child view - * - * @return TreeNodeView child view - */ - public TreeNodeView getChildView() { - return childView; - } - - /** - * Sets the TreeNodeView child view - * - * @param childView TreeNodeView child view - */ - public void setChildView(TreeNodeView childView) { - this.childView = childView; - } - - /** - * Gets the list of parent views associated with this tree transition view - * - * @return list of parent views for this tree transition view - */ - public ArrayList getParentViews() { - return parentViews; - } - - /** - * Sets the list of parent views associated with this tree transition view - * - * @param parentViews list of parent views for this tree transition view - */ - public void setParentViews(ArrayList parentViews) { - this.parentViews = parentViews; - this.lineStartPoints.clear(); - for (TreeNodeView parentView : this.parentViews) { - this.lineStartPoints.add(new Point()); - } - } + graphics2D.setColor(c); + graphics2D.fillPolygon(arrowhead); - /** - * Adds a TreeNodeView to the list of parent views - * - * @param nodeView TreeNodeView to add to the list of parent views - */ - public void addParentView(TreeNodeView nodeView) { - parentViews.add(nodeView); - lineStartPoints.add(new Point()); - } - - /** - * Removes a TreeNodeView from the list of parent views - * - * @param nodeView TreeNodeView to remove from the list of parent views - */ - public void removeParentView(TreeNodeView nodeView) { - int index = parentViews.indexOf(nodeView); - parentViews.remove(nodeView); - if (index != -1) { - lineStartPoints.remove(index); - } - } - - public Point getEndPoint() { - return endPoint; - } - - public void setEndPoint(Point endPoint) { - this.endPoint = endPoint; - } - - public int getEndX() { - return endPoint.x; - } - - public void setEndX(int x) { - this.endPoint.x = x; - } - - public int getEndY() { - return endPoint.y; - } - - public void setEndY(int y) { - this.endPoint.y = y; - } - - public List getLineStartPoints() { - return lineStartPoints; - } - - public void setLineStartPoints(List lineStartPoints) { - this.lineStartPoints = lineStartPoints; - } - - public Point getLineStartPoint(int index) { - return index < lineStartPoints.size() ? lineStartPoints.get(index) : null; - } - - @Override - public Rectangle getBounds() { - return arrowhead.getBounds(); - } - - @Override - public Rectangle2D getBounds2D() { - return arrowhead.getBounds2D(); - } - - @Override - public boolean contains(double x, double y) { - return arrowhead.contains(x, y); - } - - @Override - public boolean contains(Point2D p) { - return arrowhead != null && arrowhead.contains(p); - } - - @Override - public boolean intersects(double x, double y, double w, double h) { - return arrowhead.intersects(x, y, w, h); - } - - @Override - public boolean intersects(Rectangle2D r) { - return arrowhead.intersects(r); - } - - @Override - public boolean contains(double x, double y, double w, double h) { - return arrowhead.contains(x, y, w, h); - } - - @Override - public boolean contains(Rectangle2D r) { - return arrowhead.contains(r); + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); + } } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return arrowhead.getPathIterator(at); + } + + /** Constructs the arrowhead shape from the start and end points */ + private Polygon createTransitionTriangle(int radius) { + double thetaArrow = Math.toRadians(30); + + int point1X = endPoint.x; + int point1Y = endPoint.y; + + int point2X = point1X - radius; + int point2Y = point1Y + (int) Math.round(radius / (2 * cos(thetaArrow))); + + int point3X = point1X - radius; + int point3Y = point1Y - (int) Math.round(radius / (2 * cos(thetaArrow))); + + lineEndPoint.x = point2X; + lineEndPoint.y = (point3Y - point2Y) / 2 + point2Y; + + Polygon tri = new Polygon(); + tri.addPoint(point1X, point1Y); + tri.addPoint(point2X, point2Y); + tri.addPoint(point3X, point3Y); + + return tri; + } + + /** + * Gets the TreeElement associated with this view + * + * @return the TreeElement associated with this view + */ + public TreeTransition getTreeElement() { + return (TreeTransition) treeElement; + } + + /** + * Gets the TreeNodeView child view + * + * @return TreeNodeView child view + */ + public TreeNodeView getChildView() { + return childView; + } + + /** + * Sets the TreeNodeView child view + * + * @param childView TreeNodeView child view + */ + public void setChildView(TreeNodeView childView) { + this.childView = childView; + } + + /** + * Gets the list of parent views associated with this tree transition view + * + * @return list of parent views for this tree transition view + */ + public ArrayList getParentViews() { + return parentViews; + } + + /** + * Sets the list of parent views associated with this tree transition view + * + * @param parentViews list of parent views for this tree transition view + */ + public void setParentViews(ArrayList parentViews) { + this.parentViews = parentViews; + this.lineStartPoints.clear(); + for (TreeNodeView parentView : this.parentViews) { + this.lineStartPoints.add(new Point()); } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return arrowhead.getPathIterator(at, flatness); + } + + /** + * Adds a TreeNodeView to the list of parent views + * + * @param nodeView TreeNodeView to add to the list of parent views + */ + public void addParentView(TreeNodeView nodeView) { + parentViews.add(nodeView); + lineStartPoints.add(new Point()); + } + + /** + * Removes a TreeNodeView from the list of parent views + * + * @param nodeView TreeNodeView to remove from the list of parent views + */ + public void removeParentView(TreeNodeView nodeView) { + int index = parentViews.indexOf(nodeView); + parentViews.remove(nodeView); + if (index != -1) { + lineStartPoints.remove(index); } + } + + public Point getEndPoint() { + return endPoint; + } + + public void setEndPoint(Point endPoint) { + this.endPoint = endPoint; + } + + public int getEndX() { + return endPoint.x; + } + + public void setEndX(int x) { + this.endPoint.x = x; + } + + public int getEndY() { + return endPoint.y; + } + + public void setEndY(int y) { + this.endPoint.y = y; + } + + public List getLineStartPoints() { + return lineStartPoints; + } + + public void setLineStartPoints(List lineStartPoints) { + this.lineStartPoints = lineStartPoints; + } + + public Point getLineStartPoint(int index) { + return index < lineStartPoints.size() ? lineStartPoints.get(index) : null; + } + + @Override + public Rectangle getBounds() { + return arrowhead.getBounds(); + } + + @Override + public Rectangle2D getBounds2D() { + return arrowhead.getBounds2D(); + } + + @Override + public boolean contains(double x, double y) { + return arrowhead.contains(x, y); + } + + @Override + public boolean contains(Point2D p) { + return arrowhead != null && arrowhead.contains(p); + } + + @Override + public boolean intersects(double x, double y, double w, double h) { + return arrowhead.intersects(x, y, w, h); + } + + @Override + public boolean intersects(Rectangle2D r) { + return arrowhead.intersects(r); + } + + @Override + public boolean contains(double x, double y, double w, double h) { + return arrowhead.contains(x, y, w, h); + } + + @Override + public boolean contains(Rectangle2D r) { + return arrowhead.contains(r); + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return arrowhead.getPathIterator(at); + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return arrowhead.getPathIterator(at, flatness); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java index 9bfffe60a..b46090fed 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java @@ -1,9 +1,13 @@ package edu.rpi.legup.ui.proofeditorui.treeview; +import static edu.rpi.legup.model.tree.TreeElementType.NODE; +import static edu.rpi.legup.model.tree.TreeElementType.TRANSITION; +import static edu.rpi.legup.ui.proofeditorui.treeview.TreeNodeView.DIAMETER; +import static edu.rpi.legup.ui.proofeditorui.treeview.TreeNodeView.RADIUS; + import edu.rpi.legup.app.GameBoardFacade; import edu.rpi.legup.controller.TreeController; import edu.rpi.legup.model.gameboard.Board; -import edu.rpi.legup.model.gameboard.GridCell; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.observer.ITreeListener; import edu.rpi.legup.model.rules.CaseRule; @@ -14,873 +18,864 @@ import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.ui.ScrollView; import edu.rpi.legup.utility.DisjointSets; - -import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.*; import java.util.List; - +import javax.swing.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import static edu.rpi.legup.model.tree.TreeElementType.NODE; -import static edu.rpi.legup.model.tree.TreeElementType.TRANSITION; -import static edu.rpi.legup.ui.proofeditorui.treeview.TreeNodeView.DIAMETER; -import static edu.rpi.legup.ui.proofeditorui.treeview.TreeNodeView.RADIUS; - public class TreeView extends ScrollView implements ITreeListener { - private final static Logger LOGGER = LogManager.getLogger(TreeView.class.getName()); - - private static final int TRANS_GAP = 5; - - private static final int NODE_GAP_WIDTH = 70; - private static final int NODE_GAP_HEIGHT = 15; - - private static final int BORDER_GAP_HEIGHT = 20; - private static final int BORDER_GAP_WIDTH = 20; - - private static final int BORDER_SPACING = 100; - - private TreeNodeView nodeHover; - - private ArrayList currentStateBoxes; - private Rectangle bounds = new Rectangle(0, 0, 0, 0); - - private Tree tree; - private TreeNodeView rootNodeView; - private Map viewMap; - private Dimension dimension; - - private TreeViewSelection selection; - - public TreeView(TreeController treeController) { - super(treeController); - currentStateBoxes = new ArrayList<>(); - setSize(dimension = new Dimension(100, 200)); - setPreferredSize(new Dimension(640, 160)); - - viewMap = new HashMap<>(); - - selection = new TreeViewSelection(); - } - - public TreeViewSelection getSelection() { - return selection; - } - - /** - * Gets the tree node puzzleElement that the mouse is hovering over - * - * @return tree node puzzleElement that the mouse is hovering over - */ - public TreeNodeView getNodeHover() { - return nodeHover; - } - - /** - * Sets the tree node puzzleElement that the mouse is hovering over - * - * @param nodeHover tree node puzzleElement the mouse is hovering over - */ - public void setNodeHover(TreeNodeView nodeHover) { - this.nodeHover = nodeHover; - } - - /** - * Gets the TreeElementView by the specified point or null if no view exists at the specified point - * - * @param point location to query for a view - * @return TreeElementView at the point specified, otherwise null - */ - public TreeElementView getTreeElementView(Point point) { - return getTreeElementView(point, rootNodeView); - } - - /** - * Recursively gets the TreeElementView by the specified point or null if no view exists at the specified point or - * the view specified is null - * - * @param point location to query for a view - * @param elementView view to determine if the point is contained within it - * @return TreeElementView at the point specified, otherwise null - */ - private TreeElementView getTreeElementView(Point point, TreeElementView elementView) { - if (elementView == null) { - return null; + private static final Logger LOGGER = LogManager.getLogger(TreeView.class.getName()); + + private static final int TRANS_GAP = 5; + + private static final int NODE_GAP_WIDTH = 70; + private static final int NODE_GAP_HEIGHT = 15; + + private static final int BORDER_GAP_HEIGHT = 20; + private static final int BORDER_GAP_WIDTH = 20; + + private static final int BORDER_SPACING = 100; + + private TreeNodeView nodeHover; + + private ArrayList currentStateBoxes; + private Rectangle bounds = new Rectangle(0, 0, 0, 0); + + private Tree tree; + private TreeNodeView rootNodeView; + private Map viewMap; + private Dimension dimension; + + private TreeViewSelection selection; + + public TreeView(TreeController treeController) { + super(treeController); + currentStateBoxes = new ArrayList<>(); + setSize(dimension = new Dimension(100, 200)); + setPreferredSize(new Dimension(640, 160)); + + viewMap = new HashMap<>(); + + selection = new TreeViewSelection(); + } + + public TreeViewSelection getSelection() { + return selection; + } + + /** + * Gets the tree node puzzleElement that the mouse is hovering over + * + * @return tree node puzzleElement that the mouse is hovering over + */ + public TreeNodeView getNodeHover() { + return nodeHover; + } + + /** + * Sets the tree node puzzleElement that the mouse is hovering over + * + * @param nodeHover tree node puzzleElement the mouse is hovering over + */ + public void setNodeHover(TreeNodeView nodeHover) { + this.nodeHover = nodeHover; + } + + /** + * Gets the TreeElementView by the specified point or null if no view exists at the specified + * point + * + * @param point location to query for a view + * @return TreeElementView at the point specified, otherwise null + */ + public TreeElementView getTreeElementView(Point point) { + return getTreeElementView(point, rootNodeView); + } + + /** + * Recursively gets the TreeElementView by the specified point or null if no view exists at the + * specified point or the view specified is null + * + * @param point location to query for a view + * @param elementView view to determine if the point is contained within it + * @return TreeElementView at the point specified, otherwise null + */ + private TreeElementView getTreeElementView(Point point, TreeElementView elementView) { + if (elementView == null) { + return null; + } else { + if (elementView.contains(point) && elementView.isVisible()) { + if (elementView.getType() == NODE && ((TreeNodeView) elementView).isContradictoryState()) { + return null; } - else { - if (elementView.contains(point) && elementView.isVisible()) { - if (elementView.getType() == NODE && ((TreeNodeView) elementView).isContradictoryState()) { - return null; - } - return elementView; - } - else { - if (elementView.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) elementView; - for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { - TreeElementView view = getTreeElementView(point, transitionView); - if (view != null) { - return view; - } - } - } - else { - TreeTransitionView transitionView = (TreeTransitionView) elementView; - return getTreeElementView(point, transitionView.getChildView()); - } + return elementView; + } else { + if (elementView.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) elementView; + for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { + TreeElementView view = getTreeElementView(point, transitionView); + if (view != null) { + return view; } + } + } else { + TreeTransitionView transitionView = (TreeTransitionView) elementView; + return getTreeElementView(point, transitionView.getChildView()); } - return null; - } - - public void updateTreeView(Tree tree) { - this.tree = tree; - if (selection.getSelectedViews().size() == 0) { - selection.newSelection(new TreeNodeView(tree.getRootNode())); - } - repaint(); - } - - /** - * Sets the tree associated with this TreeView - * - * @param tree tree - */ - public void setTree(Tree tree) { - this.tree = tree; - } - - public void updateTreeSize() { - if (GameBoardFacade.getInstance().getTree() == null) { - return; - } - setSize(bounds.getSize()); - } - - public void reset() { - if (bounds.x != 0 || bounds.y != 0) { - updateTreeSize(); - } - } - - public void zoomFit() { - double fitWidth = (viewport.getWidth() - 8.0) / (getSize().width - 200); - double fitHeight = (viewport.getHeight() - 8.0) / (getSize().height - 120); - zoomTo(Math.min(fitWidth, fitHeight)); - viewport.setViewPosition(new Point(0, viewport.getHeight() / 2)); - } - - /** - * Creates a customized viewport for the scroll pane - * - * @return viewport for the scroll pane - */ - @Override - protected JViewport createViewport() { - return new JViewport() { - @Override - protected LayoutManager createLayoutManager() { - return new ViewportLayout() { - @Override - public void layoutContainer(Container parent) { - Point point = viewport.getViewPosition(); - // determine the maximum x and y view positions - int mx = getCanvas().getWidth() - viewport.getWidth(); - int my = getCanvas().getHeight() - viewport.getHeight(); - // obey edge boundaries - if (point.x < 0) { - point.x = 0; - } - if (point.x > mx) { - point.x = mx; - } - if (point.y < 0) { - point.y = 0; - } - if (point.y > my) { - point.y = my; - } - // center margins - if (mx < 0) { - point.x = 0; - } - if (my < 0) { - point.y = my / 2; - } - viewport.setViewPosition(point); - } - }; + } + } + return null; + } + + public void updateTreeView(Tree tree) { + this.tree = tree; + if (selection.getSelectedViews().size() == 0) { + selection.newSelection(new TreeNodeView(tree.getRootNode())); + } + repaint(); + } + + /** + * Sets the tree associated with this TreeView + * + * @param tree tree + */ + public void setTree(Tree tree) { + this.tree = tree; + } + + public void updateTreeSize() { + if (GameBoardFacade.getInstance().getTree() == null) { + return; + } + setSize(bounds.getSize()); + } + + public void reset() { + if (bounds.x != 0 || bounds.y != 0) { + updateTreeSize(); + } + } + + public void zoomFit() { + double fitWidth = (viewport.getWidth() - 8.0) / (getSize().width - 200); + double fitHeight = (viewport.getHeight() - 8.0) / (getSize().height - 120); + zoomTo(Math.min(fitWidth, fitHeight)); + viewport.setViewPosition(new Point(0, viewport.getHeight() / 2)); + } + + /** + * Creates a customized viewport for the scroll pane + * + * @return viewport for the scroll pane + */ + @Override + protected JViewport createViewport() { + return new JViewport() { + @Override + protected LayoutManager createLayoutManager() { + return new ViewportLayout() { + @Override + public void layoutContainer(Container parent) { + Point point = viewport.getViewPosition(); + // determine the maximum x and y view positions + int mx = getCanvas().getWidth() - viewport.getWidth(); + int my = getCanvas().getHeight() - viewport.getHeight(); + // obey edge boundaries + if (point.x < 0) { + point.x = 0; } - }; - } - - public void draw(Graphics2D graphics2D) { - currentStateBoxes.clear(); - Tree tree = GameBoardFacade.getInstance().getTree(); - if (tree != null) { - //setSize(bounds.getDimension()); - graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - - drawTree(graphics2D); - - dimension.width += BORDER_SPACING; - setSize(dimension); -// graphics2D.drawRect(0,0, dimension.width, dimension.height); - - if (selection.getHover() != null) { - drawMouseOver(graphics2D); + if (point.x > mx) { + point.x = mx; + } + if (point.y < 0) { + point.y = 0; + } + if (point.y > my) { + point.y = my; + } + // center margins + if (mx < 0) { + point.x = 0; } + if (my < 0) { + point.y = my / 2; + } + viewport.setViewPosition(point); + } + }; + } + }; + } + + public void draw(Graphics2D graphics2D) { + currentStateBoxes.clear(); + Tree tree = GameBoardFacade.getInstance().getTree(); + if (tree != null) { + // setSize(bounds.getDimension()); + graphics2D.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics2D.setRenderingHint( + RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + drawTree(graphics2D); + + dimension.width += BORDER_SPACING; + setSize(dimension); + // graphics2D.drawRect(0,0, dimension.width, dimension.height); + + if (selection.getHover() != null) { + drawMouseOver(graphics2D); + } + } + } + + public void zoomReset() { + zoomTo(1.0); + viewport.setViewPosition(new Point(0, 0)); + } + + private void redrawTree(Graphics2D graphics2D, TreeNodeView nodeView) { + if (nodeView != null) { + nodeView.draw(graphics2D); + for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { + transitionView.draw(graphics2D); + redrawTree(graphics2D, transitionView.getChildView()); + } + } + } + + public void removeTreeElement(TreeElementView view) { + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + nodeView.getParentView().setChildView(null); + } else { + TreeTransitionView transitionView = (TreeTransitionView) view; + transitionView + .getParentViews() + .forEach((TreeNodeView n) -> n.removeChildrenView(transitionView)); + } + } + + /** + * When the edu.rpi.legup.user hovers over the transition, draws the corresponding rules image + * + * @param g the graphics to use to draw + */ + public void drawMouseOver(Graphics2D g) { + if (selection.getHover().getType() == TRANSITION + && ((TreeTransitionView) selection.getHover()).getTreeElement().isJustified()) { + TreeTransition transition = (TreeTransition) selection.getHover().treeElement; + int imgWidth = 100; + int imgHeight = 100; + + BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); + image.createGraphics().drawImage(transition.getRule().getImageIcon().getImage(), 0, 0, null); + Point mousePoint = selection.getMousePoint(); + g.drawImage(image, mousePoint.x, mousePoint.y - 50, imgWidth, imgHeight, null); + } + } + + public void resetView() { + this.tree = null; + this.rootNodeView = null; + this.selection.clearSelection(); + this.selection.clearHover(); + } + + /** + * Called when a tree puzzleElement is added to the tree + * + * @param treeElement TreeElement that was added to the tree + */ + @Override + public void onTreeElementAdded(TreeElement treeElement) { + if (treeElement.getType() == NODE) { + addTreeNode((TreeNode) treeElement); + } else { + addTreeTransition((TreeTransition) treeElement); + } + repaint(); + } + + /** + * Called when a tree puzzleElement is removed from the tree + * + * @param element TreeElement that was removed to the tree + */ + @Override + public void onTreeElementRemoved(TreeElement element) { + if (element.getType() == NODE) { + TreeNode node = (TreeNode) element; + TreeNodeView nodeView = (TreeNodeView) viewMap.get(node); + + nodeView.getParentView().setChildView(null); + removeTreeNode(node); + } else { + TreeTransition trans = (TreeTransition) element; + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + + // unlock ancestor elements if case rule deleted + Rule rule = trans.getRule(); + for (TreeNode node : trans.getParents()) { + + // only if the last case of a case rule will be deleted + if (!(rule instanceof CaseRule && node.getChildren().isEmpty())) { + continue; } - } - - public void zoomReset() { - zoomTo(1.0); - viewport.setViewPosition(new Point(0, 0)); - } - private void redrawTree(Graphics2D graphics2D, TreeNodeView nodeView) { - if (nodeView != null) { - nodeView.draw(graphics2D); - for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { - transitionView.draw(graphics2D); - redrawTree(graphics2D, transitionView.getChildView()); + CaseRule caseRule = (CaseRule) rule; + // set dependent elements to be modifiable by ancestors (if not dependent on others) + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + + for (PuzzleElement pelement : + caseRule.dependentElements(node.getBoard(), trans.getSelection())) { + // decrement, unlock if 0 cases depended + PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); + oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); + if (oldElement.getCasesDepended() != 0) { + continue; } - } - } - public void removeTreeElement(TreeElementView view) { - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - nodeView.getParentView().setChildView(null); - } - else { - TreeTransitionView transitionView = (TreeTransitionView) view; - transitionView.getParentViews().forEach((TreeNodeView n) -> n.removeChildrenView(transitionView)); - } - } + // set modifiable if started modifiable + boolean modifiable = + tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); - /** - * When the edu.rpi.legup.user hovers over the transition, draws the corresponding rules image - * - * @param g the graphics to use to draw - */ - public void drawMouseOver(Graphics2D g) { - if (selection.getHover().getType() == TRANSITION && ((TreeTransitionView) selection.getHover()).getTreeElement().isJustified()) { - TreeTransition transition = (TreeTransition) selection.getHover().treeElement; - int imgWidth = 100; - int imgHeight = 100; - - BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); - image.createGraphics().drawImage(transition.getRule().getImageIcon().getImage(), 0, 0, null); - Point mousePoint = selection.getMousePoint(); - g.drawImage(image, mousePoint.x, mousePoint.y - 50, imgWidth, imgHeight, null); + // unmodifiable if already modified + TreeNode modNode = ancestor.getParent().getParents().get(0); + while (modNode.getParent() != null) { + Board modBoard = modNode.getParent().getBoard(); + if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { + modifiable = false; + break; + } + modNode = modNode.getParent().getParents().get(0); + } + oldElement.setModifiable(modifiable); + } } - } + } + + transView.getParentViews().forEach(n -> n.removeChildrenView(transView)); + removeTreeTransition(trans); + } + repaint(); + } + + /** + * Called when the tree selection was changed + * + * @param selection tree selection that was changed + */ + @Override + public void onTreeSelectionChanged(TreeViewSelection selection) { + this.selection.getSelectedViews().forEach(v -> v.setSelected(false)); + selection.getSelectedViews().forEach(v -> v.setSelected(true)); + this.selection = selection; + repaint(); + } + + /** Called when the model has finished updating the tree. */ + @Override + public void onUpdateTree() { + repaint(); + } + + /** + * Gets the TreeElementView by the corresponding TreeElement associated with it + * + * @param element TreeElement of the view + * @return TreeElementView of the TreeElement associated with it + */ + public TreeElementView getElementView(TreeElement element) { + return viewMap.get(element); + } + + private void removeTreeNode(TreeNode node) { + viewMap.remove(node); + List children = node.getChildren(); + + // if child is a case rule, unlock ancestor elements + if (!children.isEmpty()) { + Rule rule = children.get(0).getRule(); + if (rule instanceof CaseRule) { + CaseRule caseRule = (CaseRule) rule; + // set dependent elements to be modifiable by ancestors (if not dependent on others) + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement pelement : + caseRule.dependentElements(node.getBoard(), children.get(0).getSelection())) { + // decrement, unlock if 0 cases depended + PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); + oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); + if (oldElement.getCasesDepended() == 0) { + continue; + } - public void resetView() { - this.tree = null; - this.rootNodeView = null; - this.selection.clearSelection(); - this.selection.clearHover(); - } + // set modifiable if started modifiable + boolean modifiable = + tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); - /** - * Called when a tree puzzleElement is added to the tree - * - * @param treeElement TreeElement that was added to the tree - */ - @Override - public void onTreeElementAdded(TreeElement treeElement) { - if (treeElement.getType() == NODE) { - addTreeNode((TreeNode) treeElement); - } - else { - addTreeTransition((TreeTransition) treeElement); + // unmodifiable if already modified + TreeNode modNode = ancestor.getParent().getParents().get(0); + while (modNode.getParent() != null) { + Board modBoard = modNode.getParent().getBoard(); + if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { + modifiable = false; + break; + } + modNode = modNode.getParent().getParents().get(0); + } + oldElement.setModifiable(modifiable); + } } - repaint(); - } - - /** - * Called when a tree puzzleElement is removed from the tree - * - * @param element TreeElement that was removed to the tree - */ - @Override - public void onTreeElementRemoved(TreeElement element) { - if (element.getType() == NODE) { - TreeNode node = (TreeNode) element; - TreeNodeView nodeView = (TreeNodeView) viewMap.get(node); - - nodeView.getParentView().setChildView(null); - removeTreeNode(node); + } + } + node.getChildren().forEach(t -> removeTreeTransition(t)); + } + + private void removeTreeTransition(TreeTransition trans) { + viewMap.remove(trans); + if (trans.getChildNode() != null) { + removeTreeNode(trans.getChildNode()); + } + } + + private void addTreeNode(TreeNode node) { + TreeTransition parent = node.getParent(); + + TreeNodeView nodeView = new TreeNodeView(node); + TreeTransitionView parentView = (TreeTransitionView) viewMap.get(parent); + + nodeView.setParentView(parentView); + parentView.setChildView(nodeView); + + viewMap.put(node, nodeView); + + if (!node.getChildren().isEmpty()) { + + // if adding a case rule, lock dependent ancestor elements + Rule rule = node.getChildren().get(0).getRule(); + if (rule instanceof CaseRule) { + CaseRule caseRule = (CaseRule) rule; + + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement element : + caseRule.dependentElements( + node.getBoard(), node.getChildren().get(0).getSelection())) { + // increment and lock + PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); + oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); + oldElement.setModifiable(false); + } } - else { - TreeTransition trans = (TreeTransition) element; - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - - // unlock ancestor elements if case rule deleted - Rule rule = trans.getRule(); - for (TreeNode node : trans.getParents()) { - - // only if the last case of a case rule will be deleted - if (!(rule instanceof CaseRule && node.getChildren().isEmpty())) { - continue; - } - - CaseRule caseRule = (CaseRule)rule; - // set dependent elements to be modifiable by ancestors (if not dependent on others) - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - - for (PuzzleElement pelement : caseRule.dependentElements(node.getBoard(), trans.getSelection())) { - // decrement, unlock if 0 cases depended - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); - oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); - if (oldElement.getCasesDepended() != 0) { - continue; - } - - // set modifiable if started modifiable - boolean modifiable = tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); - - // unmodifiable if already modified - TreeNode modNode = ancestor.getParent().getParents().get(0); - while (modNode.getParent()!=null) { - Board modBoard = modNode.getParent().getBoard(); - if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { - modifiable = false; - break; - } - modNode = modNode.getParent().getParents().get(0); - } - oldElement.setModifiable(modifiable); - } - } - } - - transView.getParentViews().forEach(n -> n.removeChildrenView(transView)); - removeTreeTransition(trans); + } + + node.getChildren().forEach(t -> addTreeTransition(t)); + } + } + + private void addTreeTransition(TreeTransition trans) { + List parents = trans.getParents(); + + TreeTransitionView transView = new TreeTransitionView(trans); + for (TreeNode parent : parents) { + TreeNodeView parentNodeView = (TreeNodeView) viewMap.get(parent); + transView.addParentView(parentNodeView); + parentNodeView.addChildrenView(transView); + + // if transition is a new case rule, lock dependent ancestor elements + Rule rule = trans.getRule(); + if (rule instanceof CaseRule && parent.getChildren().size() == 1) { + CaseRule caseRule = (CaseRule) rule; + + List ancestors = parent.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement element : + caseRule.dependentElements(parent.getBoard(), trans.getSelection())) { + // increment and lock + PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); + oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); + oldElement.setModifiable(false); + } } - repaint(); + } } - /** - * Called when the tree selection was changed - * - * @param selection tree selection that was changed - */ - @Override - public void onTreeSelectionChanged(TreeViewSelection selection) { - this.selection.getSelectedViews().forEach(v -> v.setSelected(false)); - selection.getSelectedViews().forEach(v -> v.setSelected(true)); - this.selection = selection; - repaint(); - } + viewMap.put(trans, transView); - /** - * Called when the model has finished updating the tree. - */ - @Override - public void onUpdateTree() { - repaint(); + if (trans.getChildNode() != null) { + addTreeNode(trans.getChildNode()); } + } - /** - * Gets the TreeElementView by the corresponding TreeElement associated with it - * - * @param element TreeElement of the view - * @return TreeElementView of the TreeElement associated with it - */ - public TreeElementView getElementView(TreeElement element) { - return viewMap.get(element); - } + /// New Draw Methods - private void removeTreeNode(TreeNode node) { - viewMap.remove(node); - List children = node.getChildren(); - - // if child is a case rule, unlock ancestor elements - if (!children.isEmpty()) { - Rule rule = children.get(0).getRule(); - if (rule instanceof CaseRule) { - CaseRule caseRule = (CaseRule)rule; - // set dependent elements to be modifiable by ancestors (if not dependent on others) - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement pelement : caseRule.dependentElements(node.getBoard(), children.get(0).getSelection())) { - // decrement, unlock if 0 cases depended - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); - oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); - if (oldElement.getCasesDepended() == 0) { - continue; - } - - // set modifiable if started modifiable - boolean modifiable = tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); - - // unmodifiable if already modified - TreeNode modNode = ancestor.getParent().getParents().get(0); - while (modNode.getParent() != null) { - Board modBoard = modNode.getParent().getBoard(); - if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { - modifiable = false; - break; - } - modNode = modNode.getParent().getParents().get(0); - } - oldElement.setModifiable(modifiable); - } - } - } - } - node.getChildren().forEach(t -> removeTreeTransition(t)); - } + public void drawTree(Graphics2D graphics2D) { + if (tree == null) { + LOGGER.error("Unable to draw tree."); + } else { + if (rootNodeView == null) { + rootNodeView = new TreeNodeView(tree.getRootNode()); - private void removeTreeTransition(TreeTransition trans) { - viewMap.remove(trans); - if (trans.getChildNode() != null) { - removeTreeNode(trans.getChildNode()); - } - } + LOGGER.debug("Creating new views for tree view."); + createViews(rootNodeView); - private void addTreeNode(TreeNode node) { - TreeTransition parent = node.getParent(); - - TreeNodeView nodeView = new TreeNodeView(node); - TreeTransitionView parentView = (TreeTransitionView) viewMap.get(parent); - - nodeView.setParentView(parentView); - parentView.setChildView(nodeView); - - viewMap.put(node, nodeView); - - if (!node.getChildren().isEmpty()) { - - // if adding a case rule, lock dependent ancestor elements - Rule rule = node.getChildren().get(0).getRule(); - if (rule instanceof CaseRule) { - CaseRule caseRule = (CaseRule)rule; - - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement element : caseRule.dependentElements(node.getBoard(), node.getChildren().get(0).getSelection())) { - // increment and lock - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); - oldElement.setCasesDepended(oldElement.getCasesDepended()+1); - oldElement.setModifiable(false); - } - } - } - - node.getChildren().forEach(t -> addTreeTransition(t)); - } - } + selection.newSelection(rootNodeView); + } - private void addTreeTransition(TreeTransition trans) { - List parents = trans.getParents(); - - TreeTransitionView transView = new TreeTransitionView(trans); - for (TreeNode parent : parents) { - TreeNodeView parentNodeView = (TreeNodeView) viewMap.get(parent); - transView.addParentView(parentNodeView); - parentNodeView.addChildrenView(transView); - - // if transition is a new case rule, lock dependent ancestor elements - Rule rule = trans.getRule(); - if (rule instanceof CaseRule && parent.getChildren().size()==1) { - CaseRule caseRule = (CaseRule)rule; - - List ancestors = parent.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement element : caseRule.dependentElements(parent.getBoard(), trans.getSelection())) { - // increment and lock - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); - oldElement.setCasesDepended(oldElement.getCasesDepended()+1); - oldElement.setModifiable(false); - } - } - } - } + dimension = new Dimension(0, 0); + calcSpan(rootNodeView); + rootNodeView.setSpan(rootNodeView.getSpan() + DIAMETER + BORDER_SPACING); - viewMap.put(trans, transView); + calculateViewLocations(rootNodeView, 0); + dimension.height = (int) rootNodeView.getSpan(); - if (trans.getChildNode() != null) { - addTreeNode(trans.getChildNode()); - } + redrawTree(graphics2D, rootNodeView); + LOGGER.debug("DrawTree: dimensions - " + dimension.width + "x" + dimension.height); } + } - ///New Draw Methods + public void createViews(TreeNodeView nodeView) { + if (nodeView != null) { + viewMap.put(nodeView.getTreeElement(), nodeView); - public void drawTree(Graphics2D graphics2D) { - if (tree == null) { - LOGGER.error("Unable to draw tree."); + TreeNode node = nodeView.getTreeElement(); + for (TreeTransition trans : node.getChildren()) { + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + if (transView != null) { + nodeView.addChildrenView(transView); + transView.addParentView(nodeView); + break; } - else { - if (rootNodeView == null) { - rootNodeView = new TreeNodeView(tree.getRootNode()); + transView = new TreeTransitionView(trans); - LOGGER.debug("Creating new views for tree view."); - createViews(rootNodeView); + viewMap.put(transView.getTreeElement(), transView); - selection.newSelection(rootNodeView); - } + transView.addParentView(nodeView); + nodeView.addChildrenView(transView); - dimension = new Dimension(0, 0); - calcSpan(rootNodeView); - rootNodeView.setSpan(rootNodeView.getSpan() + DIAMETER + BORDER_SPACING); + TreeNode childNode = trans.getChildNode(); + if (childNode != null) { + TreeNodeView childNodeView = new TreeNodeView(childNode); + viewMap.put(childNodeView.getTreeElement(), childNodeView); - calculateViewLocations(rootNodeView, 0); - dimension.height = (int) rootNodeView.getSpan(); + childNodeView.setParentView(transView); + transView.setChildView(childNodeView); - redrawTree(graphics2D, rootNodeView); - LOGGER.debug("DrawTree: dimensions - " + dimension.width + "x" + dimension.height); + createViews(childNodeView); } + } } + } - public void createViews(TreeNodeView nodeView) { - if (nodeView != null) { - viewMap.put(nodeView.getTreeElement(), nodeView); + public void calculateViewLocations(TreeNodeView nodeView, int depth) { + nodeView.setDepth(depth); + int xLoc = (NODE_GAP_WIDTH + DIAMETER) * depth + DIAMETER; + nodeView.setX(xLoc); + dimension.width = Math.max(dimension.width, xLoc); - TreeNode node = nodeView.getTreeElement(); - for (TreeTransition trans : node.getChildren()) { - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - if (transView != null) { - nodeView.addChildrenView(transView); - transView.addParentView(nodeView); - break; - } - transView = new TreeTransitionView(trans); + TreeTransitionView parentTransView = nodeView.getParentView(); + int yLoc = parentTransView == null ? (int) nodeView.getSpan() / 2 : parentTransView.getEndY(); + nodeView.setY(yLoc); - viewMap.put(transView.getTreeElement(), transView); + ArrayList children = nodeView.getChildrenViews(); + switch (children.size()) { + case 0: + break; + case 1: + { + TreeTransitionView childView = children.get(0); - transView.addParentView(nodeView); - nodeView.addChildrenView(transView); + List parentsViews = childView.getParentViews(); + if (parentsViews.size() == 1) { + childView.setEndY(yLoc); - TreeNode childNode = trans.getChildNode(); - if (childNode != null) { - TreeNodeView childNodeView = new TreeNodeView(childNode); - viewMap.put(childNodeView.getTreeElement(), childNodeView); + childView.setDepth(depth); - childNodeView.setParentView(transView); - transView.setChildView(childNodeView); + Point lineStartPoint = childView.getLineStartPoint(0); + lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = yLoc; + childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - createViews(childNodeView); - } - } - } - } - - public void calculateViewLocations(TreeNodeView nodeView, int depth) { - nodeView.setDepth(depth); - int xLoc = (NODE_GAP_WIDTH + DIAMETER) * depth + DIAMETER; - nodeView.setX(xLoc); - dimension.width = Math.max(dimension.width, xLoc); + dimension.width = Math.max(dimension.width, childView.getEndX()); - TreeTransitionView parentTransView = nodeView.getParentView(); - int yLoc = parentTransView == null ? (int) nodeView.getSpan() / 2 : parentTransView.getEndY(); - nodeView.setY(yLoc); - - ArrayList children = nodeView.getChildrenViews(); - switch (children.size()) { - case 0: - break; - case 1: { - TreeTransitionView childView = children.get(0); - - List parentsViews = childView.getParentViews(); - if (parentsViews.size() == 1) { - childView.setEndY(yLoc); - - childView.setDepth(depth); - - Point lineStartPoint = childView.getLineStartPoint(0); - lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = yLoc; - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - - dimension.width = Math.max(dimension.width, childView.getEndX()); - - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } - else { - if (parentsViews.size() > 1 && parentsViews.get(parentsViews.size() - 1) == nodeView) { - int yAvg = 0; - for (int i = 0; i < parentsViews.size(); i++) { - TreeNodeView parentNodeView = parentsViews.get(i); - depth = Math.max(depth, parentNodeView.getDepth()); - yAvg += parentNodeView.getY(); - - Point lineStartPoint = childView.getLineStartPoint(i); - lineStartPoint.x = parentNodeView.getX() + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = parentNodeView.getY(); - } - yAvg /= parentsViews.size(); - childView.setEndY(yAvg); - - childView.setDepth(depth); - - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - - dimension.width = Math.max(dimension.width, childView.getEndX()); - - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } - } - break; + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); } - default: { - int span = 0; - for (TreeTransitionView childView : children) { - span += childView.getSpan(); - } - - span = (int) ((nodeView.getSpan() - span) / 2); - for (int i = 0; i < children.size(); i++) { - TreeTransitionView childView = children.get(i); - - childView.setDepth(depth); - - Point lineStartPoint = childView.getLineStartPoint(0); - lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = yLoc; - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - childView.setEndY(yLoc - (int) (nodeView.getSpan() / 2) + span + (int) (childView.getSpan() / 2)); - - span += childView.getSpan(); - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } - break; + } else { + if (parentsViews.size() > 1 && parentsViews.get(parentsViews.size() - 1) == nodeView) { + int yAvg = 0; + for (int i = 0; i < parentsViews.size(); i++) { + TreeNodeView parentNodeView = parentsViews.get(i); + depth = Math.max(depth, parentNodeView.getDepth()); + yAvg += parentNodeView.getY(); + + Point lineStartPoint = childView.getLineStartPoint(i); + lineStartPoint.x = parentNodeView.getX() + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = parentNodeView.getY(); + } + yAvg /= parentsViews.size(); + childView.setEndY(yAvg); + + childView.setDepth(depth); + + childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + + dimension.width = Math.max(dimension.width, childView.getEndX()); + + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } } + } + break; } - } - - public void calcSpan(TreeElementView view) { - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - TreeNode node = nodeView.getTreeElement(); - if (nodeView.getChildrenViews().size() == 0) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } - else { - if (nodeView.getChildrenViews().size() == 1) { - TreeTransitionView childView = nodeView.getChildrenViews().get(0); - calcSpan(childView); - if (childView.getParentViews().size() > 1) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } - else { - nodeView.setSpan(childView.getSpan()); - } - } - else { - DisjointSets branches = node.findMergingBranches(); - List children = node.getChildren(); - - if (node == children.get(0).getParents().get(0)) { - reorderBranches(node, branches); - ArrayList newChildrenViews = new ArrayList<>(); - for (TreeTransition trans : node.getChildren()) { - newChildrenViews.add((TreeTransitionView) viewMap.get(trans)); - } - nodeView.setChildrenViews(newChildrenViews); - } - - List> mergingSets = branches.getAllSets(); - - double span = 0.0; - for (Set mergeSet : mergingSets) { - if (mergeSet.size() > 1) { - TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); - TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); - double subSpan = 0.0; - for (TreeTransition branch : mergeSet) { - TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); - subCalcSpan(branchView, mergePointView); - subSpan += branchView.getSpan(); - } - calcSpan(mergePointView); - span += Math.max(mergePointView.getSpan(), subSpan); - } - else { - TreeTransition trans = mergeSet.iterator().next(); - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - calcSpan(transView); - span += transView.getSpan(); - } - } - nodeView.setSpan(span); - } - } - } - else { - TreeTransitionView transView = (TreeTransitionView) view; - TreeNodeView nodeView = transView.getChildView(); - if (nodeView == null) { - transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } - else { - calcSpan(nodeView); - transView.setSpan(nodeView.getSpan()); + default: + { + int span = 0; + for (TreeTransitionView childView : children) { + span += childView.getSpan(); + } + + span = (int) ((nodeView.getSpan() - span) / 2); + for (int i = 0; i < children.size(); i++) { + TreeTransitionView childView = children.get(i); + + childView.setDepth(depth); + + Point lineStartPoint = childView.getLineStartPoint(0); + lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = yLoc; + childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + childView.setEndY( + yLoc - (int) (nodeView.getSpan() / 2) + span + (int) (childView.getSpan() / 2)); + + span += childView.getSpan(); + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); } + } + break; } } - - /** - * Calculates the sub span of a given sub tree rooted at the specified view and stops at the tree puzzleElement view - * specified as stop. Stop tree puzzleElement is NOT included in the span calculation - * - * @param view - * @param stop - */ - private void subCalcSpan(TreeElementView view, TreeElementView stop) { - //safe-guard for infinite loop - if (view == stop) { - return; - } - - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - TreeNode node = nodeView.getTreeElement(); - if (nodeView.getChildrenViews().size() == 0) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } + + public void calcSpan(TreeElementView view) { + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + TreeNode node = nodeView.getTreeElement(); + if (nodeView.getChildrenViews().size() == 0) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + if (nodeView.getChildrenViews().size() == 1) { + TreeTransitionView childView = nodeView.getChildrenViews().get(0); + calcSpan(childView); + if (childView.getParentViews().size() > 1) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + nodeView.setSpan(childView.getSpan()); + } + } else { + DisjointSets branches = node.findMergingBranches(); + List children = node.getChildren(); + + if (node == children.get(0).getParents().get(0)) { + reorderBranches(node, branches); + ArrayList newChildrenViews = new ArrayList<>(); + for (TreeTransition trans : node.getChildren()) { + newChildrenViews.add((TreeTransitionView) viewMap.get(trans)); } - else { - if (nodeView.getChildrenViews().size() == 1) { - TreeTransitionView childView = nodeView.getChildrenViews().get(0); - if (childView == stop) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } - else { - subCalcSpan(childView, stop); - if (childView.getParentViews().size() > 1) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } - else { - nodeView.setSpan(childView.getSpan()); - } - } - } - else { - DisjointSets branches = node.findMergingBranches(); - List children = node.getChildren(); - - if (node == children.get(0).getParents().get(0)) { - reorderBranches(node, branches); - } - - List> mergingSets = branches.getAllSets(); - - double span = 0.0; - for (Set mergeSet : mergingSets) { - if (mergeSet.size() > 1) { - TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); - TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); - double subSpan = 0.0; - for (TreeTransition branch : mergeSet) { - TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); - subCalcSpan(branchView, mergePointView); - subSpan += branchView.getSpan(); - } - subCalcSpan(mergePointView, stop); - span += Math.max(mergePointView.getSpan(), subSpan); - } - else { - TreeTransition trans = mergeSet.iterator().next(); - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - subCalcSpan(transView, stop); - span += transView.getSpan(); - } - } - - nodeView.setSpan(span); - } + nodeView.setChildrenViews(newChildrenViews); + } + + List> mergingSets = branches.getAllSets(); + + double span = 0.0; + for (Set mergeSet : mergingSets) { + if (mergeSet.size() > 1) { + TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); + TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); + double subSpan = 0.0; + for (TreeTransition branch : mergeSet) { + TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); + subCalcSpan(branchView, mergePointView); + subSpan += branchView.getSpan(); + } + calcSpan(mergePointView); + span += Math.max(mergePointView.getSpan(), subSpan); + } else { + TreeTransition trans = mergeSet.iterator().next(); + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + calcSpan(transView); + span += transView.getSpan(); } + } + nodeView.setSpan(span); } - else { - TreeTransitionView transView = (TreeTransitionView) view; - TreeNodeView nodeView = transView.getChildView(); - if (nodeView == null || nodeView == stop) { - transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } + } else { + TreeTransitionView transView = (TreeTransitionView) view; + TreeNodeView nodeView = transView.getChildView(); + if (nodeView == null) { + transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + calcSpan(nodeView); + transView.setSpan(nodeView.getSpan()); + } + } + } + + /** + * Calculates the sub span of a given sub tree rooted at the specified view and stops at the tree + * puzzleElement view specified as stop. Stop tree puzzleElement is NOT included in the span + * calculation + * + * @param view + * @param stop + */ + private void subCalcSpan(TreeElementView view, TreeElementView stop) { + // safe-guard for infinite loop + if (view == stop) { + return; + } + + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + TreeNode node = nodeView.getTreeElement(); + if (nodeView.getChildrenViews().size() == 0) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + if (nodeView.getChildrenViews().size() == 1) { + TreeTransitionView childView = nodeView.getChildrenViews().get(0); + if (childView == stop) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + subCalcSpan(childView, stop); + if (childView.getParentViews().size() > 1) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + nodeView.setSpan(childView.getSpan()); } - else { - calcSpan(nodeView); - transView.setSpan(nodeView.getSpan()); + } + } else { + DisjointSets branches = node.findMergingBranches(); + List children = node.getChildren(); + + if (node == children.get(0).getParents().get(0)) { + reorderBranches(node, branches); + } + + List> mergingSets = branches.getAllSets(); + + double span = 0.0; + for (Set mergeSet : mergingSets) { + if (mergeSet.size() > 1) { + TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); + TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); + double subSpan = 0.0; + for (TreeTransition branch : mergeSet) { + TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); + subCalcSpan(branchView, mergePointView); + subSpan += branchView.getSpan(); + } + subCalcSpan(mergePointView, stop); + span += Math.max(mergePointView.getSpan(), subSpan); + } else { + TreeTransition trans = mergeSet.iterator().next(); + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + subCalcSpan(transView, stop); + span += transView.getSpan(); } - } - } + } - /** - * Reorders branches such that merging branches are sequentially grouped together and transitions are kept in - * relative order in the list of child transitions of the specified node - * - * @param node root node of the branches - * @param branches DisjointSets of the child branches of the specified node which determine which branches merge - */ - private void reorderBranches(TreeNode node, DisjointSets branches) { - List children = node.getChildren(); - List> mergingSets = branches.getAllSets(); - - List> newOrder = new ArrayList<>(); - for (Set set : mergingSets) { - List mergeBranch = new ArrayList<>(); - newOrder.add(mergeBranch); - children.forEach(t -> { - if (set.contains(t)) { - mergeBranch.add(t); - } - }); - mergeBranch.sort((TreeTransition t1, TreeTransition t2) -> - children.indexOf(t1) <= children.indexOf(t2) ? -1 : 1); + nodeView.setSpan(span); } - - newOrder.sort((List b1, List b2) -> { - int low1 = -1; - int low2 = -1; - for (TreeTransition t1 : b1) { - int curIndex = children.indexOf(t1); - if (low1 == -1 || curIndex < low1) { - low1 = curIndex; - } + } + } else { + TreeTransitionView transView = (TreeTransitionView) view; + TreeNodeView nodeView = transView.getChildView(); + if (nodeView == null || nodeView == stop) { + transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + calcSpan(nodeView); + transView.setSpan(nodeView.getSpan()); + } + } + } + + /** + * Reorders branches such that merging branches are sequentially grouped together and transitions + * are kept in relative order in the list of child transitions of the specified node + * + * @param node root node of the branches + * @param branches DisjointSets of the child branches of the specified node which determine which + * branches merge + */ + private void reorderBranches(TreeNode node, DisjointSets branches) { + List children = node.getChildren(); + List> mergingSets = branches.getAllSets(); + + List> newOrder = new ArrayList<>(); + for (Set set : mergingSets) { + List mergeBranch = new ArrayList<>(); + newOrder.add(mergeBranch); + children.forEach( + t -> { + if (set.contains(t)) { + mergeBranch.add(t); + } + }); + mergeBranch.sort( + (TreeTransition t1, TreeTransition t2) -> + children.indexOf(t1) <= children.indexOf(t2) ? -1 : 1); + } + + newOrder.sort( + (List b1, List b2) -> { + int low1 = -1; + int low2 = -1; + for (TreeTransition t1 : b1) { + int curIndex = children.indexOf(t1); + if (low1 == -1 || curIndex < low1) { + low1 = curIndex; } - for (TreeTransition t1 : b2) { - int curIndex = children.indexOf(t1); - if (low1 == -1 || curIndex < low1) { - low1 = curIndex; - } + } + for (TreeTransition t1 : b2) { + int curIndex = children.indexOf(t1); + if (low1 == -1 || curIndex < low1) { + low1 = curIndex; } - return low1 < low2 ? -1 : 1; + } + return low1 < low2 ? -1 : 1; }); - List newChildren = new ArrayList<>(); - newOrder.forEach(l -> newChildren.addAll(l)); - node.setChildren(newChildren); - } -} \ No newline at end of file + List newChildren = new ArrayList<>(); + newOrder.forEach(l -> newChildren.addAll(l)); + node.setChildren(newChildren); + } +} diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java index 042eb8880..e8eddaa6c 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java @@ -1,172 +1,164 @@ package edu.rpi.legup.ui.proofeditorui.treeview; import java.awt.*; -import java.util.List; import java.util.ArrayList; +import java.util.List; public class TreeViewSelection { - private ArrayList selectedViews; - private TreeElementView hover; - private Point mousePoint; - - /** - * TreeViewSelection Constructor creates a tree view selection - */ - public TreeViewSelection() { - this.selectedViews = new ArrayList<>(); - this.hover = null; - this.mousePoint = null; - } - - /** - * TreeViewSelection Constructor creates a tree view selection with a selected view - * - * @param view selected view - */ - public TreeViewSelection(TreeElementView view) { - this(); - this.selectedViews.add(view); - } - - /** - * TreeViewSelection Constructor creates a tree view selection with a list of selected views - * - * @param views list of selected views - */ - public TreeViewSelection(List views) { - this(); - this.selectedViews.addAll(views); - } - - - /** - * Gets the list of selected tree puzzleElement views - * - * @return list of selected tree puzzleElement views - */ - public List getSelectedViews() { - return selectedViews; + private ArrayList selectedViews; + private TreeElementView hover; + private Point mousePoint; + + /** TreeViewSelection Constructor creates a tree view selection */ + public TreeViewSelection() { + this.selectedViews = new ArrayList<>(); + this.hover = null; + this.mousePoint = null; + } + + /** + * TreeViewSelection Constructor creates a tree view selection with a selected view + * + * @param view selected view + */ + public TreeViewSelection(TreeElementView view) { + this(); + this.selectedViews.add(view); + } + + /** + * TreeViewSelection Constructor creates a tree view selection with a list of selected views + * + * @param views list of selected views + */ + public TreeViewSelection(List views) { + this(); + this.selectedViews.addAll(views); + } + + /** + * Gets the list of selected tree puzzleElement views + * + * @return list of selected tree puzzleElement views + */ + public List getSelectedViews() { + return selectedViews; + } + + /** + * Gets the first selectedViews in the list of views + * + * @return first selectedViews in the list of views + */ + public TreeElementView getFirstSelection() { + return selectedViews.size() == 0 ? null : selectedViews.get(0); + } + + /** + * Toggles a tree puzzleElement view selectedViews + * + * @param treeElementView a tree puzzleElement view to toggle + */ + public void toggleSelection(TreeElementView treeElementView) { + if (selectedViews.contains(treeElementView)) { + selectedViews.remove(treeElementView); + treeElementView.setSelected(false); + } else { + selectedViews.add(treeElementView); + treeElementView.setSelected(true); } - - /** - * Gets the first selectedViews in the list of views - * - * @return first selectedViews in the list of views - */ - public TreeElementView getFirstSelection() { - return selectedViews.size() == 0 ? null : selectedViews.get(0); + } + + /** + * Adds a tree puzzleElement view selectedViews + * + * @param treeElementView a tree puzzleElement view to add + */ + public void addToSelection(TreeElementView treeElementView) { + if (!selectedViews.contains(treeElementView)) { + selectedViews.add(treeElementView); + treeElementView.setSelected(true); } - - /** - * Toggles a tree puzzleElement view selectedViews - * - * @param treeElementView a tree puzzleElement view to toggle - */ - public void toggleSelection(TreeElementView treeElementView) { - if (selectedViews.contains(treeElementView)) { - selectedViews.remove(treeElementView); - treeElementView.setSelected(false); - } - else { - selectedViews.add(treeElementView); - treeElementView.setSelected(true); - } + } + + /** + * Creates a new selectedViews and add the specified tree puzzleElement view + * + * @param treeElementView tree puzzleElement view + */ + public void newSelection(TreeElementView treeElementView) { + clearSelection(); + selectedViews.add(treeElementView); + treeElementView.setSelected(true); + } + + /** Clears all selected views */ + public void clearSelection() { + for (TreeElementView treeElementView : selectedViews) { + treeElementView.setSelected(false); } - - /** - * Adds a tree puzzleElement view selectedViews - * - * @param treeElementView a tree puzzleElement view to add - */ - public void addToSelection(TreeElementView treeElementView) { - if (!selectedViews.contains(treeElementView)) { - selectedViews.add(treeElementView); - treeElementView.setSelected(true); - } - } - - /** - * Creates a new selectedViews and add the specified tree puzzleElement view - * - * @param treeElementView tree puzzleElement view - */ - public void newSelection(TreeElementView treeElementView) { - clearSelection(); - selectedViews.add(treeElementView); - treeElementView.setSelected(true); + selectedViews.clear(); + } + + /** + * Gets tree puzzleElement view that the mouse is hovering over or null is no such view exists + * + * @return tree puzzleElement view that the mouse is hovering over or null is no such view exists + */ + public TreeElementView getHover() { + return hover; + } + + /** + * Clears the previous hover and sets the specified tree puzzleElement view to the new hover + * + * @param newHovered tree puzzleElement view for the new hover + */ + public void newHover(TreeElementView newHovered) { + newHovered.setHover(true); + if (hover != null) { + hover.setHover(false); } - - /** - * Clears all selected views - */ - public void clearSelection() { - for (TreeElementView treeElementView : selectedViews) { - treeElementView.setSelected(false); - } - selectedViews.clear(); - } - - /** - * Gets tree puzzleElement view that the mouse is hovering over or null is no such view exists - * - * @return tree puzzleElement view that the mouse is hovering over or null is no such view exists - */ - public TreeElementView getHover() { - return hover; - } - - /** - * Clears the previous hover and sets the specified tree puzzleElement view to the new hover - * - * @param newHovered tree puzzleElement view for the new hover - */ - public void newHover(TreeElementView newHovered) { - newHovered.setHover(true); - if (hover != null) { - hover.setHover(false); - } - hover = newHovered; - } - - /** - * Clears the current hover tree puzzleElement view - */ - public void clearHover() { - if (hover != null) { - hover.setHover(false); - hover = null; - } - } - - /** - * Gets the current mouse location relative to the tree view - * - * @return the current mouse location relative to the tree view - */ - public Point getMousePoint() { - return mousePoint; - } - - /** - * Sets the current mouse location relative to the tree view - * - * @param point the current mouse location relative to the tree view - */ - public void setMousePoint(Point point) { - this.mousePoint = point; - } - - /** - * Copies the TreeViewSelection - * - * @return a copy of this TreeViewSelection - */ - @SuppressWarnings("unchecked") - public TreeViewSelection copy() { - TreeViewSelection cpy = new TreeViewSelection(); - cpy.selectedViews = (ArrayList) selectedViews.clone(); - cpy.hover = hover; - cpy.mousePoint = mousePoint; - return cpy; + hover = newHovered; + } + + /** Clears the current hover tree puzzleElement view */ + public void clearHover() { + if (hover != null) { + hover.setHover(false); + hover = null; } + } + + /** + * Gets the current mouse location relative to the tree view + * + * @return the current mouse location relative to the tree view + */ + public Point getMousePoint() { + return mousePoint; + } + + /** + * Sets the current mouse location relative to the tree view + * + * @param point the current mouse location relative to the tree view + */ + public void setMousePoint(Point point) { + this.mousePoint = point; + } + + /** + * Copies the TreeViewSelection + * + * @return a copy of this TreeViewSelection + */ + @SuppressWarnings("unchecked") + public TreeViewSelection copy() { + TreeViewSelection cpy = new TreeViewSelection(); + cpy.selectedViews = (ArrayList) selectedViews.clone(); + cpy.hover = hover; + cpy.mousePoint = mousePoint; + return cpy; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java index de2281ad1..4c7098765 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java @@ -1,39 +1,37 @@ package edu.rpi.legup.ui.puzzleeditorui.elementsview; import edu.rpi.legup.model.elements.Element; -import edu.rpi.legup.model.rules.Rule; - +import java.awt.*; import javax.swing.*; import javax.swing.border.Border; -import java.awt.*; public class ElementButton extends JButton { - private Element element; - private final Border originalBorder; - - ElementButton(Element e) { - super(e.getImageIcon()); - this.element = e; - this.originalBorder = this.getBorder(); - this.setFocusPainted(false); - } - - public Element getElement() { - return element; - } - - public void setElement(Element e) { - this.element = e; - } - - public void setBorderToSelected() { - Border newBorderIn = BorderFactory.createLineBorder(new Color(20, 140, 70), 2, true); - Border newBorder = BorderFactory.createCompoundBorder(newBorderIn, this.originalBorder); - this.setBorder(newBorder); - } - - public void resetBorder() { - this.setBorder(this.originalBorder); - } + private Element element; + private final Border originalBorder; + + ElementButton(Element e) { + super(e.getImageIcon()); + this.element = e; + this.originalBorder = this.getBorder(); + this.setFocusPainted(false); + } + + public Element getElement() { + return element; + } + + public void setElement(Element e) { + this.element = e; + } + + public void setBorderToSelected() { + Border newBorderIn = BorderFactory.createLineBorder(new Color(20, 140, 70), 2, true); + Border newBorder = BorderFactory.createCompoundBorder(newBorderIn, this.originalBorder); + this.setBorder(newBorder); + } + + public void resetBorder() { + this.setBorder(this.originalBorder); + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java index 1fc2b3792..2a7119abb 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java @@ -3,89 +3,96 @@ import edu.rpi.legup.controller.EditorElementController; import edu.rpi.legup.model.Puzzle; import edu.rpi.legup.ui.lookandfeel.components.MaterialTabbedPaneUI; - +import java.awt.*; import javax.swing.*; import javax.swing.border.TitledBorder; -import java.awt.*; public class ElementFrame extends JPanel { - private static final String checkBox = " \u2714 "; - private static final String xBox = " \u2718 "; - private static final String htmlHead = ""; - private static final String htmlTail = ""; - - private PlaceableElementPanel placeableElementPanel; - private NonPlaceableElementPanel nonPlaceableElementPanel; - private JTabbedPane tabbedPane; - private ButtonGroup buttonGroup; - - private EditorElementController controller; - - public ElementFrame(EditorElementController controller) { - this.controller = controller; - MaterialTabbedPaneUI tabOverride = new MaterialTabbedPaneUI() { - //this prevents the tabs from moving around when you select them - @Override - protected boolean shouldRotateTabRuns(int i) { - return false; - } + private static final String checkBox = " \u2714 "; + private static final String xBox = " \u2718 "; + private static final String htmlHead = ""; + private static final String htmlTail = ""; + + private PlaceableElementPanel placeableElementPanel; + private NonPlaceableElementPanel nonPlaceableElementPanel; + private JTabbedPane tabbedPane; + private ButtonGroup buttonGroup; + + private EditorElementController controller; + + public ElementFrame(EditorElementController controller) { + this.controller = controller; + MaterialTabbedPaneUI tabOverride = + new MaterialTabbedPaneUI() { + // this prevents the tabs from moving around when you select them + @Override + protected boolean shouldRotateTabRuns(int i) { + return false; + } }; - this.tabbedPane = new JTabbedPane(); - tabbedPane.setUI(tabOverride); - JLabel status = new JLabel("", SwingConstants.CENTER); - this.buttonGroup = new ButtonGroup(); - - nonPlaceableElementPanel = new NonPlaceableElementPanel(this); - //nonPlaceableElementPanel.setMinimumSize(new Dimension(100,200)); - tabbedPane.addTab(nonPlaceableElementPanel.getName(), nonPlaceableElementPanel.getIcon(), new JScrollPane(nonPlaceableElementPanel), nonPlaceableElementPanel.getToolTip()); - - placeableElementPanel = new PlaceableElementPanel(this); - //placeableElementPanel.setMinimuSize(new Dimension(100,200)); - tabbedPane.addTab(placeableElementPanel.getName(), placeableElementPanel.getIcon(), new JScrollPane(placeableElementPanel), placeableElementPanel.getToolTip()); - tabbedPane.setTabPlacement(JTabbedPane.TOP); - - - setLayout(new BorderLayout()); - setMinimumSize(new Dimension(250, 256)); - setPreferredSize(new Dimension(330, 256)); - - add(tabbedPane); - add(status, BorderLayout.SOUTH); - - TitledBorder title = BorderFactory.createTitledBorder("Elements"); - title.setTitleJustification(TitledBorder.CENTER); - setBorder(title); - } - - public ButtonGroup getButtonGroup() { - return buttonGroup; - } - - public void resetSize() { - int buttonWidth = ((ElementPanel) tabbedPane.getSelectedComponent()).getElementButtons()[0].getWidth(); - this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); - } - - public void setElements(Puzzle puzzle) { - nonPlaceableElementPanel.setElements(puzzle.getNonPlaceableElements()); - placeableElementPanel.setElements(puzzle.getPlaceableElements()); - - } - - public EditorElementController getController() { - return controller; - } - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - public NonPlaceableElementPanel getNonPlaceableElementPanel() { - return nonPlaceableElementPanel; - } - - public PlaceableElementPanel getPlaceableElementPanel() { - return placeableElementPanel; - } + this.tabbedPane = new JTabbedPane(); + tabbedPane.setUI(tabOverride); + JLabel status = new JLabel("", SwingConstants.CENTER); + this.buttonGroup = new ButtonGroup(); + + nonPlaceableElementPanel = new NonPlaceableElementPanel(this); + // nonPlaceableElementPanel.setMinimumSize(new Dimension(100,200)); + tabbedPane.addTab( + nonPlaceableElementPanel.getName(), + nonPlaceableElementPanel.getIcon(), + new JScrollPane(nonPlaceableElementPanel), + nonPlaceableElementPanel.getToolTip()); + + placeableElementPanel = new PlaceableElementPanel(this); + // placeableElementPanel.setMinimuSize(new Dimension(100,200)); + tabbedPane.addTab( + placeableElementPanel.getName(), + placeableElementPanel.getIcon(), + new JScrollPane(placeableElementPanel), + placeableElementPanel.getToolTip()); + tabbedPane.setTabPlacement(JTabbedPane.TOP); + + setLayout(new BorderLayout()); + setMinimumSize(new Dimension(250, 256)); + setPreferredSize(new Dimension(330, 256)); + + add(tabbedPane); + add(status, BorderLayout.SOUTH); + + TitledBorder title = BorderFactory.createTitledBorder("Elements"); + title.setTitleJustification(TitledBorder.CENTER); + setBorder(title); + } + + public ButtonGroup getButtonGroup() { + return buttonGroup; + } + + public void resetSize() { + int buttonWidth = + ((ElementPanel) tabbedPane.getSelectedComponent()).getElementButtons()[0].getWidth(); + this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); + } + + public void setElements(Puzzle puzzle) { + nonPlaceableElementPanel.setElements(puzzle.getNonPlaceableElements()); + placeableElementPanel.setElements(puzzle.getPlaceableElements()); + } + + public EditorElementController getController() { + return controller; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public NonPlaceableElementPanel getNonPlaceableElementPanel() { + return nonPlaceableElementPanel; + } + + public PlaceableElementPanel getPlaceableElementPanel() { + return placeableElementPanel; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java index 2b0c4c63e..725bafe3b 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java @@ -1,84 +1,80 @@ package edu.rpi.legup.ui.puzzleeditorui.elementsview; -import edu.rpi.legup.model.rules.Rule; -import edu.rpi.legup.ui.WrapLayout; import edu.rpi.legup.model.elements.Element; -import edu.rpi.legup.ui.proofeditorui.rulesview.RuleButton; - -import javax.swing.*; +import edu.rpi.legup.ui.WrapLayout; import java.util.ArrayList; import java.util.List; +import javax.swing.*; public abstract class ElementPanel extends JPanel { - protected ImageIcon icon; - protected String name; - protected String toolTip; - protected ElementButton[] elementButtons; - protected ElementFrame elementFrame; - protected List elements; - - public ElementPanel(ElementFrame eFrame) { - this.elementFrame = eFrame; - this.elements = new ArrayList<>(); - setLayout(new WrapLayout()); + protected ImageIcon icon; + protected String name; + protected String toolTip; + protected ElementButton[] elementButtons; + protected ElementFrame elementFrame; + protected List elements; + + public ElementPanel(ElementFrame eFrame) { + this.elementFrame = eFrame; + this.elements = new ArrayList<>(); + setLayout(new WrapLayout()); + } + + public void setElements(List elements) { + this.elements = elements; + clearButtons(); + + elementButtons = new ElementButton[elements.size()]; + System.out.println("adding " + elements.size() + " elements to panel"); + for (int i = 0; i < elements.size(); i++) { + Element element = elements.get(i); + elementButtons[i] = new ElementButton(element); + elementFrame.getButtonGroup().add(elementButtons[i]); + System.out.printf("added button: %d, element %s\n", i, element.getElementName()); + + elementButtons[i].setToolTipText(element.getElementName() + ": " + element.getDescription()); + elementButtons[i].addActionListener(elementFrame.getController()); + add(elementButtons[i]); } - - public void setElements(List elements) { - this.elements = elements; - clearButtons(); - - elementButtons = new ElementButton[elements.size()]; - System.out.println("adding " + elements.size() + " elements to panel"); - for (int i = 0; i < elements.size(); i++) { - Element element = elements.get(i); - elementButtons[i] = new ElementButton(element); - elementFrame.getButtonGroup().add(elementButtons[i]); - System.out.printf("added button: %d, element %s\n", i, element.getElementName()); - - elementButtons[i].setToolTipText(element.getElementName() + ": " + element.getDescription()); - elementButtons[i].addActionListener(elementFrame.getController()); - add(elementButtons[i]); - } - revalidate(); + revalidate(); + } + + protected void clearButtons() { + if (elementButtons != null) { + removeAll(); + for (int x = 0; x < elementButtons.length; ++x) { + elementButtons[x].removeActionListener(elementFrame.getController()); + } } + } - protected void clearButtons() { - if (elementButtons != null) { - removeAll(); - for (int x = 0; x < elementButtons.length; ++x) { - elementButtons[x].removeActionListener(elementFrame.getController()); - } - } - } + public ElementButton[] getElementButtons() { + return elementButtons; + } - public ElementButton[] getElementButtons() { - return elementButtons; - } + public ImageIcon getIcon() { + return icon; + } - public ImageIcon getIcon() { - return icon; - } + public void setIcon(ImageIcon icon) { + this.icon = icon; + } - public void setIcon(ImageIcon icon) { - this.icon = icon; - } + @Override + public String getName() { + return name; + } - @Override - public String getName() { - return name; - } + @Override + public void setName(String name) { + this.name = name; + } - @Override - public void setName(String name) { - this.name = name; - } + public String getToolTip() { + return toolTip; + } - public String getToolTip() { - return toolTip; - } - - public void setToolTip(String toolTip) { - this.toolTip = toolTip; - } + public void setToolTip(String toolTip) { + this.toolTip = toolTip; + } } - diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java index 7920f564c..b6d447c8f 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java @@ -3,10 +3,13 @@ import javax.swing.*; public class NonPlaceableElementPanel extends ElementPanel { - public NonPlaceableElementPanel(ElementFrame elementFrame) { - super(elementFrame); - this.icon = new ImageIcon(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Non-Placeable Elements"; - this.toolTip = "Non-Placeable Elements"; - } + public NonPlaceableElementPanel(ElementFrame elementFrame) { + super(elementFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Non-Placeable Elements"; + this.toolTip = "Non-Placeable Elements"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java index 1fa8eabfb..2d9a09962 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java @@ -3,10 +3,13 @@ import javax.swing.*; public class PlaceableElementPanel extends ElementPanel { - public PlaceableElementPanel(ElementFrame elementFrame) { - super(elementFrame); - this.icon = new ImageIcon(ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Placeable Elements"; - this.toolTip = "Placeable Elements"; - } + public PlaceableElementPanel(ElementFrame elementFrame) { + super(elementFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Placeable Elements"; + this.toolTip = "Placeable Elements"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/resizeview/ResizePanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/resizeview/ResizePanel.java index 7cb7856e7..902d9dbd3 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/resizeview/ResizePanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/resizeview/ResizePanel.java @@ -1,4 +1,3 @@ package edu.rpi.legup.ui.puzzleeditorui.resizeview; -public class ResizePanel { -} +public class ResizePanel {} diff --git a/src/main/java/edu/rpi/legup/user/Submission.java b/src/main/java/edu/rpi/legup/user/Submission.java index eb2b8446c..2fe174946 100644 --- a/src/main/java/edu/rpi/legup/user/Submission.java +++ b/src/main/java/edu/rpi/legup/user/Submission.java @@ -3,11 +3,7 @@ import edu.rpi.legup.model.gameboard.Board; public class Submission { - public Submission(Board board) { + public Submission(Board board) {} - } - - public void submit() { - - } + public void submit() {} } diff --git a/src/main/java/edu/rpi/legup/user/UsageStatistics.java b/src/main/java/edu/rpi/legup/user/UsageStatistics.java index 192db593f..80867e445 100644 --- a/src/main/java/edu/rpi/legup/user/UsageStatistics.java +++ b/src/main/java/edu/rpi/legup/user/UsageStatistics.java @@ -1,63 +1,53 @@ package edu.rpi.legup.user; +import java.io.IOException; +import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; -import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.message.BasicNameValuePair; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; public class UsageStatistics { - private static final String url = "https://legup-3b4a5.firebaseio.com/databases/test.json"; + private static final String url = "https://legup-3b4a5.firebaseio.com/databases/test.json"; - public UsageStatistics() { + public UsageStatistics() {} - } + public boolean sendErrorReport() { + try { + HttpClient httpclient = new DefaultHttpClient(); + + HttpPost httppost = new HttpPost(url); + + // Request parameters and other properties. + httppost.setEntity(new StringEntity("{\"test\": \"jeff\"}")); + // List params = new ArrayList<>(2); + // params.add(new BasicNameValuePair("param-1", "12345")); + // params.add(new BasicNameValuePair("param-2", "Hello!")); + // httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + + // Execute and get the response. + HttpResponse response = httpclient.execute(httppost); + HttpEntity entity = response.getEntity(); + + if (entity != null) { + InputStream instream = entity.getContent(); - public boolean sendErrorReport() { try { - HttpClient httpclient = new DefaultHttpClient(); - - HttpPost httppost = new HttpPost(url); - - // Request parameters and other properties. - httppost.setEntity(new StringEntity("{\"test\": \"jeff\"}")); -// List params = new ArrayList<>(2); -// params.add(new BasicNameValuePair("param-1", "12345")); -// params.add(new BasicNameValuePair("param-2", "Hello!")); -// httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); - - //Execute and get the response. - HttpResponse response = httpclient.execute(httppost); - HttpEntity entity = response.getEntity(); - - if (entity != null) { - InputStream instream = entity.getContent(); - - try { -// System.err.println(new String(instream.readAllBytes())); - } - finally { - instream.close(); - } - } - } - catch (IOException e) { - return false; + // System.err.println(new String(instream.readAllBytes())); + } finally { + instream.close(); } - return false; + } + } catch (IOException e) { + return false; } + return false; + } - public static void main(String[] args) { - new UsageStatistics().sendErrorReport(); - } + public static void main(String[] args) { + new UsageStatistics().sendErrorReport(); + } } diff --git a/src/main/java/edu/rpi/legup/user/User.java b/src/main/java/edu/rpi/legup/user/User.java index 2e542a96c..63280a72d 100644 --- a/src/main/java/edu/rpi/legup/user/User.java +++ b/src/main/java/edu/rpi/legup/user/User.java @@ -1,5 +1,3 @@ package edu.rpi.legup.user; -public class User { - -} +public class User {} diff --git a/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java b/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java index ce4b74bdc..c52264674 100644 --- a/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java +++ b/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java @@ -7,61 +7,66 @@ import java.util.Set; public final class ConnectedRegions { - public static List> getConnectedRegions(int boundaryCell, int[][] cells, int width, int height) { - Set boundaryCells = new HashSet<>(); - boundaryCells.add(boundaryCell); - return getConnectedRegions(boundaryCells, cells, width, height); - } + public static List> getConnectedRegions( + int boundaryCell, int[][] cells, int width, int height) { + Set boundaryCells = new HashSet<>(); + boundaryCells.add(boundaryCell); + return getConnectedRegions(boundaryCells, cells, width, height); + } - public static List> getConnectedRegions(Set boundaryCells, int[][] cells, int width, int height) { - boolean[][] visited = new boolean[height][width]; - List> results = new ArrayList<>(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - Set region = floodfill(boundaryCells, cells, visited, width, height, x, y); - if (region.size() > 0) { - results.add(region); - } - } + public static List> getConnectedRegions( + Set boundaryCells, int[][] cells, int width, int height) { + boolean[][] visited = new boolean[height][width]; + List> results = new ArrayList<>(); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + Set region = floodfill(boundaryCells, cells, visited, width, height, x, y); + if (region.size() > 0) { + results.add(region); } - return results; + } } + return results; + } - public static boolean regionContains(int toFind, int[][] cells, Set region) { - for (Point p : region) { - if (cells[p.y][p.x] == toFind) { - return true; - } - } - return false; + public static boolean regionContains(int toFind, int[][] cells, Set region) { + for (Point p : region) { + if (cells[p.y][p.x] == toFind) { + return true; + } } + return false; + } - public static Set getRegionAroundPoint(Point p, int boundaryCell, int[][] cells, int width, int height) { - Set boundaryCells = new HashSet<>(); - boundaryCells.add(boundaryCell); - return getRegionAroundPoint(p, boundaryCells, cells, width, height); - } + public static Set getRegionAroundPoint( + Point p, int boundaryCell, int[][] cells, int width, int height) { + Set boundaryCells = new HashSet<>(); + boundaryCells.add(boundaryCell); + return getRegionAroundPoint(p, boundaryCells, cells, width, height); + } - public static Set getRegionAroundPoint(Point p, Set boundaryCells, int[][] cells, int width, int height) { - return floodfill(boundaryCells, cells, new boolean[height][width], width, height, p.x, p.y); - } + public static Set getRegionAroundPoint( + Point p, Set boundaryCells, int[][] cells, int width, int height) { + return floodfill(boundaryCells, cells, new boolean[height][width], width, height, p.x, p.y); + } - private static Set floodfill(Set boundaryCells, int[][] cells, boolean[][] visited, int w, int h, int x, int y) { - HashSet result = new HashSet<>(); - if ((x < 0) || (x >= w)) { - return result; - } - if ((y < 0) || (y >= h)) { - return result; - } - if (!visited[y][x] && (!boundaryCells.contains(cells[y][x]))) { - result.add(new Point(x, y)); - visited[y][x] = true; - for (int delta = -1; delta < 2; delta += 2) { - result.addAll(floodfill(boundaryCells, cells, visited, w, h, x + delta, y)); - result.addAll(floodfill(boundaryCells, cells, visited, w, h, x, y + delta)); - } - } - return result; + private static Set floodfill( + Set boundaryCells, int[][] cells, boolean[][] visited, int w, int h, int x, int y) { + HashSet result = new HashSet<>(); + if ((x < 0) || (x >= w)) { + return result; + } + if ((y < 0) || (y >= h)) { + return result; + } + if (!visited[y][x] && (!boundaryCells.contains(cells[y][x]))) { + result.add(new Point(x, y)); + visited[y][x] = true; + for (int delta = -1; delta < 2; delta += 2) { + result.addAll(floodfill(boundaryCells, cells, visited, w, h, x + delta, y)); + result.addAll(floodfill(boundaryCells, cells, visited, w, h, x, y + delta)); + } } -} \ No newline at end of file + return result; + } +} diff --git a/src/main/java/edu/rpi/legup/utility/DisjointSets.java b/src/main/java/edu/rpi/legup/utility/DisjointSets.java index 1e2270318..da2dcb408 100644 --- a/src/main/java/edu/rpi/legup/utility/DisjointSets.java +++ b/src/main/java/edu/rpi/legup/utility/DisjointSets.java @@ -3,164 +3,164 @@ import java.util.*; public class DisjointSets { - private Map parents; - private Map depths; - private Map> sets; + private Map parents; + private Map depths; + private Map> sets; - /** - * DisjointSets Constructor creates an empty DisjointSets - */ - public DisjointSets() { - this.parents = new HashMap<>(); - this.depths = new HashMap<>(); - this.sets = new HashMap<>(); - } + /** DisjointSets Constructor creates an empty DisjointSets */ + public DisjointSets() { + this.parents = new HashMap<>(); + this.depths = new HashMap<>(); + this.sets = new HashMap<>(); + } - /** - * Creates a unique set that contains the specified puzzleElement. If the specified puzzleElement is null or another set already - * contains that puzzleElement, this method returns false, indicating that a set was not created - * - * @param u puzzleElement to create the set from - * @return true if the set was created, false otherwise - */ - public boolean createSet(T u) { - if (u == null || parents.containsKey(u)) { - return false; - } - else { - parents.put(u, u); - depths.put(u, 0); - Set newSet = new HashSet<>(); - newSet.add(u); - sets.put(u, newSet); - return true; - } + /** + * Creates a unique set that contains the specified puzzleElement. If the specified puzzleElement + * is null or another set already contains that puzzleElement, this method returns false, + * indicating that a set was not created + * + * @param u puzzleElement to create the set from + * @return true if the set was created, false otherwise + */ + public boolean createSet(T u) { + if (u == null || parents.containsKey(u)) { + return false; + } else { + parents.put(u, u); + depths.put(u, 0); + Set newSet = new HashSet<>(); + newSet.add(u); + sets.put(u, newSet); + return true; } + } - /** - * Finds and returns the representative set puzzleElement of the set that the specified puzzleElement contains - * - * @param p puzzleElement of the set of which to find - * @return representative set puzzleElement or null if the specified puzzleElement is null or is not in the DisjointSets - */ - public T find(T p) { - if (p == null || parents.get(p) == null) { - return null; - } - else { - if (p != parents.get(p)) { - parents.put(p, find(parents.get(p))); - } - } - return parents.get(p); + /** + * Finds and returns the representative set puzzleElement of the set that the specified + * puzzleElement contains + * + * @param p puzzleElement of the set of which to find + * @return representative set puzzleElement or null if the specified puzzleElement is null or is + * not in the DisjointSets + */ + public T find(T p) { + if (p == null || parents.get(p) == null) { + return null; + } else { + if (p != parents.get(p)) { + parents.put(p, find(parents.get(p))); + } } + return parents.get(p); + } - /** - * Unions two sets together. If the set are non-null and disjoint, then it returns true, false otherwise - * - * @param p set one - * @param q set two - * @return returns true if sets are non-null and disjoint, false otherwise - */ - public boolean union(T p, T q) { - T pid = find(p); - T qid = find(q); - if (pid == null || qid == null || pid == qid) { - return false; - } - else { - if (depths.get(pid) > depths.get(qid)) { - parents.put(qid, pid); - sets.get(pid).addAll(sets.get(qid)); - sets.remove(qid); - } - else { - parents.put(pid, qid); - sets.get(qid).addAll(sets.get(pid)); - sets.remove(pid); - if (depths.get(pid) == depths.get(qid)) { - depths.put(qid, depths.get(qid) + 1); - } - } - return true; + /** + * Unions two sets together. If the set are non-null and disjoint, then it returns true, false + * otherwise + * + * @param p set one + * @param q set two + * @return returns true if sets are non-null and disjoint, false otherwise + */ + public boolean union(T p, T q) { + T pid = find(p); + T qid = find(q); + if (pid == null || qid == null || pid == qid) { + return false; + } else { + if (depths.get(pid) > depths.get(qid)) { + parents.put(qid, pid); + sets.get(pid).addAll(sets.get(qid)); + sets.remove(qid); + } else { + parents.put(pid, qid); + sets.get(qid).addAll(sets.get(pid)); + sets.remove(pid); + if (depths.get(pid) == depths.get(qid)) { + depths.put(qid, depths.get(qid) + 1); } + } + return true; } + } - /** - * Unions to elements together, if either puzzleElement is not already in the DisjointSets, it creates a set for the - * puzzleElement then unions the sets together. If either puzzleElement is null, no action is taken. - * - * @param p puzzleElement one - * @param q puzzleElement two - */ - public void addAndUnion(T p, T q) { - if (p != null && q != null) { - T pid = find(p); - if (pid == null) { - createSet(p); - } - T qid = find(q); - if (qid == null) { - createSet(q); - } - union(p, q); - } + /** + * Unions to elements together, if either puzzleElement is not already in the DisjointSets, it + * creates a set for the puzzleElement then unions the sets together. If either puzzleElement is + * null, no action is taken. + * + * @param p puzzleElement one + * @param q puzzleElement two + */ + public void addAndUnion(T p, T q) { + if (p != null && q != null) { + T pid = find(p); + if (pid == null) { + createSet(p); + } + T qid = find(q); + if (qid == null) { + createSet(q); + } + union(p, q); } + } - /** - * Determines whether the specified puzzleElement is in the DisjointSets - * - * @param u puzzleElement to check - * @return true if the DisjointSets contains the specified puzzleElement, false otherwise - */ - public boolean contains(T u) { - return parents.containsKey(u); - } + /** + * Determines whether the specified puzzleElement is in the DisjointSets + * + * @param u puzzleElement to check + * @return true if the DisjointSets contains the specified puzzleElement, false otherwise + */ + public boolean contains(T u) { + return parents.containsKey(u); + } - /** - * Gets the set of elements that the specified puzzleElement is contained in, or null if no such set exists. - * - * @param p puzzleElement to get the set of - * @return the set of elements that the specified puzzleElement if contained in, or null if no such set exists - */ - public Set getSet(T p) { - T pid = find(p); - if (pid != null) { - return new HashSet<>(sets.get(pid)); - } - else { - return null; - } + /** + * Gets the set of elements that the specified puzzleElement is contained in, or null if no such + * set exists. + * + * @param p puzzleElement to get the set of + * @return the set of elements that the specified puzzleElement if contained in, or null if no + * such set exists + */ + public Set getSet(T p) { + T pid = find(p); + if (pid != null) { + return new HashSet<>(sets.get(pid)); + } else { + return null; } + } - /** - * Gets a list of all of the sets in the DisjointSets - * - * @return list of the sets in the DisjointSets - */ - public List> getAllSets() { - ArrayList> list = new ArrayList<>(); - for (T e : sets.keySet()) { - list.add(new HashSet<>(sets.get(e))); - } - return list; + /** + * Gets a list of all of the sets in the DisjointSets + * + * @return list of the sets in the DisjointSets + */ + public List> getAllSets() { + ArrayList> list = new ArrayList<>(); + for (T e : sets.keySet()) { + list.add(new HashSet<>(sets.get(e))); } + return list; + } - /** - * Gets the number of disjoint sets - * - * @return the number of disjoint sets - */ - public int setCount() { - return sets.size(); - } + /** + * Gets the number of disjoint sets + * + * @return the number of disjoint sets + */ + public int setCount() { + return sets.size(); + } - /** - * Gets the total number of elements among all sets in the DisjointSets - * - * @return the number of elements in the DisjointSets - */ - public int size() { - return parents.size(); - } + /** + * Gets the total number of elements among all sets in the DisjointSets + * + * @return the number of elements in the DisjointSets + */ + public int size() { + return parents.size(); + } } diff --git a/src/main/java/edu/rpi/legup/utility/Entry.java b/src/main/java/edu/rpi/legup/utility/Entry.java index 1819f7eb0..9cff78750 100644 --- a/src/main/java/edu/rpi/legup/utility/Entry.java +++ b/src/main/java/edu/rpi/legup/utility/Entry.java @@ -1,53 +1,53 @@ package edu.rpi.legup.utility; public class Entry { - private K key; - private V value; + private K key; + private V value; - /** - * Entry Constructor creates a key value pair - * - * @param key key - * @param value value - */ - public Entry(K key, V value) { - this.key = key; - this.value = value; - } + /** + * Entry Constructor creates a key value pair + * + * @param key key + * @param value value + */ + public Entry(K key, V value) { + this.key = key; + this.value = value; + } - /** - * Gets the key - * - * @return key - */ - public K getKey() { - return key; - } + /** + * Gets the key + * + * @return key + */ + public K getKey() { + return key; + } - /** - * Sets the key - * - * @param key key - */ - public void setKey(K key) { - this.key = key; - } + /** + * Sets the key + * + * @param key key + */ + public void setKey(K key) { + this.key = key; + } - /** - * Gets the value - * - * @return value - */ - public V getValue() { - return value; - } + /** + * Gets the value + * + * @return value + */ + public V getValue() { + return value; + } - /** - * Set the value - * - * @param value value - */ - public void setValue(V value) { - this.value = value; - } + /** + * Set the value + * + * @param value value + */ + public void setValue(V value) { + this.value = value; + } } diff --git a/src/main/java/edu/rpi/legup/utility/LegupUtils.java b/src/main/java/edu/rpi/legup/utility/LegupUtils.java index dbdd24e7f..cde415f6a 100644 --- a/src/main/java/edu/rpi/legup/utility/LegupUtils.java +++ b/src/main/java/edu/rpi/legup/utility/LegupUtils.java @@ -14,80 +14,85 @@ public class LegupUtils { - private static final Logger LOGGER = Logger.getLogger(LegupUtils.class.getName()); + private static final Logger LOGGER = Logger.getLogger(LegupUtils.class.getName()); - /** - * Scans all classes accessible from the context class loader which belong to the given package and subpackages. - * - * @param packageName The base package - * @return The classes - * @throws ClassNotFoundException if class is not in package - * @throws IOException if file is not found - */ - public static Class[] getClasses(String packageName) - throws ClassNotFoundException, IOException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - assert classLoader != null; - String path = packageName.replace('.', '/'); + /** + * Scans all classes accessible from the context class loader which belong to the given package + * and subpackages. + * + * @param packageName The base package + * @return The classes + * @throws ClassNotFoundException if class is not in package + * @throws IOException if file is not found + */ + public static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + assert classLoader != null; + String path = packageName.replace('.', '/'); - URL url = LegupUtils.class.getProtectionDomain().getCodeSource().getLocation(); - String jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); - if (jarPath.contains(".jar")) { - List css = findClassesZip(jarPath, path); - return css.toArray(new Class[css.size()]); - } + URL url = LegupUtils.class.getProtectionDomain().getCodeSource().getLocation(); + String jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); + if (jarPath.contains(".jar")) { + List css = findClassesZip(jarPath, path); + return css.toArray(new Class[css.size()]); + } - Enumeration resources = classLoader.getResources(path); - List dirs = new ArrayList<>(); - while (resources.hasMoreElements()) { - URL resource = resources.nextElement(); - dirs.add(new File(resource.getFile())); - } + Enumeration resources = classLoader.getResources(path); + List dirs = new ArrayList<>(); + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + dirs.add(new File(resource.getFile())); + } - ArrayList classes = new ArrayList<>(); - for (File directory : dirs) { - classes.addAll(findClasses(directory, packageName)); - } - return classes.toArray(new Class[classes.size()]); + ArrayList classes = new ArrayList<>(); + for (File directory : dirs) { + classes.addAll(findClasses(directory, packageName)); } + return classes.toArray(new Class[classes.size()]); + } - /** - * Recursive method used to find all classes in a given directory and subdirs. - * - * @param directory The base directory - * @param packageName The package name for classes found inside the base directory - * @return The classes - * @throws ClassNotFoundException - */ - private static List findClasses(File directory, String packageName) throws ClassNotFoundException { - List classes = new ArrayList<>(); - if (!directory.exists()) { - return classes; - } - File[] files = directory.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - assert !file.getName().contains("."); - classes.addAll(findClasses(file, packageName + "." + file.getName())); - } - else { - if (file.getName().endsWith(".class")) { - classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); - } - } + /** + * Recursive method used to find all classes in a given directory and subdirs. + * + * @param directory The base directory + * @param packageName The package name for classes found inside the base directory + * @return The classes + * @throws ClassNotFoundException + */ + private static List findClasses(File directory, String packageName) + throws ClassNotFoundException { + List classes = new ArrayList<>(); + if (!directory.exists()) { + return classes; + } + File[] files = directory.listFiles(); + for (File file : files) { + if (file.isDirectory()) { + assert !file.getName().contains("."); + classes.addAll(findClasses(file, packageName + "." + file.getName())); + } else { + if (file.getName().endsWith(".class")) { + classes.add( + Class.forName( + packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); } - return classes; + } } + return classes; + } - private static List findClassesZip(String path, String packageName) throws IOException, ClassNotFoundException { - List classes = new ArrayList<>(); - ZipInputStream zip = new ZipInputStream(new FileInputStream(path)); - for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { - if (!entry.isDirectory() && entry.getName().endsWith(".class") && entry.getName().startsWith(packageName)) { - String className = entry.getName().replace('/', '.'); - classes.add(Class.forName(className.substring(0, className.length() - ".class".length()))); - } - } - return classes; + private static List findClassesZip(String path, String packageName) + throws IOException, ClassNotFoundException { + List classes = new ArrayList<>(); + ZipInputStream zip = new ZipInputStream(new FileInputStream(path)); + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + if (!entry.isDirectory() + && entry.getName().endsWith(".class") + && entry.getName().startsWith(packageName)) { + String className = entry.getName().replace('/', '.'); + classes.add(Class.forName(className.substring(0, className.length() - ".class".length()))); + } } + return classes; + } } diff --git a/src/main/java/edu/rpi/legup/utility/Logger.java b/src/main/java/edu/rpi/legup/utility/Logger.java index 1feb56f04..d423043e7 100644 --- a/src/main/java/edu/rpi/legup/utility/Logger.java +++ b/src/main/java/edu/rpi/legup/utility/Logger.java @@ -1,6 +1,6 @@ package edu.rpi.legup.utility; -import edu.rpi.legup.Legup; +import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.ConsoleAppender; @@ -10,34 +10,35 @@ import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.layout.PatternLayout; -import java.io.File; - public class Logger { - private static final String LEGUP_HOME = System.getProperty("user.home") + File.separator + ".legup" + File.separator; - - public static void initLogger() { - LoggerContext context = (LoggerContext) LogManager.getContext(false); - Configuration config = context.getConfiguration(); - ConsoleAppender consoleAppender = config.getAppender("console"); - PatternLayout consolePattern = (PatternLayout) consoleAppender.getLayout(); - TimeBasedTriggeringPolicy triggeringPolicy = TimeBasedTriggeringPolicy.newBuilder().withInterval(1).withModulate(true).build(); - PatternLayout patternLayout = PatternLayout.newBuilder().withPattern(consolePattern.getConversionPattern()).build(); - RollingFileAppender rollingFileAppender = RollingFileAppender.newBuilder() - .setName("fileLogger") - .withFileName(LEGUP_HOME + "legup.log") - .withFilePattern(LEGUP_HOME + "legup-%d{yyyy-MM-dd}.log.gz") - .withPolicy(triggeringPolicy) - .setLayout(patternLayout) - .setConfiguration(config) - .build(); - rollingFileAppender.start(); - config.addAppender(rollingFileAppender); - LoggerConfig rootLogger = config.getRootLogger(); - rootLogger.addAppender(config.getAppender("fileLogger"), null, null); - context.updateLoggers(); + private static final String LEGUP_HOME = + System.getProperty("user.home") + File.separator + ".legup" + File.separator; - System.setProperty("sun.java2d.noddraw", Boolean.TRUE.toString()); - } + public static void initLogger() { + LoggerContext context = (LoggerContext) LogManager.getContext(false); + Configuration config = context.getConfiguration(); + ConsoleAppender consoleAppender = config.getAppender("console"); + PatternLayout consolePattern = (PatternLayout) consoleAppender.getLayout(); + TimeBasedTriggeringPolicy triggeringPolicy = + TimeBasedTriggeringPolicy.newBuilder().withInterval(1).withModulate(true).build(); + PatternLayout patternLayout = + PatternLayout.newBuilder().withPattern(consolePattern.getConversionPattern()).build(); + RollingFileAppender rollingFileAppender = + RollingFileAppender.newBuilder() + .setName("fileLogger") + .withFileName(LEGUP_HOME + "legup.log") + .withFilePattern(LEGUP_HOME + "legup-%d{yyyy-MM-dd}.log.gz") + .withPolicy(triggeringPolicy) + .setLayout(patternLayout) + .setConfiguration(config) + .build(); + rollingFileAppender.start(); + config.addAppender(rollingFileAppender); + LoggerConfig rootLogger = config.getRootLogger(); + rootLogger.addAppender(config.getAppender("fileLogger"), null, null); + context.updateLoggers(); + System.setProperty("sun.java2d.noddraw", Boolean.TRUE.toString()); + } } diff --git a/src/test/java/legup/MockGameBoardFacade.java b/src/test/java/legup/MockGameBoardFacade.java index 7840b61b7..a1505455c 100644 --- a/src/test/java/legup/MockGameBoardFacade.java +++ b/src/test/java/legup/MockGameBoardFacade.java @@ -6,42 +6,37 @@ import edu.rpi.legup.model.Puzzle; public class MockGameBoardFacade extends GameBoardFacade { - protected MockGameBoardFacade() { - super(); - Config config = null; - try { - config = new Config(); - } - catch (InvalidConfigException e) { - System.exit(1); - } - setConfig(config); + protected MockGameBoardFacade() { + super(); + Config config = null; + try { + config = new Config(); + } catch (InvalidConfigException e) { + System.exit(1); } - - /** - * Gets the singleton instance of GameBoardFacade - * - * @return single instance of GameBoardFacade - */ - public synchronized static GameBoardFacade getInstance() { - if (instance == null) { - instance = new MockGameBoardFacade(); - } - return instance; - } - - @Override - public void initializeUI() { - + setConfig(config); + } + + /** + * Gets the singleton instance of GameBoardFacade + * + * @return single instance of GameBoardFacade + */ + public static synchronized GameBoardFacade getInstance() { + if (instance == null) { + instance = new MockGameBoardFacade(); } + return instance; + } - @Override - public void setPuzzle(Puzzle puzzle) { - this.puzzle = puzzle; - } + @Override + public void initializeUI() {} - @Override - public void setWindowTitle(String puzzleName, String fileName) { + @Override + public void setPuzzle(Puzzle puzzle) { + this.puzzle = puzzle; + } - } + @Override + public void setWindowTitle(String puzzleName, String fileName) {} } diff --git a/src/test/java/legup/TestRunner.java b/src/test/java/legup/TestRunner.java index 5e95a16bf..c8c43bcda 100644 --- a/src/test/java/legup/TestRunner.java +++ b/src/test/java/legup/TestRunner.java @@ -1,6 +1,5 @@ package legup; - import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; @@ -10,100 +9,98 @@ import puzzles.skyscrapers.rules.*; import puzzles.treetent.rules.*; -/** - * This class runs all of the tests for the project without needing to run build scripts. - */ +/** This class runs all of the tests for the project without needing to run build scripts. */ public class TestRunner { - public static void main(String[] args) { - // Battleship Tests - Result result1 = JUnitCore.runClasses(AdjacentShipsContradictionRuleTest.class); - printTestResults(result1); - Result result2 = JUnitCore.runClasses(FinishWithShipsDirectRuleTests.class); - printTestResults(result2); - - // Lightup Tests - Result result3 = JUnitCore.runClasses(BulbsInPathContradictionRuleTest.class); - printTestResults(result3); - Result result4 = JUnitCore.runClasses(CannotLightACellContradictionRuleTest.class); - printTestResults(result4); - Result result5 = JUnitCore.runClasses(EmptyCellinLightDirectRuleTest.class); - printTestResults(result5); - Result result6 = JUnitCore.runClasses(EmptyCornersDirectRuleTest.class); - printTestResults(result6); - Result result7 = JUnitCore.runClasses(FinishWithBulbsDirectRuleTest.class); - printTestResults(result7); - Result result8 = JUnitCore.runClasses(LightOrEmptyCaseRuleTest.class); - printTestResults(result8); - Result result9 = JUnitCore.runClasses(MustLightDirectRuleTest.class); - printTestResults(result9); - Result result10 = JUnitCore.runClasses(SatisfyNumberCaseRuleTest.class); - printTestResults(result10); - Result result11 = JUnitCore.runClasses(TooFewBulbsContradictionRuleTest.class); - printTestResults(result11); - Result result12 = JUnitCore.runClasses(TooManyBulbsContradictionRuleTest.class); - printTestResults(result12); + public static void main(String[] args) { + // Battleship Tests + Result result1 = JUnitCore.runClasses(AdjacentShipsContradictionRuleTest.class); + printTestResults(result1); + Result result2 = JUnitCore.runClasses(FinishWithShipsDirectRuleTests.class); + printTestResults(result2); - //nurikabe tests - Result result13 = JUnitCore.runClasses(BlackBetweenRegionsDirectRuleTest.class); - printTestResults(result13); - Result result14 = JUnitCore.runClasses(BlackBottleNeckDirectRuleTest.class); - printTestResults(result14); - Result result15 = JUnitCore.runClasses(BlackOrWhiteCaseRuleTest.class); - printTestResults(result15); - Result result16 = JUnitCore.runClasses(BlackSquareContradictionRuleTest.class); - printTestResults(result16); - Result result17 = JUnitCore.runClasses(CornerBlackDirectRuleTest.class); - printTestResults(result17); - Result result18 = JUnitCore.runClasses(FillinBlackDirectRuleTest.class); - printTestResults(result18); - Result result19 = JUnitCore.runClasses(FillinWhiteDirectRuleTest.class); - printTestResults(result19); - Result result20 = JUnitCore.runClasses(IsolateBlackContradictionRuleTest.class); - printTestResults(result20); - Result result21 = JUnitCore.runClasses(MultipleNumbersContradictionRuleTest.class); - printTestResults(result21); - Result result22 = JUnitCore.runClasses(NoNumbersContradictionRuleTest.class); - printTestResults(result22); - Result result23 = JUnitCore.runClasses(PreventBlackSquareDirectRuleTest.class); - printTestResults(result23); - Result result24 = JUnitCore.runClasses(SurroundRegionDirectRuleTest.class); - printTestResults(result24); - Result result25 = JUnitCore.runClasses(TooFewSpacesContradictionRuleTest.class); - printTestResults(result25); - Result result26 = JUnitCore.runClasses(TooManySpacesContradictionRuleTest.class); - printTestResults(result26); - Result result27 = JUnitCore.runClasses(WhiteBottleNeckDirectRuleTest.class); - printTestResults(result27); + // Lightup Tests + Result result3 = JUnitCore.runClasses(BulbsInPathContradictionRuleTest.class); + printTestResults(result3); + Result result4 = JUnitCore.runClasses(CannotLightACellContradictionRuleTest.class); + printTestResults(result4); + Result result5 = JUnitCore.runClasses(EmptyCellinLightDirectRuleTest.class); + printTestResults(result5); + Result result6 = JUnitCore.runClasses(EmptyCornersDirectRuleTest.class); + printTestResults(result6); + Result result7 = JUnitCore.runClasses(FinishWithBulbsDirectRuleTest.class); + printTestResults(result7); + Result result8 = JUnitCore.runClasses(LightOrEmptyCaseRuleTest.class); + printTestResults(result8); + Result result9 = JUnitCore.runClasses(MustLightDirectRuleTest.class); + printTestResults(result9); + Result result10 = JUnitCore.runClasses(SatisfyNumberCaseRuleTest.class); + printTestResults(result10); + Result result11 = JUnitCore.runClasses(TooFewBulbsContradictionRuleTest.class); + printTestResults(result11); + Result result12 = JUnitCore.runClasses(TooManyBulbsContradictionRuleTest.class); + printTestResults(result12); - // Treetent - Result result28 = JUnitCore.runClasses(EmptyFieldDirectRuleTest.class); - printTestResults(result28); - Result result29 = JUnitCore.runClasses(FinishWithGrassDirectRuleTest.class); - printTestResults(result29); - Result result30 = JUnitCore.runClasses(FinishWithTentsDirectRuleTest.class); - printTestResults(result30); - Result result31 = JUnitCore.runClasses(LastCampingSpotDirectRuleTest.class); - printTestResults(result31); - Result result32 = JUnitCore.runClasses(NoTentForTreeContradictionRuleTest.class); - printTestResults(result32); - Result result33 = JUnitCore.runClasses(NoTreeForTentContradictionRuleTest.class); - printTestResults(result33); - Result result34 = JUnitCore.runClasses(SurroundTentWithGrassDirectRuleTest.class); - printTestResults(result34); - Result result35 = JUnitCore.runClasses(TreeForTentDirectRuleTest.class); - printTestResults(result35); - Result result36 = JUnitCore.runClasses(TentOrGrassCaseRuleTest.class); - printTestResults(result36); - } + // nurikabe tests + Result result13 = JUnitCore.runClasses(BlackBetweenRegionsDirectRuleTest.class); + printTestResults(result13); + Result result14 = JUnitCore.runClasses(BlackBottleNeckDirectRuleTest.class); + printTestResults(result14); + Result result15 = JUnitCore.runClasses(BlackOrWhiteCaseRuleTest.class); + printTestResults(result15); + Result result16 = JUnitCore.runClasses(BlackSquareContradictionRuleTest.class); + printTestResults(result16); + Result result17 = JUnitCore.runClasses(CornerBlackDirectRuleTest.class); + printTestResults(result17); + Result result18 = JUnitCore.runClasses(FillinBlackDirectRuleTest.class); + printTestResults(result18); + Result result19 = JUnitCore.runClasses(FillinWhiteDirectRuleTest.class); + printTestResults(result19); + Result result20 = JUnitCore.runClasses(IsolateBlackContradictionRuleTest.class); + printTestResults(result20); + Result result21 = JUnitCore.runClasses(MultipleNumbersContradictionRuleTest.class); + printTestResults(result21); + Result result22 = JUnitCore.runClasses(NoNumbersContradictionRuleTest.class); + printTestResults(result22); + Result result23 = JUnitCore.runClasses(PreventBlackSquareDirectRuleTest.class); + printTestResults(result23); + Result result24 = JUnitCore.runClasses(SurroundRegionDirectRuleTest.class); + printTestResults(result24); + Result result25 = JUnitCore.runClasses(TooFewSpacesContradictionRuleTest.class); + printTestResults(result25); + Result result26 = JUnitCore.runClasses(TooManySpacesContradictionRuleTest.class); + printTestResults(result26); + Result result27 = JUnitCore.runClasses(WhiteBottleNeckDirectRuleTest.class); + printTestResults(result27); - private static void printTestResults(Result result) { - for (Failure failure : result.getFailures()) { - System.out.println(failure.toString()); - } + // Treetent + Result result28 = JUnitCore.runClasses(EmptyFieldDirectRuleTest.class); + printTestResults(result28); + Result result29 = JUnitCore.runClasses(FinishWithGrassDirectRuleTest.class); + printTestResults(result29); + Result result30 = JUnitCore.runClasses(FinishWithTentsDirectRuleTest.class); + printTestResults(result30); + Result result31 = JUnitCore.runClasses(LastCampingSpotDirectRuleTest.class); + printTestResults(result31); + Result result32 = JUnitCore.runClasses(NoTentForTreeContradictionRuleTest.class); + printTestResults(result32); + Result result33 = JUnitCore.runClasses(NoTreeForTentContradictionRuleTest.class); + printTestResults(result33); + Result result34 = JUnitCore.runClasses(SurroundTentWithGrassDirectRuleTest.class); + printTestResults(result34); + Result result35 = JUnitCore.runClasses(TreeForTentDirectRuleTest.class); + printTestResults(result35); + Result result36 = JUnitCore.runClasses(TentOrGrassCaseRuleTest.class); + printTestResults(result36); + } - System.out.println("Tests run: " + result.getRunCount()); - System.out.println("Tests failed: " + result.getFailureCount()); - System.out.println("All tests passed: " + result.wasSuccessful()); - System.out.println(); + private static void printTestResults(Result result) { + for (Failure failure : result.getFailures()) { + System.out.println(failure.toString()); } + + System.out.println("Tests run: " + result.getRunCount()); + System.out.println("Tests failed: " + result.getFailureCount()); + System.out.println("All tests passed: " + result.wasSuccessful()); + System.out.println(); + } } diff --git a/src/test/java/legup/TestUtilities.java b/src/test/java/legup/TestUtilities.java index 9f203b223..a5349197c 100644 --- a/src/test/java/legup/TestUtilities.java +++ b/src/test/java/legup/TestUtilities.java @@ -8,12 +8,13 @@ import edu.rpi.legup.save.InvalidFileFormatException; public final class TestUtilities { - public static void importTestBoard(String fileName, Puzzle puzzle) throws InvalidFileFormatException { - puzzle.importPuzzle(ClassLoader.getSystemResourceAsStream(fileName)); - Tree tree = puzzle.getTree(); - TreeNode rootNode = tree.getRootNode(); - Board board = rootNode.getBoard().copy(); - TreeTransition transition = new TreeTransition(rootNode, board); - rootNode.getChildren().add(transition); - } + public static void importTestBoard(String fileName, Puzzle puzzle) + throws InvalidFileFormatException { + puzzle.importPuzzle(ClassLoader.getSystemResourceAsStream(fileName)); + Tree tree = puzzle.getTree(); + TreeNode rootNode = tree.getRootNode(); + Board board = rootNode.getBoard().copy(); + TreeTransition transition = new TreeTransition(rootNode, board); + rootNode.getChildren().add(transition); + } } diff --git a/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java b/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java index c9e65e9c1..350b6b0e7 100644 --- a/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java +++ b/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java @@ -1,75 +1,70 @@ package puzzles.battleship.rules; -import edu.rpi.legup.puzzle.battleship.BattleshipType; -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; import edu.rpi.legup.puzzle.battleship.Battleship; import edu.rpi.legup.puzzle.battleship.BattleshipBoard; -import edu.rpi.legup.puzzle.battleship.BattleshipCell; import edu.rpi.legup.puzzle.battleship.rules.AdjacentShipsContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; - import java.awt.*; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class AdjacentShipsContradictionRuleTest { - private static final AdjacentShipsContradictionRule RULE - = new AdjacentShipsContradictionRule(); + private static final AdjacentShipsContradictionRule RULE = new AdjacentShipsContradictionRule(); - private static Battleship battleship; + private static Battleship battleship; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - battleship = new Battleship(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + battleship = new Battleship(); + } - @Test - public void OrthogonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/battleship/rules" + - "/AdjacentShipsContradictionRule/OrthogonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void OrthogonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/AdjacentShipsContradictionRule/OrthogonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction( - board)); - } + Assert.assertNotNull(RULE.checkContradiction(board)); + } - @Test - public void InvalidOrthogonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/battleship/rules" + - "/AdjacentShipsContradictionRule" + - "/InvalidOrthogonalAdjacentBoards", battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void InvalidOrthogonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/AdjacentShipsContradictionRule" + + "/InvalidOrthogonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction( - board)); - } + Assert.assertNull(RULE.checkContradiction(board)); + } - @Test - public void DiagonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/battleship/rules" + - "/AdjacentShipsContradictionRule" + - "/DiagonalAdjacentBoards", battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void DiagonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/AdjacentShipsContradictionRule" + "/DiagonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction( - board)); - } + Assert.assertNull(RULE.checkContradiction(board)); + } } diff --git a/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java b/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java index ac7e8cb8e..a0cf6dc61 100644 --- a/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java +++ b/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java @@ -1,72 +1,70 @@ package puzzles.battleship.rules; -import org.junit.*; - -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.battleship.*; import edu.rpi.legup.puzzle.battleship.rules.*; import edu.rpi.legup.save.InvalidFileFormatException; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.*; public class FinishWithShipsDirectRuleTests { - private static final FinishWithShipsDirectRule RULE - = new FinishWithShipsDirectRule(); + private static final FinishWithShipsDirectRule RULE = new FinishWithShipsDirectRule(); - private static Battleship battleship; + private static Battleship battleship; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - battleship = new Battleship(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + battleship = new Battleship(); + } - //@Test - public void HorizontalValidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/battleship/rules" + - "/FinishWithShipsBasicRuleTests/HorizontalValidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void HorizontalValidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalValidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } + Assert.assertNull(RULE.checkRule(transition)); + } - //@Test - public void VerticaValidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/battleship/rules" + - "/FinishWithShipsBasicRuleTests/VerticalValidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void VerticaValidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalValidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } + Assert.assertNull(RULE.checkRule(transition)); + } - //@Test - public void HorizontalInvalidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/battleship/rules" + - "/FinishWithShipsBasicRuleTests/HorizontalInvalidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void HorizontalInvalidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalInvalidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - } + Assert.assertNotNull(RULE.checkRule(transition)); + } - //@Test - public void VerticalInvalidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/battleship/rules" + - "/FinishWithShipsBasicRuleTests/VerticalInvalidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void VerticalInvalidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalInvalidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - } + Assert.assertNotNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java index 0e7930751..b2357b157 100644 --- a/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java @@ -1,86 +1,89 @@ package puzzles.lightup.rules; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; import edu.rpi.legup.puzzle.lightup.LightUp; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.rules.BulbsInPathContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; - +import legup.TestUtilities; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class BulbsInPathContradictionRuleTest { - private static final BulbsInPathContradictionRule RULE = new BulbsInPathContradictionRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - @Test - public void BulbsInPathContradictionRule_LightInHorizontalPath() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/BulbsInPathContradictionRule/LightInHorizontalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - - - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - } - - @Test - public void BulbsInPathContradictionRule_LightInVerticalPath() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/BulbsInPathContradictionRule/LightInVerticalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } - - @Test - public void BulbsInPathContradictionRule_BlockInVerticalPath() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInVerticalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } - - @Test - public void BulbsInPathContradictionRule_BlockInHorizontalPath() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInHorizontalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkContradictionAt(board,board.getCell(0,0))); - Assert.assertNotNull(RULE.checkContradictionAt(board,board.getCell(2,0))); - Assert.assertNotNull(RULE.checkContradictionAt(board,board.getCell(1,1))); - - } + private static final BulbsInPathContradictionRule RULE = new BulbsInPathContradictionRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + public void BulbsInPathContradictionRule_LightInHorizontalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInHorizontalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + } + + @Test + public void BulbsInPathContradictionRule_LightInVerticalPath() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInVerticalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } + + @Test + public void BulbsInPathContradictionRule_BlockInVerticalPath() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInVerticalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } + + @Test + public void BulbsInPathContradictionRule_BlockInHorizontalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInHorizontalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } } diff --git a/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java index 7b3ffd2b9..84dc80c83 100644 --- a/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java @@ -1,91 +1,94 @@ package puzzles.lightup.rules; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; import edu.rpi.legup.puzzle.lightup.LightUp; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.rules.CannotLightACellContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; - +import legup.TestUtilities; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class CannotLightACellContradictionRuleTest { - private static final CannotLightACellContradictionRule RULE = new CannotLightACellContradictionRule(); - private static LightUp lightUp; + private static final CannotLightACellContradictionRule RULE = + new CannotLightACellContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - //extensive full testing of null and non-null in a 5x5 board - public void FullLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/CannotLightACellContradictionRule/FullLightTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // extensive full testing of null and non-null in a 5x5 board + public void FullLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/FullLightTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - //confirm it is impossible to light up these squares - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); + // confirm it is impossible to light up these squares + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); - //confirm these are not required to be lit because they are already lit or unable to be - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); - } + // confirm these are not required to be lit because they are already lit or unable to be + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); + } - @Test - //simple contradiction testing for null and non-null in a 3x3 board - public void CannotLightMiddleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/CannotLightACellContradictionRule/CannotLight", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // simple contradiction testing for null and non-null in a 3x3 board + public void CannotLightMiddleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/CannotLight", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - //confirm it is impossible to light up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to light up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - //every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } - @Test - public void CanLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/CannotLightACellContradictionRule/CanLightTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void CanLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/CanLightTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm there is not a contradiction somewhere on the board - Assert.assertNotNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is not a contradiction somewhere on the board + Assert.assertNotNull(RULE.checkContradiction(board)); - //confirm that these cells can be lit, are already lit, or that they are just black blocks - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); - } + // confirm that these cells can be lit, are already lit, or that they are just black blocks + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); + } } diff --git a/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java index b0a2d10ed..289d17e5d 100644 --- a/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java @@ -1,97 +1,103 @@ package puzzles.lightup.rules; -import org.junit.BeforeClass; -import org.junit.Test; -import edu.rpi.legup.puzzle.lightup.LightUp; -import edu.rpi.legup.puzzle.lightup.rules.EmptyCellinLightDirectRule; -import edu.rpi.legup.save.InvalidFileFormatException; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUp; import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; +import edu.rpi.legup.puzzle.lightup.rules.EmptyCellinLightDirectRule; +import edu.rpi.legup.save.InvalidFileFormatException; +import legup.TestUtilities; import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class EmptyCellinLightDirectRuleTest { - private static final EmptyCellinLightDirectRule RULE = new EmptyCellinLightDirectRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - @Test - //tests a 3x3 board with with a 0 black tile in the center and lightbulbs in top left and bototm right - //confirms the rest of the tiles must be empty - public void EmptyCellinLightDirectRule() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/lightup/rules/EmptyCellinLightDirectRule/EmptyCells", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - //get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); - - //change the board's cells considering the emptycellinlight rule - LightUpCell cell2 = board.getCell(1,0); - cell2.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell2); - - LightUpCell cell3 = board.getCell(0,1); - cell3.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell3); - - LightUpCell cell4 = board.getCell(2,0); - cell4.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell4); - - LightUpCell cell5 = board.getCell(0,2); - cell5.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell5); - - LightUpCell cell6 = board.getCell(1,2); - cell6.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell6); - - LightUpCell cell7 = board.getCell(2,1); - cell7.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell7); - - LightUpCell cell8 = board.getCell(3,0); - cell8.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell8); - - LightUpCell cell9 = board.getCell(3,2); - cell9.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell9); - - LightUpCell cell10 = board.getCell(2,3); - cell10.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell10); - - LightUpCell cell11 = board.getCell(0,3); - cell11.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell11); - - //confirm there is a logical following of the EmptyCellinLight rule - Assert.assertNull(RULE.checkRule(transition)); - - //cells (0,0) and (2,2) are not empty because they have lightbulbs, (1,1) - //because it is a black tile, and (1,3),(3,1),(3,3) because they are not lit. Confirm the rest are empty - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 0 && j == 0) || (i == 2 && j == 2) || (i == 1 && j == 1) || (i == 1 && j == 3) || (i == 3 && j == 1) - || (i==3 && j==3)){ - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - else { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - } + private static final EmptyCellinLightDirectRule RULE = new EmptyCellinLightDirectRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + // tests a 3x3 board with with a 0 black tile in the center and lightbulbs in top left and bototm + // right + // confirms the rest of the tiles must be empty + public void EmptyCellinLightDirectRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/EmptyCellinLightDirectRule/EmptyCells", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); + + // change the board's cells considering the emptycellinlight rule + LightUpCell cell2 = board.getCell(1, 0); + cell2.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell2); + + LightUpCell cell3 = board.getCell(0, 1); + cell3.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell3); + + LightUpCell cell4 = board.getCell(2, 0); + cell4.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell4); + + LightUpCell cell5 = board.getCell(0, 2); + cell5.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell5); + + LightUpCell cell6 = board.getCell(1, 2); + cell6.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell6); + + LightUpCell cell7 = board.getCell(2, 1); + cell7.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell7); + + LightUpCell cell8 = board.getCell(3, 0); + cell8.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell8); + + LightUpCell cell9 = board.getCell(3, 2); + cell9.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell9); + + LightUpCell cell10 = board.getCell(2, 3); + cell10.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell10); + + LightUpCell cell11 = board.getCell(0, 3); + cell11.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell11); + + // confirm there is a logical following of the EmptyCellinLight rule + Assert.assertNull(RULE.checkRule(transition)); + + // cells (0,0) and (2,2) are not empty because they have lightbulbs, (1,1) + // because it is a black tile, and (1,3),(3,1),(3,3) because they are not lit. Confirm the rest + // are empty + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 0 && j == 0) + || (i == 2 && j == 2) + || (i == 1 && j == 1) + || (i == 1 && j == 3) + || (i == 3 && j == 1) + || (i == 3 && j == 3)) { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, c)); } + } } + } } diff --git a/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java index bea69b95f..0af76baeb 100644 --- a/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java @@ -1,79 +1,78 @@ package puzzles.lightup.rules; -import org.junit.BeforeClass; -import org.junit.Test; -import edu.rpi.legup.puzzle.lightup.LightUp; -import edu.rpi.legup.puzzle.lightup.rules.EmptyCornersDirectRule; -import edu.rpi.legup.save.InvalidFileFormatException; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUp; import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; +import edu.rpi.legup.puzzle.lightup.rules.EmptyCornersDirectRule; +import edu.rpi.legup.save.InvalidFileFormatException; +import legup.TestUtilities; import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class EmptyCornersDirectRuleTest { - private static final EmptyCornersDirectRule RULE = new EmptyCornersDirectRule(); - private static LightUp lightUp; - + private static final EmptyCornersDirectRule RULE = new EmptyCornersDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void EmptyCornersTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/EmptyCornersDirectRule/EmptyCorners", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void EmptyCornersTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/EmptyCornersDirectRule/EmptyCorners", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - //get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - //change the board's cells considering the EmptyCorners rule to empty - LightUpCell cell1 = board.getCell(2,2); - cell1.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell1); + // change the board's cells considering the EmptyCorners rule to empty + LightUpCell cell1 = board.getCell(2, 2); + cell1.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell1); - LightUpCell cell2 = board.getCell(0,2); - cell2.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell2); + LightUpCell cell2 = board.getCell(0, 2); + cell2.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell2); - LightUpCell cell3 = board.getCell(4,3); - cell3.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell3); + LightUpCell cell3 = board.getCell(4, 3); + cell3.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell3); - //confirm there is a logical following of the EmptyCorners rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the EmptyCorners rule + Assert.assertNull(RULE.checkRule(transition)); - //this should not be accepted, the cell should remain unknown - LightUpCell cell4 = board.getCell(4,5); - cell4.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell4); + // this should not be accepted, the cell should remain unknown + LightUpCell cell4 = board.getCell(4, 5); + cell4.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell4); - //this should not be accepted, the cell should be empty but not because of this rule - LightUpCell cell5 = board.getCell(4,1); - cell5.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell5); + // this should not be accepted, the cell should be empty but not because of this rule + LightUpCell cell5 = board.getCell(4, 1); + cell5.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell5); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - //confirm the two expected cells are emptied USING THE RULE - // and none of the rest are (others can be empty just not by the same rule) - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 2 && j == 0) || (i == 2 && j == 2) || (i==3 && j==4)){ - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + // confirm the two expected cells are emptied USING THE RULE + // and none of the rest are (others can be empty just not by the same rule) + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 2 && j == 0) || (i == 2 && j == 2) || (i == 3 && j == 4)) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java index f98a48303..d1b0422f9 100644 --- a/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java @@ -1,103 +1,104 @@ package puzzles.lightup.rules; -import org.junit.BeforeClass; -import org.junit.Test; -import edu.rpi.legup.puzzle.lightup.LightUp; -import edu.rpi.legup.puzzle.lightup.rules.FinishWithBulbsDirectRule; -import edu.rpi.legup.save.InvalidFileFormatException; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUp; import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; +import edu.rpi.legup.puzzle.lightup.rules.FinishWithBulbsDirectRule; +import edu.rpi.legup.save.InvalidFileFormatException; +import legup.TestUtilities; import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class FinishWithBulbsDirectRuleTest { - private static final FinishWithBulbsDirectRule RULE = new FinishWithBulbsDirectRule(); - private static LightUp lightUp; + private static final FinishWithBulbsDirectRule RULE = new FinishWithBulbsDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + public void FinishBulbTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbs", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - @Test - public void FinishBulbTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbs", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - //get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - //change the board's cells considering the FinishWithBulbs rule to empty - LightUpCell cell1 = board.getCell(1,0); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); + // change the board's cells considering the FinishWithBulbs rule to empty + LightUpCell cell1 = board.getCell(1, 0); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); - //confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - //check every square except the top center (2,0) - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if (i == 0 && j == 1){ - //logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - //does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + // check every square except the top center (2,0) + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if (i == 0 && j == 1) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } + } + + // even though this test isnt a completely filled board because it is unsolveable, it tests + // FinishBulbs properly + @Test + public void FinishBulbTestWithThree() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbsWithThree", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - //even though this test isnt a completely filled board because it is unsolveable, it tests FinishBulbs properly - @Test - public void FinishBulbTestWithThree() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbsWithThree", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - //get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - //change the board's cells considering the FinishWithBulbs rule to empty - LightUpCell cell1 = board.getCell(1,2); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); + // change the board's cells considering the FinishWithBulbs rule to empty + LightUpCell cell1 = board.getCell(1, 2); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); - LightUpCell cell2 = board.getCell(0,1); - cell2.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell2); + LightUpCell cell2 = board.getCell(0, 1); + cell2.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell2); - LightUpCell cell3 = board.getCell(2,1); - cell3.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell3); + LightUpCell cell3 = board.getCell(2, 1); + cell3.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell3); - //confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - //check every square for logical following - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 1 && j == 2) || (i == 2 && j == 1) || (i == 1 && j == 0)){ - //logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - //does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + // check every square for logical following + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 1 && j == 2) || (i == 2 && j == 1) || (i == 1 && j == 0)) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } + } } diff --git a/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java b/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java index 2e6a1e879..447e6af24 100644 --- a/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java @@ -1,72 +1,74 @@ package puzzles.lightup.rules; -import org.junit.BeforeClass; -import org.junit.Test; -import edu.rpi.legup.puzzle.lightup.LightUp; -import edu.rpi.legup.puzzle.lightup.rules.LightOrEmptyCaseRule; -import edu.rpi.legup.save.InvalidFileFormatException; -import legup.TestUtilities; +import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUp; import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; -import org.junit.Assert; +import edu.rpi.legup.puzzle.lightup.rules.LightOrEmptyCaseRule; +import edu.rpi.legup.save.InvalidFileFormatException; import java.util.ArrayList; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class LightOrEmptyCaseRuleTest { - private static final LightOrEmptyCaseRule RULE = new LightOrEmptyCaseRule(); - private static LightUp lightUp; + private static final LightOrEmptyCaseRule RULE = new LightOrEmptyCaseRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - //creates boards for what is expected output, and checks that the getcases function produces the correct boards - //IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) - @Test - public void LightOrEmptyTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/LightOrEmptyCaseRule/LightOrEmpty", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // creates boards for what is expected output, and checks that the getcases function produces the + // correct boards + // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) + @Test + public void LightOrEmptyTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/LightOrEmptyCaseRule/LightOrEmpty", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - //get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(0,0); //the focus cell - ArrayList cases = RULE.getCases(b, numbered_cell); + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(0, 0); // the focus cell + ArrayList cases = RULE.getCases(b, numbered_cell); - //assert correct number of cases - Assert.assertEquals(2, cases.size()); + // assert correct number of cases + Assert.assertEquals(2, cases.size()); - //make a list of boards that I expect - LightUpCell change_cell; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + // make a list of boards that I expect + LightUpCell change_cell; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - //change the cells of the first new case board - change_cell = case1.getCell(0,0); - change_cell.setData(LightUpCellType.BULB.value); - //case1.addModifiedData(change_cell); + // change the cells of the first new case board + change_cell = case1.getCell(0, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); - change_cell = case1.getCell(1,1); - change_cell.setData(LightUpCellType.BULB.value); - //case1.addModifiedData(change_cell); + change_cell = case1.getCell(1, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); - //change the cells of the second new case board - change_cell = case2.getCell(0,1); - change_cell.setData(LightUpCellType.BULB.value); - //case2.addModifiedData(change_cell); + // change the cells of the second new case board + change_cell = case2.getCell(0, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); - change_cell = case2.getCell(1,0); - change_cell.setData(LightUpCellType.BULB.value); - //case2.addModifiedData(change_cell); + change_cell = case2.getCell(1, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); - //check each board I expect and make sure it exists in returned board list - //currently cases is not made correctly, so the getCases function is flawed. - //Assert.assertTrue(cases.contains((Board) case1)); - //Assert.assertTrue(cases.contains((Board) case2)); - } + // check each board I expect and make sure it exists in returned board list + // currently cases is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + } } diff --git a/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java index 07958895b..1602b8135 100644 --- a/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java @@ -1,59 +1,58 @@ package puzzles.lightup.rules; -import org.junit.BeforeClass; -import org.junit.Test; -import edu.rpi.legup.puzzle.lightup.LightUp; -import edu.rpi.legup.puzzle.lightup.rules.MustLightDirectRule; -import edu.rpi.legup.save.InvalidFileFormatException; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUp; import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; +import edu.rpi.legup.puzzle.lightup.rules.MustLightDirectRule; +import edu.rpi.legup.save.InvalidFileFormatException; +import legup.TestUtilities; import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class MustLightDirectRuleTest { - private static final MustLightDirectRule RULE = new MustLightDirectRule(); - private static LightUp lightUp; + private static final MustLightDirectRule RULE = new MustLightDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + public void MustLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/lightup/rules/MustLightDirectRule/MustLight", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); + + // change the board's cells considering the MustLight rule + LightUpCell cell1 = board.getCell(1, 2); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); + + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - @Test - public void MustLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/MustLightDirectRule/MustLight", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - //get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); - - //change the board's cells considering the MustLight rule - LightUpCell cell1 = board.getCell(1,2); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); - - //confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); - - //only the cell above should change following the rule - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if (i == 2 && j == 1){ - //logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - //does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + // only the cell above should change following the rule + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if (i == 2 && j == 1) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } + } } diff --git a/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java b/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java index de3551778..b525b0266 100644 --- a/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java @@ -1,155 +1,160 @@ package puzzles.lightup.rules; -import org.junit.BeforeClass; -import org.junit.Test; -import edu.rpi.legup.puzzle.lightup.LightUp; -import edu.rpi.legup.puzzle.lightup.rules.SatisfyNumberCaseRule; -import edu.rpi.legup.save.InvalidFileFormatException; -import legup.TestUtilities; +import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; +import edu.rpi.legup.puzzle.lightup.LightUp; import edu.rpi.legup.puzzle.lightup.LightUpBoard; -import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.puzzle.lightup.LightUpCell; import edu.rpi.legup.puzzle.lightup.LightUpCellType; -import org.junit.Assert; +import edu.rpi.legup.puzzle.lightup.rules.SatisfyNumberCaseRule; +import edu.rpi.legup.save.InvalidFileFormatException; import java.util.ArrayList; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class SatisfyNumberCaseRuleTest { - private static final SatisfyNumberCaseRule RULE = new SatisfyNumberCaseRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - //creates two boards for what is expected output, and checks that the getcases function produces the correct boards - //IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) - @Test - public void SatisfyNumberTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumber", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - //get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(1,0); //the tile cell - ArrayList cases = RULE.getCases(b, numbered_cell);//C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE - - //assert correct number of cases - Assert.assertEquals(2, cases.size()); - - //make a list of boards that I expect - LightUpCell change_cell; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - - //change the cells of the first new case board - change_cell = case1.getCell(0,0); - change_cell.setData(LightUpCellType.BULB.value); - //case1.addModifiedData(change_cell); - - change_cell = case1.getCell(1,1); - change_cell.setData(LightUpCellType.EMPTY.value); - //case1.addModifiedData(change_cell); - - //change the cells of the second new case board - change_cell = case2.getCell(0,0); - change_cell.setData(LightUpCellType.EMPTY.value); - //case2.addModifiedData(change_cell); - - change_cell = case2.getCell(1,1); - change_cell.setData(LightUpCellType.BULB.value); - //case2.addModifiedData(change_cell); - - //check each board I expect and make sure it exists in returned board list - //currently cases is not made correctly, so the getCases function is flawed. - //Assert.assertTrue(cases.contains((Board) case1)); - //Assert.assertTrue(cases.contains((Board) case2)); - } - - @Test - public void SatisfyNumberTestTwo() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumberTwo", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - //get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(1,1); //the tile cell - ArrayList cases = RULE.getCases(b, numbered_cell);//C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE - - //assert correct number of cases - Assert.assertEquals(6, cases.size()); - - //make a list of boards that I expect - LightUpCell change_cell1; - LightUpCell change_cell2; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case3 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case4 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case5 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case6 = ((LightUpBoard) transition.getBoard()).copy(); - - //case 1: lights in (1,0) and (0,1) - change_cell1 = case1.getCell(1,0); - change_cell2 = case1.getCell(0,1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case1.addModifiedData(change_cell1); - case1.addModifiedData(change_cell2); - - //case 2: lights in (1,0) and (1,2) - change_cell1 = case2.getCell(1,0); - change_cell2 = case2.getCell(1,2); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case2.addModifiedData(change_cell1); - case2.addModifiedData(change_cell2); - - //case 3: lights in (1,0) and (2,1) - change_cell1 = case3.getCell(1,0); - change_cell2 = case3.getCell(2,1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case3.addModifiedData(change_cell1); - case3.addModifiedData(change_cell2); - - //case 4: lights in (0,1) and (2,1) - change_cell1 = case4.getCell(0,1); - change_cell2 = case4.getCell(2,1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case4.addModifiedData(change_cell1); - case4.addModifiedData(change_cell2); - - //case 5: lights in (0,1) and (1,2) - change_cell1 = case5.getCell(0,1); - change_cell2 = case5.getCell(1,2); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case5.addModifiedData(change_cell1); - case5.addModifiedData(change_cell2); - - //case 6: lights in (1,2) and (2,1) - change_cell1 = case6.getCell(1,2); - change_cell2 = case6.getCell(2,1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case6.addModifiedData(change_cell1); - case6.addModifiedData(change_cell2); - - //check each board I expect and make sure it exists in returned board list - //currently the cases list is not made correctly, so the getCases function is flawed. - //Assert.assertTrue(cases.contains((Board) case1)); - //Assert.assertTrue(cases.contains((Board) case2)); - //Assert.assertTrue(cases.contains((Board) case3)); - //Assert.assertTrue(cases.contains((Board) case4)); - //Assert.assertTrue(cases.contains((Board) case5)); - //Assert.assertTrue(cases.contains((Board) case6)); - } -} \ No newline at end of file + private static final SatisfyNumberCaseRule RULE = new SatisfyNumberCaseRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + // creates two boards for what is expected output, and checks that the getcases function produces + // the correct boards + // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) + @Test + public void SatisfyNumberTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumber", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(1, 0); // the tile cell + ArrayList cases = + RULE.getCases(b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE + + // assert correct number of cases + Assert.assertEquals(2, cases.size()); + + // make a list of boards that I expect + LightUpCell change_cell; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + + // change the cells of the first new case board + change_cell = case1.getCell(0, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); + + change_cell = case1.getCell(1, 1); + change_cell.setData(LightUpCellType.EMPTY.value); + // case1.addModifiedData(change_cell); + + // change the cells of the second new case board + change_cell = case2.getCell(0, 0); + change_cell.setData(LightUpCellType.EMPTY.value); + // case2.addModifiedData(change_cell); + + change_cell = case2.getCell(1, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); + + // check each board I expect and make sure it exists in returned board list + // currently cases is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + } + + @Test + public void SatisfyNumberTestTwo() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumberTwo", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(1, 1); // the tile cell + ArrayList cases = + RULE.getCases(b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE + + // assert correct number of cases + Assert.assertEquals(6, cases.size()); + + // make a list of boards that I expect + LightUpCell change_cell1; + LightUpCell change_cell2; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case3 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case4 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case5 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case6 = ((LightUpBoard) transition.getBoard()).copy(); + + // case 1: lights in (1,0) and (0,1) + change_cell1 = case1.getCell(1, 0); + change_cell2 = case1.getCell(0, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case1.addModifiedData(change_cell1); + case1.addModifiedData(change_cell2); + + // case 2: lights in (1,0) and (1,2) + change_cell1 = case2.getCell(1, 0); + change_cell2 = case2.getCell(1, 2); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case2.addModifiedData(change_cell1); + case2.addModifiedData(change_cell2); + + // case 3: lights in (1,0) and (2,1) + change_cell1 = case3.getCell(1, 0); + change_cell2 = case3.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case3.addModifiedData(change_cell1); + case3.addModifiedData(change_cell2); + + // case 4: lights in (0,1) and (2,1) + change_cell1 = case4.getCell(0, 1); + change_cell2 = case4.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case4.addModifiedData(change_cell1); + case4.addModifiedData(change_cell2); + + // case 5: lights in (0,1) and (1,2) + change_cell1 = case5.getCell(0, 1); + change_cell2 = case5.getCell(1, 2); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case5.addModifiedData(change_cell1); + case5.addModifiedData(change_cell2); + + // case 6: lights in (1,2) and (2,1) + change_cell1 = case6.getCell(1, 2); + change_cell2 = case6.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case6.addModifiedData(change_cell1); + case6.addModifiedData(change_cell2); + + // check each board I expect and make sure it exists in returned board list + // currently the cases list is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + // Assert.assertTrue(cases.contains((Board) case3)); + // Assert.assertTrue(cases.contains((Board) case4)); + // Assert.assertTrue(cases.contains((Board) case5)); + // Assert.assertTrue(cases.contains((Board) case6)); + } +} diff --git a/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java index bab616198..25389f299 100644 --- a/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java @@ -1,66 +1,68 @@ package puzzles.lightup.rules; -import org.junit.BeforeClass; -import org.junit.Test; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.lightup.LightUp; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.rules.TooFewBulbsContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; import legup.TestUtilities; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class TooFewBulbsContradictionRuleTest { - private static final TooFewBulbsContradictionRule RULE = new TooFewBulbsContradictionRule(); - private static LightUp lightUp; + private static final TooFewBulbsContradictionRule RULE = new TooFewBulbsContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/TooFewBulbsContradictionRule/FullTooFewTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooFewBulbsContradictionRule/FullTooFewTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - //confirm that there arent enough bulbs around the black tiles - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(4, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); + // confirm that there arent enough bulbs around the black tiles + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(4, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); - //confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(4, 4))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); - } + // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(4, 4))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); + } - @Test - public void TooFewSimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/TooFewBulbsContradictionRule/TooFew", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void TooFewSimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooFewBulbsContradictionRule/TooFew", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); + LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm it is impossible to satisfy up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to satisfy up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - //every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } } diff --git a/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java index fe3dad2e0..0ee6fdb5e 100644 --- a/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java @@ -1,65 +1,68 @@ package puzzles.lightup.rules; -import org.junit.BeforeClass; -import org.junit.Test; +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.lightup.LightUp; +import edu.rpi.legup.puzzle.lightup.LightUpBoard; import edu.rpi.legup.puzzle.lightup.rules.TooManyBulbsContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; import legup.TestUtilities; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; -import edu.rpi.legup.puzzle.lightup.LightUpBoard; import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class TooManyBulbsContradictionRuleTest { - private static final TooManyBulbsContradictionRule RULE = new TooManyBulbsContradictionRule(); - private static LightUp lightUp; + private static final TooManyBulbsContradictionRule RULE = new TooManyBulbsContradictionRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - @Test - //complex extensive toofew test - public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/TooManyBulbsContradictionRule/FullTooManyTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // complex extensive toofew test + public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooManyBulbsContradictionRule/FullTooManyTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - //confirm that there are too many bulbs around the black tiles - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); + // confirm that there are too many bulbs around the black tiles + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); - //confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); - } + // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); + } - @Test - //tests a 3x3 board with a 3 in the center and 4 surrounding lightbulbs - public void TooManySimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/TooManyBulbsContradictionRule/TooMany", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // tests a 3x3 board with a 3 in the center and 4 surrounding lightbulbs + public void TooManySimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooManyBulbsContradictionRule/TooMany", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); + LightUpBoard board = (LightUpBoard) transition.getBoard(); - //confirm it is impossible to satisfy up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to satisfy up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - //every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java index 18ee3d42b..3fda4956d 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java @@ -1,190 +1,202 @@ package puzzles.nurikabe.rules; -//import javafx.scene.layout.Pane; +// import javafx.scene.layout.Pane; -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.rpi.legup.puzzle.nurikabe.Nurikabe; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; import edu.rpi.legup.puzzle.nurikabe.NurikabeType; import edu.rpi.legup.puzzle.nurikabe.rules.BlackBetweenRegionsDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; - import java.awt.*; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class BlackBetweenRegionsDirectRuleTest { - private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other (diagonal going from top left to bottom right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(2, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(1, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Black Between Regions direct rule for regions that are diagonal to each other + * (diagonal going from top left to bottom right) + */ + @Test + public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell1 = board.getCell(2, 1); + cell1.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell2 = board.getCell(1, 2); + cell2.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other (diagonal going from bottom left to top right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(1, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(2, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Black Between Regions direct rule for regions that are diagonal to each other + * (diagonal going from bottom left to top right) + */ + @Test + public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell1 = board.getCell(1, 1); + cell1.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell2 = board.getCell(2, 2); + cell2.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Black Between Regions direct rule for regions that are horizontally opposite each other - */ - @Test - public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Black Between Regions direct rule for regions that are horizontally opposite each + * other + */ + @Test + public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Black Between Regions direct rule for regions that are vertically opposite each other - */ - @Test - public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Black Between Regions direct rule for regions that are vertically opposite each other + */ + @Test + public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Black Between Regions direct rule for a false application of the rule, where a black tile is enclosed by one region - */ - @Test - public void BlackBetweenRegionsDirectRule_FalseBlackBetweenRegionsTest() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/FalseBlackBetweenRegions",nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1,1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for(int i=0; i cases = RULE.getCases(board,cell); - - Assert.assertEquals(2,cases.size()); - - NurikabeBoard caseBoard = (NurikabeBoard) cases.get(0); - NurikabeBoard caseBoard2 = (NurikabeBoard) cases.get(1); - - NurikabeType board1Type = caseBoard.getCell(0,0).getType(); - NurikabeType board2Type = caseBoard2.getCell(0,0).getType(); - - Assert.assertTrue((board1Type.equals(NurikabeType.BLACK) || board1Type.equals(NurikabeType.WHITE)) && - (board2Type.equals(NurikabeType.BLACK) || board2Type.equals(NurikabeType.WHITE))); - Assert.assertFalse(board1Type.equals(board2Type)); - - Assert.assertEquals(caseBoard.getHeight(),caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard.getWidth(),caseBoard2.getWidth(), board.getWidth()); - - for(int i=0; i cases = RULE.getCases(board, cell); + + Assert.assertEquals(2, cases.size()); + + NurikabeBoard caseBoard = (NurikabeBoard) cases.get(0); + NurikabeBoard caseBoard2 = (NurikabeBoard) cases.get(1); + + NurikabeType board1Type = caseBoard.getCell(0, 0).getType(); + NurikabeType board2Type = caseBoard2.getCell(0, 0).getType(); + + Assert.assertTrue( + (board1Type.equals(NurikabeType.BLACK) || board1Type.equals(NurikabeType.WHITE)) + && (board2Type.equals(NurikabeType.BLACK) || board2Type.equals(NurikabeType.WHITE))); + Assert.assertFalse(board1Type.equals(board2Type)); + + Assert.assertEquals(caseBoard.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + for (int i = 0; i < caseBoard.getHeight(); i++) { + for (int k = 0; k < caseBoard.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(caseBoard.getCell(k, i).getLocation())) { + continue; } - - + Assert.assertTrue(caseBoard.getCell(k, i).equals(caseBoard2.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java index b06d0e32c..d317a7835 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java @@ -1,111 +1,111 @@ package puzzles.nurikabe.rules; -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; import edu.rpi.legup.puzzle.nurikabe.Nurikabe; import edu.rpi.legup.puzzle.nurikabe.NurikabeBoard; import edu.rpi.legup.puzzle.nurikabe.NurikabeCell; import edu.rpi.legup.puzzle.nurikabe.rules.BlackSquareContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; - import java.awt.*; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class BlackSquareContradictionRuleTest { - private static final BlackSquareContradictionRule RULE = new BlackSquareContradictionRule(); - private static Nurikabe nurikabe; + private static final BlackSquareContradictionRule RULE = new BlackSquareContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Black Square contradiction rule for a black square in the middle of the board - */ - @Test - public void BlackSquareContradictionRule_TwoSurroundBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackSquareContradictionRule/SimpleBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a black square in the middle of the board */ + @Test + public void BlackSquareContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/SimpleBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); - NurikabeCell cell2 = board.getCell(1, 2); - NurikabeCell cell3 = board.getCell(2, 1); - NurikabeCell cell4 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); + NurikabeCell cell2 = board.getCell(1, 2); + NurikabeCell cell3 = board.getCell(2, 1); + NurikabeCell cell4 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation()) || - point.equals(cell3.getLocation()) || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** - * Tests the Black Square contradiction rule for a square in the corner of the board - */ - @Test - public void BlackSquareContradictionRule_CornerSquareTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/nurikabe/rules/BlackSquareContradictionRule/CornerBlackSquare",nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a square in the corner of the board */ + @Test + public void BlackSquareContradictionRule_CornerSquareTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/CornerBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2,2); - NurikabeCell cell2 = board.getCell(2,3); - NurikabeCell cell3 = board.getCell(3,2); - NurikabeCell cell4 = board.getCell(3,3); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(2, 2); + NurikabeCell cell2 = board.getCell(2, 3); + NurikabeCell cell3 = board.getCell(3, 2); + NurikabeCell cell4 = board.getCell(3, 3); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for(int i=0; i cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); - - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); - ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); - - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); - ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); - - // Assert that the corresponding cells for the different case rules do not - // match with each other - Assert.assertNotEquals(board1A, board2A); - Assert.assertNotEquals(board1B, board2B); - - // First assert the two cells are not equal, then verify that they are either - // unknown or false. - Assert.assertNotEquals(board1A, board1B); - Assert.assertTrue(board1A.equals(ShortTruthTableCellType.UNKNOWN) || board1A.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue(board1B.equals(ShortTruthTableCellType.UNKNOWN) || board1B.equals(ShortTruthTableCellType.FALSE)); - - Assert.assertNotEquals(board2A, board2B); - Assert.assertTrue(board2A.equals(ShortTruthTableCellType.UNKNOWN) || board1A.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue(board2B.equals(ShortTruthTableCellType.UNKNOWN) || board2B.equals(ShortTruthTableCellType.FALSE)); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - - // Verify that everywhere else on the board is unchanged - for (int i = 0; i< caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the two cells that should be different - if (!((i == aX && j == aY) || (i == bX && j == bY))) { - Assert.assertEquals(caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); - } - } + private static final CaseRuleAnd RULE = new CaseRuleAnd(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + private void falseAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); + + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); + ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); + + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); + ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); + + // Assert that the corresponding cells for the different case rules do not + // match with each other + Assert.assertNotEquals(board1A, board2A); + Assert.assertNotEquals(board1B, board2B); + + // First assert the two cells are not equal, then verify that they are either + // unknown or false. + Assert.assertNotEquals(board1A, board1B); + Assert.assertTrue( + board1A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + board1B.equals(ShortTruthTableCellType.UNKNOWN) + || board1B.equals(ShortTruthTableCellType.FALSE)); + + Assert.assertNotEquals(board2A, board2B); + Assert.assertTrue( + board2A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + board2B.equals(ShortTruthTableCellType.UNKNOWN) + || board2B.equals(ShortTruthTableCellType.FALSE)); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the two cells that should be different + if (!((i == aX && j == aY) || (i == bX && j == bY))) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); } + } } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that - * two branches are created: one where A is false and one where B is false. - */ - @Test - public void SimpleStatement1FalseTest() throws InvalidFileFormatException { - falseAndTest("SimpleStatement1_False", 1, 0, 0, 0, - 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule - * by ensuring that two branches are created: one where ~ is false and one where - * the second ^ is false. - */ - @Test - public void ComplexStatement1FalseTest() throws InvalidFileFormatException { - falseAndTest("ComplexStatement1_False", 6, 0, 0, 0, - 9, 0); - } - - private void trueAndTest(String fileName, - int andX, int andY, - int aX, int aY, - int bX, int bY) throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX,andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // There should only be 1 branch - Assert.assertEquals(1, cases.size()); - - ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); - ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); - - // Both cells should be true - Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.TRUE); - Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.TRUE); - Assert.assertEquals(caseBoardAType, caseBoardBType); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that - * one branch is created where A and B are both true. - */ - @Test - public void SimpleStatement1AndTest() throws InvalidFileFormatException { - trueAndTest("SimpleStatement1_True", 1, 0, 0, 0, - 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule - * by ensuring that one branch is created where both ~ and the second ^ are true. - */ - @Test - public void ComplexStatement1TrueTest() throws InvalidFileFormatException { - trueAndTest("ComplexStatement1_True", 6, 0, 0, 0, - 9, 0); - } -} \ No newline at end of file + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches + * are created: one where A is false and one where B is false. + */ + @Test + public void SimpleStatement1FalseTest() throws InvalidFileFormatException { + falseAndTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring + * that two branches are created: one where ~ is false and one where the second ^ is false. + */ + @Test + public void ComplexStatement1FalseTest() throws InvalidFileFormatException { + falseAndTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); + } + + private void trueAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // There should only be 1 branch + Assert.assertEquals(1, cases.size()); + + ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); + ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); + + // Both cells should be true + Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.TRUE); + Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.TRUE); + Assert.assertEquals(caseBoardAType, caseBoardBType); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is + * created where A and B are both true. + */ + @Test + public void SimpleStatement1AndTest() throws InvalidFileFormatException { + trueAndTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring that + * one branch is created where both ~ and the second ^ are true. + */ + @Test + public void ComplexStatement1TrueTest() throws InvalidFileFormatException { + trueAndTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java index 0d94eb672..94b99801b 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java @@ -15,190 +15,198 @@ import org.junit.Test; public class AndEliminationDirectRuleTest { - private static final DirectRuleAndElimination RULE = new DirectRuleAndElimination(); - private static ShortTruthTable stt; + private static final DirectRuleAndElimination RULE = new DirectRuleAndElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: B^C where ^ is true + * + *

Checks all possible combinations of true, false, and unknown for B and C except for where + * both B and C are true and asserts that each one of them is not a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void trueAndTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.TRUE) { + continue; + } - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); - /** - * Given one statement: B^C where ^ is true - * - * Checks all possible combinations of true, false, and unknown for B and C - * except for where both B and C are true and asserts that each one of them - * is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void trueAndTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.TRUE) { - continue; - } - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); - - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); - } - - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } - - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); } - } - /** - * Given one statement: B^C where ^ is true - * - * Checks all possible combinations of true and unknown for B and C - * except for where both B and C are unknown and asserts that each one - * of them is a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void trueAndTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.UNKNOWN) { - continue; - } - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); - - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); - } - - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } - - Assert.assertNull(RULE.checkRule(transition)); - } + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); } - } - /** - * Given one statement: B^C where ^ is false - * - * Checks all possible combinations of true, false, and unknown for B and C - * and asserts that each one of them is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithUnknownsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); - - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); - } - - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); + } } - - /** - * Given one statement: B^C where both B and ^ are false - * - * Asserts that this is not a valid application of the rule if C is set to - * either true or false. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithKnownFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownFalse", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + } + + /** + * Given one statement: B^C where ^ is true + * + *

Checks all possible combinations of true and unknown for B and C except for where both B and + * C are unknown and asserts that each one of them is a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void trueAndTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.UNKNOWN) { + continue; + } ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - + ShortTruthTableCell bonnie = board.getCell(0, 0); ShortTruthTableCell clyde = board.getCell(2, 0); - clyde.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - clyde.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } - /** - * Given one statement: B^C where B is true and ^ is false - * - * Asserts that this is a valid application of the rule if and only if C is - * set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithKnownTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownTrue", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + Assert.assertNull(RULE.checkRule(transition)); + } + } + } + + /** + * Given one statement: B^C where ^ is false + * + *

Checks all possible combinations of true, false, and unknown for B and C and asserts that + * each one of them is not a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithUnknownsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - + ShortTruthTableCell bonnie = board.getCell(0, 0); ShortTruthTableCell clyde = board.getCell(2, 0); - clyde.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - clyde.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(clyde); - Assert.assertNull(RULE.checkRule(transition)); + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } + + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + + Assert.assertNotNull(RULE.checkRule(transition)); + } } -} \ No newline at end of file + } + + /** + * Given one statement: B^C where both B and ^ are false + * + *

Asserts that this is not a valid application of the rule if C is set to either true or + * false. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithKnownFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownFalse", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell clyde = board.getCell(2, 0); + clyde.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); + + clyde.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: B^C where B is true and ^ is false + * + *

Asserts that this is a valid application of the rule if and only if C is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithKnownTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownTrue", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell clyde = board.getCell(2, 0); + clyde.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); + + clyde.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(clyde); + Assert.assertNull(RULE.checkRule(transition)); + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java index 4d4e009b2..d17ffd6cf 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java @@ -15,91 +15,91 @@ import org.junit.Test; public class AndIntroductionDirectRuleTest { - private static final DirectRuleAndIntroduction RULE = new DirectRuleAndIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleAndIntroduction RULE = new DirectRuleAndIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A ^ B - * - * Asserts that if at least 1 of A or B is false, then this is a valid application - * of the rule if and only if ^ is false. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseAndTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; - falseAndTestHelper(path + "FUF"); - falseAndTestHelper(path + "FUU"); - falseAndTestHelper(path + "UUF"); - falseAndTestHelper(path + "FUT"); - falseAndTestHelper(path + "TUF"); - } + /** + * Given a statement: A ^ B + * + *

Asserts that if at least 1 of A or B is false, then this is a valid application of the rule + * if and only if ^ is false. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseAndTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; + falseAndTestHelper(path + "FUF"); + falseAndTestHelper(path + "FUU"); + falseAndTestHelper(path + "UUF"); + falseAndTestHelper(path + "FUT"); + falseAndTestHelper(path + "TUF"); + } - private void falseAndTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseAndTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell and = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell and = board.getCell(1, 0); - and.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(and); - Assert.assertNotNull(RULE.checkRule(transition)); + and.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(and); + Assert.assertNotNull(RULE.checkRule(transition)); - and.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(and); - Assert.assertNull(RULE.checkRule(transition)); - } + and.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(and); + Assert.assertNull(RULE.checkRule(transition)); + } - /** - * Given a statement: A ^ B - * - * Asserts that setting ^ to true is a valid application of the rule if - * and only if both A and B are true. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String first : letters) { - for (String second : letters) { - trueAndTestHelper(path + first + "U" + second); - } - } + /** + * Given a statement: A ^ B + * + *

Asserts that setting ^ to true is a valid application of the rule if and only if both A and + * B are true. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; + String[] letters = {"T", "F", "U"}; + for (String first : letters) { + for (String second : letters) { + trueAndTestHelper(path + first + "U" + second); + } } + } - private void trueAndTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueAndTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - ShortTruthTableCell and = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell and = board.getCell(1, 0); - and.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(and); + and.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(and); - if (a.getType() == ShortTruthTableCellType.TRUE && b.getType() == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (a.getType() == ShortTruthTableCellType.TRUE + && b.getType() == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java index 51aa213c6..2126fc60d 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java @@ -15,174 +15,156 @@ import org.junit.Test; public class AtomicDirectRuleTest { - private static final DirectRuleAtomic RULE = new DirectRuleAtomic(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given two statements: - * A - * A - * where the first A is set to false. - * - * This test sets the second A to false and then asserts that this - * is a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MatchingFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: - * A - * A - * where the first A is set to false. - * - * This test sets the second A to true and then asserts that this - * is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MismatchingFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: - * B - * B - * where the first B is set to true. - * - * This test sets the second B to true and then asserts that this - * is a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MatchingTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: - * B - * B - * where the first B is set to true. - * - * This test sets the second B to false and then asserts that this - * is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MismatchingTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: - * C - * C - * where neither statement is set to anything. - * - * This test sets the second C to false and then asserts that this - * is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void NothingPreviouslyMarkedTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: - * C - * C - * where neither statement is set to anything. - * - * This test sets the second C to true and then asserts that this - * is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void NothingPreviouslyMarkedTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } -} \ No newline at end of file + private static final DirectRuleAtomic RULE = new DirectRuleAtomic(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given two statements: A A where the first A is set to false. + * + *

This test sets the second A to false and then asserts that this is a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MatchingFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: A A where the first A is set to false. + * + *

This test sets the second A to true and then asserts that this is not a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MismatchingFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: B B where the first B is set to true. + * + *

This test sets the second B to true and then asserts that this is a valid application of the + * rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MatchingTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: B B where the first B is set to true. + * + *

This test sets the second B to false and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MismatchingTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: C C where neither statement is set to anything. + * + *

This test sets the second C to false and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void NothingPreviouslyMarkedTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: C C where neither statement is set to anything. + * + *

This test sets the second C to true and then asserts that this is not a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void NothingPreviouslyMarkedTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java index 05faf87bb..36824faee 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java @@ -15,359 +15,380 @@ import org.junit.Test; public class BiconditionalEliminationTest { - private static final DirectRuleBiconditionalElimination RULE = new DirectRuleBiconditionalElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: A <-> B where both A and <-> are true - * - * Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where both B and <-> are true - * - * Asserts that this is a valid application of the rule if and only if A is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + private static final DirectRuleBiconditionalElimination RULE = + new DirectRuleBiconditionalElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: A <-> B where both A and <-> are true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where both B and <-> are true + * + *

Asserts that this is a valid application of the rule if and only if A is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A is false and <-> is true + * + *

Asserts that this is a valid application of the rule if and only if B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B is false and <-> is true + * + *

Asserts that this is a valid application of the rule if and only if A is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A is true and <-> is false + * + *

Asserts that this is a valid application of the rule if and only if B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B is true and <-> is false + * + *

Asserts that this is a valid application of the rule if and only if A is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A and <-> are false + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B and <-> are false + * + *

Asserts that this is a valid application of the rule if and only if A is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where <-> is true + * + *

Asserts that setting any combination of A and B at the same time is not a valid application + * of this rule + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalSetBothAtOnceTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - - /** - * Given one statement: A <-> B where A is false and <-> is true - * - * Asserts that this is a valid application of the rule if and only if B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell morty = board.getCell(2, 0); - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B is false and <-> is true - * - * Asserts that this is a valid application of the rule if and only if A is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); + rick.setData(cellType1); + morty.setData(cellType2); - // Asserts that this is a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A is true and <-> is false - * - * Asserts that this is a valid application of the rule if and only if B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - // Asserts that this is not a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); + } } - - /** - * Given one statement: A <-> B where B is true and <-> is false - * - * Asserts that this is a valid application of the rule if and only if A is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + } + + /** + * Asserts that setting any combination of A and B at the same time is not a valid application of + * this rule. This is tested on multiple files. + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAandBAtOnceTest() throws InvalidFileFormatException { + String directory = "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/"; + setAandBBothAtOnceTest(directory + "FalseBiconditional"); + setAandBBothAtOnceTest(directory + "TrueBiconditional"); + setAandBBothAtOnceTest(directory + "FalseBiconditionalWithFalseA"); + setAandBBothAtOnceTest(directory + "TrueBiconditionalWithFalseA"); + setAandBBothAtOnceTest(directory + "FalseBiconditionalWithTrueA"); + setAandBBothAtOnceTest(directory + "TrueBiconditionalWithTrueA"); + } + + /** + * Helper function to test biconditional elimination rule with given file path. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + private void setAandBBothAtOnceTest(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A and <-> are false - * - * Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell morty = board.getCell(2, 0); - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B and <-> are false - * - * Asserts that this is a valid application of the rule if and only if A is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); + rick.setData(cellType1); + morty.setData(cellType2); - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); + board.addModifiedData(morty); - // Asserts that this is not a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where <-> is true - * - * Asserts that setting any combination of A and B at the same time is not a valid - * application of this rule - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalSetBothAtOnceTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - ShortTruthTableCell morty = board.getCell(2, 0); - - rick.setData(cellType1); - morty.setData(cellType2); - - board.addModifiedData(rick); - board.addModifiedData(morty); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - - /** - * Asserts that setting any combination of A and B at the same time is not a valid - * application of this rule. This is tested on multiple files. - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAandBAtOnceTest() throws InvalidFileFormatException { - String directory = "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/"; - setAandBBothAtOnceTest(directory + "FalseBiconditional"); - setAandBBothAtOnceTest(directory + "TrueBiconditional"); - setAandBBothAtOnceTest(directory + "FalseBiconditionalWithFalseA"); - setAandBBothAtOnceTest(directory + "TrueBiconditionalWithFalseA"); - setAandBBothAtOnceTest(directory + "FalseBiconditionalWithTrueA"); - setAandBBothAtOnceTest(directory + "TrueBiconditionalWithTrueA"); - } - - /** - * Helper function to test biconditional elimination rule with given file path. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - private void setAandBBothAtOnceTest(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - ShortTruthTableCell morty = board.getCell(2, 0); - - rick.setData(cellType1); - morty.setData(cellType2); - - board.addModifiedData(rick); - board.addModifiedData(morty); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java index fe2574b5e..99a86c6f1 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java @@ -15,104 +15,103 @@ import org.junit.Test; public class BiconditionalIntroductionTest { - private static final DirectRuleBiconditionalIntroduction RULE = new DirectRuleBiconditionalIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleBiconditionalIntroduction RULE = + new DirectRuleBiconditionalIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A <-> B - * - * Asserts that if setting <-> to false is a valid application of this rule if and - * only if A and B do not match. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; + /** + * Given a statement: A <-> B + * + *

Asserts that if setting <-> to false is a valid application of this rule if and only if A + * and B do not match. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - System.out.println(a + b); - falseConditionalHelper(path + a + "U" + b); - } - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + System.out.println(a + b); + falseConditionalHelper(path + a + "U" + b); + } } + } - private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() != b.getType()) { - // Not valid if they don't match but at least one of the values of A or B is unknown - if (a.getType() == ShortTruthTableCellType.UNKNOWN || b.getType() == ShortTruthTableCellType.UNKNOWN) { - Assert.assertNotNull(RULE.checkRule(transition)); - } - else { - Assert.assertNull(RULE.checkRule(transition)); - } - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() != b.getType()) { + // Not valid if they don't match but at least one of the values of A or B is unknown + if (a.getType() == ShortTruthTableCellType.UNKNOWN + || b.getType() == ShortTruthTableCellType.UNKNOWN) { + Assert.assertNotNull(RULE.checkRule(transition)); + } else { + Assert.assertNull(RULE.checkRule(transition)); + } + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } - /** - * Given a statement: A <-> B - * - * Asserts that if setting <-> to true is a valid application of this rule if and - * only if A and B match. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; + /** + * Given a statement: A <-> B + * + *

Asserts that if setting <-> to true is a valid application of this rule if and only if A and + * B match. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - System.out.println(a + b); - trueConditionalHelper(path + a + "U" + b); - } - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + System.out.println(a + b); + trueConditionalHelper(path + a + "U" + b); + } } + } - private void trueConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == b.getType() && a.getType() != ShortTruthTableCellType.UNKNOWN) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == b.getType() && a.getType() != ShortTruthTableCellType.UNKNOWN) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java index 8d0bb4e1a..7574ce337 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java @@ -15,219 +15,229 @@ import org.junit.Test; public class ConditionalEliminationTest { - private static final DirectRuleConditionalElimination RULE = new DirectRuleConditionalElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: A -> B where -> is false - * - * Asserts that the only valid combination of A and B that is a valid application - * of this rule is when A is true and B is false - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - ShortTruthTableCell boniato = board.getCell(2, 0); - - aubergine.setData(cellType1); - boniato.setData(cellType2); - - board.addModifiedData(aubergine); - board.addModifiedData(boniato); - - if (cellType1 == ShortTruthTableCellType.TRUE && cellType2 == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - } - - /** - * Given one statement: A -> B where -> is false - * - * Asserts that this is a valid application of the rule if and only if A - * is set to true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + private static final DirectRuleConditionalElimination RULE = + new DirectRuleConditionalElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that the only valid combination of A and B that is a valid application of this rule + * is when A is true and B is false + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell aubergine = board.getCell(0, 0); - - aubergine.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(aubergine); - Assert.assertNull(RULE.checkRule(transition)); - - aubergine.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(aubergine); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where -> is false - * - * Asserts that this is a valid application of the rule if and only if B is - * set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell boniato = board.getCell(2, 0); - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNull(RULE.checkRule(transition)); + aubergine.setData(cellType1); + boniato.setData(cellType2); - boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(aubergine); board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } - /** - * Given one statement: A -> B where -> is true - * - * Asserts that you cannot set any combination of both A and B at the same time. - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAandBTrueConditionalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - ShortTruthTableCell boniato = board.getCell(2, 0); - - aubergine.setData(cellType1); - boniato.setData(cellType2); - - board.addModifiedData(aubergine); - board.addModifiedData(boniato); - - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType1 == ShortTruthTableCellType.TRUE + && cellType2 == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } } - - /** - * Given one statement: A -> B where A and -> are true - * - * Asserts that this is a valid application of this rule if and only if B - * is set to true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueAMeansTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that this is a valid application of the rule if and only if A is set to true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); + + aubergine.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(aubergine); + Assert.assertNull(RULE.checkRule(transition)); + + aubergine.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(aubergine); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that this is a valid application of the rule if and only if B is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where -> is true + * + *

Asserts that you cannot set any combination of both A and B at the same time. + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAandBTrueConditionalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); ShortTruthTableCell boniato = board.getCell(2, 0); - boniato.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(boniato); - Assert.assertNull(RULE.checkRule(transition)); - - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } + aubergine.setData(cellType1); + boniato.setData(cellType2); - /** - * Given one statement: A -> B where B is false and -> is true - * - * Asserts that this is a valid application of this rule if and only if A - * is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBMeansFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithFalseB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - - aubergine.setData(ShortTruthTableCellType.FALSE); board.addModifiedData(aubergine); - Assert.assertNull(RULE.checkRule(transition)); - - aubergine.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(aubergine); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where B and -> are true - * - * Asserts that this is not a valid application of this rule no matter what - * A is set to. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBCannotDetermineA() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); Assert.assertNotNull(RULE.checkRule(transition)); + } } -} \ No newline at end of file + } + + /** + * Given one statement: A -> B where A and -> are true + * + *

Asserts that this is a valid application of this rule if and only if B is set to true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueAMeansTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(boniato); + Assert.assertNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where B is false and -> is true + * + *

Asserts that this is a valid application of this rule if and only if A is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBMeansFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); + + aubergine.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(aubergine); + Assert.assertNull(RULE.checkRule(transition)); + + aubergine.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(aubergine); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where B and -> are true + * + *

Asserts that this is not a valid application of this rule no matter what A is set to. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBCannotDetermineA() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java index c1507eab1..5eea810a7 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java @@ -15,96 +15,97 @@ import org.junit.Test; public class ConditionalIntroductionTest { - private static final DirectRuleConditionalIntroduction RULE = new DirectRuleConditionalIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleConditionalIntroduction RULE = + new DirectRuleConditionalIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A -> B - * - * Asserts that if setting -> to false is a valid application of this rule if and - * only if A is true and B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; + /** + * Given a statement: A -> B + * + *

Asserts that if setting -> to false is a valid application of this rule if and only if A is + * true and B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - falseConditionalHelper(path + a + "U" + b); - } - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + falseConditionalHelper(path + a + "U" + b); + } } + } - private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == ShortTruthTableCellType.TRUE && b.getType() == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == ShortTruthTableCellType.TRUE + && b.getType() == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } - /** - * Given a statement: A -> B - * - * Asserts that if setting -> to true is a valid application of this rule if and - * only if A is false or B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; + /** + * Given a statement: A -> B + * + *

Asserts that if setting -> to true is a valid application of this rule if and only if A is + * false or B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - trueConditionalTestHelper(path + a + "U" + b); - } - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + trueConditionalTestHelper(path + a + "U" + b); + } } + } - private void trueConditionalTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueConditionalTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == ShortTruthTableCellType.FALSE || b.getType() == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == ShortTruthTableCellType.FALSE + || b.getType() == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java index 6dbbf141c..9caf2414a 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java @@ -15,110 +15,116 @@ import org.junit.Test; public class NotEliminationTest { - private static final DirectRuleNotElimination RULE = new DirectRuleNotElimination(); - private static ShortTruthTable stt; + private static final DirectRuleNotElimination RULE = new DirectRuleNotElimination(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given one statement: ¬A where ¬ is false - * - * Asserts that this is a valid application of this rule if and only if A is true - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/FalseNot", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Given one statement: ¬A where ¬ is false + * + *

Asserts that this is a valid application of this rule if and only if A is true + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotEliminationDirectRule/FalseNot", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(1, 0); - a.setData(cellType); - board.addModifiedData(a); + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(1, 0); + a.setData(cellType); + board.addModifiedData(a); - if (cellType == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + if (cellType == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } - /** - * Given one statement: ¬A where ¬ is true - * - * Asserts that this is a valid application of this rule if and only if A is false - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/TrueNot", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Given one statement: ¬A where ¬ is true + * + *

Asserts that this is a valid application of this rule if and only if A is false + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotEliminationDirectRule/TrueNot", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(1, 0); - a.setData(cellType); - board.addModifiedData(a); + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(1, 0); + a.setData(cellType); + board.addModifiedData(a); - if (cellType == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + if (cellType == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } -// /** -// * Given one statement: ¬A -// * -// * Asserts that setting both ¬ and A to any values would not be a valid -// * application of this rule -// * -// * @throws InvalidFileFormatException -// */ -// @Test -// public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { -// TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/BlankNot", stt); -// TreeNode rootNode = stt.getTree().getRootNode(); -// TreeTransition transition = rootNode.getChildren().get(0); -// transition.setRule(RULE); -// -// ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; -// -// for (ShortTruthTableCellType cellType1 : cellTypes) { -// for (ShortTruthTableCellType cellType2 : cellTypes) { -// ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); -// ShortTruthTableCell not = board.getCell(0, 0); -// ShortTruthTableCell a = board.getCell(1, 0); -// -// not.setData(cellType1); -// a.setData(cellType2); -// -// board.addModifiedData(not); -// board.addModifiedData(a); -// -// System.out.println("TYPE1:" + cellType1); -// System.out.println("TYPE2:" + cellType2); -// Assert.assertNotNull(RULE.checkRule(transition)); -// } -// } -// } -} \ No newline at end of file + // /** + // * Given one statement: ¬A + // * + // * Asserts that setting both ¬ and A to any values would not be a valid + // * application of this rule + // * + // * @throws InvalidFileFormatException + // */ + // @Test + // public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { + // + // TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/BlankNot", stt); + // TreeNode rootNode = stt.getTree().getRootNode(); + // TreeTransition transition = rootNode.getChildren().get(0); + // transition.setRule(RULE); + // + // ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, + // ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; + // + // for (ShortTruthTableCellType cellType1 : cellTypes) { + // for (ShortTruthTableCellType cellType2 : cellTypes) { + // ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + // ShortTruthTableCell not = board.getCell(0, 0); + // ShortTruthTableCell a = board.getCell(1, 0); + // + // not.setData(cellType1); + // a.setData(cellType2); + // + // board.addModifiedData(not); + // board.addModifiedData(a); + // + // System.out.println("TYPE1:" + cellType1); + // System.out.println("TYPE2:" + cellType2); + // Assert.assertNotNull(RULE.checkRule(transition)); + // } + // } + // } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java index a0a062ab3..9949651eb 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java @@ -15,108 +15,115 @@ import org.junit.Test; public class NotIntroductionTest { - private static final DirectRuleNotIntroduction RULE = new DirectRuleNotIntroduction(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); + private static final DirectRuleNotIntroduction RULE = new DirectRuleNotIntroduction(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: ¬A where A is false + * + *

Asserts that this is a valid application of this rule if and only if ¬ is true + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + not.setData(cellType); + board.addModifiedData(not); + + if (cellType == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - - /** - * Given one statement: ¬A where A is false - * - * Asserts that this is a valid application of this rule if and only if ¬ is true - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotIntroductionDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - not.setData(cellType); - board.addModifiedData(not); - - if (cellType == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + } + + /** + * Given one statement: ¬A where A is true + * + *

Asserts that this is a valid application of this rule if and only if ¬ is false + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/TrueA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + not.setData(cellType); + board.addModifiedData(not); + + if (cellType == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - - /** - * Given one statement: ¬A where A is true - * - * Asserts that this is a valid application of this rule if and only if ¬ is false - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotIntroductionDirectRule/TrueA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - not.setData(cellType); - board.addModifiedData(not); - - if (cellType == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - - /** - * Given one statement: ¬A - * - * Asserts that setting both ¬ and A to any values would not be a valid - * application of this rule - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotIntroductionDirectRule/BlankA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - ShortTruthTableCell a = board.getCell(1, 0); - - not.setData(cellType1); - a.setData(cellType2); - - board.addModifiedData(not); - board.addModifiedData(a); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + } + + /** + * Given one statement: ¬A + * + *

Asserts that setting both ¬ and A to any values would not be a valid application of this + * rule + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/BlankA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + ShortTruthTableCell a = board.getCell(1, 0); + + not.setData(cellType1); + a.setData(cellType2); + + board.addModifiedData(not); + board.addModifiedData(a); + + Assert.assertNotNull(RULE.checkRule(transition)); + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java index 0f7e93db5..a2cc2abc0 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java @@ -7,155 +7,153 @@ import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableBoard; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCell; import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; -import edu.rpi.legup.puzzle.shorttruthtable.rules.caserule.CaseRuleAnd; import edu.rpi.legup.puzzle.shorttruthtable.rules.caserule.CaseRuleOr; import edu.rpi.legup.save.InvalidFileFormatException; +import java.util.ArrayList; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.util.ArrayList; - public class OrCaseRuleTest { - private static final CaseRuleOr RULE = new CaseRuleOr(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - private void trueOrTest(String fileName, - int andX, int andY, - int aX, int aY, - int bX, int bY) throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX,andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); - - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); - ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); - - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); - ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); - - // Assert that the corresponding cells for the different case rules do not - // match with each other - Assert.assertNotEquals(board1A, board2A); - Assert.assertNotEquals(board1B, board2B); - - // First assert the two cells are not equal, then verify that they are either - // unknown or false. - Assert.assertNotEquals(board1A, board1B); - Assert.assertTrue(board1A.equals(ShortTruthTableCellType.UNKNOWN) || board1A.equals(ShortTruthTableCellType.TRUE)); - Assert.assertTrue(board1B.equals(ShortTruthTableCellType.UNKNOWN) || board1B.equals(ShortTruthTableCellType.TRUE)); - - Assert.assertNotEquals(board2A, board2B); - Assert.assertTrue(board2A.equals(ShortTruthTableCellType.UNKNOWN) || board1A.equals(ShortTruthTableCellType.TRUE)); - Assert.assertTrue(board2B.equals(ShortTruthTableCellType.UNKNOWN) || board2B.equals(ShortTruthTableCellType.TRUE)); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - - // Verify that everywhere else on the board is unchanged - for (int i = 0; i< caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the two cells that should be different - if (!((i == aX && j == aY) || (i == bX && j == bY))) { - Assert.assertEquals(caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); - } - } + private static final CaseRuleOr RULE = new CaseRuleOr(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + private void trueOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); + + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); + ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); + + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); + ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); + + // Assert that the corresponding cells for the different case rules do not + // match with each other + Assert.assertNotEquals(board1A, board2A); + Assert.assertNotEquals(board1B, board2B); + + // First assert the two cells are not equal, then verify that they are either + // unknown or false. + Assert.assertNotEquals(board1A, board1B); + Assert.assertTrue( + board1A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.TRUE)); + Assert.assertTrue( + board1B.equals(ShortTruthTableCellType.UNKNOWN) + || board1B.equals(ShortTruthTableCellType.TRUE)); + + Assert.assertNotEquals(board2A, board2B); + Assert.assertTrue( + board2A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.TRUE)); + Assert.assertTrue( + board2B.equals(ShortTruthTableCellType.UNKNOWN) + || board2B.equals(ShortTruthTableCellType.TRUE)); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the two cells that should be different + if (!((i == aX && j == aY) || (i == bX && j == bY))) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); } + } } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that - * two branches are created: one where A is false and one where B is false. - */ - @Test - public void SimpleStatement1TrueTest() throws InvalidFileFormatException { - trueOrTest("SimpleStatement1_True", 1, 0, 0, 0, - 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule - * by ensuring that two branches are created: one where ~ is false and one where - * the second ^ is false. - */ - @Test - public void ComplexStatement1TrueTest() throws InvalidFileFormatException { - trueOrTest("ComplexStatement1_True", 6, 0, 0, 0, - 9, 0); - } - - private void falseOrTest(String fileName, - int andX, int andY, - int aX, int aY, - int bX, int bY) throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX,andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // There should only be 1 branch - Assert.assertEquals(1, cases.size()); - - ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); - ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); - - // Both cells should be true - Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.FALSE); - Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.FALSE); - Assert.assertEquals(caseBoardAType, caseBoardBType); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that - * one branch is created where A and B are both true. - */ - @Test - public void SimpleStatement1FalseTest() throws InvalidFileFormatException { - falseOrTest("SimpleStatement1_False", 1, 0, 0, 0, - 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule - * by ensuring that one branch is created where both ~ and the second ^ are true. - */ - @Test - public void ComplexStatement1FalseTest() throws InvalidFileFormatException { - falseOrTest("ComplexStatement1_False", 6, 0, 0, 0, - 9, 0); - } -} \ No newline at end of file + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches + * are created: one where A is false and one where B is false. + */ + @Test + public void SimpleStatement1TrueTest() throws InvalidFileFormatException { + trueOrTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring + * that two branches are created: one where ~ is false and one where the second ^ is false. + */ + @Test + public void ComplexStatement1TrueTest() throws InvalidFileFormatException { + trueOrTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); + } + + private void falseOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // There should only be 1 branch + Assert.assertEquals(1, cases.size()); + + ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); + ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); + + // Both cells should be true + Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.FALSE); + Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.FALSE); + Assert.assertEquals(caseBoardAType, caseBoardBType); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is + * created where A and B are both true. + */ + @Test + public void SimpleStatement1FalseTest() throws InvalidFileFormatException { + falseOrTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring that + * one branch is created where both ~ and the second ^ are true. + */ + @Test + public void ComplexStatement1FalseTest() throws InvalidFileFormatException { + falseOrTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java index 6cdd0d639..b678b6610 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java @@ -15,136 +15,139 @@ import org.junit.Test; public class OrEliminationTest { - private static final DirectRuleOrElimination RULE = new DirectRuleOrElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given a statement: A V B, where A is false and V is true - * - * Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FTUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/FTU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + private static final DirectRuleOrElimination RULE = new DirectRuleOrElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given a statement: A V B, where A is false and V is true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FTUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/FTU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(2, 0); + + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + Assert.assertNull(RULE.checkRule(transition)); + + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given a statement: A V B, where B is false and V is true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void UTFTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTF", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(0, 0); + + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + Assert.assertNull(RULE.checkRule(transition)); + + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given a statement: A V B, where V is false + * + *

Asserts that this is a valid application of the rule if and only if both A and B are false. + * + * @throws InvalidFileFormatException + */ + @Test + public void UFUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UFU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(2, 0); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + a.setData(cellType1); + b.setData(cellType2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given a statement: A V B, where B is false and V is true - * - * Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void UTFTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTF", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + board.addModifiedData(a); + board.addModifiedData(b); + if (cellType1 == ShortTruthTableCellType.FALSE + && cellType2 == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + } + + /** + * Given a statement: A V B, where V is true + * + *

Asserts that setting both A and B is not a valid application of this rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void UTUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(0, 0); - - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); - } + a.setData(cellType1); + b.setData(cellType2); - /** - * Given a statement: A V B, where V is false - * - * Asserts that this is a valid application of the rule if and only if both A - * and B are false. - * - * @throws InvalidFileFormatException - */ - @Test - public void UFUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UFU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - - a.setData(cellType1); - b.setData(cellType2); - - board.addModifiedData(a); - board.addModifiedData(b); - - if (cellType1 == ShortTruthTableCellType.FALSE && cellType2 == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - } + board.addModifiedData(a); + board.addModifiedData(b); - /** - * Given a statement: A V B, where V is true - * - * Asserts that setting both A and B is not a valid application of this rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void UTUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - - a.setData(cellType1); - b.setData(cellType2); - - board.addModifiedData(a); - board.addModifiedData(b); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java index 13cb10d55..67a111da7 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java @@ -15,91 +15,91 @@ import org.junit.Test; public class OrIntroductionTest { - private static final DirectRuleOrIntroduction RULE = new DirectRuleOrIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleOrIntroduction RULE = new DirectRuleOrIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A V B - * - * Asserts that if at least 1 of A or B is true, then this is a valid application - * of the rule if and only if V is true. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void TrueOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; - trueOrTestHelper(path + "TUT"); - trueOrTestHelper(path + "TUU"); - trueOrTestHelper(path + "UUT"); - trueOrTestHelper(path + "TUF"); - trueOrTestHelper(path + "FUT"); - } + /** + * Given a statement: A V B + * + *

Asserts that if at least 1 of A or B is true, then this is a valid application of the rule + * if and only if V is true. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void TrueOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; + trueOrTestHelper(path + "TUT"); + trueOrTestHelper(path + "TUU"); + trueOrTestHelper(path + "UUT"); + trueOrTestHelper(path + "TUF"); + trueOrTestHelper(path + "FUT"); + } - private void trueOrTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueOrTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell or = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell or = board.getCell(1, 0); - or.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(or); - Assert.assertNull(RULE.checkRule(transition)); + or.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(or); + Assert.assertNull(RULE.checkRule(transition)); - or.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(or); - Assert.assertNotNull(RULE.checkRule(transition)); - } + or.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(or); + Assert.assertNotNull(RULE.checkRule(transition)); + } - /** - * Given a statement: A V B - * - * Asserts that setting V to false is a valid application of the rule if - * and only if both A and B are false. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String first : letters) { - for (String second : letters) { - falseOrTestHelper(path + first + "U" + second); - } - } + /** + * Given a statement: A V B + * + *

Asserts that setting V to false is a valid application of the rule if and only if both A and + * B are false. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; + String[] letters = {"T", "F", "U"}; + for (String first : letters) { + for (String second : letters) { + falseOrTestHelper(path + first + "U" + second); + } } + } - private void falseOrTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseOrTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - ShortTruthTableCell or = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell or = board.getCell(1, 0); - or.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(or); + or.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(or); - if (a.getType() == ShortTruthTableCellType.FALSE && b.getType() == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } - else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (a.getType() == ShortTruthTableCellType.FALSE + && b.getType() == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java index 2c0b9fb15..3a9c749e7 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java @@ -9,70 +9,75 @@ import edu.rpi.legup.puzzle.shorttruthtable.ShortTruthTableCellType; import edu.rpi.legup.puzzle.shorttruthtable.rules.caserule.CaseRuleAtomic; import edu.rpi.legup.save.InvalidFileFormatException; +import java.util.ArrayList; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.util.ArrayList; - public class TrueOrFalseCaseRuleTest { - private static final CaseRuleAtomic RULE = new CaseRuleAtomic(); - private static ShortTruthTable stt; + private static final CaseRuleAtomic RULE = new CaseRuleAtomic(); + private static ShortTruthTable stt; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Tests the True or False case rule by ensuring that it results in two children, - * one that contains Statement as true and one that contains Statement as false. - */ - @Test - public void TwoBranchesTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/TrueOrFalseCaseRule/Statement", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the True or False case rule by ensuring that it results in two children, one that + * contains Statement as true and one that contains Statement as false. + */ + @Test + public void TwoBranchesTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/TrueOrFalseCaseRule/Statement", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(0,0); - ArrayList cases = RULE.getCases(board, cell); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, cell); - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType cellType1 = caseBoard1.getCell(0,0).getType(); - ShortTruthTableCellType cellType2 = caseBoard2.getCell(0,0).getType(); + ShortTruthTableCellType cellType1 = caseBoard1.getCell(0, 0).getType(); + ShortTruthTableCellType cellType2 = caseBoard2.getCell(0, 0).getType(); - // First assert the two cells are not equal, then verify that they are true - // or false. - Assert.assertNotEquals(cellType1, cellType2); - Assert.assertTrue(cellType1.equals(ShortTruthTableCellType.TRUE) || cellType1.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue(cellType2.equals(ShortTruthTableCellType.TRUE) || cellType2.equals(ShortTruthTableCellType.FALSE)); + // First assert the two cells are not equal, then verify that they are true + // or false. + Assert.assertNotEquals(cellType1, cellType2); + Assert.assertTrue( + cellType1.equals(ShortTruthTableCellType.TRUE) + || cellType1.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + cellType2.equals(ShortTruthTableCellType.TRUE) + || cellType2.equals(ShortTruthTableCellType.FALSE)); - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - // Verify that everywhere else on the board is unchanged - for (int i = 0; i< caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the one cell that should be different - if (i != 0 && j != 0) { - Assert.assertEquals(caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); - } - } + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the one cell that should be different + if (i != 0 && j != 0) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java b/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java index eb2b692c8..598e9fd9c 100644 --- a/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.tree.TreeNode; @@ -9,246 +8,247 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.rules.CellForNumberCaseRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.util.ArrayList; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.util.ArrayList; - public class CellForNumberCaseRuleTest { - private static final CellForNumberCaseRule RULE = new CellForNumberCaseRule(); - private static Skyscrapers skyscrapers; + private static final CellForNumberCaseRule RULE = new CellForNumberCaseRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - //basic, max cases - @Test - public void CellForNumberCaseRule_BasicEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // basic, max cases + @Test + public void CellForNumberCaseRule_BasicEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(false); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCasesFor(board,board.getNorthClues().get(0), 1); + board.setDupeFlag(false); + board.setViewFlag(false); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); - for(int i=0;i cases = RULE.getCasesFor(board,board.getNorthClues().get(0), 1); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); - for(int i=0;i cases = RULE.getCasesFor(board,board.getWestClues().get(3),1); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(1, cases.size()); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2,3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + Assert.assertEquals(1, cases.size()); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - //dupe, no cases - @Test - public void CellForNumberCaseRule_DupeNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // dupe, no cases + @Test + public void CellForNumberCaseRule_DupeNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(true); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCasesFor(board,board.getWestClues().get(3),1); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(0, cases.size()); - } + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - //visibility, max cases - @Test - public void CellForNumberCaseRule_ViewEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + Assert.assertEquals(0, cases.size()); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // visibility, max cases + @Test + public void CellForNumberCaseRule_ViewEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(false); - board.setViewFlag(true); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCasesFor(board,board.getWestClues().get(1), 1); + board.setDupeFlag(false); + board.setViewFlag(true); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(1), 1); - for(int i=0;i cases = RULE.getCasesFor(board,board.getWestClues().get(3),1); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2,3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - //visibility, 1 Case, implied - @Test - public void CellForNumberCaseRule_ImpliedViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // visibility, 1 Case, implied + @Test + public void CellForNumberCaseRule_ImpliedViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board,board.getWestClues().get(0),5); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(0), 5); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(4,0); - changedCell.setData(5); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(4, 0); + changedCell.setData(5); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - //visibility, no cases - @Test - public void CellForNumberCaseRule_ViewNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + // visibility, no cases + @Test + public void CellForNumberCaseRule_ViewNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board,board.getWestClues().get(3),1); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - Assert.assertEquals(0, cases.size()); - } -} \ No newline at end of file + Assert.assertEquals(0, cases.size()); + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java index 00cce1b91..cf74604f8 100644 --- a/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java @@ -1,150 +1,156 @@ package puzzles.skyscrapers.rules; - +import edu.rpi.legup.model.tree.TreeNode; +import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.rules.DuplicateNumberContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; import legup.MockGameBoardFacade; import legup.TestUtilities; -import edu.rpi.legup.model.tree.TreeNode; -import edu.rpi.legup.model.tree.TreeTransition; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class DuplicateNumberContradictionTest { - private static final DuplicateNumberContradictionRule RULE = new DuplicateNumberContradictionRule(); - private static Skyscrapers skyscrapers; + private static final DuplicateNumberContradictionRule RULE = + new DuplicateNumberContradictionRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - //empty - @Test - public void DuplicateNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // empty + @Test + public void DuplicateNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } - //correct board, no cont - @Test - public void DuplicateNumberContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // correct board, no cont + @Test + public void DuplicateNumberContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - //invalid board, no cont - @Test - public void DuplicateNumberContradictionRule_OtherContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // invalid board, no cont + @Test + public void DuplicateNumberContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - //on row - @Test - public void DuplicateNumberContradictionRule_RowContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if((k==0 || k==1) && i==0){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // on row + @Test + public void DuplicateNumberContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if ((k == 0 || k == 1) && i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //on col - @Test - public void DuplicateNumberContradictionRule_ColContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if(k==0 && (i==0 || i==1)){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // on col + @Test + public void DuplicateNumberContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/ColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 0 && (i == 0 || i == 1)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //multitudes - @Test - public void DuplicateNumberContradictionRule_AllContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/AllContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // multitudes + @Test + public void DuplicateNumberContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/AllContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java index c7f73c998..5fbadf555 100644 --- a/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -15,124 +14,133 @@ public class ExceedingVisibilityContradictionTest { - private static final ExceedingVisibilityContradictionRule RULE = new ExceedingVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; + private static final ExceedingVisibilityContradictionRule RULE = + new ExceedingVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - //empty - @Test - public void ExceedingVisibilityContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // empty + @Test + public void ExceedingVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //correct board, no cont - @Test - public void ExceedingVisibilityContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // correct board, no cont + @Test + public void ExceedingVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //invalid board, no cont - @Test - public void ExceedingVisibilityContradictionRule_OtherContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); + // invalid board, no cont + @Test + public void ExceedingVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } - - //on row - @Test - public void ExceedingVisibilityContradictionRule_RowContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if(i==1 || i==3){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on row + @Test + public void ExceedingVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - //on col - @Test - public void ExceedingVisibilityContradictionRule_ColContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if(i==2 || i==3){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on col + @Test + public void ExceedingVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } + } - //multitudes - @Test - public void ExceedingVisibilityContradictionRule_AllContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void ExceedingVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java index 4e90861fc..a59fa3746 100644 --- a/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -15,124 +14,133 @@ public class InsufficientVisibilityContradictionTest { - private static final InsufficientVisibilityContradictionRule RULE = new InsufficientVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; + private static final InsufficientVisibilityContradictionRule RULE = + new InsufficientVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - //empty - @Test - public void InsufficientVisibilityContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // empty + @Test + public void InsufficientVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //correct board, no cont - @Test - public void InsufficientVisibilityContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // correct board, no cont + @Test + public void InsufficientVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //invalid board, no cont - @Test - public void InsufficientVisibilityContradictionRule_OtherContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); + // invalid board, no cont + @Test + public void InsufficientVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } - - //on row - @Test - public void InsufficientVisibilityContradictionRule_RowContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if(i==1 || i==3){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on row + @Test + public void InsufficientVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - //on col - @Test - public void InsufficientVisibilityContradictionRule_ColContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if(i==2 || i==3){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on col + @Test + public void InsufficientVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } + } - //multitudes - @Test - public void InsufficientVisibilityContradictionRule_AllContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void InsufficientVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java index 855c358e8..78ba581b9 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -8,225 +7,222 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.rules.LastSingularCellDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; - public class LastSingularCellDirectTest { - private static final LastSingularCellDirectRule RULE = new LastSingularCellDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - //full row - @Test - public void LastSingularCellDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(2,3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastSingularCellDirectRule RULE = new LastSingularCellDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastSingularCellDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //full col - @Test - public void LastSingularCellDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(3,1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // full col + @Test + public void LastSingularCellDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //empty row/col - @Test - public void LastSingularCellDirectRule_EmptyTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastSingularCellDirectRule/0-3Opening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(0,1); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty row/col + @Test + public void LastSingularCellDirectRule_EmptyTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/0-3Opening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 1); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2-1 row - @Test - public void LastSingularCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(3,1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 row + @Test + public void LastSingularCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2-1 col - @Test - public void LastSingularCellDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(1,2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 col + @Test + public void LastSingularCellDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //1-2 row - @Test - public void LastSingularCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(1,1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 row + @Test + public void LastSingularCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //1-2 col - @Test - public void LastSingularCellDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(0,0); - cell.setData(4); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 col + @Test + public void LastSingularCellDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 0); + cell.setData(4); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java index f08774a8a..5cecb9b4c 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -8,138 +7,135 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.rules.LastSingularNumberDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; - public class LastSingularNumberDirectTest { - private static final LastSingularNumberDirectRule RULE = new LastSingularNumberDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - //full row / empty col - @Test - public void LastSingularNumberDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(2,3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastSingularNumberDirectRule RULE = new LastSingularNumberDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row / empty col + @Test + public void LastSingularNumberDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //full col / empty row - @Test - public void LastSingularNumberDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(3,1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // full col / empty row + @Test + public void LastSingularNumberDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2-1 row / 1-2 col - @Test - public void LastSingularNumberDirectRule_PartialRowColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(2,1); - cell.setData(4); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 row / 1-2 col + @Test + public void LastSingularNumberDirectRule_PartialRowColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 1); + cell.setData(4); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2-1 col / 1-2 row - @Test - public void LastSingularNumberDirectRule_PartialRowColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(0,2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 col / 1-2 row + @Test + public void LastSingularNumberDirectRule_PartialRowColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java index ca50bc873..3fe530a32 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -8,250 +7,245 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.rules.LastVisibleCellDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; - public class LastVisibleCellDirectTest { - private static final LastVisibleCellDirectRule RULE = new LastVisibleCellDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - //full row - @Test - public void LastVisibleCellDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(2,3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastVisibleCellDirectRule RULE = new LastVisibleCellDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastVisibleCellDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //full col - @Test - public void LastVisibleCellDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(3,1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // full col + @Test + public void LastVisibleCellDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //empty row - @Test - public void LastVisibleCellDirectRule_EmptyRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(0,2); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty row + @Test + public void LastVisibleCellDirectRule_EmptyRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //empty col - @Test - public void LastVisibleCellDirectRule_EmptyColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(3,4); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty col + @Test + public void LastVisibleCellDirectRule_EmptyColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 4); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //1-2 row - public void LastVisibleCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(1,2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 row + public void LastVisibleCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //1-2 col - public void LastVisibleCellDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(2,2); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 col + public void LastVisibleCellDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 2); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2-1 row - public void LastVisibleCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(1,1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 row + public void LastVisibleCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2-1 col - public void LastVisibleCellDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(0,2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 col + public void LastVisibleCellDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java index 1816832b6..65311f2ca 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java @@ -1,258 +1,251 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; -import edu.rpi.legup.puzzle.skyscrapers.rules.LastSingularCellDirectRule; import edu.rpi.legup.puzzle.skyscrapers.rules.LastVisibleNumberDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; - public class LastVisibleNumberDirectTest { - private static final LastVisibleNumberDirectRule RULE = new LastVisibleNumberDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - //full row - @Test - public void LastVisibleNumberDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(2,3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastVisibleNumberDirectRule RULE = new LastVisibleNumberDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastVisibleNumberDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //full col - @Test - public void LastVisibleNumberDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(3,1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // full col + @Test + public void LastVisibleNumberDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //empty row - @Test - public void LastVisibleNumberDirectRule_EmptyRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(0,2); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty row + @Test + public void LastVisibleNumberDirectRule_EmptyRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //empty col - @Test - public void LastVisibleNumberDirectRule_EmptyColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(3,4); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty col + @Test + public void LastVisibleNumberDirectRule_EmptyColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 4); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //1-2 row - public void LastVisibleNumberDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(1,2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 row + public void LastVisibleNumberDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //1-2 col - public void LastVisibleNumberDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(2,2); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 col + public void LastVisibleNumberDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 2); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2-1 row - public void LastVisibleNumberDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(1,1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 row + public void LastVisibleNumberDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2-1 col - public void LastVisibleNumberDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(0,2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 col + public void LastVisibleNumberDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java index cc39d8183..2ba6d7ad7 100644 --- a/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -8,138 +7,136 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersCell; import edu.rpi.legup.puzzle.skyscrapers.rules.NEdgeDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; - public class NEdgeDirectTest { - private static final NEdgeDirectRule RULE = new NEdgeDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); + private static final NEdgeDirectRule RULE = new NEdgeDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // -> row, empty -> full + @Test + public void NEdgeDirectRule_RightRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < 5; i++) { + SkyscrapersCell cell = board.getCell(i, 0); + cell.setData(i + 1); + board.addModifiedData(cell); } - //-> row, empty -> full - @Test - public void NEdgeDirectRule_RightRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - for(int i = 0; i < 5; i++){ - SkyscrapersCell cell = board.getCell(i,0); - cell.setData(i + 1); - board.addModifiedData(cell); - } + Assert.assertNull(RULE.checkRule(transition)); - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - if(i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //<-row, partial -> partial - @Test - public void NEdgeDirectRule_LeftRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/NEdgeDirectRule/LeftRowPartial", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - SkyscrapersCell cell = board.getCell(1,3); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if(point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // <-row, partial -> partial + @Test + public void NEdgeDirectRule_LeftRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/LeftRowPartial", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 3); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } + } + } + + // up col, partial -> full + @Test + public void NEdgeDirectRule_UpColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/UpColPartial", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < 2; i++) { + SkyscrapersCell cell = board.getCell(1, i); + cell.setData(i + 1); + board.addModifiedData(cell); } - //up col, partial -> full - @Test - public void NEdgeDirectRule_UpColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/NEdgeDirectRule/UpColPartial", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - for(int i = 0; i < 2; i++){ - SkyscrapersCell cell = board.getCell(1,i); - cell.setData(i + 1); - board.addModifiedData(cell); - } + Assert.assertNull(RULE.checkRule(transition)); - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - if(k == 1 && i < 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 1 && i < 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } + } + } + + // down col, empty -> partial + @Test + public void NEdgeDirectRule_DownColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/DownColEmpty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 1; i < 5; i++) { + SkyscrapersCell cell = board.getCell(3, i); + cell.setData(5 - i); + board.addModifiedData(cell); } - //down col, empty -> partial - @Test - public void NEdgeDirectRule_DownColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/NEdgeDirectRule/DownColEmpty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard)transition.getBoard(); - for(int i = 1; i < 5; i++){ - SkyscrapersCell cell = board.getCell(3,i); - cell.setData(5 - i); - board.addModifiedData(cell); - } + Assert.assertNull(RULE.checkRule(transition)); - Assert.assertNull(RULE.checkRule(transition)); - - for(int i = 0; i < board.getHeight(); i++) { - for(int k = 0; k < board.getWidth(); k++) { - if(k == 3 && i > 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 3 && i > 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java b/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java index 40c21e604..f4a298c7c 100644 --- a/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.gameboard.Board; import edu.rpi.legup.model.gameboard.PuzzleElement; import edu.rpi.legup.model.tree.TreeNode; @@ -9,220 +8,221 @@ import edu.rpi.legup.puzzle.skyscrapers.SkyscrapersBoard; import edu.rpi.legup.puzzle.skyscrapers.rules.NumberForCellCaseRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.util.ArrayList; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.util.ArrayList; - public class NumberForCellCaseRuleTest { - private static final NumberForCellCaseRule RULE = new NumberForCellCaseRule(); - private static Skyscrapers skyscrapers; + private static final NumberForCellCaseRule RULE = new NumberForCellCaseRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - //basic, max cases - @Test - public void NumberForCellCaseRule_BasicEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // basic, max cases + @Test + public void NumberForCellCaseRule_BasicEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(false); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCases(board,board.getCell(0,0)); + board.setDupeFlag(false); + board.setViewFlag(false); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); - for(int i=0;i cases = RULE.getCases(board,board.getCell(0,0)); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); - for(int i=0;i cases = RULE.getCases(board,board.getCell(2,3)); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(1, cases.size()); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2,3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + Assert.assertEquals(1, cases.size()); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - //dupe, no cases - @Test - public void NumberForCellCaseRule_DupeNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // dupe, no cases + @Test + public void NumberForCellCaseRule_DupeNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(true); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCases(board,board.getCell(2,3)); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(0, cases.size()); - } + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - //visibility, max cases - @Test - public void NumberForCellCaseRule_ViewEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + Assert.assertEquals(0, cases.size()); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // visibility, max cases + @Test + public void NumberForCellCaseRule_ViewEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(false); - board.setViewFlag(true); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCases(board,board.getCell(1,4)); + board.setDupeFlag(false); + board.setViewFlag(true); - Assert.assertEquals(4, cases.size()); + ArrayList cases = RULE.getCases(board, board.getCell(1, 4)); - for(int i=0;i cases = RULE.getCases(board,board.getCell(2,3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2,3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - //visibility, no cases - @Test - public void NumberForCellCaseRule_ViewNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + // visibility, no cases + @Test + public void NumberForCellCaseRule_ViewNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board,board.getCell(2,3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(0, cases.size()); - } -} \ No newline at end of file + Assert.assertEquals(0, cases.size()); + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java index 69f4e593a..b615ce7fb 100644 --- a/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -15,141 +14,155 @@ public class PreemptiveVisibilityContradictionTest { - private static final PreemptiveVisibilityContradictionRule RULE = new PreemptiveVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; + private static final PreemptiveVisibilityContradictionRule RULE = + new PreemptiveVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - //empty - @Test - public void PreemptiveVisibilityContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // empty + @Test + public void PreemptiveVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //correct board, no cont - @Test - public void PreemptiveVisibilityContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // correct board, no cont + @Test + public void PreemptiveVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //invalid board, no cont - @Test - public void PreemptiveVisibilityContradictionRule_OtherContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); + // invalid board, no cont + @Test + public void PreemptiveVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } - - //on row - @Test - public void PreemptiveVisibilityContradictionRule_RowContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if(i==1){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on row + @Test + public void PreemptiveVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - //on col - @Test - public void PreemptiveVisibilityContradictionRule_ColContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if(i==2){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on col + @Test + public void PreemptiveVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } + } - //multitudes - @Test - public void PreemptiveVisibilityContradictionRule_AllContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void PreemptiveVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //multitudes - preemptive - @Test - public void PreemptiveVisibilityContradictionRule_ImpliedAllContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", skyscrapers); + // multitudes - preemptive + @Test + public void PreemptiveVisibilityContradictionRule_ImpliedAllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java index d5f21a8d7..f9509990a 100644 --- a/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -15,141 +14,147 @@ public class UnresolvedCellContradictionTest { - private static final UnresolvedCellContradictionRule RULE = new UnresolvedCellContradictionRule(); - private static Skyscrapers skyscrapers; + private static final UnresolvedCellContradictionRule RULE = new UnresolvedCellContradictionRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - //empty - @Test - public void UnresolvedCellContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // empty + @Test + public void UnresolvedCellContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } - //correct board, no cont - @Test - public void UnresolvedCellContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // correct board, no cont + @Test + public void UnresolvedCellContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - //invalid board, no cont - @Test - public void UnresolvedCellContradictionRule_OtherContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // invalid board, no cont + @Test + public void UnresolvedCellContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - //3 in a row, 1 in col creates contradiction - @Test - public void UnresolvedCellContradictionRule_RowContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if(k==2 && i==3){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 3 in a row, 1 in col creates contradiction + @Test + public void UnresolvedCellContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 2 && i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //3 in a col, 1 in row creates contradiction - @Test - public void UnresolvedCellContradictionRule_ColContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if(k==1 && i==0){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 3 in a col, 1 in row creates contradiction + @Test + public void UnresolvedCellContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 1 && i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - //2 in a col, 2 in row creates cell contradiction - @Test - public void UnresolvedCellContradictionRule_MixedContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if(k==2 && i==3){ - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else{ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2 in a col, 2 in row creates cell contradiction + @Test + public void UnresolvedCellContradictionRule_MixedContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 2 && i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java index fe4a4865a..eb6cf566c 100644 --- a/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java @@ -1,6 +1,5 @@ package puzzles.skyscrapers.rules; - import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; import edu.rpi.legup.puzzle.skyscrapers.Skyscrapers; @@ -15,151 +14,162 @@ public class UnresolvedNumberContradictionTest { - private static final UnresolvedNumberContradictionRule RULE = new UnresolvedNumberContradictionRule(); - private static Skyscrapers skyscrapers; + private static final UnresolvedNumberContradictionRule RULE = + new UnresolvedNumberContradictionRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - //empty - @Test - public void UnresolvedNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // empty + @Test + public void UnresolvedNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //correct board, no cont - @Test - public void UnresolvedNumberContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // correct board, no cont + @Test + public void UnresolvedNumberContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - //invalid board, no cont - @Test - public void UnresolvedNumberContradictionRule_OtherContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", skyscrapers); + // invalid board, no cont + @Test + public void UnresolvedNumberContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } - - //3 in a row, 1 in col creates contradiction - @Test - public void UnresolvedNumberContradictionRule_RowContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // 3 in a row, 1 in col creates contradiction + @Test + public void UnresolvedNumberContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - //3 in a col, 1 in row creates contradiction - @Test - public void UnresolvedNumberContradictionRule_ColContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // 3 in a col, 1 in row creates contradiction + @Test + public void UnresolvedNumberContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - //2 in a row/col, 2 in other row/cols creates number contradiction - @Test - public void UnresolvedNumberContradictionRule_TwoContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2NumberContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // 2 in a row/col, 2 in other row/cols creates number contradiction + @Test + public void UnresolvedNumberContradictionRule_TwoContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2NumberContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - //1 in a row/col, 3 in other row/cols creates number contradiction - @Test - public void UnresolvedNumberContradictionRule_ThreeContradictionTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/UnresolvedContradictionRules/1-3NumberContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // 1 in a row/col, 3 in other row/cols creates number contradiction + @Test + public void UnresolvedNumberContradictionRule_ThreeContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/1-3NumberContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java index b7ec8eb02..df343b6b9 100644 --- a/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java @@ -8,265 +8,268 @@ import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.rules.EmptyFieldDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; - public class EmptyFieldDirectRuleTest { - private static final EmptyFieldDirectRule RULE = new EmptyFieldDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - // creates a 3x3 puzzle with no trees - // make the (1,1) tile GRASS - // checks if tiles logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/EmptyFieldDirectRule/EmptyField", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final EmptyFieldDirectRule RULE = new EmptyFieldDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + // creates a 3x3 puzzle with no trees + // make the (1,1) tile GRASS + // checks if tiles logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyField", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - // creates a 3x3 puzzle with 4 trees - // trees are at (0,0), (2,0), (0,2), and (2,2) - // make the (1,1) tile GRASS. - // checks if tiles logically follow the EmptyFieldDirectRule - @Test - public void DiagonalTreeTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/EmptyFieldDirectRule/DiagonalTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - //change the board's cells considering the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 4 trees + // trees are at (0,0), (2,0), (0,2), and (2,2) + // make the (1,1) tile GRASS. + // checks if tiles logically follow the EmptyFieldDirectRule + @Test + public void DiagonalTreeTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/DiagonalTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - // creates a 3x3 puzzle with 4 trees - // trees are at (0,1), (1,0), (1,2), and (2,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFail() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - //change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 4 trees + // trees are at (0,1), (1,0), (1,2), and (2,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFail() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - - // creates a 3x3 puzzle with 1 tree - // tree is at (1,0) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailTop() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailTop", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - //change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 1 tree + // tree is at (1,0) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailTop() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailTop", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - - // creates a 3x3 puzzle with 1 tree - // tree is at (1,2) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailTopBottom() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailBottom", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - //change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 1 tree + // tree is at (1,2) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailTopBottom() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailBottom", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - - // creates a 3x3 puzzle with 1 tree - // tree is at (0,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - //change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 1 tree + // tree is at (0,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - - // creates a 3x3 puzzle with 1 tree - // tree is at (2,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - //change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 1 tree + // tree is at (2,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } + } } - diff --git a/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java index 2517df563..45a1add86 100644 --- a/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java @@ -8,363 +8,361 @@ import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.rules.FinishWithGrassDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; -import java.util.List; -import java.util.ArrayList; - public class FinishWithGrassDirectRuleTest { - private static final FinishWithGrassDirectRule RULE = new FinishWithGrassDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) - * Tests FinishWithGrassDirectRule on GRASS tiles horizontal of the tent - * at (1,0) and (2,0) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassHorizontalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) || c.getLocation().equals(cell2.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final FinishWithGrassDirectRule RULE = new FinishWithGrassDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles + * horizontal of the tent at (1,0) and (2,0) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassHorizontalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) - * Tests FinishWithGrassDirectRule on GRASS tiles vertical of the tent - * at (0,1) and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassVerticalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) || c.getLocation().equals(cell2.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles + * vertical of the tent at (0,1) and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassVerticalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) - * Tests FinishWithGrassDirectRule on GRASS tiles - * at (1,0), (2,0), (0,1), and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.GRASS); - TreeTentCell cell3 = board.getCell(0, 1); - cell3.setData(TreeTentType.GRASS); - TreeTentCell cell4 = board.getCell(0, 2); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) || - c.getLocation().equals(cell2.getLocation()) || - c.getLocation().equals(cell3.getLocation()) || - c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles at + * (1,0), (2,0), (0,1), and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.GRASS); + TreeTentCell cell3 = board.getCell(0, 1); + cell3.setData(TreeTentType.GRASS); + TreeTentCell cell4 = board.getCell(0, 2); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } + } + } + + /** + * 3x3 TreeTent puzzle with no tents Tests FinishWithGrassDirectRule on GRASS tiles GRASS tiles + * fill entire board + * + * @throws InvalidFileFormatException + */ + @Test + public void NoTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/NoTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + List cells = new ArrayList(); + for (int i = 0; i < board.getWidth(); i++) { + for (int k = 0; k < board.getHeight(); k++) { + TreeTentCell c = board.getCell(i, k); + c.setData(TreeTentType.GRASS); + cells.add(c); + } } - /** - * 3x3 TreeTent puzzle with no tents - * Tests FinishWithGrassDirectRule on GRASS tiles - * GRASS tiles fill entire board - * - * @throws InvalidFileFormatException - */ - @Test - public void NoTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithGrassDirectRule/NoTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - List cells = new ArrayList(); - for (int i = 0; i < board.getWidth(); i++) { - for (int k = 0; k < board.getHeight(); k++) { - TreeTentCell c = board.getCell(i, k); - c.setData(TreeTentType.GRASS); - cells.add(c); - } - } - - for (TreeTentCell c : cells) { - board.addModifiedData(c); - } + for (TreeTentCell c : cells) { + board.addModifiedData(c); + } - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); - // all cells should change following the rule - for (TreeTentCell c : cells) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } + // all cells should change following the rule + for (TreeTentCell c : cells) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); } - /** - * 3x3 TreeTent puzzle with a tent at (1,1) - * Tests FinishWithGrassDirectRule on GRASS tiles surrounding the tent - * at (1,0), (0,1), (2,1), and (1,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void MiddleTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithGrassDirectRule/MiddleTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(0, 1); - TreeTentCell cell3 = board.getCell(2, 1); - TreeTentCell cell4 = board.getCell(1, 2); - - cell1.setData(TreeTentType.GRASS); - cell2.setData(TreeTentType.GRASS); - cell3.setData(TreeTentType.GRASS); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) || - c.getLocation().equals(cell2.getLocation()) || - c.getLocation().equals(cell3.getLocation()) || - c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a tent at (1,1) Tests FinishWithGrassDirectRule on GRASS tiles + * surrounding the tent at (1,0), (0,1), (2,1), and (1,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void MiddleTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/MiddleTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(0, 1); + TreeTentCell cell3 = board.getCell(2, 1); + TreeTentCell cell4 = board.getCell(1, 2); + + cell1.setData(TreeTentType.GRASS); + cell2.setData(TreeTentType.GRASS); + cell3.setData(TreeTentType.GRASS); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } + } + } + + /** + * 3x3 TreeTent puzzle with missing tents Tests FinishWithGrassDirectRule on GRASS tiles filling + * the puzzle all GRASS tiles should fail the FinishWithGrassDirectRule + * + * @throws InvalidFileFormatException + */ + @Test + public void FailTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/FailTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells not following the FinishWithGrass rule + List cells = new ArrayList(); + for (int i = 0; i < board.getWidth(); i++) { + for (int k = 0; k < board.getHeight(); k++) { + TreeTentCell c = board.getCell(i, k); + c.setData(TreeTentType.GRASS); + cells.add(c); + } } - /** - * 3x3 TreeTent puzzle with missing tents - * Tests FinishWithGrassDirectRule on GRASS tiles filling the puzzle - * all GRASS tiles should fail the FinishWithGrassDirectRule - * - * @throws InvalidFileFormatException - */ - @Test - public void FailTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithGrassDirectRule/FailTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells not following the FinishWithGrass rule - List cells = new ArrayList(); - for (int i = 0; i < board.getWidth(); i++) { - for (int k = 0; k < board.getHeight(); k++) { - TreeTentCell c = board.getCell(i, k); - c.setData(TreeTentType.GRASS); - cells.add(c); - } - } - - for (TreeTentCell c : cells) { - board.addModifiedData(c); - } + for (TreeTentCell c : cells) { + board.addModifiedData(c); + } - // confirm there is a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); + // confirm there is a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); - // all cells should fail the rule test - for (TreeTentCell c : cells) { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + // all cells should fail the rule test + for (TreeTentCell c : cells) { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } - /** - * 7x7 TreeTent puzzle with multiple tents spaced out - * Tests FinishWithGrassDirectRule on GRASS tiles between the tents - * at (0,3), (2,3), (4,3), and (6,3) - * - * @throws InvalidFileFormatException - */ - @Test - public void SpacedOutTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithGrassDirectRule/SpacedOutTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(0, 3); - TreeTentCell cell2 = board.getCell(2, 3); - TreeTentCell cell3 = board.getCell(4, 3); - TreeTentCell cell4 = board.getCell(6, 3); - - cell1.setData(TreeTentType.GRASS); - cell2.setData(TreeTentType.GRASS); - cell3.setData(TreeTentType.GRASS); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) || - c.getLocation().equals(cell2.getLocation()) || - c.getLocation().equals(cell3.getLocation()) || - c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 7x7 TreeTent puzzle with multiple tents spaced out Tests FinishWithGrassDirectRule on GRASS + * tiles between the tents at (0,3), (2,3), (4,3), and (6,3) + * + * @throws InvalidFileFormatException + */ + @Test + public void SpacedOutTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/SpacedOutTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(0, 3); + TreeTentCell cell2 = board.getCell(2, 3); + TreeTentCell cell3 = board.getCell(4, 3); + TreeTentCell cell4 = board.getCell(6, 3); + + cell1.setData(TreeTentType.GRASS); + cell2.setData(TreeTentType.GRASS); + cell3.setData(TreeTentType.GRASS); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } -} \ No newline at end of file + } +} diff --git a/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java index 725c3c9de..9903a9685 100644 --- a/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java @@ -8,354 +8,345 @@ import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.rules.FinishWithTentsDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; +import java.util.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; -import java.util.*; - public class FinishWithTentsDirectRuleTest { - private static final FinishWithTentsDirectRule RULE = new FinishWithTentsDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (0,0) - * Tests FinishWithTentsDirectRule on TENT tiles horizontal of the GRASS tile - * at (1,0) and (2,0) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithHorizontalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithHorizontalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.TENT); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) || (c.getLocation()).equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final FinishWithTentsDirectRule RULE = new FinishWithTentsDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles + * horizontal of the GRASS tile at (1,0) and (2,0) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithHorizontalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithHorizontalTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.TENT); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (0,0) - * Tests FinishWithTentsDirectRule on TENT tiles vertical of the GRASS tile - * at (0,1) and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithVerticalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithVerticalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.TENT); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) || (c.getLocation()).equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles + * vertical of the GRASS tile at (0,1) and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithVerticalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithVerticalTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.TENT); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (1,1) - * Tests FinishWithTentsDirectRule on TENT tiles around the GRASS tile - * at (1,0), (1,2), (0,1), and (2,1) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 2); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(2, 1); - - cell1.setData(TreeTentType.TENT); - cell2.setData(TreeTentType.TENT); - cell3.setData(TreeTentType.TENT); - cell4.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) || - (c.getLocation()).equals(cell2.getLocation()) || - (c.getLocation()).equals(cell3.getLocation()) || - (c.getLocation()).equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the GRASS tile at (1,0), (1,2), (0,1), and (2,1) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 2); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(2, 1); + + cell1.setData(TreeTentType.TENT); + cell2.setData(TreeTentType.TENT); + cell3.setData(TreeTentType.TENT); + cell4.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation()) + || (c.getLocation()).equals(cell3.getLocation()) + || (c.getLocation()).equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) - * Tests FinishWithTentsDirectRule on TENT tiles around the TENT tile - * at (1,0), (1,2), (0,1), and (2,1) - * - * @throws InvalidFileFormatException - */ - @Test - public void AdditionalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithTentsDirectRule/AdditionalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 2); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(2, 1); - - cell1.setData(TreeTentType.TENT); - cell2.setData(TreeTentType.TENT); - cell3.setData(TreeTentType.TENT); - cell4.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) || - (c.getLocation()).equals(cell2.getLocation()) || - (c.getLocation()).equals(cell3.getLocation()) || - (c.getLocation()).equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) + * + * @throws InvalidFileFormatException + */ + @Test + public void AdditionalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/AdditionalTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 2); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(2, 1); + + cell1.setData(TreeTentType.TENT); + cell2.setData(TreeTentType.TENT); + cell3.setData(TreeTentType.TENT); + cell4.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation()) + || (c.getLocation()).equals(cell3.getLocation()) + || (c.getLocation()).equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } + } + } + + /** + * Empty 3x3 TreeTent puzzle Tests FinishWithTentsDirectRule on TENT tiles of entire puzzle all + * TENT tiles should fail FinishWithTentsDirectRule as no TENT tiles should be there + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithTentsFailTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTentsFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + ArrayList cells = new ArrayList(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + c.setData(TreeTentType.TENT); + board.addModifiedData(c); + cells.add(c); + } } - /** - * Empty 3x3 TreeTent puzzle - * Tests FinishWithTentsDirectRule on TENT tiles of entire puzzle - * all TENT tiles should fail FinishWithTentsDirectRule - * as no TENT tiles should be there - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithTentsFailTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTentsFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - ArrayList cells = new ArrayList(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - c.setData(TreeTentType.TENT); - board.addModifiedData(c); - cells.add(c); - } - } - - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) - * Tests FinishWithTentsDirectRule on TENT tiles around the TENT tile - * at (1,0), (1,2), (0,1), and (2,1) - * all TENT tiles should fail FinishWithTentsDirectRule - * as there were already sufficient number of TENT tiles - * - * @throws InvalidFileFormatException - */ - @Test - public void TooManyTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithTentsDirectRule/TooManyTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - ArrayList cells = new ArrayList(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if((k == 1)&&(i == 1)) { - continue; - } - TreeTentCell c = board.getCell(k, i); - c.setData(TreeTentType.TENT); - board.addModifiedData(c); - cells.add(c); - } + } + + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail + * FinishWithTentsDirectRule as there were already sufficient number of TENT tiles + * + * @throws InvalidFileFormatException + */ + @Test + public void TooManyTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/TooManyTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + ArrayList cells = new ArrayList(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if ((k == 1) && (i == 1)) { + continue; } + TreeTentCell c = board.getCell(k, i); + c.setData(TreeTentType.TENT); + board.addModifiedData(c); + cells.add(c); + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } + } + + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail + * FinishWithTentsDirectRule as there are multiple configurations of the placement of the TENT + * tiles + * + * @throws InvalidFileFormatException + */ + @Test + public void AmbiguousTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/AmbiguousTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell = board.getCell(0, 1); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) - * Tests FinishWithTentsDirectRule on TENT tiles around the TENT tile - * at (1,0), (1,2), (0,1), and (2,1) - * all TENT tiles should fail FinishWithTentsDirectRule - * as there are multiple configurations of the placement - * of the TENT tiles - * - * @throws InvalidFileFormatException - */ - @Test - public void AmbiguousTentsTest () throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/FinishWithTentsDirectRule/AmbiguousTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell = board.getCell(0, 1); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(1, 0); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(1, 0); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(2, 1); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(2, 1); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(1, 2); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(1, 2); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } - - - diff --git a/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java index 3e1b390fb..b3a1de6d5 100644 --- a/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java @@ -8,161 +8,157 @@ import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.rules.LastCampingSpotDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; - public class LastCampingSpotDirectRuleTest { - private static final LastCampingSpotDirectRule RULE = new LastCampingSpotDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException - * - * Checks if a test works for an empty square above a tree which is surrounded on all other sides. - */ - @Test - public void EmptyFieldTest_Up() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotUp", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastCampingSpotDirectRule RULE = new LastCampingSpotDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square above a tree which is surrounded on all other + * sides. + */ + @Test + public void EmptyFieldTest_Up() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotUp", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * - * Checks if a test works for an empty square below a tree which is surrounded on all other sides. - */ - @Test - public void EmptyFieldTest_Down() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotDown", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 2); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square below a tree which is surrounded on all other + * sides. + */ + @Test + public void EmptyFieldTest_Down() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotDown", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 2); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * - * Checks if a test works for an empty square to the left of a tree which is surrounded on all other sides. - */ - @Test - public void EmptyFieldTest_Left() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square to the left of a tree which is surrounded on + * all other sides. + */ + @Test + public void EmptyFieldTest_Left() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * - * Checks if a test works for an empty square to the right of a tree which is surrounded on all other sides. - */ - @Test - public void EmptyFieldTest_Right() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(2, 1); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square to the right of a tree which is surrounded on + * all other sides. + */ + @Test + public void EmptyFieldTest_Right() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(2, 1); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } - - - diff --git a/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java index 52aea28c0..8d099f283 100644 --- a/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java @@ -1,111 +1,110 @@ package puzzles.treetent.rules; -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.rpi.legup.puzzle.treetent.TreeTent; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.rules.NoTentForTreeContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; - import java.awt.*; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class NoTentForTreeContradictionRuleTest { - private static final NoTentForTreeContradictionRule RULE = new NoTentForTreeContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException - * Tests if a tree is next to only grass in a 2x2 grid triggers the contradiction - */ - @Test - public void NoTentForTreeContradictionRule_Basic() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException - * Tests similarly to above, but now with a tent diagonally next to the tree, which should still contradict - */ - @Test - public void NoTentForTreeContradictionRule_Diagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeDiagonal", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException - * Tests that adjacent trees do not allow a pass - */ - @Test - public void NoTentForTreeContradictionRule_TwoTrees() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTrees", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException - * Tests similarly to above, but now with a tent diagonally next to two trees, which should still contradict on one. - */ - @Test - public void NoTentForTreeContradictionRule_TwoTreesDiagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTreesDiagonal", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } + private static final NoTentForTreeContradictionRule RULE = new NoTentForTreeContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Tests if a tree is next to only grass in a 2x2 grid triggers + * the contradiction + */ + @Test + public void NoTentForTreeContradictionRule_Basic() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally + * next to the tree, which should still contradict + */ + @Test + public void NoTentForTreeContradictionRule_Diagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeDiagonal", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests that adjacent trees do not allow a pass + */ + @Test + public void NoTentForTreeContradictionRule_TwoTrees() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTrees", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally + * next to two trees, which should still contradict on one. + */ + @Test + public void NoTentForTreeContradictionRule_TwoTreesDiagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTreesDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } } - diff --git a/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java index 2ad2ac90e..c639b2a25 100644 --- a/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java @@ -1,207 +1,214 @@ package puzzles.treetent.rules; -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.rpi.legup.puzzle.treetent.TreeTent; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.rules.NoTreeForTentContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class NoTreeForTentContradictionRuleTest { - private static final NoTreeForTentContradictionRule RULE = new NoTreeForTentContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException - * Tests if, in a 2x2 Grid, a Tent in the NW corner has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_NW() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNW", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException - * Tests if, in a 2x2 Grid, a Tent in the NE corner has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_NE() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNE", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException - * Tests if, in a 2x2 Grid, a Tent in the NW corner has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_SW() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSW", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException - * Tests if, in a 2x2 Grid, a Tent in the SE corner has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_SE() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSE", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException - * Tests if, in a 3x3 Grid with no trees, a Tent in the center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_3x3() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTent3x3", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException - * Tests if, in a 3x3 Grid with diagonal trees, a Tent in the center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_3x3WithDiagonalTrees() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentDiagonals", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException - * Tests if, in a 3x3 Grid with an adjacent tree, test does not assert null. - */ - @Test - public void NoTreeForTentContradictionRule_YesTree() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentYesTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException - * Tests if, in a 3x3 Grid with touching tents, a Tent in the center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_JustTent() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentJustTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } + private static final NoTreeForTentContradictionRule RULE = new NoTreeForTentContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_NW() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNW", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NE corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_NE() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNE", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_SW() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSW", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the SE corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_SE() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSE", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with no trees, a Tent in the center + * cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_3x3() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTent3x3", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with diagonal trees, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_3x3WithDiagonalTrees() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentDiagonals", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with an adjacent tree, test does not + * assert null. + */ + @Test + public void NoTreeForTentContradictionRule_YesTree() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentYesTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with touching tents, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_JustTent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentJustTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } } - diff --git a/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java index 999405747..e48fd0979 100644 --- a/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java @@ -8,145 +8,147 @@ import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.rules.SurroundTentWithGrassDirectRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; - public class SurroundTentWithGrassDirectRuleTest { - private static final SurroundTentWithGrassDirectRule RULE = new SurroundTentWithGrassDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException - * Test to check if all adjacent and diagonals not filled with a tree are filled with grass - */ - @Test - public void SurroundTentWithGrassBasicRuleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrass", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final SurroundTentWithGrassDirectRule RULE = new SurroundTentWithGrassDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Test to check if all adjacent and diagonals not filled with + * a tree are filled with grass + */ + @Test + public void SurroundTentWithGrassBasicRuleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrass", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * - * Test with a 3x3 board with an absolutely empty area aside from a tent in the middle - * While such a situation is an illegal treetent setup, this direct rule doesn't consider that aspect, so its ok in this context - */ - @Test - public void SurroundTentWithGrassBasicRuleTest_BadBoard() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassBad", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(1, 0); - cell2.setData(TreeTentType.GRASS); - TreeTentCell cell3 = board.getCell(2, 0); - cell3.setData(TreeTentType.GRASS); - TreeTentCell cell4 = board.getCell(0, 1); - cell4.setData(TreeTentType.GRASS); - //Skip (1,1) due to being the Tent - TreeTentCell cell5 = board.getCell(2, 1); - cell5.setData(TreeTentType.GRASS); - TreeTentCell cell6 = board.getCell(0, 2); - cell6.setData(TreeTentType.GRASS); - TreeTentCell cell7 = board.getCell(1, 2); - cell7.setData(TreeTentType.GRASS); - TreeTentCell cell8 = board.getCell(2, 2); - cell8.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - //board.addModifiedData(cell4); - board.addModifiedData(cell5); - board.addModifiedData(cell6); - board.addModifiedData(cell7); - board.addModifiedData(cell8); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation()) || - point.equals(cell3.getLocation()) || //point.equals(cell4.getLocation()) || - point.equals(cell5.getLocation()) || point.equals(cell6.getLocation()) || - point.equals(cell7.getLocation()) || point.equals(cell8.getLocation()) - ) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Test with a 3x3 board with an absolutely empty area aside from a tent in the middle + * While such a situation is an illegal treetent setup, this direct rule doesn't consider that + * aspect, so its ok in this context + */ + @Test + public void SurroundTentWithGrassBasicRuleTest_BadBoard() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassBad", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(1, 0); + cell2.setData(TreeTentType.GRASS); + TreeTentCell cell3 = board.getCell(2, 0); + cell3.setData(TreeTentType.GRASS); + TreeTentCell cell4 = board.getCell(0, 1); + cell4.setData(TreeTentType.GRASS); + // Skip (1,1) due to being the Tent + TreeTentCell cell5 = board.getCell(2, 1); + cell5.setData(TreeTentType.GRASS); + TreeTentCell cell6 = board.getCell(0, 2); + cell6.setData(TreeTentType.GRASS); + TreeTentCell cell7 = board.getCell(1, 2); + cell7.setData(TreeTentType.GRASS); + TreeTentCell cell8 = board.getCell(2, 2); + cell8.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + // board.addModifiedData(cell4); + board.addModifiedData(cell5); + board.addModifiedData(cell6); + board.addModifiedData(cell7); + board.addModifiedData(cell8); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || // point.equals(cell4.getLocation()) || + point.equals(cell5.getLocation()) + || point.equals(cell6.getLocation()) + || point.equals(cell7.getLocation()) + || point.equals(cell8.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * - * Test to see if the rule passes even if no grass was able to be placed due to the presence of trees. - */ - @Test - public void SurroundTentWithGrassBasicRuleTest_FullBoard() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassTrees", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++){ - for (int k = 0; k < board.getWidth(); k++){ - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Test to see if the rule passes even if no grass was able to be placed due to the + * presence of trees. + */ + @Test + public void SurroundTentWithGrassBasicRuleTest_FullBoard() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassTrees", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } - - - diff --git a/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java index 33f37910c..237013212 100644 --- a/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java @@ -3,15 +3,12 @@ // This feature is no longer supported public class TentForTreeDirectRuleTest { -// private static final TentForTreeBasicRule RULE = new TentForTreeBasicRule(); -// private static TreeTent treetent; -// -// @BeforeClass -// public static void setUp() { -// MockGameBoardFacade.getInstance(); -// treetent = new TreeTent(); -// } + // private static final TentForTreeBasicRule RULE = new TentForTreeBasicRule(); + // private static TreeTent treetent; + // + // @BeforeClass + // public static void setUp() { + // MockGameBoardFacade.getInstance(); + // treetent = new TreeTent(); + // } } - - - diff --git a/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java b/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java index 4ec8b4e36..1f08fa597 100644 --- a/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java @@ -9,75 +9,71 @@ import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.rules.TentOrGrassCaseRule; import edu.rpi.legup.save.InvalidFileFormatException; +import java.awt.*; +import java.util.ArrayList; import legup.MockGameBoardFacade; import legup.TestUtilities; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.awt.*; -import java.util.ArrayList; - public class TentOrGrassCaseRuleTest { - private static final TentOrGrassCaseRule RULE = new TentOrGrassCaseRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } + private static final TentOrGrassCaseRule RULE = new TentOrGrassCaseRule(); + private static TreeTent treetent; - /** - * empty 3x3 TreeTent puzzle - * Tests TentOrGrassCaseRule on UNKOWN tile - * at (0,0) - * - * checks 2 cases are created - * checks first case is TENT tile - * checks second case is GRASS tile - * checks other cells have not been modified - * - * @throws InvalidFileFormatException - */ - @Test - public void TentOrTreeTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TentOrGrassCaseRule/TestPuzzle", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentCell testing_cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, testing_cell); + /** + * empty 3x3 TreeTent puzzle Tests TentOrGrassCaseRule on UNKOWN tile at (0,0) + * + *

checks 2 cases are created checks first case is TENT tile checks second case is GRASS tile + * checks other cells have not been modified + * + * @throws InvalidFileFormatException + */ + @Test + public void TentOrTreeTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TentOrGrassCaseRule/TestPuzzle", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // assert correct number of cases created - Assert.assertEquals(2, cases.size()); + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentCell testing_cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, testing_cell); - // TENT case - TreeTentBoard tentCase = (TreeTentBoard) cases.get(0); - Assert.assertEquals(tentCase.getCell(0, 0).getType(), TreeTentType.TENT); + // assert correct number of cases created + Assert.assertEquals(2, cases.size()); - // GRASS case - TreeTentBoard grassCase = (TreeTentBoard) cases.get(1); - Assert.assertEquals(grassCase.getCell(0, 0).getType(), TreeTentType.GRASS); + // TENT case + TreeTentBoard tentCase = (TreeTentBoard) cases.get(0); + Assert.assertEquals(tentCase.getCell(0, 0).getType(), TreeTentType.TENT); - // checks other cells have not been modified - TreeTentCell original_cell; - TreeTentCell case_cell; + // GRASS case + TreeTentBoard grassCase = (TreeTentBoard) cases.get(1); + Assert.assertEquals(grassCase.getCell(0, 0).getType(), TreeTentType.GRASS); - for (int w =0; w < board.getWidth(); w++) { - for (int h = 0; h < board.getHeight(); h++) { - if (w == 0 && h ==0) { - continue; - } - original_cell = board.getCell(w, h); - case_cell = tentCase.getCell(w, h); - Assert.assertEquals(original_cell.getType(), case_cell.getType()); + // checks other cells have not been modified + TreeTentCell original_cell; + TreeTentCell case_cell; - case_cell = grassCase.getCell(w, h); - Assert.assertEquals(original_cell.getType(), case_cell.getType()); - } + for (int w = 0; w < board.getWidth(); w++) { + for (int h = 0; h < board.getHeight(); h++) { + if (w == 0 && h == 0) { + continue; } + original_cell = board.getCell(w, h); + case_cell = tentCase.getCell(w, h); + Assert.assertEquals(original_cell.getType(), case_cell.getType()); + + case_cell = grassCase.getCell(w, h); + Assert.assertEquals(original_cell.getType(), case_cell.getType()); + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java index a5999dc6e..f08d87a3b 100644 --- a/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java @@ -1,251 +1,240 @@ package puzzles.treetent.rules; -import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.rpi.legup.puzzle.treetent.TreeTent; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; +import edu.rpi.legup.puzzle.treetent.TreeTentCell; import edu.rpi.legup.puzzle.treetent.rules.TooFewTentsContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; - import java.awt.*; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class TooFewTentsContradictionRuleTest { - private static final TooFewTentsContradictionRule RULE = new TooFewTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException - * Using a 1x1 Puzzle Grid, which is just grass, checks if the fact it expects a tent on the y-axis is caught. - */ - @Test - public void TooFewTentsContradictionRule_JustY() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsJustY", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException - * Using a 1x1 Puzzle Grid, which is just a tent, checks if the fact it expects 2 tents on the y-axis is caught. - * (This is an impossible situation given the constraints, but for the purposes of the test it is fine) - */ - @Test - public void TooFewTentsContradictionRule_WithTent() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsWithTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException - * Using a 1x1 Puzzle Grid, which is just grass, checks if the fact it expects a tent on both x and y is caught. - */ - @Test - public void TooFewTentsContradictionRule_DoubleBad() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsDoubleBad", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException - * Looks at a 2x2 Board in the format: - * [] Tr - * [] Gr - * Column 2 is checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_2x2ColumnOnly() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Column",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(1,0); - TreeTentCell cell2 = board.getCell(1,1); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final TooFewTentsContradictionRule RULE = new TooFewTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if the + * fact it expects a tent on the y-axis is caught. + */ + @Test + public void TooFewTentsContradictionRule_JustY() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsJustY", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just a tent, checks if the + * fact it expects 2 tents on the y-axis is caught. (This is an impossible situation given the + * constraints, but for the purposes of the test it is fine) + */ + @Test + public void TooFewTentsContradictionRule_WithTent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsWithTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if the + * fact it expects a tent on both x and y is caught. + */ + @Test + public void TooFewTentsContradictionRule_DoubleBad() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsDoubleBad", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: [] Tr [] Gr Column 2 is + * checked to have 1 Tent (which is not present, thus producing a contradiction) + */ + @Test + public void TooFewTentsContradictionRule_2x2ColumnOnly() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Column", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 1); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Looks at a 2x2 Board in the format: - * Tr Gr - * [] [] - * Row 1 is checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_2x2RowOnly() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Row",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(0,0); - TreeTentCell cell2 = board.getCell(1,0); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tr Gr [] [] Row 1 is + * checked to have 1 Tent (which is not present, thus producing a contradiction) + */ + @Test + public void TooFewTentsContradictionRule_2x2RowOnly() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Row", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(1, 0); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Looks at a 3x3 Board in the format: - * [] Tr [] - * [] Gr [] - * [] Gr [] - * Column 2 is checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_3x3OneColumn() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3Column",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(1,0); - TreeTentCell cell2 = board.getCell(1,1); - TreeTentCell cell3 = board.getCell(1,2); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation()) || point.equals(cell3.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: [] Tr [] [] Gr [] [] Gr + * [] Column 2 is checked to have 1 Tent (which is not present, thus producing a + * contradiction) + */ + @Test + public void TooFewTentsContradictionRule_3x3OneColumn() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3Column", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 1); + TreeTentCell cell3 = board.getCell(1, 2); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Looks at a 3x3 Board in the format: - * Gr Tr Gr - * Gr [] Gr - * Gr Tr Gr - * Column 1 and 3 are checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_3x3TwoColumn() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3DoubleColumn",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(0,0); - TreeTentCell cell2 = board.getCell(0,1); - TreeTentCell cell3 = board.getCell(0,2); - TreeTentCell cell4 = board.getCell(2,0); - TreeTentCell cell5 = board.getCell(2,1); - TreeTentCell cell6 = board.getCell(2,2); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation()) || point.equals(cell3.getLocation()) || - point.equals(cell4.getLocation()) || point.equals(cell5.getLocation()) || point.equals(cell6.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: Gr Tr Gr Gr [] Gr Gr Tr + * Gr Column 1 and 3 are checked to have 1 Tent (which is not present, thus producing a + * contradiction) + */ + @Test + public void TooFewTentsContradictionRule_3x3TwoColumn() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3DoubleColumn", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(0, 1); + TreeTentCell cell3 = board.getCell(0, 2); + TreeTentCell cell4 = board.getCell(2, 0); + TreeTentCell cell5 = board.getCell(2, 1); + TreeTentCell cell6 = board.getCell(2, 2); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation()) + || point.equals(cell5.getLocation()) + || point.equals(cell6.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Looks at a 2x2 Board in the format: - * Tn [] - * Tr [] - * This should fail the contradiction as it is a legal board. - */ - @Test - public void TooFewTentsContradictionRule_NoContradiction() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsNoContradiction",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tn [] Tr [] This should + * fail the contradiction as it is a legal board. + */ + @Test + public void TooFewTentsContradictionRule_NoContradiction() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsNoContradiction", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - - + } } - diff --git a/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java index 2a351556b..fb94aa006 100644 --- a/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java @@ -1,275 +1,261 @@ package puzzles.treetent.rules; -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.rpi.legup.puzzle.treetent.TreeTent; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.TreeTentCell; -import edu.rpi.legup.puzzle.treetent.TreeTentType; import edu.rpi.legup.puzzle.treetent.rules.TooManyTentsContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; - import java.awt.*; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class TooManyTentsContradictionRuleTest { - private static final TooManyTentsContradictionRule RULE = new TooManyTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /* - TESTING BASIS: - All test in this Rule use a 3x3 table. - There is a Tree at (1,1) - There are tents at (0,1) and (2,2) - All Tent Counts are listed left to right or top to bottom - */ - - /** - * @throws InvalidFileFormatException - * Tests for TooManyTents if: - * Row Tent Counts: 0,0,0 - * Column Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_TotalFail() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTotalFail",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0,1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final TooManyTentsContradictionRule RULE = new TooManyTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /* + TESTING BASIS: + All test in this Rule use a 3x3 table. + There is a Tree at (1,1) + There are tents at (0,1) and (2,2) + All Tent Counts are listed left to right or top to bottom + */ + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_TotalFail() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTotalFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Tests for TooManyTents if: - * Row Tent Counts: 1,0,0 - * Column Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_TopRight() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopRight",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0,0); - TreeTentCell cell2 = board.getCell(0,1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 1,0,0 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_TopRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(0, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Tests for TooManyTests if: - * Row Tent Counts: 0,0,1 - * Column Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_BottomRight() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomRight",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0,1); - TreeTentCell cell2 = board.getCell(0,2); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTests if: Row Tent Counts: 0,0,1 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_BottomRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(0, 2); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Tests for TooManyTents if: - * Row Tent Counts: 0,0,0 - * Column Tent Counts: 0,1,0 - */ - @Test - public void TooManyTentsContradictionRule_TopDown() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopDown",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0,1); - TreeTentCell cell2 = board.getCell(1,1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,1,0 + */ + @Test + public void TooManyTentsContradictionRule_TopDown() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopDown", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(1, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Tests for TooManyTents if: - * Row Tent Counts: 0,0,0 - * Column Tent Counts: 0,0,1 - */ - @Test - public void TooManyTentsContradictionRule_BottomDown() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomDown",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0,1); - TreeTentCell cell2 = board.getCell(2,1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,0,1 + */ + @Test + public void TooManyTentsContradictionRule_BottomDown() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomDown", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(2, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Tests for TooManyTents if the Top Tent is completely accounted for, but not the bottom - * Row Tent Counts: 1,0,0 - * Column Tent Counts: 0,1,0 - */ - @Test - public void TooManyTentsContradictionRule_TopAccount() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopAccount",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0,0); - TreeTentCell cell2 = board.getCell(1,0); - TreeTentCell cell3 = board.getCell(0,1); - TreeTentCell cell4 = board.getCell(1,1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation()) || - point.equals(cell3.getLocation()) || point.equals(cell4.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if the Top Tent is completely + * accounted for, but not the bottom Row Tent Counts: 1,0,0 Column Tent Counts: 0,1,0 + */ + @Test + public void TooManyTentsContradictionRule_TopAccount() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopAccount", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(1, 0); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(1, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - * Tests for TooManyTents if the Bottom Tent is completely accounted for, but not the Top - * Row Tent Counts: 0,0,1 - * Column Tent Counts: 0,0,1 - */ - @Test - public void TooManyTentsContradictionRule_BottomAccount() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomAccount",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0,1); - TreeTentCell cell2 = board.getCell(2,1); - TreeTentCell cell3 = board.getCell(0,2); - TreeTentCell cell4 = board.getCell(2,2); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation()) || - point.equals(cell3.getLocation()) || point.equals(cell4.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if the Bottom Tent is completely + * accounted for, but not the Top Row Tent Counts: 0,0,1 Column Tent Counts: 0,0,1 + */ + @Test + public void TooManyTentsContradictionRule_BottomAccount() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomAccount", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(2, 1); + TreeTentCell cell3 = board.getCell(0, 2); + TreeTentCell cell4 = board.getCell(2, 2); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } - diff --git a/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java index f48afe5d7..6018b6853 100644 --- a/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java @@ -1,249 +1,252 @@ package puzzles.treetent.rules; -import legup.MockGameBoardFacade; -import legup.TestUtilities; import edu.rpi.legup.model.tree.TreeNode; import edu.rpi.legup.model.tree.TreeTransition; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import edu.rpi.legup.puzzle.treetent.TreeTent; import edu.rpi.legup.puzzle.treetent.TreeTentBoard; import edu.rpi.legup.puzzle.treetent.rules.TouchingTentsContradictionRule; import edu.rpi.legup.save.InvalidFileFormatException; +import legup.MockGameBoardFacade; +import legup.TestUtilities; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; public class TouchingTentsContradictionRuleTest { - private static final TouchingTentsContradictionRule RULE = new TouchingTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - //DIAGONAL TESTS - /** - * @throws InvalidFileFormatException - * Tests a tent diagonal of orientation T - * T - **/ - @Test - public void TouchingTentsContradictionRule_DiagonalUpLeftToDownRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonal", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - - /** - * @throws InvalidFileFormatException - * Tests a tent diagonal of orientation T - * T - **/ - @Test - public void TouchingTentsContradictionRule_DiagonalDownLeftToUpRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonalAlt",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition,board.getCell(1,0))); - Assert.assertNull(RULE.checkRuleAt(transition,board.getCell(0,1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - //ADJACENT TESTS - /** - * @throws InvalidFileFormatException - * Tests a tent adjacent of orientation T - * T - **/ - @Test - public void TouchingTentsContradictionRule_AdjacentVertical() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException - * Tests a tent adjacent of orientation TT - **/ - @Test - public void TouchingTentsContradictionRule_AdjacentHorizontal() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacentAlt", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - //MIXED TESTS - /** - * @throws InvalidFileFormatException - * Tests a tent of orientation TT - * TT - **/ - @Test - public void TouchingTentsContradictionRule_2By2Square() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsFull2By2",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - /** - * @throws InvalidFileFormatException - * Tests a tent of orientation TT - * T - **/ - @Test - public void TouchingTentsContradictionRule_UpLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpLeft",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - /** - * @throws InvalidFileFormatException - * Tests a tent of orientation TT - * T - **/ - @Test - public void TouchingTentsContradictionRule_UpRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpRight",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - /** - * @throws InvalidFileFormatException - * Tests a tent of orientation T - * TT - **/ - @Test - public void TouchingTentsContradictionRule_DownLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownLeft",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - } - /** - * @throws InvalidFileFormatException - * Tests a tent of orientation T - * TT - **/ - @Test - public void TouchingTentsContradictionRule_DownRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownRight",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - /** - * @throws InvalidFileFormatException - * Tests if tree adjacent triggers a null - */ - @Test - public void TouchingTentsContradictionRule_TreeAdjacent() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeAdjacent",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - } - /** - * @throws InvalidFileFormatException - * Tests if tree diagonal triggers a null - */ - @Test - public void TouchingTentsContradictionRule_TreeDiagonal() throws InvalidFileFormatException{ - TestUtilities.importTestBoard("puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeDiagonal",treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - + private static final TouchingTentsContradictionRule RULE = new TouchingTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + // DIAGONAL TESTS + /** + * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_DiagonalUpLeftToDownRight() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonal", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } + + /** + * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_DiagonalDownLeftToUpRight() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonalAlt", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + // ADJACENT TESTS + /** + * @throws InvalidFileFormatException Tests a tent adjacent of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_AdjacentVertical() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent adjacent of orientation TT + */ + @Test + public void TouchingTentsContradictionRule_AdjacentHorizontal() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacentAlt", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + // MIXED TESTS + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT TT + */ + @Test + public void TouchingTentsContradictionRule_2By2Square() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsFull2By2", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT T + */ + @Test + public void TouchingTentsContradictionRule_UpLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT T + */ + @Test + public void TouchingTentsContradictionRule_UpRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation T TT + */ + @Test + public void TouchingTentsContradictionRule_DownLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownLeft", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation T TT + */ + @Test + public void TouchingTentsContradictionRule_DownRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Tests if tree adjacent triggers a null + */ + @Test + public void TouchingTentsContradictionRule_TreeAdjacent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeAdjacent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if tree diagonal triggers a null + */ + @Test + public void TouchingTentsContradictionRule_TreeDiagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } } - - diff --git a/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java index 5b96fcf1c..2aecd0f0a 100644 --- a/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java @@ -3,15 +3,12 @@ // This feature is no longer supported public class TreeForTentDirectRuleTest { -// private static final TreeForTentBasicRule RULE = new TreeForTentBasicRule(); -// private static TreeTent treetent; - -// @BeforeClass -// public static void setUp() { -// MockGameBoardFacade.getInstance(); -// treetent = new TreeTent(); -// } + // private static final TreeForTentBasicRule RULE = new TreeForTentBasicRule(); + // private static TreeTent treetent; + + // @BeforeClass + // public static void setUp() { + // MockGameBoardFacade.getInstance(); + // treetent = new TreeTent(); + // } } - - - From b9000bb470a87e68207738d609110d04ad8275e3 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 18:23:33 -0500 Subject: [PATCH 38/54] Different format type Trying to get it to pass checkstyle --- build.gradle | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index f7bde7b55..1579e13b0 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,6 @@ version '2.0.0' apply plugin: 'java' apply plugin: 'application' -// apply plugin: 'checkstyle' spotless{ enforceCheck false @@ -34,10 +33,12 @@ spotless{ formatAnnotations() - googleJavaFormat('1.19.2') + googleJavaFormat('1.19.2').aosp().reflowLongStrings() } } +apply plugin: 'checkstyle' + mainClassName = 'edu.rpi.legup.Legup' sourceCompatibility = 11 From 55a1b32389317928ad957699634000efb9625d87 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 18:25:18 -0500 Subject: [PATCH 39/54] Disable checkstyle temporarily --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 1579e13b0..ae16e26c8 100644 --- a/build.gradle +++ b/build.gradle @@ -37,7 +37,7 @@ spotless{ } } -apply plugin: 'checkstyle' +//apply plugin: 'checkstyle' mainClassName = 'edu.rpi.legup.Legup' From 77fff2c85d678d0829f58970f65cdf2e108fa0c8 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln Date: Tue, 13 Feb 2024 23:26:59 +0000 Subject: [PATCH 40/54] Automated Java code formatting changes --- src/main/java/edu/rpi/legup/Legup.java | 20 +- src/main/java/edu/rpi/legup/app/Config.java | 253 +-- .../edu/rpi/legup/app/GameBoardFacade.java | 910 ++++---- .../rpi/legup/app/InvalidConfigException.java | 6 +- .../edu/rpi/legup/app/LegupPreferences.java | 229 +- .../rpi/legup/app/PuzzleKeyAccelerator.java | 140 +- .../rpi/legup/controller/BoardController.java | 150 +- .../edu/rpi/legup/controller/Controller.java | 196 +- .../legup/controller/CursorController.java | 80 +- .../controller/EditorElementController.java | 66 +- .../legup/controller/ElementController.java | 570 ++--- .../rpi/legup/controller/RuleController.java | 181 +- .../legup/controller/ToolbarController.java | 34 +- .../rpi/legup/controller/TreeController.java | 267 +-- .../legup/history/AddTreeElementCommand.java | 167 +- .../ApplyDefaultDirectRuleCommand.java | 206 +- .../legup/history/AutoCaseRuleCommand.java | 235 +- .../edu/rpi/legup/history/CommandError.java | 44 +- .../edu/rpi/legup/history/CommandState.java | 24 +- .../history/DeleteTreeElementCommand.java | 153 +- .../rpi/legup/history/EditDataCommand.java | 272 +-- .../java/edu/rpi/legup/history/History.java | 154 +- .../java/edu/rpi/legup/history/ICommand.java | 38 +- .../rpi/legup/history/IHistoryListener.java | 44 +- .../rpi/legup/history/IHistorySubject.java | 36 +- .../InvalidCommandStateTransition.java | 20 +- .../edu/rpi/legup/history/MergeCommand.java | 224 +- .../edu/rpi/legup/history/PuzzleCommand.java | 144 +- .../history/ValidateCaseRuleCommand.java | 212 +- .../ValidateContradictionRuleCommand.java | 279 +-- .../history/ValidateDirectRuleCommand.java | 222 +- src/main/java/edu/rpi/legup/model/Puzzle.java | 1205 +++++----- .../edu/rpi/legup/model/PuzzleExporter.java | 233 +- .../edu/rpi/legup/model/PuzzleImporter.java | 716 +++--- .../edu/rpi/legup/model/elements/Element.java | 109 +- .../rpi/legup/model/elements/ElementType.java | 4 +- .../model/elements/NonPlaceableElement.java | 10 +- .../model/elements/PlaceableElement.java | 10 +- .../edu/rpi/legup/model/gameboard/Board.java | 410 ++-- .../rpi/legup/model/gameboard/CaseBoard.java | 90 +- .../legup/model/gameboard/ElementFactory.java | 38 +- .../rpi/legup/model/gameboard/GridBoard.java | 280 +-- .../rpi/legup/model/gameboard/GridCell.java | 100 +- .../legup/model/gameboard/PuzzleElement.java | 354 +-- .../legup/model/observer/IBoardListener.java | 36 +- .../legup/model/observer/IBoardSubject.java | 36 +- .../legup/model/observer/ITreeListener.java | 40 +- .../legup/model/observer/ITreeSubject.java | 36 +- .../edu/rpi/legup/model/rules/CaseRule.java | 246 +- .../legup/model/rules/ContradictionRule.java | 178 +- .../edu/rpi/legup/model/rules/DirectRule.java | 169 +- .../edu/rpi/legup/model/rules/MergeRule.java | 152 +- .../java/edu/rpi/legup/model/rules/Rule.java | 300 +-- .../edu/rpi/legup/model/rules/RuleType.java | 8 +- .../java/edu/rpi/legup/model/tree/Tree.java | 345 +-- .../edu/rpi/legup/model/tree/TreeElement.java | 114 +- .../rpi/legup/model/tree/TreeElementType.java | 4 +- .../edu/rpi/legup/model/tree/TreeNode.java | 606 ++--- .../rpi/legup/model/tree/TreeTransition.java | 781 ++++--- .../legup/puzzle/battleship/Battleship.java | 294 +-- .../puzzle/battleship/BattleshipBoard.java | 256 +-- .../puzzle/battleship/BattleshipCell.java | 58 +- .../battleship/BattleshipCellController.java | 64 +- .../battleship/BattleshipCellFactory.java | 112 +- .../puzzle/battleship/BattleshipClue.java | 124 +- .../puzzle/battleship/BattleshipClueView.java | 98 +- .../battleship/BattleshipElementView.java | 179 +- .../puzzle/battleship/BattleshipExporter.java | 100 +- .../puzzle/battleship/BattleshipImporter.java | 341 +-- .../puzzle/battleship/BattleshipType.java | 86 +- .../puzzle/battleship/BattleshipView.java | 31 +- .../rules/AdjacentShipsContradictionRule.java | 126 +- .../rules/ContinueShipDirectRule.java | 63 +- .../rules/FinishWithShipsDirectRule.java | 159 +- .../rules/FinishWithWaterDirectRule.java | 63 +- .../IncompleteShipContradictionRule.java | 40 +- .../battleship/rules/SegmentTypeCaseRule.java | 110 +- .../rules/SegmentTypeDirectRule.java | 63 +- .../rules/ShipLocationCaseRule.java | 110 +- .../battleship/rules/ShipOrWaterCaseRule.java | 110 +- .../rules/SurroundShipDirectRule.java | 63 +- .../rules/TooFewInFleetContradictionRule.java | 40 +- .../rules/TooFewRowColContradictionRule.java | 40 +- .../TooManyInFleetContradictionRule.java | 40 +- .../rules/TooManyRowColContradiction.java | 40 +- .../rpi/legup/puzzle/fillapix/Fillapix.java | 94 +- .../legup/puzzle/fillapix/FillapixBoard.java | 98 +- .../legup/puzzle/fillapix/FillapixCell.java | 161 +- .../fillapix/FillapixCellController.java | 70 +- .../puzzle/fillapix/FillapixCellFactory.java | 107 +- .../puzzle/fillapix/FillapixCellType.java | 20 +- .../puzzle/fillapix/FillapixElementView.java | 97 +- .../puzzle/fillapix/FillapixExporter.java | 52 +- .../puzzle/fillapix/FillapixImporter.java | 190 +- .../puzzle/fillapix/FillapixUtilities.java | 415 ++-- .../legup/puzzle/fillapix/FillapixView.java | 23 +- .../puzzle/fillapix/elements/BlackTile.java | 14 +- .../puzzle/fillapix/elements/NumberTile.java | 42 +- .../puzzle/fillapix/elements/UnknownTile.java | 14 +- .../puzzle/fillapix/elements/WhiteTile.java | 14 +- .../fillapix/rules/BlackOrWhiteCaseRule.java | 130 +- .../rules/FinishWithBlackDirectRule.java | 91 +- .../rules/FinishWithWhiteDirectRule.java | 91 +- .../fillapix/rules/MirrorDirectRule.java | 155 +- .../rules/NonTouchingSharedDirectRule.java | 148 +- .../fillapix/rules/SatisfyClueCaseRule.java | 383 ++-- .../TooFewBlackCellsContradictionRule.java | 78 +- .../TooManyBlackCellsContradictionRule.java | 72 +- .../rules/TouchingCornersDirectRule.java | 164 +- .../rules/TouchingSidesDirectRule.java | 188 +- .../rpi/legup/puzzle/heyawake/Heyawake.java | 102 +- .../legup/puzzle/heyawake/HeyawakeBoard.java | 80 +- .../legup/puzzle/heyawake/HeyawakeCell.java | 32 +- .../puzzle/heyawake/HeyawakeElementView.java | 73 +- .../puzzle/heyawake/HeyawakeExporter.java | 52 +- .../puzzle/heyawake/HeyawakeFactory.java | 113 +- .../puzzle/heyawake/HeyawakeImporter.java | 170 +- .../legup/puzzle/heyawake/HeyawakeView.java | 69 +- .../AdjacentBlacksContradictionRule.java | 40 +- .../heyawake/rules/BlackOrWhiteCaseRule.java | 110 +- .../heyawake/rules/BlackPathDirectRule.java | 6 +- .../heyawake/rules/BottleNeckDirectRule.java | 6 +- .../rules/FillRoomBlackDirectRule.java | 63 +- .../rules/FillRoomWhiteDirectRule.java | 63 +- .../heyawake/rules/OneRowDirectRule.java | 6 +- .../rules/PreventWhiteLineDirectRule.java | 6 +- .../rules/RoomTooEmptyContradictionRule.java | 40 +- .../rules/RoomTooFullContradictionRule.java | 40 +- .../rules/ThreeByThreeDirectRule.java | 6 +- .../heyawake/rules/TwoInCornerDirectRule.java | 6 +- .../rules/WhiteAreaContradictionRule.java | 40 +- .../rules/WhiteAroundBlackDirectRule.java | 63 +- .../heyawake/rules/WhiteEscapeDirectRule.java | 6 +- .../rules/WhiteLineContradictionRule.java | 40 +- .../puzzle/heyawake/rules/ZigZagCaseRule.java | 6 +- .../heyawake/rules/ZigZagWhiteDirectRule.java | 6 +- .../edu/rpi/legup/puzzle/lightup/LightUp.java | 133 +- .../legup/puzzle/lightup/LightUpBoard.java | 292 +-- .../rpi/legup/puzzle/lightup/LightUpCell.java | 128 +- .../puzzle/lightup/LightUpCellController.java | 66 +- .../puzzle/lightup/LightUpCellFactory.java | 106 +- .../legup/puzzle/lightup/LightUpCellType.java | 18 +- .../puzzle/lightup/LightUpElementView.java | 145 +- .../legup/puzzle/lightup/LightUpExporter.java | 52 +- .../legup/puzzle/lightup/LightUpImporter.java | 192 +- .../rpi/legup/puzzle/lightup/LightUpView.java | 144 +- .../puzzle/lightup/elements/BlackTile.java | 11 +- .../puzzle/lightup/elements/BulbTile.java | 10 +- .../puzzle/lightup/elements/NumberTile.java | 32 +- .../puzzle/lightup/elements/UnknownTile.java | 14 +- .../rules/BulbsInPathContradictionRule.java | 122 +- .../CannotLightACellContradictionRule.java | 140 +- .../rules/EmptyCellinLightDirectRule.java | 99 +- .../lightup/rules/EmptyCornersDirectRule.java | 181 +- .../rules/FinishWithBulbsDirectRule.java | 170 +- .../rules/FinishWithEmptyDirectRule.java | 193 +- .../lightup/rules/LightOrEmptyCaseRule.java | 171 +- .../lightup/rules/MustLightDirectRule.java | 249 +- .../lightup/rules/SatisfyNumberCaseRule.java | 598 ++--- .../rules/TooFewBulbsContradictionRule.java | 58 +- .../rules/TooManyBulbsContradictionRule.java | 90 +- .../legup/puzzle/masyu/EditLineCommand.java | 271 +-- .../edu/rpi/legup/puzzle/masyu/Masyu.java | 102 +- .../rpi/legup/puzzle/masyu/MasyuBoard.java | 90 +- .../edu/rpi/legup/puzzle/masyu/MasyuCell.java | 28 +- .../legup/puzzle/masyu/MasyuCellFactory.java | 104 +- .../legup/puzzle/masyu/MasyuController.java | 154 +- .../legup/puzzle/masyu/MasyuElementView.java | 80 +- .../rpi/legup/puzzle/masyu/MasyuExporter.java | 47 +- .../rpi/legup/puzzle/masyu/MasyuImporter.java | 168 +- .../edu/rpi/legup/puzzle/masyu/MasyuLine.java | 72 +- .../rpi/legup/puzzle/masyu/MasyuLineView.java | 36 +- .../edu/rpi/legup/puzzle/masyu/MasyuType.java | 30 +- .../edu/rpi/legup/puzzle/masyu/MasyuView.java | 76 +- .../rules/BadLoopingContradictionRule.java | 40 +- .../masyu/rules/BlackContradictionRule.java | 32 +- .../masyu/rules/BlackEdgeDirectRule.java | 55 +- .../masyu/rules/BlackSplitCaseRule.java | 102 +- .../masyu/rules/BlockedBlackDirectRule.java | 59 +- .../masyu/rules/ConnectedCellsDirectRule.java | 63 +- .../masyu/rules/FinishPathDirectRule.java | 59 +- .../masyu/rules/NearWhiteDirectRule.java | 55 +- .../rules/NoOptionsContradictionRule.java | 40 +- .../masyu/rules/NormalSplitCaseRule.java | 106 +- .../masyu/rules/OnlyOneChoiceDirectRule.java | 63 +- .../masyu/rules/OnlyTwoContradictionRule.java | 36 +- .../masyu/rules/WhiteContradictionRule.java | 32 +- .../masyu/rules/WhiteEdgeDirectRule.java | 55 +- .../masyu/rules/WhiteSplitCaseRule.java | 102 +- .../rpi/legup/puzzle/nurikabe/Nurikabe.java | 126 +- .../legup/puzzle/nurikabe/NurikabeBoard.java | 84 +- .../legup/puzzle/nurikabe/NurikabeCell.java | 150 +- .../puzzle/nurikabe/NurikabeCellFactory.java | 107 +- .../puzzle/nurikabe/NurikabeController.java | 66 +- .../puzzle/nurikabe/NurikabeElementView.java | 103 +- .../puzzle/nurikabe/NurikabeExporter.java | 52 +- .../puzzle/nurikabe/NurikabeImporter.java | 192 +- .../legup/puzzle/nurikabe/NurikabeType.java | 14 +- .../puzzle/nurikabe/NurikabeUtilities.java | 522 ++--- .../legup/puzzle/nurikabe/NurikabeView.java | 23 +- .../puzzle/nurikabe/elements/BlackTile.java | 14 +- .../puzzle/nurikabe/elements/NumberTile.java | 42 +- .../puzzle/nurikabe/elements/UnknownTile.java | 14 +- .../puzzle/nurikabe/elements/WhiteTile.java | 14 +- .../rules/BlackBetweenRegionsDirectRule.java | 177 +- .../rules/BlackBottleNeckDirectRule.java | 90 +- .../nurikabe/rules/BlackOrWhiteCaseRule.java | 173 +- .../rules/BlackSquareContradictionRule.java | 88 +- .../rules/CannotReachCellDirectRule.java | 86 +- .../nurikabe/rules/CornerBlackDirectRule.java | 206 +- .../nurikabe/rules/FillinBlackDirectRule.java | 83 +- .../nurikabe/rules/FillinWhiteDirectRule.java | 83 +- .../rules/IsolateBlackContradictionRule.java | 82 +- .../MultipleNumbersContradictionRule.java | 67 +- .../rules/NoNumberContradictionRule.java | 101 +- .../rules/PreventBlackSquareDirectRule.java | 87 +- .../rules/SurroundRegionDirectRule.java | 139 +- .../rules/TooFewSpacesContradictionRule.java | 87 +- .../rules/TooManySpacesContradictionRule.java | 85 +- ...UnreachableWhiteCellContradictionRule.java | 159 +- .../rules/WhiteBottleNeckDirectRule.java | 92 +- .../shorttruthtable/ShortTruthTable.java | 186 +- .../shorttruthtable/ShortTruthTableBoard.java | 196 +- .../shorttruthtable/ShortTruthTableCell.java | 391 ++-- .../ShortTruthTableCellFactory.java | 95 +- .../ShortTruthTableCellType.java | 100 +- .../ShortTruthTableController.java | 42 +- .../ShortTruthTableElementView.java | 119 +- .../ShortTruthTableExporter.java | 67 +- .../ShortTruthTableImporter.java | 629 +++--- .../ShortTruthTableOperation.java | 74 +- .../ShortTruthTableStatement.java | 514 ++--- .../shorttruthtable/ShortTruthTableView.java | 25 +- .../elements/ArgumentElement.java | 14 +- .../elements/GreenElement.java | 14 +- .../elements/LogicSymbolElement.java | 14 +- .../shorttruthtable/elements/RedElement.java | 14 +- .../elements/UnknownElement.java | 14 +- .../rules/basic/DirectRuleAtomic.java | 18 +- .../rules/basic/DirectRule_Generic.java | 128 +- .../elimination/DirectRuleAndElimination.java | 6 +- .../DirectRuleBiconditionalElimination.java | 6 +- .../DirectRuleConditionalElimination.java | 6 +- .../elimination/DirectRuleNotElimination.java | 6 +- .../elimination/DirectRuleOrElimination.java | 6 +- .../DirectRule_GenericElimination.java | 20 +- .../DirectRuleAndIntroduction.java | 6 +- .../DirectRuleBiconditionalIntroduction.java | 6 +- .../DirectRuleConditionalIntroduction.java | 6 +- .../DirectRuleNotIntroduction.java | 6 +- .../DirectRuleOrIntroduction.java | 6 +- .../DirectRule_GenericIntroduction.java | 20 +- .../rules/caserule/CaseRuleAnd.java | 16 +- .../rules/caserule/CaseRuleAtomic.java | 92 +- .../rules/caserule/CaseRuleBiconditional.java | 32 +- .../rules/caserule/CaseRuleConditional.java | 30 +- .../rules/caserule/CaseRuleOr.java | 20 +- .../rules/caserule/CaseRule_Generic.java | 99 +- .../caserule/CaseRule_GenericStatement.java | 259 +-- .../contradiction/ContradictionRuleAnd.java | 28 +- .../ContradictionRuleAtomic.java | 83 +- .../ContradictionRuleBiconditional.java | 28 +- .../ContradictionRuleConditional.java | 26 +- .../contradiction/ContradictionRuleNot.java | 24 +- .../contradiction/ContradictionRuleOr.java | 26 +- .../ContradictionRule_GenericStatement.java | 131 +- .../legup/puzzle/skyscrapers/Skyscrapers.java | 128 +- .../puzzle/skyscrapers/SkyscrapersBoard.java | 448 ++-- .../puzzle/skyscrapers/SkyscrapersCell.java | 94 +- .../skyscrapers/SkyscrapersCellFactory.java | 106 +- .../puzzle/skyscrapers/SkyscrapersClue.java | 94 +- .../skyscrapers/SkyscrapersClueView.java | 96 +- .../skyscrapers/SkyscrapersController.java | 42 +- .../skyscrapers/SkyscrapersElementView.java | 51 +- .../skyscrapers/SkyscrapersExporter.java | 104 +- .../skyscrapers/SkyscrapersImporter.java | 389 ++-- .../puzzle/skyscrapers/SkyscrapersType.java | 62 +- .../puzzle/skyscrapers/SkyscrapersView.java | 333 +-- .../puzzle/skyscrapers/elements/ClueTile.java | 14 +- .../skyscrapers/elements/NumberTile.java | 14 +- .../skyscrapers/elements/UnknownTile.java | 14 +- .../rules/CellForNumberCaseRule.java | 343 +-- .../DuplicateNumberContradictionRule.java | 96 +- .../ExceedingVisibilityContradictionRule.java | 221 +- ...sufficientVisibilityContradictionRule.java | 223 +- .../rules/LastSingularCellDirectRule.java | 200 +- .../rules/LastSingularNumberDirectRule.java | 156 +- .../rules/LastVisibleCellDirectRule.java | 206 +- .../rules/LastVisibleNumberDirectRule.java | 158 +- .../skyscrapers/rules/NEdgeDirectRule.java | 161 +- .../rules/NumberForCellCaseRule.java | 298 +-- ...PreemptiveVisibilityContradictionRule.java | 345 +-- .../UnresolvedCellContradictionRule.java | 50 +- .../UnresolvedNumberContradictionRule.java | 159 +- .../rpi/legup/puzzle/sudoku/GroupType.java | 6 +- .../sudoku/PossibleNumberCaseBoard.java | 118 +- .../edu/rpi/legup/puzzle/sudoku/Sudoku.java | 178 +- .../rpi/legup/puzzle/sudoku/SudokuBoard.java | 306 +-- .../rpi/legup/puzzle/sudoku/SudokuCell.java | 106 +- .../puzzle/sudoku/SudokuCellController.java | 52 +- .../puzzle/sudoku/SudokuCellFactory.java | 106 +- .../puzzle/sudoku/SudokuElementView.java | 114 +- .../legup/puzzle/sudoku/SudokuExporter.java | 50 +- .../legup/puzzle/sudoku/SudokuImporter.java | 213 +- .../rpi/legup/puzzle/sudoku/SudokuView.java | 286 +-- .../puzzle/sudoku/elements/NumberTile.java | 34 +- .../rules/AdvancedDeductionDirectRule.java | 152 +- .../rules/LastCellForNumberDirectRule.java | 143 +- .../rules/LastNumberForCellDirectRule.java | 124 +- .../rules/NoSolutionContradictionRule.java | 90 +- .../sudoku/rules/PossibleCellCaseRule.java | 166 +- .../sudoku/rules/PossibleNumberCaseRule.java | 200 +- .../RepeatedNumberContradictionRule.java | 98 +- .../legup/puzzle/treetent/ClueCommand.java | 317 +-- .../puzzle/treetent/EditLineCommand.java | 378 ++-- .../rpi/legup/puzzle/treetent/TreeTent.java | 136 +- .../legup/puzzle/treetent/TreeTentBoard.java | 430 ++-- .../legup/puzzle/treetent/TreeTentCell.java | 80 +- .../puzzle/treetent/TreeTentCellFactory.java | 152 +- .../legup/puzzle/treetent/TreeTentClue.java | 98 +- .../puzzle/treetent/TreeTentClueView.java | 88 +- .../puzzle/treetent/TreeTentController.java | 199 +- .../puzzle/treetent/TreeTentElementView.java | 104 +- .../puzzle/treetent/TreeTentExporter.java | 114 +- .../puzzle/treetent/TreeTentImporter.java | 378 ++-- .../legup/puzzle/treetent/TreeTentLine.java | 72 +- .../puzzle/treetent/TreeTentLineView.java | 38 +- .../legup/puzzle/treetent/TreeTentType.java | 38 +- .../legup/puzzle/treetent/TreeTentView.java | 403 ++-- .../puzzle/treetent/elements/GrassTile.java | 14 +- .../puzzle/treetent/elements/TentTile.java | 10 +- .../puzzle/treetent/elements/TreeTile.java | 10 +- .../puzzle/treetent/elements/UnknownTile.java | 14 +- .../treetent/rules/EmptyFieldDirectRule.java | 135 +- .../treetent/rules/FillinRowCaseRule.java | 356 +-- .../rules/FinishWithGrassDirectRule.java | 125 +- .../rules/FinishWithTentsDirectRule.java | 129 +- .../rules/LastCampingSpotDirectRule.java | 154 +- .../treetent/rules/LinkTentCaseRule.java | 292 +-- .../treetent/rules/LinkTreeCaseRule.java | 307 +-- .../rules/NoTentForTreeContradictionRule.java | 98 +- .../rules/NoTreeForTentContradictionRule.java | 86 +- .../SurroundTentWithGrassDirectRule.java | 127 +- .../treetent/rules/TentForTreeDirectRule.java | 193 +- .../treetent/rules/TentOrGrassCaseRule.java | 172 +- .../rules/TooFewTentsContradictionRule.java | 62 +- .../rules/TooManyTentsContradictionRule.java | 58 +- .../rules/TouchingTentsContradictionRule.java | 60 +- .../treetent/rules/TreeForTentDirectRule.java | 193 +- .../rpi/legup/save/ExportFileException.java | 6 +- .../save/InvalidFileFormatException.java | 6 +- .../java/edu/rpi/legup/save/SavableBoard.java | 14 +- .../edu/rpi/legup/ui/CreatePuzzleDialog.java | 377 ++-- .../java/edu/rpi/legup/ui/DynamicView.java | 397 ++-- .../edu/rpi/legup/ui/DynamicViewType.java | 4 +- src/main/java/edu/rpi/legup/ui/HomePanel.java | 1217 +++++----- .../java/edu/rpi/legup/ui/LegupPanel.java | 6 +- src/main/java/edu/rpi/legup/ui/LegupUI.java | 370 +-- .../legup/ui/ManualPuzzleCreatorDialog.java | 2 +- .../java/edu/rpi/legup/ui/PickGameDialog.java | 260 +-- .../edu/rpi/legup/ui/PreferencesDialog.java | 803 +++---- .../edu/rpi/legup/ui/ProofEditorPanel.java | 1999 +++++++++-------- .../edu/rpi/legup/ui/PuzzleEditorPanel.java | 987 ++++---- .../java/edu/rpi/legup/ui/ScrollView.java | 559 ++--- .../java/edu/rpi/legup/ui/ToolbarName.java | 48 +- .../java/edu/rpi/legup/ui/WrapLayout.java | 293 +-- .../java/edu/rpi/legup/ui/ZoomWidget.java | 78 +- .../java/edu/rpi/legup/ui/ZoomablePane.java | 56 +- .../edu/rpi/legup/ui/boardview/BoardView.java | 386 ++-- .../legup/ui/boardview/DataSelectionView.java | 8 +- .../legup/ui/boardview/ElementSelection.java | 104 +- .../rpi/legup/ui/boardview/ElementView.java | 661 +++--- .../rpi/legup/ui/boardview/GridBoardView.java | 134 +- .../legup/ui/boardview/GridElementView.java | 6 +- .../legup/ui/boardview/SelectionItemView.java | 38 +- .../ui/lookandfeel/LegupLookAndFeel.java | 664 +++--- .../animation/MaterialUIMovement.java | 14 +- .../animation/MaterialUITimer.java | 184 +- .../components/MaterialButtonUI.java | 50 +- .../MaterialCheckBoxMenuItemUI.java | 80 +- .../components/MaterialCheckBoxUI.java | 34 +- .../components/MaterialComboBoxRenderer.java | 29 +- .../components/MaterialComboBoxUI.java | 74 +- .../components/MaterialEditorPaneUI.java | 14 +- .../components/MaterialFileChooserUI.java | 88 +- .../components/MaterialLabelUI.java | 34 +- .../components/MaterialMenuBarUI.java | 32 +- .../components/MaterialMenuItemUI.java | 36 +- .../components/MaterialMenuUI.java | 34 +- .../components/MaterialPanelUI.java | 32 +- .../components/MaterialPasswordFieldUI.java | 341 +-- .../components/MaterialPopupMenuUI.java | 30 +- .../components/MaterialProgressBarUI.java | 30 +- .../MaterialRadioButtonMenuItemUI.java | 86 +- .../components/MaterialRadioButtonUI.java | 34 +- .../components/MaterialScrollBarUI.java | 72 +- .../components/MaterialSeparatorUI.java | 22 +- .../components/MaterialSliderUI.java | 236 +- .../components/MaterialSpinnerUI.java | 108 +- .../components/MaterialSplitPaneDivider.java | 32 +- .../components/MaterialSplitPaneUI.java | 36 +- .../components/MaterialTabbedPaneUI.java | 134 +- .../components/MaterialTableCellEditor.java | 35 +- .../components/MaterialTableCellRenderer.java | 25 +- .../MaterialTableHeaderCellRenderer.java | 27 +- .../components/MaterialTableHeaderUI.java | 26 +- .../components/MaterialTableUI.java | 60 +- .../components/MaterialTextFieldUI.java | 350 +-- .../components/MaterialTextPaneUI.java | 14 +- .../components/MaterialToggleButtonUI.java | 38 +- .../components/MaterialToolBarUI.java | 40 +- .../components/MaterialToolTipUI.java | 22 +- .../components/MaterialTreeCellEditor.java | 78 +- .../components/MaterialTreeCellRenderer.java | 66 +- .../components/MaterialTreeUI.java | 58 +- .../materialdesign/DropShadowBorder.java | 745 +++--- .../materialdesign/MaterialBorders.java | 18 +- .../materialdesign/MaterialColors.java | 528 ++--- .../materialdesign/MaterialDrawingUtils.java | 40 +- .../materialdesign/MaterialFonts.java | 89 +- .../materialdesign/MaterialImages.java | 70 +- .../rulesview/CaseRulePanel.java | 28 +- .../rulesview/CaseRuleSelectionView.java | 20 +- .../rulesview/ContradictionRulePanel.java | 28 +- .../rulesview/DirectRulePanel.java | 30 +- .../proofeditorui/rulesview/RuleButton.java | 58 +- .../ui/proofeditorui/rulesview/RuleFrame.java | 325 +-- .../ui/proofeditorui/rulesview/RulePanel.java | 633 +++--- .../rulesview/SearchBarPanel.java | 30 +- .../treeview/TreeElementView.java | 330 +-- .../proofeditorui/treeview/TreeNodeView.java | 578 ++--- .../ui/proofeditorui/treeview/TreePanel.java | 188 +- .../treeview/TreeToolBarButton.java | 24 +- .../treeview/TreeToolBarName.java | 8 +- .../treeview/TreeToolbarPanel.java | 100 +- .../treeview/TreeTransitionView.java | 650 +++--- .../ui/proofeditorui/treeview/TreeView.java | 1612 ++++++------- .../treeview/TreeViewSelection.java | 303 +-- .../elementsview/ElementButton.java | 54 +- .../elementsview/ElementFrame.java | 175 +- .../elementsview/ElementPanel.java | 113 +- .../NonPlaceableElementPanel.java | 18 +- .../elementsview/PlaceableElementPanel.java | 18 +- .../java/edu/rpi/legup/user/Submission.java | 4 +- .../edu/rpi/legup/user/UsageStatistics.java | 66 +- .../rpi/legup/utility/ConnectedRegions.java | 112 +- .../edu/rpi/legup/utility/DisjointSets.java | 286 +-- .../java/edu/rpi/legup/utility/Entry.java | 88 +- .../edu/rpi/legup/utility/LegupUtils.java | 148 +- .../java/edu/rpi/legup/utility/Logger.java | 56 +- src/test/java/legup/MockGameBoardFacade.java | 54 +- src/test/java/legup/TestRunner.java | 174 +- src/test/java/legup/TestUtilities.java | 18 +- .../AdjacentShipsContradictionRuleTest.java | 87 +- .../rules/FinishWithShipsDirectRuleTests.java | 95 +- .../BulbsInPathContradictionRuleTest.java | 128 +- ...CannotLightACellContradictionRuleTest.java | 134 +- .../rules/EmptyCellinLightDirectRuleTest.java | 170 +- .../rules/EmptyCornersDirectRuleTest.java | 96 +- .../rules/FinishWithBulbsDirectRuleTest.java | 141 +- .../rules/LightOrEmptyCaseRuleTest.java | 91 +- .../rules/MustLightDirectRuleTest.java | 79 +- .../rules/SatisfyNumberCaseRuleTest.java | 285 +-- .../TooFewBulbsContradictionRuleTest.java | 88 +- .../TooManyBulbsContradictionRuleTest.java | 88 +- .../BlackBetweenRegionsDirectRuleTest.java | 344 +-- .../rules/BlackBottleNeckDirectRuleTest.java | 160 +- .../rules/BlackOrWhiteCaseRuleTest.java | 83 +- .../BlackSquareContradictionRuleTest.java | 152 +- .../rules/CannotReachCellDirectRuleTest.java | 113 +- .../rules/CornerBlackDirectRuleTest.java | 98 +- .../rules/FillinBlackDirectRuleTest.java | 229 +- .../rules/FillinWhiteDirectRuleTest.java | 233 +- .../IsolateBlackContradictionRuleTest.java | 147 +- .../MultipleNumbersContradictionRuleTest.java | 157 +- .../rules/NoNumbersContradictionRuleTest.java | 113 +- .../PreventBlackSquareDirectRuleTest.java | 293 +-- .../rules/SurroundRegionDirectRuleTest.java | 166 +- .../TooFewSpacesContradictionRuleTest.java | 129 +- .../TooManySpacesContradictionRuleTest.java | 144 +- ...achableWhiteCellContradictionRuleTest.java | 104 +- .../rules/WhiteBottleNeckDirectRuleTest.java | 158 +- .../rules/AndCaseRuleTest.java | 272 +-- .../rules/AndEliminationDirectRuleTest.java | 361 +-- .../rules/AndIntroductionDirectRuleTest.java | 148 +- .../rules/AtomicDirectRuleTest.java | 304 +-- .../rules/BiconditionalEliminationTest.java | 719 +++--- .../rules/BiconditionalIntroductionTest.java | 164 +- .../rules/ConditionalEliminationTest.java | 422 ++-- .../rules/ConditionalIntroductionTest.java | 152 +- .../rules/NotEliminationTest.java | 204 +- .../rules/NotIntroductionTest.java | 222 +- .../shorttruthtable/rules/OrCaseRuleTest.java | 272 +-- .../rules/OrEliminationTest.java | 261 +-- .../rules/OrIntroductionTest.java | 148 +- .../rules/TrueOrFalseCaseRuleTest.java | 100 +- .../rules/CellForNumberCaseRuleTest.java | 338 +-- .../DuplicateNumberContradictionTest.java | 260 +-- .../ExceedingVisibilityContradictionTest.java | 226 +- ...sufficientVisibilityContradictionTest.java | 226 +- .../rules/LastSingularCellDirectTest.java | 392 ++-- .../rules/LastSingularNumberDirectTest.java | 234 +- .../rules/LastVisibleCellDirectTest.java | 434 ++-- .../rules/LastVisibleNumberDirectTest.java | 434 ++-- .../skyscrapers/rules/NEdgeDirectTest.java | 216 +- .../rules/NumberForCellCaseRuleTest.java | 302 +-- ...PreemptiveVisibilityContradictionTest.java | 258 +-- .../UnresolvedCellContradictionTest.java | 265 +-- .../UnresolvedNumberContradictionTest.java | 289 +-- .../rules/EmptyFieldDirectRuleTest.java | 492 ++-- .../rules/FinishWithGrassDirectRuleTest.java | 656 +++--- .../rules/FinishWithTentsDirectRuleTest.java | 614 ++--- .../rules/LastCampingSpotDirectRuleTest.java | 272 +-- .../NoTentForTreeContradictionRuleTest.java | 187 +- .../NoTreeForTentContradictionRuleTest.java | 397 ++-- .../SurroundTentWithGrassDirectRuleTest.java | 260 +-- .../rules/TentForTreeDirectRuleTest.java | 16 +- .../rules/TentOrGrassCaseRuleTest.java | 96 +- .../TooFewTentsContradictionRuleTest.java | 430 ++-- .../TooManyTentsContradictionRuleTest.java | 463 ++-- .../TouchingTentsContradictionRuleTest.java | 477 ++-- .../rules/TreeForTentDirectRuleTest.java | 14 +- 522 files changed, 40888 insertions(+), 39996 deletions(-) diff --git a/src/main/java/edu/rpi/legup/Legup.java b/src/main/java/edu/rpi/legup/Legup.java index 0ea5b638a..79471286b 100644 --- a/src/main/java/edu/rpi/legup/Legup.java +++ b/src/main/java/edu/rpi/legup/Legup.java @@ -5,14 +5,14 @@ public class Legup { - /** - * Starts the Legup Program - * - * @param args arguments to Legup - */ - public static void main(String[] args) { - Logger.initLogger(); - GameBoardFacade.getInstance(); - GameBoardFacade.setupConfig(); - } + /** + * Starts the Legup Program + * + * @param args arguments to Legup + */ + public static void main(String[] args) { + Logger.initLogger(); + GameBoardFacade.getInstance(); + GameBoardFacade.setupConfig(); + } } diff --git a/src/main/java/edu/rpi/legup/app/Config.java b/src/main/java/edu/rpi/legup/app/Config.java index baaeb1dbd..8a8e9665d 100644 --- a/src/main/java/edu/rpi/legup/app/Config.java +++ b/src/main/java/edu/rpi/legup/app/Config.java @@ -13,139 +13,140 @@ import org.xml.sax.SAXException; public class Config { - private static final Logger Logger = LogManager.getLogger(Config.class.getName()); - - private Map puzzles; - private Map fileCreationDisabledStatuses; - private static final String CONFIG_LOCATION = "edu/rpi/legup/legup/config"; - - /** - * Config Constructor for logic puzzles - * - * @throws InvalidConfigException if configuration is invalid - */ - public Config() throws InvalidConfigException { - this.puzzles = new Hashtable<>(); - this.fileCreationDisabledStatuses = new Hashtable<>(); - loadConfig(this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION)); - } - - /** - * Gets a list of all available Puzzle names - * - * @return Vector of Puzzle names which are Strings - */ - public List getPuzzleClassNames() { - return new LinkedList<>(puzzles.keySet()); - } - - /** - * Returns a list of the names of the puzzles which can have puzzles created and edited within the - * proof editor. - * - * @return the aforementioned list of Strings - */ - public List getFileCreationEnabledPuzzles() { - LinkedList puzzles = new LinkedList(); - for (String puzzle : this.getPuzzleClassNames()) { - if (!this.fileCreationDisabledStatuses.get(puzzle)) { - puzzles.add(puzzle); - } + private static final Logger Logger = LogManager.getLogger(Config.class.getName()); + + private Map puzzles; + private Map fileCreationDisabledStatuses; + private static final String CONFIG_LOCATION = "edu/rpi/legup/legup/config"; + + /** + * Config Constructor for logic puzzles + * + * @throws InvalidConfigException if configuration is invalid + */ + public Config() throws InvalidConfigException { + this.puzzles = new Hashtable<>(); + this.fileCreationDisabledStatuses = new Hashtable<>(); + loadConfig(this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION)); } - return puzzles; - } - - /** - * Converts the class name of the puzzles to their display names. Some examples of the conversion: - * convertClassNameToDisplayName("TreeTent") will return "Tree Tent" - * convertClassNameToDisplayName("Nurikabe") will return "Nurikabe" - * - * @param className the name of the class - * @return displayName the name of the puzzle - */ - public static String convertClassNameToDisplayName(String className) { - String displayName = ""; - for (int i = 0; i < className.length(); i++) { - if (Character.isUpperCase(className.charAt(i)) && i != 0) { - displayName += " "; - } - displayName += className.charAt(i); + + /** + * Gets a list of all available Puzzle names + * + * @return Vector of Puzzle names which are Strings + */ + public List getPuzzleClassNames() { + return new LinkedList<>(puzzles.keySet()); + } + + /** + * Returns a list of the names of the puzzles which can have puzzles created and edited within + * the proof editor. + * + * @return the aforementioned list of Strings + */ + public List getFileCreationEnabledPuzzles() { + LinkedList puzzles = new LinkedList(); + for (String puzzle : this.getPuzzleClassNames()) { + if (!this.fileCreationDisabledStatuses.get(puzzle)) { + puzzles.add(puzzle); + } + } + return puzzles; + } + + /** + * Converts the class name of the puzzles to their display names. Some examples of the + * conversion: convertClassNameToDisplayName("TreeTent") will return "Tree Tent" + * convertClassNameToDisplayName("Nurikabe") will return "Nurikabe" + * + * @param className the name of the class + * @return displayName the name of the puzzle + */ + public static String convertClassNameToDisplayName(String className) { + String displayName = ""; + for (int i = 0; i < className.length(); i++) { + if (Character.isUpperCase(className.charAt(i)) && i != 0) { + displayName += " "; + } + displayName += className.charAt(i); + } + return displayName; } - return displayName; - } - - public static String convertDisplayNameToClassName(String displayName) { - String className = ""; - for (int i = 0; i < displayName.length(); i++) { - if (displayName.charAt(i) != ' ') { - className += displayName.charAt(i); - } + + public static String convertDisplayNameToClassName(String displayName) { + String className = ""; + for (int i = 0; i < displayName.length(); i++) { + if (displayName.charAt(i) != ' ') { + className += displayName.charAt(i); + } + } + return className; } - return className; - } - public List getPuzzleNames() { - List names = new LinkedList(); - for (String puzzle : this.getPuzzleClassNames()) { - names.add(Config.convertClassNameToDisplayName(puzzle)); + public List getPuzzleNames() { + List names = new LinkedList(); + for (String puzzle : this.getPuzzleClassNames()) { + names.add(Config.convertClassNameToDisplayName(puzzle)); + } + return names; } - return names; - } - public List getFileCreationEnabledPuzzleNames() { - List names = new LinkedList(); - for (String puzzle : this.getFileCreationEnabledPuzzles()) { - names.add(Config.convertClassNameToDisplayName(puzzle)); + public List getFileCreationEnabledPuzzleNames() { + List names = new LinkedList(); + for (String puzzle : this.getFileCreationEnabledPuzzles()) { + names.add(Config.convertClassNameToDisplayName(puzzle)); + } + return names; } - return names; - } - - /** - * Gets a {@link edu.rpi.legup.model.Puzzle} class for a puzzle name - * - * @param puzzleName puzzle name of the class - * @return class name for the puzzle name - */ - public String getPuzzleClassForName(String puzzleName) { - if (puzzles.containsKey(puzzleName)) { - return puzzles.get(puzzleName); + + /** + * Gets a {@link edu.rpi.legup.model.Puzzle} class for a puzzle name + * + * @param puzzleName puzzle name of the class + * @return class name for the puzzle name + */ + public String getPuzzleClassForName(String puzzleName) { + if (puzzles.containsKey(puzzleName)) { + return puzzles.get(puzzleName); + } + return null; } - return null; - } - - /** - * Loads the config object from the config xml file - * - * @param stream file stream for the config xml file - */ - private void loadConfig(InputStream stream) throws InvalidConfigException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.parse(stream); - Element configNode = document.getDocumentElement(); - - if (!configNode.getNodeName().equalsIgnoreCase("Legup")) { - throw new InvalidConfigException("Config is not formatted correctly"); - } - - Element puzzleList = (Element) configNode.getElementsByTagName("puzzles").item(0); - Logger.debug(puzzleList); - NodeList puzzleNodes = puzzleList.getElementsByTagName("puzzle"); - - for (int i = 0; i < puzzleNodes.getLength(); i++) { - Element puzzle = (Element) puzzleNodes.item(i); - String name = puzzle.getAttribute("name"); - String className = puzzle.getAttribute("qualifiedClassName"); - boolean status = - Boolean.parseBoolean(puzzle.getAttribute("fileCreationDisabled").toLowerCase()); - Logger.debug("Class Name: " + className); - this.puzzles.put(name, className); - this.fileCreationDisabledStatuses.put(name, Boolean.valueOf(status)); - } - - } catch (ParserConfigurationException | SAXException | IOException e) { - throw new InvalidConfigException(e.getMessage()); + + /** + * Loads the config object from the config xml file + * + * @param stream file stream for the config xml file + */ + private void loadConfig(InputStream stream) throws InvalidConfigException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(stream); + Element configNode = document.getDocumentElement(); + + if (!configNode.getNodeName().equalsIgnoreCase("Legup")) { + throw new InvalidConfigException("Config is not formatted correctly"); + } + + Element puzzleList = (Element) configNode.getElementsByTagName("puzzles").item(0); + Logger.debug(puzzleList); + NodeList puzzleNodes = puzzleList.getElementsByTagName("puzzle"); + + for (int i = 0; i < puzzleNodes.getLength(); i++) { + Element puzzle = (Element) puzzleNodes.item(i); + String name = puzzle.getAttribute("name"); + String className = puzzle.getAttribute("qualifiedClassName"); + boolean status = + Boolean.parseBoolean( + puzzle.getAttribute("fileCreationDisabled").toLowerCase()); + Logger.debug("Class Name: " + className); + this.puzzles.put(name, className); + this.fileCreationDisabledStatuses.put(name, Boolean.valueOf(status)); + } + + } catch (ParserConfigurationException | SAXException | IOException e) { + throw new InvalidConfigException(e.getMessage()); + } } - } } diff --git a/src/main/java/edu/rpi/legup/app/GameBoardFacade.java b/src/main/java/edu/rpi/legup/app/GameBoardFacade.java index 0dccc739e..c928c1209 100644 --- a/src/main/java/edu/rpi/legup/app/GameBoardFacade.java +++ b/src/main/java/edu/rpi/legup/app/GameBoardFacade.java @@ -32,489 +32,495 @@ import org.xml.sax.SAXException; public class GameBoardFacade implements IHistorySubject { - private static final Logger LOGGER = LogManager.getLogger(GameBoardFacade.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(GameBoardFacade.class.getName()); - protected static volatile GameBoardFacade instance; + protected static volatile GameBoardFacade instance; - private Config config; + private Config config; - protected Puzzle puzzle; + protected Puzzle puzzle; - private LegupUI legupUI; + private LegupUI legupUI; - private ProofEditorPanel puzzleSolver; + private ProofEditorPanel puzzleSolver; - private PuzzleEditorPanel puzzleEditor; + private PuzzleEditorPanel puzzleEditor; - private String curFileName; + private String curFileName; - private History history; - private List historyListeners; + private History history; + private List historyListeners; - /** Private GameBoardFacade Constructor creates a game board facade */ - protected GameBoardFacade() { - history = new History(); - historyListeners = new ArrayList<>(); - curFileName = null; - LegupPreferences.getInstance(); - initializeUI(); - } - - /** - * Gets the singleton instance of GameBoardFacade - * - * @return single instance of GameBoardFacade - */ - public static synchronized GameBoardFacade getInstance() { - if (instance == null) { - instance = new GameBoardFacade(); - } - return instance; - } - - public void initializeUI() { - EventQueue.invokeLater( - () -> { - legupUI = new LegupUI(); - puzzleSolver = legupUI.getProofEditor(); - puzzleEditor = legupUI.getPuzzleEditor(); - addHistoryListener(legupUI.getProofEditor()); - addHistoryListener(legupUI.getPuzzleEditor()); - }); - } - - public void setPuzzle(Puzzle puzzle) { - this.puzzle = puzzle; - this.puzzleSolver.setPuzzleView(puzzle); - this.history.clear(); - } - - public void clearPuzzle() { - this.puzzle = null; - this.curFileName = null; - this.history.clear(); - } - - public static void setupConfig() { - Config config = null; - try { - config = new Config(); - } catch (InvalidConfigException e) { - System.exit(1); + /** Private GameBoardFacade Constructor creates a game board facade */ + protected GameBoardFacade() { + history = new History(); + historyListeners = new ArrayList<>(); + curFileName = null; + LegupPreferences.getInstance(); + initializeUI(); } - GameBoardFacade.getInstance().setConfig(config); - } - - public void setPuzzleEditor(Puzzle puzzle) { - this.puzzle = puzzle; - this.puzzleEditor.setPuzzleView(puzzle); - } - - public void setConfig(Config config) { - this.config = config; - } - - /** - * Validates the given dimensions for the given puzzle - * - * @param game name of the puzzle - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @return true if it is possible to create a board for the given game with the given number of - * rows and columns, false otherwise - * @throws RuntimeException if any of the given input is invalid - */ - public boolean validateDimensions(String game, int rows, int columns) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - try { - Class c = Class.forName(qualifiedClassName); - Constructor constructor = c.getConstructor(); - Puzzle puzzle = (Puzzle) constructor.newInstance(); - return puzzle.isValidDimensions(rows, columns); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Error validating puzzle dimensions"); + + /** + * Gets the singleton instance of GameBoardFacade + * + * @return single instance of GameBoardFacade + */ + public static synchronized GameBoardFacade getInstance() { + if (instance == null) { + instance = new GameBoardFacade(); + } + return instance; } - } - - /** - * Validates the given text input for the given puzzle - * - * @param game the name of the puzzle - * @param statements an array of statements - * @return true if it is possible to create a board for the given game with the given statements, - * false otherwise - * @throws RuntimeException if any of the input is invalid - */ - public boolean validateTextInput(String game, String[] statements) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - try { - Class c = Class.forName(qualifiedClassName); - Constructor constructor = c.getConstructor(); - Puzzle puzzle = (Puzzle) constructor.newInstance(); - return puzzle.isValidTextInput(statements); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Error validating puzzle text input"); + + public void initializeUI() { + EventQueue.invokeLater( + () -> { + legupUI = new LegupUI(); + puzzleSolver = legupUI.getProofEditor(); + puzzleEditor = legupUI.getPuzzleEditor(); + addHistoryListener(legupUI.getProofEditor()); + addHistoryListener(legupUI.getPuzzleEditor()); + }); } - } - - /** - * Loads an empty puzzle - * - * @param game name of the puzzle - * @param rows the number of rows on the board - * @param columns the number of columns on the board - */ - public void loadPuzzle(String game, int rows, int columns) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - LOGGER.debug("Loading " + qualifiedClassName); - - try { - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new RuntimeException("Puzzle importer null"); - } - - // Theoretically, this exception should never be thrown, since LEGUP should not be - // allowing the user to give row/column input for a puzzle that doesn't support it - if (!importer.acceptsRowsAndColumnsInput()) { - throw new IllegalArgumentException( - puzzle.getName() + " does not accept rows and columns input"); - } - - setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); - importer.initializePuzzle(rows, columns); - - puzzle.initializeView(); - // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Puzzle creation error"); + + public void setPuzzle(Puzzle puzzle) { + this.puzzle = puzzle; + this.puzzleSolver.setPuzzleView(puzzle); + this.history.clear(); } - } - - public void loadPuzzle(String game, String[] statements) { - String qualifiedClassName = config.getPuzzleClassForName(game); - LOGGER.debug("Loading " + qualifiedClassName); - - try { - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new RuntimeException("Puzzle importer null"); - } - - // Theoretically, this exception should never be thrown, since LEGUP should not be - // allowing the user to give text input for a puzzle that doesn't support it - if (!importer.acceptsTextInput()) { - throw new IllegalArgumentException(puzzle.getName() + " does not accept text input"); - } - - setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); - importer.initializePuzzle(statements); - - puzzle.initializeView(); - // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Puzzle creation error"); + + public void clearPuzzle() { + this.puzzle = null; + this.curFileName = null; + this.history.clear(); } - } - - /** - * Loads a puzzle file - * - * @param fileName file name of the board file - * @throws InvalidFileFormatException if input is invalid - */ - public void loadPuzzle(String fileName) throws InvalidFileFormatException { - try { - loadPuzzle(new FileInputStream(fileName)); - curFileName = fileName; - setWindowTitle(puzzle.getName(), fileName); - } catch (IOException e) { - LOGGER.error("Invalid file " + fileName, e); - throw new InvalidFileFormatException("Could not find file"); + + public static void setupConfig() { + Config config = null; + try { + config = new Config(); + } catch (InvalidConfigException e) { + System.exit(1); + } + GameBoardFacade.getInstance().setConfig(config); } - } - - public void loadPuzzleEditor(String fileName) throws InvalidFileFormatException { - try { - loadPuzzleEditor(new FileInputStream(fileName)); - curFileName = fileName; - setWindowTitle(puzzle.getName(), fileName); - } catch (IOException e) { - LOGGER.error("Invalid file " + fileName, e); - throw new InvalidFileFormatException("Could not find file"); + + public void setPuzzleEditor(Puzzle puzzle) { + this.puzzle = puzzle; + this.puzzleEditor.setPuzzleView(puzzle); } - } - - public void loadPuzzleEditor(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Invalid file", e); - throw new InvalidFileFormatException("Could not find file"); + + public void setConfig(Config config) { + this.config = config; } - Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - try { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - String qualifiedClassName = - config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); - if (qualifiedClassName == null) { - throw new InvalidFileFormatException( - "Puzzle creation error: cannot find puzzle with that name"); + /** + * Validates the given dimensions for the given puzzle + * + * @param game name of the puzzle + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @return true if it is possible to create a board for the given game with the given number of + * rows and columns, false otherwise + * @throws RuntimeException if any of the given input is invalid + */ + public boolean validateDimensions(String game, int rows, int columns) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + try { + Class c = Class.forName(qualifiedClassName); + Constructor constructor = c.getConstructor(); + Puzzle puzzle = (Puzzle) constructor.newInstance(); + return puzzle.isValidDimensions(rows, columns); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Error validating puzzle dimensions"); } - // Check if puzzle is a "FileCreationEnabled" puzzle (meaning it is editable). - String[] editablePuzzles = config.getFileCreationEnabledPuzzles().toArray(new String[0]); - boolean isEditablePuzzle = false; - for (int i = 0; i < editablePuzzles.length; i++) { - if (qualifiedClassName.contains(editablePuzzles[i])) { - isEditablePuzzle = true; - break; - } + } + + /** + * Validates the given text input for the given puzzle + * + * @param game the name of the puzzle + * @param statements an array of statements + * @return true if it is possible to create a board for the given game with the given + * statements, false otherwise + * @throws RuntimeException if any of the input is invalid + */ + public boolean validateTextInput(String game, String[] statements) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + try { + Class c = Class.forName(qualifiedClassName); + Constructor constructor = c.getConstructor(); + Puzzle puzzle = (Puzzle) constructor.newInstance(); + return puzzle.isValidTextInput(statements); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Error validating puzzle text input"); } - if (!isEditablePuzzle) { - LOGGER.error("Puzzle is not editable"); - throw new InvalidFileFormatException("Puzzle is not editable"); + } + + /** + * Loads an empty puzzle + * + * @param game name of the puzzle + * @param rows the number of rows on the board + * @param columns the number of columns on the board + */ + public void loadPuzzle(String game, int rows, int columns) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + LOGGER.debug("Loading " + qualifiedClassName); + + try { + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new RuntimeException("Puzzle importer null"); + } + + // Theoretically, this exception should never be thrown, since LEGUP should not be + // allowing the user to give row/column input for a puzzle that doesn't support it + if (!importer.acceptsRowsAndColumnsInput()) { + throw new IllegalArgumentException( + puzzle.getName() + " does not accept rows and columns input"); + } + + setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); + importer.initializePuzzle(rows, columns); + + puzzle.initializeView(); + // + // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Puzzle creation error"); } - // If it is editable, start loading it + } + + public void loadPuzzle(String game, String[] statements) { + String qualifiedClassName = config.getPuzzleClassForName(game); LOGGER.debug("Loading " + qualifiedClassName); - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); + try { + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new RuntimeException("Puzzle importer null"); + } + + // Theoretically, this exception should never be thrown, since LEGUP should not be + // allowing the user to give text input for a puzzle that doesn't support it + if (!importer.acceptsTextInput()) { + throw new IllegalArgumentException( + puzzle.getName() + " does not accept text input"); + } + + setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); + importer.initializePuzzle(statements); + + puzzle.initializeView(); + // + // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Puzzle creation error"); + } + } - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new InvalidFileFormatException("Puzzle importer null"); + /** + * Loads a puzzle file + * + * @param fileName file name of the board file + * @throws InvalidFileFormatException if input is invalid + */ + public void loadPuzzle(String fileName) throws InvalidFileFormatException { + try { + loadPuzzle(new FileInputStream(fileName)); + curFileName = fileName; + setWindowTitle(puzzle.getName(), fileName); + } catch (IOException e) { + LOGGER.error("Invalid file " + fileName, e); + throw new InvalidFileFormatException("Could not find file"); } - importer.initializePuzzle(node); - puzzle.initializeView(); - puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new InvalidFileFormatException("Puzzle creation error"); - } - } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - } - - /** - * Loads a puzzle file from the input stream - * - * @throws InvalidFileFormatException if input is invalid - * @param inputStream input stream for the puzzle file - */ - public void loadPuzzle(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Invalid file", e); - throw new InvalidFileFormatException("Could not find file"); + + public void loadPuzzleEditor(String fileName) throws InvalidFileFormatException { + try { + loadPuzzleEditor(new FileInputStream(fileName)); + curFileName = fileName; + setWindowTitle(puzzle.getName(), fileName); + } catch (IOException e) { + LOGGER.error("Invalid file " + fileName, e); + throw new InvalidFileFormatException("Could not find file"); + } } - Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - try { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - String qualifiedClassName = - config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); - if (qualifiedClassName == null) { - throw new InvalidFileFormatException( - "Puzzle creation error: cannot find puzzle with that name"); + public void loadPuzzleEditor(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Invalid file", e); + throw new InvalidFileFormatException("Could not find file"); } - LOGGER.debug("Loading " + qualifiedClassName); - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); + Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + try { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + String qualifiedClassName = + config.getPuzzleClassForName( + node.getAttributes().getNamedItem("name").getNodeValue()); + if (qualifiedClassName == null) { + throw new InvalidFileFormatException( + "Puzzle creation error: cannot find puzzle with that name"); + } + // Check if puzzle is a "FileCreationEnabled" puzzle (meaning it is editable). + String[] editablePuzzles = + config.getFileCreationEnabledPuzzles().toArray(new String[0]); + boolean isEditablePuzzle = false; + for (int i = 0; i < editablePuzzles.length; i++) { + if (qualifiedClassName.contains(editablePuzzles[i])) { + isEditablePuzzle = true; + break; + } + } + if (!isEditablePuzzle) { + LOGGER.error("Puzzle is not editable"); + throw new InvalidFileFormatException("Puzzle is not editable"); + } + // If it is editable, start loading it + LOGGER.debug("Loading " + qualifiedClassName); + + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new InvalidFileFormatException("Puzzle importer null"); + } + importer.initializePuzzle(node); + puzzle.initializeView(); + puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new InvalidFileFormatException("Puzzle creation error"); + } + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); + } + } + + /** + * Loads a puzzle file from the input stream + * + * @throws InvalidFileFormatException if input is invalid + * @param inputStream input stream for the puzzle file + */ + public void loadPuzzle(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Invalid file", e); + throw new InvalidFileFormatException("Could not find file"); + } - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new InvalidFileFormatException("Puzzle importer null"); + Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + try { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + String qualifiedClassName = + config.getPuzzleClassForName( + node.getAttributes().getNamedItem("name").getNodeValue()); + if (qualifiedClassName == null) { + throw new InvalidFileFormatException( + "Puzzle creation error: cannot find puzzle with that name"); + } + LOGGER.debug("Loading " + qualifiedClassName); + + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new InvalidFileFormatException("Puzzle importer null"); + } + importer.initializePuzzle(node); + puzzle.initializeView(); + puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzle(puzzle); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new InvalidFileFormatException("Puzzle creation error"); + } + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - importer.initializePuzzle(node); - puzzle.initializeView(); - puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzle(puzzle); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new InvalidFileFormatException("Puzzle creation error"); - } - } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - } - - /** - * Sets the window title to 'PuzzleName - FileName' Removes the extension - * - * @param puzzleName puzzle name for the file - * @param fileName file name of the edu.rpi.legup.puzzle - */ - public void setWindowTitle(String puzzleName, String fileName) { - File file = new File(fileName); - legupUI.setTitle(puzzleName + " - " + file.getName()); - } - - /** - * Gets the Config info - * - * @return Config object - */ - public Config getConfig() { - return config; - } - - /** - * Gets the LegupUI - * - * @return LegupUI - */ - public LegupUI getLegupUI() { - return legupUI; - } - - /** - * Gets the initial board state - * - * @return the initial board state - */ - public Board getBoard() { - return puzzle == null ? null : puzzle.getCurrentBoard(); - } - - /** - * Sets the initial board state and the tree - * - * @param board initial board - */ - public void setBoard(Board board) { - puzzle.setCurrentBoard(board); - } - - /** - * Gets the rules tree - * - * @return rules tree - */ - public Tree getTree() { - return puzzle == null ? null : puzzle.getTree(); - } - - /** - * Gets the Puzzle for the board - * - * @return the Puzzle for the board - */ - public Puzzle getPuzzleModule() { - return puzzle; - } - - /** - * Sets the Puzzle for the board - * - * @param puzzle the PuzzleModule for the board - */ - public void setPuzzleModule(Puzzle puzzle) { - this.puzzle = puzzle; - } - - public String getCurFileName() { - return this.curFileName; - } - - /** - * Adds a {@link IHistoryListener} - * - * @param listener listener to add - */ - @Override - public void addHistoryListener(IHistoryListener listener) { - historyListeners.add(listener); - } - - /** - * Adds a {@link IHistoryListener} - * - * @param listener listener to remove - */ - @Override - public void removeHistoryListener(IHistoryListener listener) { - historyListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyHistoryListeners(Consumer algorithm) { - historyListeners.forEach(algorithm); - } - - /** - * Gets the History object for storing changes to the board states - * - * @return History object - */ - public History getHistory() { - return history; - } + + /** + * Sets the window title to 'PuzzleName - FileName' Removes the extension + * + * @param puzzleName puzzle name for the file + * @param fileName file name of the edu.rpi.legup.puzzle + */ + public void setWindowTitle(String puzzleName, String fileName) { + File file = new File(fileName); + legupUI.setTitle(puzzleName + " - " + file.getName()); + } + + /** + * Gets the Config info + * + * @return Config object + */ + public Config getConfig() { + return config; + } + + /** + * Gets the LegupUI + * + * @return LegupUI + */ + public LegupUI getLegupUI() { + return legupUI; + } + + /** + * Gets the initial board state + * + * @return the initial board state + */ + public Board getBoard() { + return puzzle == null ? null : puzzle.getCurrentBoard(); + } + + /** + * Sets the initial board state and the tree + * + * @param board initial board + */ + public void setBoard(Board board) { + puzzle.setCurrentBoard(board); + } + + /** + * Gets the rules tree + * + * @return rules tree + */ + public Tree getTree() { + return puzzle == null ? null : puzzle.getTree(); + } + + /** + * Gets the Puzzle for the board + * + * @return the Puzzle for the board + */ + public Puzzle getPuzzleModule() { + return puzzle; + } + + /** + * Sets the Puzzle for the board + * + * @param puzzle the PuzzleModule for the board + */ + public void setPuzzleModule(Puzzle puzzle) { + this.puzzle = puzzle; + } + + public String getCurFileName() { + return this.curFileName; + } + + /** + * Adds a {@link IHistoryListener} + * + * @param listener listener to add + */ + @Override + public void addHistoryListener(IHistoryListener listener) { + historyListeners.add(listener); + } + + /** + * Adds a {@link IHistoryListener} + * + * @param listener listener to remove + */ + @Override + public void removeHistoryListener(IHistoryListener listener) { + historyListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyHistoryListeners(Consumer algorithm) { + historyListeners.forEach(algorithm); + } + + /** + * Gets the History object for storing changes to the board states + * + * @return History object + */ + public History getHistory() { + return history; + } } diff --git a/src/main/java/edu/rpi/legup/app/InvalidConfigException.java b/src/main/java/edu/rpi/legup/app/InvalidConfigException.java index 03120dffe..a570e7d44 100644 --- a/src/main/java/edu/rpi/legup/app/InvalidConfigException.java +++ b/src/main/java/edu/rpi/legup/app/InvalidConfigException.java @@ -1,7 +1,7 @@ package edu.rpi.legup.app; public class InvalidConfigException extends Exception { - public InvalidConfigException(String message) { - super(message); - } + public InvalidConfigException(String message) { + super(message); + } } diff --git a/src/main/java/edu/rpi/legup/app/LegupPreferences.java b/src/main/java/edu/rpi/legup/app/LegupPreferences.java index eb5ea5981..12433d7e4 100644 --- a/src/main/java/edu/rpi/legup/app/LegupPreferences.java +++ b/src/main/java/edu/rpi/legup/app/LegupPreferences.java @@ -6,120 +6,125 @@ public class LegupPreferences { - private static LegupPreferences instance; - - private static String SAVED_PATH = ""; - - private static final Preferences preferences = - Preferences.userNodeForPackage(LegupPreferences.class); - - private static final Map preferencesMap = new HashMap<>(); - private static final Map defaultPreferencesMap = new HashMap<>(); - - public static final String WORK_DIRECTORY = "work-directory"; - public static final String START_FULL_SCREEN = "start-full-screen"; - public static final String AUTO_UPDATE = "auto-update"; - public static final String DARK_MODE = "night-mode"; - public static final String SHOW_MISTAKES = "show-mistakes"; - public static final String SHOW_ANNOTATIONS = "show-annotations"; - public static final String ALLOW_DEFAULT_RULES = "allow-default-rules"; - public static final String AUTO_GENERATE_CASES = "auto-generate-cases"; - public static final String IMMEDIATE_FEEDBACK = "immediate-feedback"; - public static final String COLOR_BLIND = "color-blind"; - - static { - defaultPreferencesMap.put(WORK_DIRECTORY, System.getProperty("user.home")); - defaultPreferencesMap.put(START_FULL_SCREEN, Boolean.toString(false)); - defaultPreferencesMap.put(AUTO_UPDATE, Boolean.toString(true)); - defaultPreferencesMap.put(DARK_MODE, Boolean.toString(false)); - defaultPreferencesMap.put(SHOW_MISTAKES, Boolean.toString(true)); - defaultPreferencesMap.put(SHOW_ANNOTATIONS, Boolean.toString(false)); - defaultPreferencesMap.put(ALLOW_DEFAULT_RULES, Boolean.toString(false)); - defaultPreferencesMap.put(AUTO_GENERATE_CASES, Boolean.toString(true)); - defaultPreferencesMap.put(IMMEDIATE_FEEDBACK, Boolean.toString(true)); - defaultPreferencesMap.put(COLOR_BLIND, Boolean.toString(false)); - } - - static { - preferencesMap.put( - WORK_DIRECTORY, preferences.get(WORK_DIRECTORY, defaultPreferencesMap.get(WORK_DIRECTORY))); - preferencesMap.put( - START_FULL_SCREEN, - preferences.get(START_FULL_SCREEN, defaultPreferencesMap.get(START_FULL_SCREEN))); - preferencesMap.put( - AUTO_UPDATE, preferences.get(AUTO_UPDATE, defaultPreferencesMap.get(AUTO_UPDATE))); - preferencesMap.put(DARK_MODE, preferences.get(DARK_MODE, defaultPreferencesMap.get(DARK_MODE))); - preferencesMap.put( - SHOW_MISTAKES, preferences.get(SHOW_MISTAKES, defaultPreferencesMap.get(SHOW_MISTAKES))); - preferencesMap.put( - SHOW_ANNOTATIONS, - preferences.get(SHOW_ANNOTATIONS, defaultPreferencesMap.get(SHOW_ANNOTATIONS))); - preferencesMap.put( - ALLOW_DEFAULT_RULES, - preferences.get(ALLOW_DEFAULT_RULES, defaultPreferencesMap.get(ALLOW_DEFAULT_RULES))); - preferencesMap.put( - AUTO_GENERATE_CASES, - preferences.get(AUTO_GENERATE_CASES, defaultPreferencesMap.get(AUTO_GENERATE_CASES))); - preferencesMap.put( - IMMEDIATE_FEEDBACK, - preferences.get(IMMEDIATE_FEEDBACK, defaultPreferencesMap.get(IMMEDIATE_FEEDBACK))); - preferencesMap.put( - COLOR_BLIND, preferences.get(COLOR_BLIND, defaultPreferencesMap.get(COLOR_BLIND))); - } - - /** - * Gets the legup preferences singleton instance. - * - * @return legup preferences - */ - public static LegupPreferences getInstance() { - if (instance == null) { - instance = new LegupPreferences(); + private static LegupPreferences instance; + + private static String SAVED_PATH = ""; + + private static final Preferences preferences = + Preferences.userNodeForPackage(LegupPreferences.class); + + private static final Map preferencesMap = new HashMap<>(); + private static final Map defaultPreferencesMap = new HashMap<>(); + + public static final String WORK_DIRECTORY = "work-directory"; + public static final String START_FULL_SCREEN = "start-full-screen"; + public static final String AUTO_UPDATE = "auto-update"; + public static final String DARK_MODE = "night-mode"; + public static final String SHOW_MISTAKES = "show-mistakes"; + public static final String SHOW_ANNOTATIONS = "show-annotations"; + public static final String ALLOW_DEFAULT_RULES = "allow-default-rules"; + public static final String AUTO_GENERATE_CASES = "auto-generate-cases"; + public static final String IMMEDIATE_FEEDBACK = "immediate-feedback"; + public static final String COLOR_BLIND = "color-blind"; + + static { + defaultPreferencesMap.put(WORK_DIRECTORY, System.getProperty("user.home")); + defaultPreferencesMap.put(START_FULL_SCREEN, Boolean.toString(false)); + defaultPreferencesMap.put(AUTO_UPDATE, Boolean.toString(true)); + defaultPreferencesMap.put(DARK_MODE, Boolean.toString(false)); + defaultPreferencesMap.put(SHOW_MISTAKES, Boolean.toString(true)); + defaultPreferencesMap.put(SHOW_ANNOTATIONS, Boolean.toString(false)); + defaultPreferencesMap.put(ALLOW_DEFAULT_RULES, Boolean.toString(false)); + defaultPreferencesMap.put(AUTO_GENERATE_CASES, Boolean.toString(true)); + defaultPreferencesMap.put(IMMEDIATE_FEEDBACK, Boolean.toString(true)); + defaultPreferencesMap.put(COLOR_BLIND, Boolean.toString(false)); } - return instance; - } - - /** Private LegupPreferences Singleton Constructor */ - private LegupPreferences() {} - - /** - * Gets the user preference by the string key - * - * @param key key name of the preference - * @return value of the preference - */ - public String getUserPref(String key) { - return preferencesMap.get(key); - } - - /** - * Gets the user preference by the string key, value pair - * - * @param key key name of the preference - * @param value value of the preference - */ - public void setUserPref(String key, String value) { - preferences.put(key, value); - preferencesMap.put(key, value); - } - - public boolean getUserPrefAsBool(String key) { - if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(true))) { - return true; - } else { - if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(false))) { - return false; - } else { - throw new RuntimeException("Cannot get user preference - " + key); - } + + static { + preferencesMap.put( + WORK_DIRECTORY, + preferences.get(WORK_DIRECTORY, defaultPreferencesMap.get(WORK_DIRECTORY))); + preferencesMap.put( + START_FULL_SCREEN, + preferences.get(START_FULL_SCREEN, defaultPreferencesMap.get(START_FULL_SCREEN))); + preferencesMap.put( + AUTO_UPDATE, preferences.get(AUTO_UPDATE, defaultPreferencesMap.get(AUTO_UPDATE))); + preferencesMap.put( + DARK_MODE, preferences.get(DARK_MODE, defaultPreferencesMap.get(DARK_MODE))); + preferencesMap.put( + SHOW_MISTAKES, + preferences.get(SHOW_MISTAKES, defaultPreferencesMap.get(SHOW_MISTAKES))); + preferencesMap.put( + SHOW_ANNOTATIONS, + preferences.get(SHOW_ANNOTATIONS, defaultPreferencesMap.get(SHOW_ANNOTATIONS))); + preferencesMap.put( + ALLOW_DEFAULT_RULES, + preferences.get( + ALLOW_DEFAULT_RULES, defaultPreferencesMap.get(ALLOW_DEFAULT_RULES))); + preferencesMap.put( + AUTO_GENERATE_CASES, + preferences.get( + AUTO_GENERATE_CASES, defaultPreferencesMap.get(AUTO_GENERATE_CASES))); + preferencesMap.put( + IMMEDIATE_FEEDBACK, + preferences.get(IMMEDIATE_FEEDBACK, defaultPreferencesMap.get(IMMEDIATE_FEEDBACK))); + preferencesMap.put( + COLOR_BLIND, preferences.get(COLOR_BLIND, defaultPreferencesMap.get(COLOR_BLIND))); + } + + /** + * Gets the legup preferences singleton instance. + * + * @return legup preferences + */ + public static LegupPreferences getInstance() { + if (instance == null) { + instance = new LegupPreferences(); + } + return instance; } - } - public String getSavedPath() { - return SAVED_PATH; - } + /** Private LegupPreferences Singleton Constructor */ + private LegupPreferences() {} + + /** + * Gets the user preference by the string key + * + * @param key key name of the preference + * @return value of the preference + */ + public String getUserPref(String key) { + return preferencesMap.get(key); + } + + /** + * Gets the user preference by the string key, value pair + * + * @param key key name of the preference + * @param value value of the preference + */ + public void setUserPref(String key, String value) { + preferences.put(key, value); + preferencesMap.put(key, value); + } - public void setSavedPath(String path) { - SAVED_PATH = path; - } + public boolean getUserPrefAsBool(String key) { + if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(true))) { + return true; + } else { + if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(false))) { + return false; + } else { + throw new RuntimeException("Cannot get user preference - " + key); + } + } + } + + public String getSavedPath() { + return SAVED_PATH; + } + + public void setSavedPath(String path) { + SAVED_PATH = path; + } } diff --git a/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java b/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java index 4a055ab3a..f3945be22 100644 --- a/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java +++ b/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java @@ -19,85 +19,87 @@ public class PuzzleKeyAccelerator implements KeyListener { - private Map keyStrokeMap; + private Map keyStrokeMap; - public PuzzleKeyAccelerator() { - this.keyStrokeMap = new HashMap<>(); - } + public PuzzleKeyAccelerator() { + this.keyStrokeMap = new HashMap<>(); + } - public void addKeyAccelerator(KeyStroke keyStroke, Rule rule) { - keyStrokeMap.put(keyStroke, rule); - } + public void addKeyAccelerator(KeyStroke keyStroke, Rule rule) { + keyStrokeMap.put(keyStroke, rule); + } - public Map getKeyStrokeMap() { - return this.keyStrokeMap; - } + public Map getKeyStrokeMap() { + return this.keyStrokeMap; + } - public void clearKeyMap() { - this.keyStrokeMap.clear(); - } + public void clearKeyMap() { + this.keyStrokeMap.clear(); + } - /** - * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a - * definition of a key typed event. - * - * @param e the event to be processed - */ - @Override - public void keyTyped(KeyEvent e) {} + /** + * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a + * definition of a key typed event. + * + * @param e the event to be processed + */ + @Override + public void keyTyped(KeyEvent e) {} - /** - * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a - * definition of a key pressed event. - * - * @param e the event to be processed - */ - @Override - public void keyPressed(KeyEvent e) { - KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); - Rule rule = keyStrokeMap.get(keyStroke); - if (rule != null) { - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + /** + * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a + * definition of a key pressed event. + * + * @param e the event to be processed + */ + @Override + public void keyPressed(KeyEvent e) { + KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); + Rule rule = keyStrokeMap.get(keyStroke); + if (rule != null) { + TreeView treeView = + GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - String update = ""; - if (rule.getRuleType() == RuleType.CASE) { - // TODO: review this line of code and figure out what it's supposed to do (remove if - // necessary) - // handleCaseRule((CaseRule)rule); - } else { - if (rule.getRuleType() == RuleType.CONTRADICTION) { - TreeViewSelection selection = treeView.getSelection(); + String update = ""; + if (rule.getRuleType() == RuleType.CASE) { + // TODO: review this line of code and figure out what it's supposed to do (remove if + // necessary) + // handleCaseRule((CaseRule)rule); + } else { + if (rule.getRuleType() == RuleType.CONTRADICTION) { + TreeViewSelection selection = treeView.getSelection(); - ICommand validate = - new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - update = validate.getError(); - } - } else { - TreeViewSelection selection = treeView.getSelection(); + ICommand validate = + new ValidateContradictionRuleCommand( + selection, (ContradictionRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + update = validate.getError(); + } + } else { + TreeViewSelection selection = treeView.getSelection(); - ICommand validate = new ValidateDirectRuleCommand(selection, (DirectRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - update = validate.getError(); - } + ICommand validate = new ValidateDirectRuleCommand(selection, (DirectRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + update = validate.getError(); + } + } + } + GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(update); } - } - GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(update); } - } - /** - * Invoked when a key has been released. See the class description for {@link KeyEvent} for a - * definition of a key released event. - * - * @param e the event to be processed - */ - @Override - public void keyReleased(KeyEvent e) {} + /** + * Invoked when a key has been released. See the class description for {@link KeyEvent} for a + * definition of a key released event. + * + * @param e the event to be processed + */ + @Override + public void keyReleased(KeyEvent e) {} } diff --git a/src/main/java/edu/rpi/legup/controller/BoardController.java b/src/main/java/edu/rpi/legup/controller/BoardController.java index f672961d2..eaae3851d 100644 --- a/src/main/java/edu/rpi/legup/controller/BoardController.java +++ b/src/main/java/edu/rpi/legup/controller/BoardController.java @@ -4,88 +4,88 @@ import java.awt.event.*; public class BoardController extends Controller { - protected Point lastLeftMousePoint; - protected Point lastRightMousePoint; + protected Point lastLeftMousePoint; + protected Point lastRightMousePoint; - /** - * BoardController Constructor creates a controller object to listen to ui events from a - * ScrollView - */ - public BoardController() { - super(); - lastLeftMousePoint = null; - lastRightMousePoint = null; - } + /** + * BoardController Constructor creates a controller object to listen to ui events from a + * ScrollView + */ + public BoardController() { + super(); + lastLeftMousePoint = null; + lastRightMousePoint = null; + } - /** - * Mouse Clicked event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event - sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); - } + /** + * Mouse Pressed event - sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); + } - /** - * Mouse Released event - sets the cursor back to the default cursor and reset info for panning - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - } + /** + * Mouse Released event - sets the cursor back to the default cursor and reset info for panning + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + } - /** - * Mouse Entered event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) {} + /** + * Mouse Entered event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) {} - /** - * Mouse Exited event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) {} + /** + * Mouse Exited event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) {} - /** - * Mouse Dragged event - adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - super.mouseDragged(e); - } + /** + * Mouse Dragged event - adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + super.mouseDragged(e); + } - /** - * Mouse Moved event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) {} + /** + * Mouse Moved event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) {} - /** - * Mouse Wheel Moved event - zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - super.mouseWheelMoved(e); - } + /** + * Mouse Wheel Moved event - zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + super.mouseWheelMoved(e); + } } diff --git a/src/main/java/edu/rpi/legup/controller/Controller.java b/src/main/java/edu/rpi/legup/controller/Controller.java index cd281fc21..57ce107ac 100644 --- a/src/main/java/edu/rpi/legup/controller/Controller.java +++ b/src/main/java/edu/rpi/legup/controller/Controller.java @@ -6,116 +6,116 @@ import javax.swing.*; public abstract class Controller implements MouseMotionListener, MouseListener, MouseWheelListener { - protected ScrollView viewer; - private int x, y; - private boolean pan; + protected ScrollView viewer; + private int x, y; + private boolean pan; - /** - * Controller Constructor creates a controller object to listen to ui events from a {@link - * ScrollView} - */ - public Controller() { - x = y = -1; - pan = false; - } + /** + * Controller Constructor creates a controller object to listen to ui events from a {@link + * ScrollView} + */ + public Controller() { + x = y = -1; + pan = false; + } - public void setViewer(ScrollView viewer) { - this.viewer = viewer; - } + public void setViewer(ScrollView viewer) { + this.viewer = viewer; + } - /** - * Mouse Clicked event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON2) { - pan = true; - x = e.getX(); - y = e.getY(); - viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); + /** + * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON2) { + pan = true; + x = e.getX(); + y = e.getY(); + viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); + } } - } - /** - * Mouse Released event sets the cursor back to the default cursor and reset info for panning - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON2) { - pan = false; - viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + /** + * Mouse Released event sets the cursor back to the default cursor and reset info for panning + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON2) { + pan = false; + viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } } - } - /** - * Mouse Entered event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) {} + /** + * Mouse Entered event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) {} - /** - * Mouse Exited event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) {} + /** + * Mouse Exited event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) {} - /** - * Mouse Dragged event adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - if (pan) { - JViewport viewport = viewer.getViewport(); - Point position = viewer.getViewport().getViewPosition(); - position.x += (x - e.getX()); - position.y += (y - e.getY()); - viewport.setViewPosition(position); - viewer.revalidate(); + /** + * Mouse Dragged event adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + if (pan) { + JViewport viewport = viewer.getViewport(); + Point position = viewer.getViewport().getViewPosition(); + position.x += (x - e.getX()); + position.y += (y - e.getY()); + viewport.setViewPosition(position); + viewer.revalidate(); + } } - } - /** - * Mouse Moved event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) {} + /** + * Mouse Moved event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) {} - /** - * Mouse Wheel Moved event zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - // System.out.println(e.getWheelRotation()); - if (e.isControlDown()) { - if (e.getWheelRotation() != 0) { - viewer.zoom(e.getWheelRotation() * 2, e.getPoint()); - } - } else { - if (e.getWheelRotation() != 0) { - viewer.zoom(e.getWheelRotation(), e.getPoint()); - } + /** + * Mouse Wheel Moved event zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + // System.out.println(e.getWheelRotation()); + if (e.isControlDown()) { + if (e.getWheelRotation() != 0) { + viewer.zoom(e.getWheelRotation() * 2, e.getPoint()); + } + } else { + if (e.getWheelRotation() != 0) { + viewer.zoom(e.getWheelRotation(), e.getPoint()); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/controller/CursorController.java b/src/main/java/edu/rpi/legup/controller/CursorController.java index a97f147b8..2706bd522 100644 --- a/src/main/java/edu/rpi/legup/controller/CursorController.java +++ b/src/main/java/edu/rpi/legup/controller/CursorController.java @@ -7,48 +7,48 @@ import java.util.TimerTask; public class CursorController { - public static final Cursor BUSY_CURSOR = new Cursor(Cursor.WAIT_CURSOR); - public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); - public static final int DELAY = 200; // in milliseconds + public static final Cursor BUSY_CURSOR = new Cursor(Cursor.WAIT_CURSOR); + public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); + public static final int DELAY = 200; // in milliseconds - private CursorController() { - // Intentionally left empty - } + private CursorController() { + // Intentionally left empty + } - /** - * Creates an ActionListener that will still do the same action processing as the given - * ActionListener while also displaying a loading cursor if the time it takes to execute the given - * process exceeds the time (in milliseconds) specified in this.DELAY - * - *

Sources consulted: http://www.catalysoft.com/articles/busycursor.html - * - * @param component The component you want to set the cursor for - * @param mainActionListener The ActionListener that does the intended action processing - * @return An ActionListener object that does the same action processing as mainActionListener - * while also modifying the cursor if needed - */ - public static ActionListener createListener( - final Component component, final ActionListener mainActionListener) { - ActionListener actionListener = - e -> { - TimerTask timerTask = - new TimerTask() { - @Override - public void run() { - component.setCursor(BUSY_CURSOR); - } - }; + /** + * Creates an ActionListener that will still do the same action processing as the given + * ActionListener while also displaying a loading cursor if the time it takes to execute the + * given process exceeds the time (in milliseconds) specified in this.DELAY + * + *

Sources consulted: http://www.catalysoft.com/articles/busycursor.html + * + * @param component The component you want to set the cursor for + * @param mainActionListener The ActionListener that does the intended action processing + * @return An ActionListener object that does the same action processing as mainActionListener + * while also modifying the cursor if needed + */ + public static ActionListener createListener( + final Component component, final ActionListener mainActionListener) { + ActionListener actionListener = + e -> { + TimerTask timerTask = + new TimerTask() { + @Override + public void run() { + component.setCursor(BUSY_CURSOR); + } + }; - Timer timer = new Timer(); - try { - timer.schedule(timerTask, DELAY); - mainActionListener.actionPerformed(e); - } finally { - timer.cancel(); - component.setCursor(DEFAULT_CURSOR); - } - }; + Timer timer = new Timer(); + try { + timer.schedule(timerTask, DELAY); + mainActionListener.actionPerformed(e); + } finally { + timer.cancel(); + component.setCursor(DEFAULT_CURSOR); + } + }; - return actionListener; - } + return actionListener; + } } diff --git a/src/main/java/edu/rpi/legup/controller/EditorElementController.java b/src/main/java/edu/rpi/legup/controller/EditorElementController.java index 7aa1fe06c..5a23885af 100644 --- a/src/main/java/edu/rpi/legup/controller/EditorElementController.java +++ b/src/main/java/edu/rpi/legup/controller/EditorElementController.java @@ -10,43 +10,43 @@ import javax.swing.*; public class EditorElementController implements ActionListener { - protected Object lastSource; - protected ElementController elementController; - protected ElementButton prevButton; - - public EditorElementController() { - super(); - elementController = null; - prevButton = null; - } - - public void setElementController(ElementController elementController) { - this.elementController = elementController; - } - - public void buttonPressed(Element element) { - // TODO: implement what happens when element is pressed - - System.out.printf("%s button pressed!\n", element.getElementName()); - if (elementController != null) { - elementController.setSelectedElement(element); + protected Object lastSource; + protected ElementController elementController; + protected ElementButton prevButton; + + public EditorElementController() { + super(); + elementController = null; + prevButton = null; } - } - @Override - public void actionPerformed(ActionEvent e) { - lastSource = e.getSource(); - ElementButton button = (ElementButton) lastSource; - buttonPressed(button.getElement()); + public void setElementController(ElementController elementController) { + this.elementController = elementController; + } + + public void buttonPressed(Element element) { + // TODO: implement what happens when element is pressed - // reset border in previous selected button - if (this.prevButton != null) { - this.prevButton.resetBorder(); + System.out.printf("%s button pressed!\n", element.getElementName()); + if (elementController != null) { + elementController.setSelectedElement(element); + } } - // change border color when select a button - button.setBorderToSelected(); + @Override + public void actionPerformed(ActionEvent e) { + lastSource = e.getSource(); + ElementButton button = (ElementButton) lastSource; + buttonPressed(button.getElement()); + + // reset border in previous selected button + if (this.prevButton != null) { + this.prevButton.resetBorder(); + } - this.prevButton = button; - } + // change border color when select a button + button.setBorderToSelected(); + + this.prevButton = button; + } } diff --git a/src/main/java/edu/rpi/legup/controller/ElementController.java b/src/main/java/edu/rpi/legup/controller/ElementController.java index f17461ebc..5840650e1 100644 --- a/src/main/java/edu/rpi/legup/controller/ElementController.java +++ b/src/main/java/edu/rpi/legup/controller/ElementController.java @@ -27,323 +27,325 @@ import java.awt.event.*; public class ElementController - implements MouseListener, MouseMotionListener, ActionListener, KeyListener { - protected BoardView boardView; - private Element selectedElement; + implements MouseListener, MouseMotionListener, ActionListener, KeyListener { + protected BoardView boardView; + private Element selectedElement; - /** - * ElementController Constructor controller to handles ui events associated interacting with a - * {@link BoardView} - */ - public ElementController() { - this.boardView = null; - this.selectedElement = null; - } + /** + * ElementController Constructor controller to handles ui events associated interacting with a + * {@link BoardView} + */ + public ElementController() { + this.boardView = null; + this.selectedElement = null; + } - public void setSelectedElement(Element selectedElement) { - this.selectedElement = selectedElement; - } + public void setSelectedElement(Element selectedElement) { + this.selectedElement = selectedElement; + } - /** - * Sets the {@link BoardView} - * - * @param boardView board view - */ - public void setBoardView(BoardView boardView) { - this.boardView = boardView; - } + /** + * Sets the {@link BoardView} + * + * @param boardView board view + */ + public void setBoardView(BoardView boardView) { + this.boardView = boardView; + } - /** - * Invoked when the mouse button has been clicked (pressed and released) on a component. - * - * @param e the event to be processed - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Invoked when the mouse button has been clicked (pressed and released) on a component. + * + * @param e the event to be processed + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e the event to be processed - */ - @Override - public void mousePressed(MouseEvent e) {} + /** + * Invoked when a mouse button has been pressed on a component. + * + * @param e the event to be processed + */ + @Override + public void mousePressed(MouseEvent e) {} - /** - * Invoked when a mouse button has been released on a component. - * - * @param e the event to be processed - */ - @Override - public void mouseReleased(MouseEvent e) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = null; - if (treePanel != null) { - treeView = treePanel.getTreeView(); - } + /** + * Invoked when a mouse button has been released on a component. + * + * @param e the event to be processed + */ + @Override + public void mouseReleased(MouseEvent e) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = null; + if (treePanel != null) { + treeView = treePanel.getTreeView(); + } - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - ElementView elementView = boardView.getElement(e.getPoint()); - TreeViewSelection selection = null; - if (treeView != null) { - selection = treeView.getSelection(); - } - // funny - if (elementView != null) { - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - AutoCaseRuleCommand autoCaseRuleCommand = - new AutoCaseRuleCommand(elementView, selection, caseBoard.getCaseRule(), caseBoard, e); - if (autoCaseRuleCommand.canExecute()) { - autoCaseRuleCommand.execute(); - getInstance().getHistory().pushChange(autoCaseRuleCommand); - if (treePanel != null) { - treePanel.updateError(""); - } - } else { - if (treePanel != null) { - treePanel.updateError(autoCaseRuleCommand.getError()); - } + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - } else { - if (selection != null) { - ICommand edit = new EditDataCommand(elementView, selection, e); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - if (treePanel != null) { - treePanel.updateError(""); - } - } else { - if (treePanel != null) { - treePanel.updateError(edit.getError()); + Board board = boardView.getBoard(); + ElementView elementView = boardView.getElement(e.getPoint()); + TreeViewSelection selection = null; + if (treeView != null) { + selection = treeView.getSelection(); + } + // funny + if (elementView != null) { + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + AutoCaseRuleCommand autoCaseRuleCommand = + new AutoCaseRuleCommand( + elementView, selection, caseBoard.getCaseRule(), caseBoard, e); + if (autoCaseRuleCommand.canExecute()) { + autoCaseRuleCommand.execute(); + getInstance().getHistory().pushChange(autoCaseRuleCommand); + if (treePanel != null) { + treePanel.updateError(""); + } + } else { + if (treePanel != null) { + treePanel.updateError(autoCaseRuleCommand.getError()); + } + } + } else { + if (selection != null) { + ICommand edit = new EditDataCommand(elementView, selection, e); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + if (treePanel != null) { + treePanel.updateError(""); + } + } else { + if (treePanel != null) { + treePanel.updateError(edit.getError()); + } + } + } } - } } - } - } - // if (selectedElement != null) { - GridBoard b = (GridBoard) this.boardView.getBoard(); - Point point = e.getPoint(); - Point scaledPoint = - new Point( - (int) Math.floor(point.x / (30 * this.boardView.getScale())), - (int) Math.floor(point.y / (30 * this.boardView.getScale()))); - if (this.boardView.getBoard() instanceof TreeTentBoard) { - scaledPoint.setLocation(scaledPoint.getX() - 1, scaledPoint.getY() - 1); + // if (selectedElement != null) { + GridBoard b = (GridBoard) this.boardView.getBoard(); + Point point = e.getPoint(); + Point scaledPoint = + new Point( + (int) Math.floor(point.x / (30 * this.boardView.getScale())), + (int) Math.floor(point.y / (30 * this.boardView.getScale()))); + if (this.boardView.getBoard() instanceof TreeTentBoard) { + scaledPoint.setLocation(scaledPoint.getX() - 1, scaledPoint.getY() - 1); + } + System.out.printf( + "selected Element is NOT null, attempting to change board at (%d, %d)\n", + scaledPoint.x, scaledPoint.y); + // System.out.println("Before: " + b.getCell(scaledPoint.x, + // scaledPoint.y).getData()); + b.setCell(scaledPoint.x, scaledPoint.y, this.selectedElement, e); + // System.out.println("After: " + b.getCell(scaledPoint.x, + // scaledPoint.y).getData()); + // } else { + // System.out.println("selected Element is null!"); + // } + boardView.repaint(); } - System.out.printf( - "selected Element is NOT null, attempting to change board at (%d, %d)\n", - scaledPoint.x, scaledPoint.y); - // System.out.println("Before: " + b.getCell(scaledPoint.x, - // scaledPoint.y).getData()); - b.setCell(scaledPoint.x, scaledPoint.y, this.selectedElement, e); - // System.out.println("After: " + b.getCell(scaledPoint.x, scaledPoint.y).getData()); - // } else { - // System.out.println("selected Element is null!"); - // } - boardView.repaint(); - } - /** - * Invoked when the mouse enters a component. - * - * @param e the event to be processed - */ - @Override - public void mouseEntered(MouseEvent e) { - boardView.setFocusable(true); - boardView.requestFocusInWindow(); - TreeElement treeElement = boardView.getTreeElement(); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); - } - Board board = boardView.getBoard(); - ElementView elementView = boardView.getElement(e.getPoint()); - ElementSelection selection = boardView.getSelection(); - String error = null; - if (elementView != null) { - selection.newHover(elementView); - if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { - PuzzleElement element = elementView.getPuzzleElement(); - if (treeElement != null - && treeElement.getType() == TreeElementType.TRANSITION - && board.getModifiedData().contains(element)) { - TreeTransition transition = (TreeTransition) treeElement; - if (transition.isJustified() && !transition.isCorrect()) { - error = transition.getRule().checkRuleAt(transition, element); - } + /** + * Invoked when the mouse enters a component. + * + * @param e the event to be processed + */ + @Override + public void mouseEntered(MouseEvent e) { + boardView.setFocusable(true); + boardView.requestFocusInWindow(); + TreeElement treeElement = boardView.getTreeElement(); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - if (error != null) { - dynamicView.updateError(error); - } else { - dynamicView.resetStatus(); + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + Board board = boardView.getBoard(); + ElementView elementView = boardView.getElement(e.getPoint()); + ElementSelection selection = boardView.getSelection(); + String error = null; + if (elementView != null) { + selection.newHover(elementView); + if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { + PuzzleElement element = elementView.getPuzzleElement(); + if (treeElement != null + && treeElement.getType() == TreeElementType.TRANSITION + && board.getModifiedData().contains(element)) { + TreeTransition transition = (TreeTransition) treeElement; + if (transition.isJustified() && !transition.isCorrect()) { + error = transition.getRule().checkRuleAt(transition, element); + } + } + if (error != null) { + dynamicView.updateError(error); + } else { + dynamicView.resetStatus(); + } + } + boardView.repaint(); } - } - boardView.repaint(); } - } - /** - * Invoked when the mouse exits a component. - * - * @param e the event to be processed - */ - @Override - public void mouseExited(MouseEvent e) { - boardView.setFocusable(false); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); - } - ElementView element = boardView.getElement(e.getPoint()); - if (element != null) { - boardView.getSelection().clearHover(); - dynamicView.resetStatus(); - boardView.repaint(); + /** + * Invoked when the mouse exits a component. + * + * @param e the event to be processed + */ + @Override + public void mouseExited(MouseEvent e) { + boardView.setFocusable(false); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + ElementView element = boardView.getElement(e.getPoint()); + if (element != null) { + boardView.getSelection().clearHover(); + dynamicView.resetStatus(); + boardView.repaint(); + } } - } - /** - * Invoked when the mouse dragged - * - * @param e the event to be processed - */ - @Override - public void mouseDragged(MouseEvent e) {} + /** + * Invoked when the mouse dragged + * + * @param e the event to be processed + */ + @Override + public void mouseDragged(MouseEvent e) {} - /** - * Invoked when the mouse moved - * - * @param e the event to be processed - */ - @Override - public void mouseMoved(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - TreeElement treeElement = boardView.getTreeElement(); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); - } - ElementView elementView = boardView.getElement(e.getPoint()); - ElementSelection selection = boardView.getSelection(); - String error = null; - if (elementView != null && elementView != selection.getHover()) { - selection.newHover(elementView); - if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { - PuzzleElement element = elementView.getPuzzleElement(); - if (treeElement != null - && treeElement.getType() == TreeElementType.TRANSITION - && board.getModifiedData().contains(element)) { - TreeTransition transition = (TreeTransition) treeElement; - if (transition.isJustified() && !transition.isCorrect()) { - error = transition.getRule().checkRuleAt(transition, element); - } + /** + * Invoked when the mouse moved + * + * @param e the event to be processed + */ + @Override + public void mouseMoved(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - if (error != null) { - dynamicView.updateError(error); - } else { - dynamicView.resetStatus(); + Board board = boardView.getBoard(); + TreeElement treeElement = boardView.getTreeElement(); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + ElementView elementView = boardView.getElement(e.getPoint()); + ElementSelection selection = boardView.getSelection(); + String error = null; + if (elementView != null && elementView != selection.getHover()) { + selection.newHover(elementView); + if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { + PuzzleElement element = elementView.getPuzzleElement(); + if (treeElement != null + && treeElement.getType() == TreeElementType.TRANSITION + && board.getModifiedData().contains(element)) { + TreeTransition transition = (TreeTransition) treeElement; + if (transition.isJustified() && !transition.isCorrect()) { + error = transition.getRule().checkRuleAt(transition, element); + } + } + if (error != null) { + dynamicView.updateError(error); + } else { + dynamicView.resetStatus(); + } + } + boardView.repaint(); } - } - boardView.repaint(); } - } - public void changeCell(MouseEvent e, PuzzleElement data) {} + public void changeCell(MouseEvent e, PuzzleElement data) {} - /** - * Invoked when an action occurs. - * - * @param e the event to be processed - */ - @SuppressWarnings("Unchecked") - @Override - public void actionPerformed(ActionEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - ElementView selectedElement = boardView.getSelection().getFirstSelection(); - PuzzleElement puzzleElement = selectedElement.getPuzzleElement(); + /** + * Invoked when an action occurs. + * + * @param e the event to be processed + */ + @SuppressWarnings("Unchecked") + @Override + public void actionPerformed(ActionEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + ElementView selectedElement = boardView.getSelection().getFirstSelection(); + PuzzleElement puzzleElement = selectedElement.getPuzzleElement(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeTransitionView transitionView = (TreeTransitionView) selectedView; + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeTransitionView transitionView = (TreeTransitionView) selectedView; - Board prevBord = transitionView.getTreeElement().getParents().get(0).getBoard(); + Board prevBord = transitionView.getTreeElement().getParents().get(0).getBoard(); - int value = (Integer) ((SelectionItemView) e.getSource()).getData().getData(); + int value = (Integer) ((SelectionItemView) e.getSource()).getData().getData(); - puzzleElement.setData(value); + puzzleElement.setData(value); - if (puzzleElement.equalsData(prevBord.getPuzzleElement(puzzleElement))) { - puzzleElement.setModified(false); - } else { - puzzleElement.setModified(true); - } + if (puzzleElement.equalsData(prevBord.getPuzzleElement(puzzleElement))) { + puzzleElement.setModified(false); + } else { + puzzleElement.setModified(true); + } - transitionView.getTreeElement().propagateChange(puzzleElement); + transitionView.getTreeElement().propagateChange(puzzleElement); - boardView.repaint(); - boardView.getSelection().clearSelection(); - } + boardView.repaint(); + boardView.getSelection().clearSelection(); + } - /** - * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a - * definition of a key typed event. - * - * @param e the event to be processed - */ - @Override - public void keyTyped(KeyEvent e) {} + /** + * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a + * definition of a key typed event. + * + * @param e the event to be processed + */ + @Override + public void keyTyped(KeyEvent e) {} - /** - * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a - * definition of a key pressed event. - * - * @param e the event to be processed - */ - @Override - public void keyPressed(KeyEvent e) {} + /** + * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a + * definition of a key pressed event. + * + * @param e the event to be processed + */ + @Override + public void keyPressed(KeyEvent e) {} - /** - * Invoked when a key has been released. See the class description for {@link KeyEvent} for a - * definition of a key released event. - * - * @param e the event to be processed - */ - @Override - public void keyReleased(KeyEvent e) { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { - puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); - } + /** + * Invoked when a key has been released. See the class description for {@link KeyEvent} for a + * definition of a key released event. + * + * @param e the event to be processed + */ + @Override + public void keyReleased(KeyEvent e) { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + Board board = boardView.getBoard(); + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/controller/RuleController.java b/src/main/java/edu/rpi/legup/controller/RuleController.java index f72dddbde..6e88dc4be 100644 --- a/src/main/java/edu/rpi/legup/controller/RuleController.java +++ b/src/main/java/edu/rpi/legup/controller/RuleController.java @@ -17,102 +17,105 @@ import java.util.List; public class RuleController implements ActionListener { - protected Object lastSource; + protected Object lastSource; - /** - * RuleController Constructor creates a controller object to listen to ui events from a {@link - * RulePanel} - */ - public RuleController() { - super(); - } + /** + * RuleController Constructor creates a controller object to listen to ui events from a {@link + * RulePanel} + */ + public RuleController() { + super(); + } - /** - * Button Pressed event occurs a when a rule button has been pressed - * - * @param rule rule of the button that was pressed - */ - public void buttonPressed(Rule rule) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = treePanel.getTreeView(); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - List selectedViews = selection.getSelectedViews(); + /** + * Button Pressed event occurs a when a rule button has been pressed + * + * @param rule rule of the button that was pressed + */ + public void buttonPressed(Rule rule) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = treePanel.getTreeView(); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + List selectedViews = selection.getSelectedViews(); - String updateErrorString = ""; - if (rule.getRuleType() == RuleType.CASE) { - CaseRule caseRule = (CaseRule) rule; - if (selectedViews.size() == 1) { - TreeElementView elementView = selection.getFirstSelection(); - TreeElement element = elementView.getTreeElement(); - if (element.getType() == TreeElementType.TRANSITION) { - ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); - if (caseRuleCommand.canExecute()) { - caseRuleCommand.execute(); - getInstance().getHistory().pushChange(caseRuleCommand); - } else { - updateErrorString = caseRuleCommand.getError(); - } - } else { - if (LegupPreferences.getInstance() - .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) - .equalsIgnoreCase(Boolean.toString(true))) { - CaseBoard caseBoard = caseRule.getCaseBoard(element.getBoard()); - if (caseBoard != null && caseBoard.getCount() > 0) { - puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); + String updateErrorString = ""; + if (rule.getRuleType() == RuleType.CASE) { + CaseRule caseRule = (CaseRule) rule; + if (selectedViews.size() == 1) { + TreeElementView elementView = selection.getFirstSelection(); + TreeElement element = elementView.getTreeElement(); + if (element.getType() == TreeElementType.TRANSITION) { + ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); + if (caseRuleCommand.canExecute()) { + caseRuleCommand.execute(); + getInstance().getHistory().pushChange(caseRuleCommand); + } else { + updateErrorString = caseRuleCommand.getError(); + } + } else { + if (LegupPreferences.getInstance() + .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) + .equalsIgnoreCase(Boolean.toString(true))) { + CaseBoard caseBoard = caseRule.getCaseBoard(element.getBoard()); + if (caseBoard != null && caseBoard.getCount() > 0) { + puzzle.notifyBoardListeners( + listener -> listener.onCaseBoardAdded(caseBoard)); + } else { + updateErrorString = "This board cannot be applied with this case rule."; + } + } else { + updateErrorString = + "Auto generated case rules are turned off in preferences."; + } + } } else { - updateErrorString = "This board cannot be applied with this case rule."; + ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); + if (caseRuleCommand.canExecute()) { + caseRuleCommand.execute(); + getInstance().getHistory().pushChange(caseRuleCommand); + } else { + updateErrorString = caseRuleCommand.getError(); + } } - } else { - updateErrorString = "Auto generated case rules are turned off in preferences."; - } - } - } else { - ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); - if (caseRuleCommand.canExecute()) { - caseRuleCommand.execute(); - getInstance().getHistory().pushChange(caseRuleCommand); - } else { - updateErrorString = caseRuleCommand.getError(); - } - } - } else { - if (rule.getRuleType() == RuleType.CONTRADICTION) { - ICommand validate = - new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); } else { - updateErrorString = validate.getError(); - } - } else { - boolean def = - LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.ALLOW_DEFAULT_RULES); - ICommand validate = - def - ? new ApplyDefaultDirectRuleCommand(selection, (DirectRule) rule) - : new ValidateDirectRuleCommand(selection, (DirectRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - updateErrorString = validate.getError(); + if (rule.getRuleType() == RuleType.CONTRADICTION) { + ICommand validate = + new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + updateErrorString = validate.getError(); + } + } else { + boolean def = + LegupPreferences.getInstance() + .getUserPrefAsBool(LegupPreferences.ALLOW_DEFAULT_RULES); + ICommand validate = + def + ? new ApplyDefaultDirectRuleCommand(selection, (DirectRule) rule) + : new ValidateDirectRuleCommand(selection, (DirectRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + updateErrorString = validate.getError(); + } + } } - } + GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(updateErrorString); } - GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(updateErrorString); - } - /** - * ICommand Performed event occurs when a rule button has been pressed - * - * @param e action event object - */ - @Override - public void actionPerformed(ActionEvent e) { - lastSource = e.getSource(); - RuleButton button = (RuleButton) lastSource; - buttonPressed(button.getRule()); - } + /** + * ICommand Performed event occurs when a rule button has been pressed + * + * @param e action event object + */ + @Override + public void actionPerformed(ActionEvent e) { + lastSource = e.getSource(); + RuleButton button = (RuleButton) lastSource; + buttonPressed(button.getRule()); + } } diff --git a/src/main/java/edu/rpi/legup/controller/ToolbarController.java b/src/main/java/edu/rpi/legup/controller/ToolbarController.java index 489e6b69f..6cbb5ee60 100644 --- a/src/main/java/edu/rpi/legup/controller/ToolbarController.java +++ b/src/main/java/edu/rpi/legup/controller/ToolbarController.java @@ -5,23 +5,23 @@ import java.awt.event.ActionListener; public class ToolbarController implements ActionListener { - private LegupUI legupUI; + private LegupUI legupUI; - /** - * ToolbarController Constructor - creates a new {@link ToolbarController} to listen for button - * pressed from the tool mBar - * - * @param legupUI legupUI - */ - public ToolbarController(LegupUI legupUI) { - this.legupUI = legupUI; - } + /** + * ToolbarController Constructor - creates a new {@link ToolbarController} to listen for button + * pressed from the tool mBar + * + * @param legupUI legupUI + */ + public ToolbarController(LegupUI legupUI) { + this.legupUI = legupUI; + } - /** - * ICommand Performed event - - * - * @param e action event - */ - @Override - public void actionPerformed(ActionEvent e) {} + /** + * ICommand Performed event - + * + * @param e action event + */ + @Override + public void actionPerformed(ActionEvent e) {} } diff --git a/src/main/java/edu/rpi/legup/controller/TreeController.java b/src/main/java/edu/rpi/legup/controller/TreeController.java index f19b40cb1..80fdee1af 100644 --- a/src/main/java/edu/rpi/legup/controller/TreeController.java +++ b/src/main/java/edu/rpi/legup/controller/TreeController.java @@ -12,152 +12,155 @@ import javax.swing.*; public class TreeController extends Controller { - /** - * TreeController Constructor creates a controller object to listen to ui events from a {@link - * TreePanel} - */ - public TreeController() {} + /** + * TreeController Constructor creates a controller object to listen to ui events from a {@link + * TreePanel} + */ + public TreeController() {} - /** - * Mouse Clicked event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); - } + /** + * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); + } - /** - * Mouse Released event sets the cursor back to the default cursor and reset info for panning Set - * board modifiability - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); + /** + * Mouse Released event sets the cursor back to the default cursor and reset info for panning + * Set board modifiability + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - if (treeElementView != null) { - if (e.isShiftDown()) { - selection.addToSelection(treeElementView); - } else { - if (e.isControlDown()) { - if (!(selection.getSelectedViews().size() == 1 - && treeElementView == selection.getFirstSelection())) { - selection.toggleSelection(treeElementView); - } - } else { - selection.newSelection(treeElementView); + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + if (treeElementView != null) { + if (e.isShiftDown()) { + selection.addToSelection(treeElementView); + } else { + if (e.isControlDown()) { + if (!(selection.getSelectedViews().size() == 1 + && treeElementView == selection.getFirstSelection())) { + selection.toggleSelection(treeElementView); + } + } else { + selection.newSelection(treeElementView); + } + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); } - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); } - } - /** - * Mouse Entered event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - Tree tree = getInstance().getTree(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - if (treeElementView != null) { - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); + /** + * Mouse Entered event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + Tree tree = getInstance().getTree(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + if (treeElementView != null) { + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); + } } - } - /** - * Mouse Exited event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView elementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); + /** + * Mouse Exited event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView elementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); - selection.setMousePoint(null); - if (elementView != null) { - TreeElementView selectedView = selection.getFirstSelection(); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(selectedView.getTreeElement())); + selection.setMousePoint(null); + if (elementView != null) { + TreeElementView selectedView = selection.getFirstSelection(); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(selectedView.getTreeElement())); + } } - } - /** - * Mouse Dragged event adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - super.mouseDragged(e); - } + /** + * Mouse Dragged event adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + super.mouseDragged(e); + } - /** - * Mouse Moved event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - if (puzzle != null) { - TreeViewSelection selection = treeView.getSelection(); - selection.setMousePoint(treeView.getActualPoint(e.getPoint())); - if (treeElementView != null && treeElementView != selection.getHover()) { - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); - selection.newHover(treeElementView); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } else { - if (treeElementView == null && selection.getHover() != null) { - puzzle.notifyBoardListeners( - listener -> - listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); - selection.clearHover(); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + /** + * Mouse Moved event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + if (puzzle != null) { + TreeViewSelection selection = treeView.getSelection(); + selection.setMousePoint(treeView.getActualPoint(e.getPoint())); + if (treeElementView != null && treeElementView != selection.getHover()) { + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged(treeElementView.getTreeElement())); + selection.newHover(treeElementView); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } else { + if (treeElementView == null && selection.getHover() != null) { + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged( + selection.getFirstSelection().getTreeElement())); + selection.clearHover(); + puzzle.notifyTreeListeners( + listener -> listener.onTreeSelectionChanged(selection)); + } + } } - } } - } - /** - * Mouse Wheel Moved event zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - super.viewer.scroll(e.getWheelRotation()); - } + /** + * Mouse Wheel Moved event zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + super.viewer.scroll(e.getWheelRotation()); + } } diff --git a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java index 2f9c3e553..b413bebb7 100644 --- a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java @@ -12,102 +12,103 @@ public class AddTreeElementCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - private Map addChild; + private Map addChild; - /** - * AddTreeElementCommand Constructor creates a command for adding a tree element to the proof tree - * - * @param selection selection of tree elements views - */ - public AddTreeElementCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - this.addChild = new HashMap<>(); - } + /** + * AddTreeElementCommand Constructor creates a command for adding a tree element to the proof + * tree + * + * @param selection selection of tree elements views + */ + public AddTreeElementCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + this.addChild = new HashMap<>(); + } - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement treeElement = view.getTreeElement(); - TreeElement child = addChild.get(treeElement); - if (child == null) { - child = tree.addTreeElement(treeElement); - } else { - if (treeElement.getType() == TreeElementType.NODE) { - child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); - } else { - child = tree.addTreeElement((TreeTransition) treeElement, (TreeNode) child); - } - } - addChild.put(treeElement, child); + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement treeElement = view.getTreeElement(); + TreeElement child = addChild.get(treeElement); + if (child == null) { + child = tree.addTreeElement(treeElement); + } else { + if (treeElement.getType() == TreeElementType.NODE) { + child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); + } else { + child = tree.addTreeElement((TreeTransition) treeElement, (TreeNode) child); + } + } + addChild.put(treeElement, child); - final TreeElement finalChild = child; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalChild)); + final TreeElement finalChild = child; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalChild)); - newSelection.addToSelection(treeView.getElementView(child)); - } + newSelection.addToSelection(treeView.getElementView(child)); + } - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) element; - if (transition.getChildNode() != null) { - return CommandError.ADD_WITH_CHILD.toString(); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } else { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - TreeTransition transition = node.getChildren().get(0); - if (transition.getParents().size() > 1) { - return CommandError.ADD_TO_MERGE.toString(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) element; + if (transition.getChildNode() != null) { + return CommandError.ADD_WITH_CHILD.toString(); + } + } else { + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + TreeTransition transition = node.getChildren().get(0); + if (transition.getParents().size() > 1) { + return CommandError.ADD_TO_MERGE.toString(); + } + } + } } - } } - } + return null; } - return null; - } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - for (TreeElementView view : selection.getSelectedViews()) { - TreeElement element = view.getTreeElement(); - TreeElement child = addChild.get(element); - tree.removeTreeElement(child); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(child)); - newSelection.addToSelection(treeView.getElementView(element)); + for (TreeElementView view : selection.getSelectedViews()) { + TreeElement element = view.getTreeElement(); + TreeElement child = addChild.get(element); + tree.removeTreeElement(child); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(child)); + newSelection.addToSelection(treeView.getElementView(element)); + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } } diff --git a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java index 558cb85d7..02dffae44 100644 --- a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java @@ -12,114 +12,118 @@ public class ApplyDefaultDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - private DirectRule rule; - private Map addMap; - - /** - * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a basic - * rule - * - * @param selection selection of tree element views - * @param rule basic rule for the command - */ - public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.rule = rule; - this.addMap = new HashMap<>(); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_SELECTED_VIEWS.toString(); - } else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); - } else { - if (rule.getDefaultBoard(node) == null) { - return CommandError.DEFAULT_APPLICATION - + " - " - + "This selection contains a tree element that this rule cannot be applied to."; - } - } + private TreeViewSelection selection; + private DirectRule rule; + private Map addMap; + + /** + * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a + * basic rule + * + * @param selection selection of tree element views + * @param rule basic rule for the command + */ + public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.rule = rule; + this.addMap = new HashMap<>(); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.DEFAULT_APPLICATION + + " - " + + CommandError.NO_SELECTED_VIEWS.toString(); } else { - return CommandError.DEFAULT_APPLICATION - + " - " - + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + + return CommandError.DEFAULT_APPLICATION + + " - " + + CommandError.NO_CHILDREN.toString(); + } else { + if (rule.getDefaultBoard(node) == null) { + return CommandError.DEFAULT_APPLICATION + + " - This selection contains a tree element that this rule" + + " cannot be applied to."; + } + } + } else { + return CommandError.DEFAULT_APPLICATION + + " - " + + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + } } - } - } - return null; - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - TreeTransition transition = addMap.get(node); - TreeNode childNode; - if (transition == null) { - transition = (TreeTransition) tree.addTreeElement(node); - childNode = (TreeNode) tree.addTreeElement(transition); - addMap.put(node, transition); - } else { - tree.addTreeElement(node, transition); - childNode = transition.getChildNode(); - } - - transition.setRule(rule); - Board defaultBoard = rule.getDefaultBoard(node); - transition.setBoard(defaultBoard); - Board copyBoard = defaultBoard.copy(); - copyBoard.setModifiable(false); - childNode.setBoard(copyBoard); - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(childNode)); + return null; } - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + TreeTransition transition = addMap.get(node); + TreeNode childNode; + if (transition == null) { + transition = (TreeTransition) tree.addTreeElement(node); + childNode = (TreeNode) tree.addTreeElement(transition); + addMap.put(node, transition); + } else { + tree.addTreeElement(node, transition); + childNode = transition.getChildNode(); + } - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + transition.setRule(rule); + Board defaultBoard = rule.getDefaultBoard(node); + transition.setBoard(defaultBoard); + Board copyBoard = defaultBoard.copy(); + copyBoard.setModifiable(false); + childNode.setBoard(copyBoard); - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - final TreeTransition transition = addMap.get(node); + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + final TreeTransition transition = addMap.get(node); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java b/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java index 501f1d0a5..54e33756a 100644 --- a/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java @@ -15,131 +15,132 @@ public class AutoCaseRuleCommand extends PuzzleCommand { - private ElementView elementView; - private TreeViewSelection selection; - private CaseRule caseRule; - private CaseBoard caseBoard; - private MouseEvent mouseEvent; - - private List caseTrans; - - private static final int MAX_CASES = 10; - - /** - * AutoCaseRuleCommand Constructor creates a command for validating a case rule - * - * @param elementView currently selected puzzle puzzleElement view that is being edited - * @param selection currently selected tree puzzleElement views that is being edited - * @param caseRule currently selected caseRule puzzleElement view that is being edited - * @param caseBoard currently selected caseBoard puzzleElement view that is being edited - * @param mouseEvent currently selected mouseEvent puzzleElement view that is being edited - */ - public AutoCaseRuleCommand( - ElementView elementView, - TreeViewSelection selection, - CaseRule caseRule, - CaseBoard caseBoard, - MouseEvent mouseEvent) { - this.elementView = elementView; - this.selection = selection.copy(); - this.caseRule = caseRule; - this.caseBoard = caseBoard; - this.mouseEvent = mouseEvent; - this.caseTrans = new ArrayList<>(); - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); - if (caseTrans.isEmpty()) { - List cases = - caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()); - for (Board board : cases) { - final TreeTransition transition = (TreeTransition) tree.addTreeElement(node); - board.setModifiable(false); - transition.setBoard(board); - transition.setRule(caseRule); - transition.setSelection(elementView.getPuzzleElement().copy()); - caseTrans.add(transition); - - TreeNode childNode = (TreeNode) tree.addTreeElement(transition); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - newSelection.addToSelection(treeView.getElementView(childNode)); - } - } else { - for (final TreeTransition transition : caseTrans) { - tree.addTreeElement(node, transition); - TreeNode childNode = transition.getChildNode(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - newSelection.addToSelection(treeView.getElementView(childNode)); - } + private ElementView elementView; + private TreeViewSelection selection; + private CaseRule caseRule; + private CaseBoard caseBoard; + private MouseEvent mouseEvent; + + private List caseTrans; + + private static final int MAX_CASES = 10; + + /** + * AutoCaseRuleCommand Constructor creates a command for validating a case rule + * + * @param elementView currently selected puzzle puzzleElement view that is being edited + * @param selection currently selected tree puzzleElement views that is being edited + * @param caseRule currently selected caseRule puzzleElement view that is being edited + * @param caseBoard currently selected caseBoard puzzleElement view that is being edited + * @param mouseEvent currently selected mouseEvent puzzleElement view that is being edited + */ + public AutoCaseRuleCommand( + ElementView elementView, + TreeViewSelection selection, + CaseRule caseRule, + CaseBoard caseBoard, + MouseEvent mouseEvent) { + this.elementView = elementView; + this.selection = selection.copy(); + this.caseRule = caseRule; + this.caseBoard = caseBoard; + this.mouseEvent = mouseEvent; + this.caseTrans = new ArrayList<>(); } - final TreeElement finalTreeElement = node.getChildren().get(0).getChildNode(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - if (selection.getSelectedViews().size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); + if (caseTrans.isEmpty()) { + List cases = + caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()); + for (Board board : cases) { + final TreeTransition transition = (TreeTransition) tree.addTreeElement(node); + board.setModifiable(false); + transition.setBoard(board); + transition.setRule(caseRule); + transition.setSelection(elementView.getPuzzleElement().copy()); + caseTrans.add(transition); + + TreeNode childNode = (TreeNode) tree.addTreeElement(transition); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + } else { + for (final TreeTransition transition : caseTrans) { + tree.addTreeElement(node, transition); + TreeNode childNode = transition.getChildNode(); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + } + + final TreeElement finalTreeElement = node.getChildren().get(0).getChildNode(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - TreeElementView treeElementView = selection.getFirstSelection(); - if (treeElementView.getType() != TreeElementType.NODE) { - return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + if (selection.getSelectedViews().size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); + } + + TreeElementView treeElementView = selection.getFirstSelection(); + if (treeElementView.getType() != TreeElementType.NODE) { + return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + + TreeNodeView nodeView = (TreeNodeView) treeElementView; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.NO_CHILDREN.toString(); + } + + if (!caseBoard.isPickable(elementView.getPuzzleElement(), mouseEvent)) { + return "The selected data element is not pickable with this case rule."; + } + + if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() + == 0) { + return "The selection must produce at least one case"; + } + + if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() + > MAX_CASES) { + return "The selection can produce a max of " + MAX_CASES + " cases"; + } + + return null; } - TreeNodeView nodeView = (TreeNodeView) treeElementView; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.NO_CHILDREN.toString(); - } + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (!caseBoard.isPickable(elementView.getPuzzleElement(), mouseEvent)) { - return "The selected data element is not pickable with this case rule."; - } + TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); - if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() == 0) { - return "The selection must produce at least one case"; - } + for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { + final TreeTransition finalTran = it.next(); + it.remove(); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); + } - if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() - > MAX_CASES) { - return "The selection can produce a max of " + MAX_CASES + " cases"; + final TreeElement finalTreeElement = node; + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } - - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); - - for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { - final TreeTransition finalTran = it.next(); - it.remove(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); - } - - final TreeElement finalTreeElement = node; - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } } diff --git a/src/main/java/edu/rpi/legup/history/CommandError.java b/src/main/java/edu/rpi/legup/history/CommandError.java index 7b2bc41ed..35b7bb15b 100644 --- a/src/main/java/edu/rpi/legup/history/CommandError.java +++ b/src/main/java/edu/rpi/legup/history/CommandError.java @@ -1,29 +1,29 @@ package edu.rpi.legup.history; public enum CommandError { - NO_SELECTED_VIEWS("The selection does not have any tree elements."), - ONE_SELECTED_VIEW("The selection must have exactly one tree element."), - UNMODIFIABLE_BOARD("The selection contains a board which is not modifiable."), - UNMODIFIABLE_DATA("The selection contains a board where the data element is not modifiable."), - CONTAINS_ROOT("The selection contains the root tree node."), - ONE_CHILD("The selection contains a tree node that does not have exactly one child."), - ADD_WITH_CHILD("The selection contains a tree transition that already has a child tree node."), - TWO_TO_MERGE("The selection must have at least two tree nodes to merge."), - CONTAINS_MERGE("The selection contains a merging transition."), - ADD_TO_MERGE("The selection contains a tree node that merges."), - NO_CHILDREN("The selection contains a tree node that has children."), - SELECTION_CONTAINS_NODE("The selection contains a tree node."), - SELECTION_CONTAINS_TRANSITION("The selection contains a tree transition."), - DEFAULT_APPLICATION("[Apply Default Rule Application]"); + NO_SELECTED_VIEWS("The selection does not have any tree elements."), + ONE_SELECTED_VIEW("The selection must have exactly one tree element."), + UNMODIFIABLE_BOARD("The selection contains a board which is not modifiable."), + UNMODIFIABLE_DATA("The selection contains a board where the data element is not modifiable."), + CONTAINS_ROOT("The selection contains the root tree node."), + ONE_CHILD("The selection contains a tree node that does not have exactly one child."), + ADD_WITH_CHILD("The selection contains a tree transition that already has a child tree node."), + TWO_TO_MERGE("The selection must have at least two tree nodes to merge."), + CONTAINS_MERGE("The selection contains a merging transition."), + ADD_TO_MERGE("The selection contains a tree node that merges."), + NO_CHILDREN("The selection contains a tree node that has children."), + SELECTION_CONTAINS_NODE("The selection contains a tree node."), + SELECTION_CONTAINS_TRANSITION("The selection contains a tree transition."), + DEFAULT_APPLICATION("[Apply Default Rule Application]"); - private String value; + private String value; - CommandError(String value) { - this.value = value; - } + CommandError(String value) { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/main/java/edu/rpi/legup/history/CommandState.java b/src/main/java/edu/rpi/legup/history/CommandState.java index 36e4def4f..f47c0405d 100644 --- a/src/main/java/edu/rpi/legup/history/CommandState.java +++ b/src/main/java/edu/rpi/legup/history/CommandState.java @@ -1,19 +1,19 @@ package edu.rpi.legup.history; public enum CommandState { - CREATED("Created"), - EXECUTED("Executed"), - UNDOED("Undoed"), - REDOED("Redoed"); + CREATED("Created"), + EXECUTED("Executed"), + UNDOED("Undoed"), + REDOED("Redoed"); - private String value; + private String value; - CommandState(String value) { - this.value = value; - } + CommandState(String value) { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java index e301175fe..0469685c1 100644 --- a/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java @@ -8,94 +8,97 @@ import java.util.List; public class DeleteTreeElementCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - /** - * DeleteTreeElementCommand Constructor creates a PuzzleCommand for deleting a tree puzzleElement - * - * @param selection the currently selected tree elements before the command is executed - */ - public DeleteTreeElementCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - } + /** + * DeleteTreeElementCommand Constructor creates a PuzzleCommand for deleting a tree + * puzzleElement + * + * @param selection the currently selected tree elements before the command is executed + */ + public DeleteTreeElementCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + } - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - List selectedViews = selection.getSelectedViews(); + List selectedViews = selection.getSelectedViews(); - TreeElementView firstSelectedView = selectedViews.get(0); - TreeElementView newSelectedView; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - newSelectedView = nodeView.getParentView(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - newSelectedView = transitionView.getParentViews().get(0); - } + TreeElementView firstSelectedView = selectedViews.get(0); + TreeElementView newSelectedView; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + newSelectedView = nodeView.getParentView(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + newSelectedView = transitionView.getParentViews().get(0); + } + + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + tree.removeTreeElement(element); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(element)); + } - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - tree.removeTreeElement(element); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(element)); + final TreeViewSelection newSelection = new TreeViewSelection(newSelectedView); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(newSelectedView.getTreeElement())); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeSelectionChanged(newSelection)); } - final TreeViewSelection newSelection = new TreeViewSelection(newSelectedView); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(newSelectedView.getTreeElement())); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeSelectionChanged(newSelection)); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE && ((TreeNode) element).isRoot()) { + return CommandError.CONTAINS_ROOT.toString(); + } + } + return null; } - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE && ((TreeNode) element).isRoot()) { - return CommandError.CONTAINS_ROOT.toString(); - } - } - return null; - } + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + List selectedViews = selection.getSelectedViews(); - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - List selectedViews = selection.getSelectedViews(); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getParent().setChildNode(node); - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getParent().setChildNode(node); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(node)); + } else { + TreeTransition transition = (TreeTransition) element; + transition.getParents().forEach(node -> node.addChild(transition)); + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(node)); - } else { - TreeTransition transition = (TreeTransition) element; - transition.getParents().forEach(node -> node.addChild(transition)); - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + } + } - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - } + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged( + selection.getFirstSelection().getTreeElement())); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } - - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } } diff --git a/src/main/java/edu/rpi/legup/history/EditDataCommand.java b/src/main/java/edu/rpi/legup/history/EditDataCommand.java index 6b5f4062f..d65f03d66 100644 --- a/src/main/java/edu/rpi/legup/history/EditDataCommand.java +++ b/src/main/java/edu/rpi/legup/history/EditDataCommand.java @@ -14,155 +14,155 @@ import java.util.List; public class EditDataCommand extends PuzzleCommand { - private TreeTransition transition; - private PuzzleElement savePuzzleElement; - private PuzzleElement puzzleElement; - - private ElementView elementView; - private TreeViewSelection selection; - private MouseEvent event; - - /** - * EditDataCommand Constructor create a puzzle command for editing a board - * - * @param elementView currently selected puzzle puzzleElement view that is being edited - * @param selection currently selected tree puzzleElement views that is being edited - * @param event mouse event - */ - public EditDataCommand(ElementView elementView, TreeViewSelection selection, MouseEvent event) { - this.elementView = elementView; - this.selection = selection.copy(); - this.event = event; - this.puzzleElement = null; - this.savePuzzleElement = null; - this.transition = null; - } - - /** Executes a command */ - @SuppressWarnings("unchecked") - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - Board board = treeElement.getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - if (treeNode.getChildren().isEmpty()) { - if (transition == null) { - transition = tree.addNewTransition(treeNode); + private TreeTransition transition; + private PuzzleElement savePuzzleElement; + private PuzzleElement puzzleElement; + + private ElementView elementView; + private TreeViewSelection selection; + private MouseEvent event; + + /** + * EditDataCommand Constructor create a puzzle command for editing a board + * + * @param elementView currently selected puzzle puzzleElement view that is being edited + * @param selection currently selected tree puzzleElement views that is being edited + * @param event mouse event + */ + public EditDataCommand(ElementView elementView, TreeViewSelection selection, MouseEvent event) { + this.elementView = elementView; + this.selection = selection.copy(); + this.event = event; + this.puzzleElement = null; + this.savePuzzleElement = null; + this.transition = null; + } + + /** Executes a command */ + @SuppressWarnings("unchecked") + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + Board board = treeElement.getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + if (treeNode.getChildren().isEmpty()) { + if (transition == null) { + transition = tree.addNewTransition(treeNode); + } + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + } + + board = transition.getBoard(); + + puzzleElement = board.getPuzzleElement(selectedPuzzleElement); + savePuzzleElement = puzzleElement.copy(); + } else { + transition = (TreeTransition) treeElement; + puzzleElement = board.getPuzzleElement(selectedPuzzleElement); + savePuzzleElement = puzzleElement.copy(); } - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - } - board = transition.getBoard(); + Board prevBoard = transition.getParents().get(0).getBoard(); - puzzleElement = board.getPuzzleElement(selectedPuzzleElement); - savePuzzleElement = puzzleElement.copy(); - } else { - transition = (TreeTransition) treeElement; - puzzleElement = board.getPuzzleElement(selectedPuzzleElement); - savePuzzleElement = puzzleElement.copy(); - } + boardView.getElementController().changeCell(event, puzzleElement); - Board prevBoard = transition.getParents().get(0).getBoard(); + if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { + board.removeModifiedData(puzzleElement); + } else { + board.addModifiedData(puzzleElement); + } + transition.propagateChange(puzzleElement); - boardView.getElementController().changeCell(event, puzzleElement); + final TreeElement finalTreeElement = transition; + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); - if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { - board.removeModifiedData(puzzleElement); - } else { - board.addModifiedData(puzzleElement); - } - transition.propagateChange(puzzleElement); - - final TreeElement finalTreeElement = transition; - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); - - final TreeViewSelection newSelection = - new TreeViewSelection(treeView.getElementView(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); + final TreeViewSelection newSelection = + new TreeViewSelection(treeView.getElementView(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - TreeElementView selectedView = selection.getFirstSelection(); - Board board = selectedView.getTreeElement().getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - if (selectedView.getType() == TreeElementType.NODE) { - - TreeNodeView nodeView = (TreeNodeView) selectedView; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } else { - if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); } - } - } else { - TreeTransitionView transitionView = (TreeTransitionView) selectedView; - if (!transitionView.getTreeElement().getBoard().isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } else { - if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); + TreeElementView selectedView = selection.getFirstSelection(); + Board board = selectedView.getTreeElement().getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + if (selectedView.getType() == TreeElementType.NODE) { + + TreeNodeView nodeView = (TreeNodeView) selectedView; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } else { + if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); + } + } + } else { + TreeTransitionView transitionView = (TreeTransitionView) selectedView; + if (!transitionView.getTreeElement().getBoard().isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } else { + if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); + } + } } - } - } - return null; - } - - /** Undoes an command */ - @SuppressWarnings("unchecked") - @Override - public void undoCommand() { - TreeElementView selectedView = selection.getFirstSelection(); - Tree tree = getInstance().getTree(); - Puzzle puzzle = getInstance().getPuzzleModule(); - - Board board = transition.getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - - if (selectedView.getType() == TreeElementType.NODE) { - tree.removeTreeElement(transition); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeElementRemoved(transition)); + return null; } - Board prevBoard = transition.getParents().get(0).getBoard(); + /** Undoes an command */ + @SuppressWarnings("unchecked") + @Override + public void undoCommand() { + TreeElementView selectedView = selection.getFirstSelection(); + Tree tree = getInstance().getTree(); + Puzzle puzzle = getInstance().getPuzzleModule(); + + Board board = transition.getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + + if (selectedView.getType() == TreeElementType.NODE) { + tree.removeTreeElement(transition); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeElementRemoved(transition)); + } - puzzleElement.setData(savePuzzleElement.getData()); - board.notifyChange(puzzleElement); + Board prevBoard = transition.getParents().get(0).getBoard(); - if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { - board.removeModifiedData(puzzleElement); - } else { - board.addModifiedData(puzzleElement); - } - transition.propagateChange(puzzleElement); + puzzleElement.setData(savePuzzleElement.getData()); + board.notifyChange(puzzleElement); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); + if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { + board.removeModifiedData(puzzleElement); + } else { + board.addModifiedData(puzzleElement); + } + transition.propagateChange(puzzleElement); + + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/History.java b/src/main/java/edu/rpi/legup/history/History.java index 8221449e6..371284f8c 100644 --- a/src/main/java/edu/rpi/legup/history/History.java +++ b/src/main/java/edu/rpi/legup/history/History.java @@ -7,92 +7,94 @@ import org.apache.logging.log4j.Logger; public class History { - private static final Logger LOGGER = LogManager.getLogger(History.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(History.class.getName()); - private final Object lock = new Object(); - private List history; - private int curIndex; + private final Object lock = new Object(); + private List history; + private int curIndex; - /** - * History Constructor this holds information about changes to the board and Tree structure for - * undoing and redoing operations. Though history is an List, it is implemented like a stack. The - * curIndex points to the top of the stack (where the last change was made). - */ - public History() { - history = new ArrayList<>(); - curIndex = -1; - } + /** + * History Constructor this holds information about changes to the board and Tree structure for + * undoing and redoing operations. Though history is an List, it is implemented like a stack. + * The curIndex points to the top of the stack (where the last change was made). + */ + public History() { + history = new ArrayList<>(); + curIndex = -1; + } - /** - * Pushes a change to the history list and increments the current index. If the current index does - * not point to the top of the stack, then at least 1 undo operation was called and that - * information will be lost by the next change - * - * @param command command to be pushed onto the stack - */ - public void pushChange(ICommand command) { - synchronized (lock) { - if (curIndex < history.size() - 1) { - for (int i = history.size() - 1; i > curIndex; i--) { - history.remove(i); + /** + * Pushes a change to the history list and increments the current index. If the current index + * does not point to the top of the stack, then at least 1 undo operation was called and that + * information will be lost by the next change + * + * @param command command to be pushed onto the stack + */ + public void pushChange(ICommand command) { + synchronized (lock) { + if (curIndex < history.size() - 1) { + for (int i = history.size() - 1; i > curIndex; i--) { + history.remove(i); + } + } + history.add(command); + curIndex++; + LOGGER.info("Pushed " + command.getClass().getSimpleName() + " to stack."); + GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onPushChange(command)); } - } - history.add(command); - curIndex++; - LOGGER.info("Pushed " + command.getClass().getSimpleName() + " to stack."); - GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onPushChange(command)); } - } - /** Undoes an action */ - public void undo() { - synchronized (lock) { - if (curIndex > -1) { - ICommand command = history.get(curIndex--); - command.undo(); - LOGGER.info("Undoed " + command.getClass().getSimpleName()); - GameBoardFacade.getInstance() - .notifyHistoryListeners(l -> l.onUndo(curIndex < 0, curIndex == history.size() - 1)); - } + /** Undoes an action */ + public void undo() { + synchronized (lock) { + if (curIndex > -1) { + ICommand command = history.get(curIndex--); + command.undo(); + LOGGER.info("Undoed " + command.getClass().getSimpleName()); + GameBoardFacade.getInstance() + .notifyHistoryListeners( + l -> l.onUndo(curIndex < 0, curIndex == history.size() - 1)); + } + } } - } - /** Redoes an action */ - public void redo() { - synchronized (lock) { - if (curIndex < history.size() - 1) { - ICommand command = history.get(++curIndex); - command.redo(); - LOGGER.info("Redoed " + command.getClass().getSimpleName()); - GameBoardFacade.getInstance() - .notifyHistoryListeners(l -> l.onRedo(curIndex < 0, curIndex == history.size() - 1)); - } + /** Redoes an action */ + public void redo() { + synchronized (lock) { + if (curIndex < history.size() - 1) { + ICommand command = history.get(++curIndex); + command.redo(); + LOGGER.info("Redoed " + command.getClass().getSimpleName()); + GameBoardFacade.getInstance() + .notifyHistoryListeners( + l -> l.onRedo(curIndex < 0, curIndex == history.size() - 1)); + } + } } - } - /** Clears all actions from the history stack */ - public void clear() { - history.clear(); - curIndex = -1; - LOGGER.debug("History Cleared"); - GameBoardFacade.getInstance().notifyHistoryListeners(IHistoryListener::onClearHistory); - } + /** Clears all actions from the history stack */ + public void clear() { + history.clear(); + curIndex = -1; + LOGGER.debug("History Cleared"); + GameBoardFacade.getInstance().notifyHistoryListeners(IHistoryListener::onClearHistory); + } - /** - * Gets the current index that points to the action at the top of stack - * - * @return index of the action on top of the stack - */ - public int getIndex() { - return curIndex; - } + /** + * Gets the current index that points to the action at the top of stack + * + * @return index of the action on top of the stack + */ + public int getIndex() { + return curIndex; + } - /** - * Gets the amount of actions that have been pushed onto the stack - * - * @return size of the history stack - */ - public int size() { - return history.size(); - } + /** + * Gets the amount of actions that have been pushed onto the stack + * + * @return size of the history stack + */ + public int size() { + return history.size(); + } } diff --git a/src/main/java/edu/rpi/legup/history/ICommand.java b/src/main/java/edu/rpi/legup/history/ICommand.java index b10cdc861..913d9daaf 100644 --- a/src/main/java/edu/rpi/legup/history/ICommand.java +++ b/src/main/java/edu/rpi/legup/history/ICommand.java @@ -1,27 +1,27 @@ package edu.rpi.legup.history; public interface ICommand { - /** Executes a command */ - void execute(); + /** Executes a command */ + void execute(); - /** - * Determines whether this command can be executed - * - * @return true if can execute, false otherwise - */ - boolean canExecute(); + /** + * Determines whether this command can be executed + * + * @return true if can execute, false otherwise + */ + boolean canExecute(); - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - String getError(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + String getError(); - /** Undoes a command */ - void undo(); + /** Undoes a command */ + void undo(); - /** Redoes a command */ - void redo(); + /** Redoes a command */ + void redo(); } diff --git a/src/main/java/edu/rpi/legup/history/IHistoryListener.java b/src/main/java/edu/rpi/legup/history/IHistoryListener.java index 1b3253b9f..f464941d6 100644 --- a/src/main/java/edu/rpi/legup/history/IHistoryListener.java +++ b/src/main/java/edu/rpi/legup/history/IHistoryListener.java @@ -1,29 +1,29 @@ package edu.rpi.legup.history; public interface IHistoryListener { - /** - * Called when a action is pushed onto the edu.rpi.legup.history stack - * - * @param command action to push onto the stack - */ - void onPushChange(ICommand command); + /** + * Called when a action is pushed onto the edu.rpi.legup.history stack + * + * @param command action to push onto the stack + */ + void onPushChange(ICommand command); - /** - * Called when an action is undone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - void onUndo(boolean isBottom, boolean isTop); + /** + * Called when an action is undone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + void onUndo(boolean isBottom, boolean isTop); - /** - * Called when an action is redone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - void onRedo(boolean isBottom, boolean isTop); + /** + * Called when an action is redone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + void onRedo(boolean isBottom, boolean isTop); - /** Called when the edu.rpi.legup.history is cleared */ - void onClearHistory(); + /** Called when the edu.rpi.legup.history is cleared */ + void onClearHistory(); } diff --git a/src/main/java/edu/rpi/legup/history/IHistorySubject.java b/src/main/java/edu/rpi/legup/history/IHistorySubject.java index 63acfa4c6..78fefff00 100644 --- a/src/main/java/edu/rpi/legup/history/IHistorySubject.java +++ b/src/main/java/edu/rpi/legup/history/IHistorySubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface IHistorySubject { - /** - * Adds a history listener - * - * @param listener listener to add - */ - void addHistoryListener(IHistoryListener listener); + /** + * Adds a history listener + * + * @param listener listener to add + */ + void addHistoryListener(IHistoryListener listener); - /** - * Removes a history listener - * - * @param listener listener to remove - */ - void removeHistoryListener(IHistoryListener listener); + /** + * Removes a history listener + * + * @param listener listener to remove + */ + void removeHistoryListener(IHistoryListener listener); - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - void notifyHistoryListeners(Consumer algorithm); + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + void notifyHistoryListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java b/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java index 42a547e84..71d072328 100644 --- a/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java +++ b/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java @@ -2,14 +2,14 @@ public class InvalidCommandStateTransition extends RuntimeException { - public InvalidCommandStateTransition( - PuzzleCommand puzzleCommand, CommandState from, CommandState to) { - super( - "PuzzleCommand - " - + puzzleCommand.getClass().getSimpleName() - + " - Attempted invalid command state transition from " - + from - + " to " - + to); - } + public InvalidCommandStateTransition( + PuzzleCommand puzzleCommand, CommandState from, CommandState to) { + super( + "PuzzleCommand - " + + puzzleCommand.getClass().getSimpleName() + + " - Attempted invalid command state transition from " + + from + + " to " + + to); + } } diff --git a/src/main/java/edu/rpi/legup/history/MergeCommand.java b/src/main/java/edu/rpi/legup/history/MergeCommand.java index e170e9856..f234a0884 100644 --- a/src/main/java/edu/rpi/legup/history/MergeCommand.java +++ b/src/main/java/edu/rpi/legup/history/MergeCommand.java @@ -11,128 +11,128 @@ import java.util.Set; public class MergeCommand extends PuzzleCommand { - private TreeViewSelection selection; - private TreeTransition transition; - - /** - * Merge Command Constructor create a command for merging tree nodes. - * - * @param selection selection of tree elements - */ - public MergeCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - this.transition = null; - } - - /** Executes an command */ - @Override - public void executeCommand() { - List selectedViews = selection.getSelectedViews(); - - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeNode mergedNode; - if (transition == null) { - List mergingNodes = new ArrayList<>(); - List mergingBoards = new ArrayList<>(); - for (TreeElementView view : selectedViews) { - TreeNode node = ((TreeNodeView) view).getTreeElement(); - mergingNodes.add(node); - mergingBoards.add(node.getBoard()); - } - - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - Board lcaBoard = lca.getBoard(); - - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); - - mergedNode = new TreeNode(mergedBoard.copy()); - transition = new TreeTransition(mergedBoard); - transition.setRule(new MergeRule()); - transition.setChildNode(mergedNode); - mergedNode.setParent(transition); - } else { - mergedNode = transition.getChildNode(); + private TreeViewSelection selection; + private TreeTransition transition; + + /** + * Merge Command Constructor create a command for merging tree nodes. + * + * @param selection selection of tree elements + */ + public MergeCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + this.transition = null; } - transition.getParents().clear(); - for (TreeElementView elementView : selectedViews) { - TreeNode node = (TreeNode) elementView.getTreeElement(); + /** Executes an command */ + @Override + public void executeCommand() { + List selectedViews = selection.getSelectedViews(); + + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeNode mergedNode; + if (transition == null) { + List mergingNodes = new ArrayList<>(); + List mergingBoards = new ArrayList<>(); + for (TreeElementView view : selectedViews) { + TreeNode node = ((TreeNodeView) view).getTreeElement(); + mergingNodes.add(node); + mergingBoards.add(node.getBoard()); + } + + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + Board lcaBoard = lca.getBoard(); + + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + mergedNode = new TreeNode(mergedBoard.copy()); + transition = new TreeTransition(mergedBoard); + transition.setRule(new MergeRule()); + transition.setChildNode(mergedNode); + mergedNode.setParent(transition); + } else { + mergedNode = transition.getChildNode(); + } + + transition.getParents().clear(); + for (TreeElementView elementView : selectedViews) { + TreeNode node = (TreeNode) elementView.getTreeElement(); + + node.addChild(transition); + transition.addParent(node); + } + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - node.addChild(transition); - transition.addParent(node); + final TreeViewSelection newSelection = new TreeViewSelection(); + newSelection.addToSelection(treeView.getElementView(mergedNode)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - - final TreeViewSelection newSelection = new TreeViewSelection(); - newSelection.addToSelection(treeView.getElementView(mergedNode)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeTransition transition = - ((TreeNode) selection.getFirstSelection().getTreeElement()).getChildren().get(0); - tree.removeTreeElement(transition); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - Tree tree = GameBoardFacade.getInstance().getTree(); - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() < 2) { - return CommandError.TWO_TO_MERGE.toString(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeTransition transition = + ((TreeNode) selection.getFirstSelection().getTreeElement()).getChildren().get(0); + tree.removeTreeElement(transition); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } - List nodeList = new ArrayList<>(); - for (TreeElementView view : selection.getSelectedViews()) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.NO_CHILDREN.toString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + Tree tree = GameBoardFacade.getInstance().getTree(); + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() < 2) { + return CommandError.TWO_TO_MERGE.toString(); } - nodeList.add(nodeView.getTreeElement()); - } else { - return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } - } - List mergingNodes = new ArrayList<>(); - for (TreeElementView view : selectedViews) { - TreeNode node = ((TreeNodeView) view).getTreeElement(); - mergingNodes.add(node); - } + List nodeList = new ArrayList<>(); + for (TreeElementView view : selection.getSelectedViews()) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.NO_CHILDREN.toString(); + } + nodeList.add(nodeView.getTreeElement()); + } else { + return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + } - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - return "Unable to merge tree elements."; - } - Set leafNodes = tree.getLeafTreeElements(lca); - if (leafNodes.size() != mergingNodes.size()) { - // return "Unable to merge tree elements."; - } + List mergingNodes = new ArrayList<>(); + for (TreeElementView view : selectedViews) { + TreeNode node = ((TreeNodeView) view).getTreeElement(); + mergingNodes.add(node); + } - for (TreeNode node : mergingNodes) { - if (!leafNodes.contains(node)) { - // return "Unable to merge tree elements."; - } - } + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + return "Unable to merge tree elements."; + } + Set leafNodes = tree.getLeafTreeElements(lca); + if (leafNodes.size() != mergingNodes.size()) { + // return "Unable to merge tree elements."; + } + + for (TreeNode node : mergingNodes) { + if (!leafNodes.contains(node)) { + // return "Unable to merge tree elements."; + } + } - return null; - } + return null; + } } diff --git a/src/main/java/edu/rpi/legup/history/PuzzleCommand.java b/src/main/java/edu/rpi/legup/history/PuzzleCommand.java index 482c11cc7..3768e3cbd 100644 --- a/src/main/java/edu/rpi/legup/history/PuzzleCommand.java +++ b/src/main/java/edu/rpi/legup/history/PuzzleCommand.java @@ -1,91 +1,91 @@ package edu.rpi.legup.history; public abstract class PuzzleCommand implements ICommand { - private CommandState state; - private boolean isCached; - private String cachedError; + private CommandState state; + private boolean isCached; + private String cachedError; - /** Puzzle Command Constructor for creating an undoable and redoable change to the model. */ - protected PuzzleCommand() { - this.state = CommandState.CREATED; - this.isCached = false; - this.cachedError = null; - } + /** Puzzle Command Constructor for creating an undoable and redoable change to the model. */ + protected PuzzleCommand() { + this.state = CommandState.CREATED; + this.isCached = false; + this.cachedError = null; + } - /** Executes an command */ - @Override - public final void execute() { - if (canExecute()) { - executeCommand(); - state = CommandState.EXECUTED; + /** Executes an command */ + @Override + public final void execute() { + if (canExecute()) { + executeCommand(); + state = CommandState.EXECUTED; + } } - } - /** Determines whether this command can be executed */ - @Override - public final boolean canExecute() { - cachedError = getError(); - isCached = true; - return cachedError == null; - } + /** Determines whether this command can be executed */ + @Override + public final boolean canExecute() { + cachedError = getError(); + isCached = true; + return cachedError == null; + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public final String getError() { - if (isCached) { - return cachedError; - } else { - return getErrorString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public final String getError() { + if (isCached) { + return cachedError; + } else { + return getErrorString(); + } } - } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - public abstract String getErrorString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + public abstract String getErrorString(); - /** Executes an command */ - public abstract void executeCommand(); + /** Executes an command */ + public abstract void executeCommand(); - /** Undoes an command */ - public abstract void undoCommand(); + /** Undoes an command */ + public abstract void undoCommand(); - /** Redoes an command */ - public void redoCommand() { - if (state == CommandState.UNDOED) { - executeCommand(); - state = CommandState.REDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); + /** Redoes an command */ + public void redoCommand() { + if (state == CommandState.UNDOED) { + executeCommand(); + state = CommandState.REDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); + } } - } - /** Undoes an command */ - @Override - public final void undo() { - if (state == CommandState.EXECUTED || state == CommandState.REDOED) { - undoCommand(); - state = CommandState.UNDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.UNDOED); + /** Undoes an command */ + @Override + public final void undo() { + if (state == CommandState.EXECUTED || state == CommandState.REDOED) { + undoCommand(); + state = CommandState.UNDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.UNDOED); + } } - } - /** Redoes an command */ - public final void redo() { - if (state == CommandState.UNDOED) { - redoCommand(); - state = CommandState.REDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); + /** Redoes an command */ + public final void redo() { + if (state == CommandState.UNDOED) { + redoCommand(); + state = CommandState.REDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); + } } - } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java index 4718a56c8..7737ecfd3 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java @@ -14,118 +14,118 @@ public class ValidateCaseRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - private CaseRule caseRule; - - private Map oldRule; - private Map addNode; - - /** - * AutoCaseRuleCommand Constructor creates a command for verifying a case rule - * - * @param selection currently selected tree puzzleElement views that is being edited - * @param caseRule currently selected caseRule puzzleElement view that is being edited - */ - public ValidateCaseRuleCommand(TreeViewSelection selection, CaseRule caseRule) { - this.selection = selection.copy(); - this.caseRule = caseRule; - this.oldRule = new HashMap<>(); - this.addNode = new HashMap<>(); - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeTransition transition = (TreeTransition) element; - oldRule.put(transition, transition.getRule()); - - transition.setRule(caseRule); - - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); - } else { - childNode = (TreeNode) tree.addTreeElement(transition, childNode); + private TreeViewSelection selection; + private CaseRule caseRule; + + private Map oldRule; + private Map addNode; + + /** + * AutoCaseRuleCommand Constructor creates a command for verifying a case rule + * + * @param selection currently selected tree puzzleElement views that is being edited + * @param caseRule currently selected caseRule puzzleElement view that is being edited + */ + public ValidateCaseRuleCommand(TreeViewSelection selection, CaseRule caseRule) { + this.selection = selection.copy(); + this.caseRule = caseRule; + this.oldRule = new HashMap<>(); + this.addNode = new HashMap<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeTransition transition = (TreeTransition) element; + oldRule.put(transition, transition.getRule()); + + transition.setRule(caseRule); + + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); + } else { + childNode = (TreeNode) tree.addTreeElement(transition, childNode); + } + + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + newSelection.addToSelection(treeView.getElementView(childNode)); } - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - newSelection.addToSelection(treeView.getElementView(childNode)); + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); + } + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); - } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - return CommandError.SELECTION_CONTAINS_NODE.toString(); - } else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + return CommandError.SELECTION_CONTAINS_NODE.toString(); + } else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); + } + } } - } - } - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeTransition transition = (TreeTransition) element; - - transition.setRule(oldRule.get(transition)); - - final TreeNode childNode = transition.getChildNode(); - if (addNode.get(transition) != null) { - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + return null; } - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeTransition transition = (TreeTransition) element; + + transition.setRule(oldRule.get(transition)); + + final TreeNode childNode = transition.getChildNode(); + if (addNode.get(transition) != null) { + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java index cc60029bf..8737b4008 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java @@ -11,147 +11,156 @@ import java.util.Map; public class ValidateContradictionRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - - private Map> saveElements; - private ContradictionRule newRule; - private Map addTran; - - /** - * ValidateContradictionRuleCommand Constructor creates a puzzle command for verifying a - * contradiction rule - * - * @param selection currently selected tree puzzleElement views - * @param rule contradiction rule to be set to all the tree elements - */ - public ValidateContradictionRuleCommand(TreeViewSelection selection, ContradictionRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.saveElements = new HashMap<>(); - this.addTran = new HashMap<>(); - } - - /** Executes a command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement treeElement = view.getTreeElement(); - TreeNode treeNode; - if (treeElement.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) treeElement; - treeNode = transition.getParents().get(0); - } else { - treeNode = (TreeNode) treeElement; - } - - if (!treeNode.getChildren().isEmpty()) { - ArrayList save = new ArrayList<>(treeNode.getChildren()); - saveElements.put(treeNode, save); - } - - treeNode - .getChildren() - .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); - - treeNode.getChildren().clear(); - - TreeTransition transition = addTran.get(treeElement); - if (transition == null) { - transition = tree.addNewTransition(treeNode); - transition.setRule(newRule); - transition.getBoard().setModifiable(false); - tree.addTreeElement(transition); - } else { - transition.getBoard().setModifiable(false); - tree.addTreeElement(treeNode, transition); - } - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(transition)); + private TreeViewSelection selection; + + private Map> saveElements; + private ContradictionRule newRule; + private Map addTran; + + /** + * ValidateContradictionRuleCommand Constructor creates a puzzle command for verifying a + * contradiction rule + * + * @param selection currently selected tree puzzleElement views + * @param rule contradiction rule to be set to all the tree elements + */ + public ValidateContradictionRuleCommand(TreeViewSelection selection, ContradictionRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.saveElements = new HashMap<>(); + this.addTran = new HashMap<>(); } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - if (transitionView.getChildView() != null) { - finalTreeElement = transitionView.getChildView().getTreeElement(); - } else { - finalTreeElement = null; - } - } + /** Executes a command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement treeElement = view.getTreeElement(); + TreeNode treeNode; + if (treeElement.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) treeElement; + treeNode = transition.getParents().get(0); + } else { + treeNode = (TreeNode) treeElement; + } + + if (!treeNode.getChildren().isEmpty()) { + ArrayList save = new ArrayList<>(treeNode.getChildren()); + saveElements.put(treeNode, save); + } + + treeNode.getChildren() + .forEach( + n -> + puzzle.notifyTreeListeners( + listener -> listener.onTreeElementRemoved(n))); + + treeNode.getChildren().clear(); + + TreeTransition transition = addTran.get(treeElement); + if (transition == null) { + transition = tree.addNewTransition(treeNode); + transition.setRule(newRule); + transition.getBoard().setModifiable(false); + tree.addTreeElement(transition); + } else { + transition.getBoard().setModifiable(false); + tree.addTreeElement(treeNode, transition); + } + + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(transition)); + } - if (finalTreeElement != null) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + if (transitionView.getChildView() != null) { + finalTreeElement = transitionView.getChildView().getTreeElement(); + } else { + finalTreeElement = null; + } + } - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.TRANSITION) { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); + if (finalTreeElement != null) { + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(finalTreeElement)); } - } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - return null; - } - - /** Undoes a command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeNode node; - if (element.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) element; - node = transition.getParents().get(0); - } else { - node = (TreeNode) element; - } - node.getChildren() - .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); - node.getChildren().clear(); - - ArrayList save = saveElements.get(node); - - if (save != null) { - node.getChildren().addAll(save); - node.getChildren() - .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(n))); - } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } + + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.TRANSITION) { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); + } + } + } + return null; } - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + /** Undoes a command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeNode node; + if (element.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) element; + node = transition.getParents().get(0); + } else { + node = (TreeNode) element; + } + node.getChildren() + .forEach( + n -> + puzzle.notifyTreeListeners( + listener -> listener.onTreeElementRemoved(n))); + node.getChildren().clear(); + + ArrayList save = saveElements.get(node); + + if (save != null) { + node.getChildren().addAll(save); + node.getChildren() + .forEach( + n -> + puzzle.notifyTreeListeners( + listener -> listener.onTreeElementAdded(n))); + } + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java index 0fe35218f..d9c063464 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java @@ -11,132 +11,132 @@ import java.util.Map; public class ValidateDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - private Map oldRules; - private Map addNode; - private DirectRule newRule; + private Map oldRules; + private Map addNode; + private DirectRule newRule; - /** - * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule - * - * @param selection selection of tree elements - * @param rule basic rule - */ - public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.oldRules = new HashMap<>(); - this.addNode = new HashMap<>(); - } + /** + * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule + * + * @param selection selection of tree elements + * @param rule basic rule + */ + public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.oldRules = new HashMap<>(); + this.addNode = new HashMap<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + List selectedViews = selection.getSelectedViews(); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); - List selectedViews = selection.getSelectedViews(); - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); + oldRules.put(transition, transition.getRule()); + transition.setRule(newRule); - oldRules.put(transition, transition.getRule()); - transition.setRule(newRule); + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); + } else { + tree.addTreeElement(transition, childNode); + } - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + newSelection.addToSelection(treeView.getElementView(childNode)); + } + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); } else { - tree.addTreeElement(transition, childNode); + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); } - - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - newSelection.addToSelection(treeView.getElementView(childNode)); - } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } - - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (nodeView.getChildrenViews().size() != 1) { - return CommandError.ONE_CHILD.toString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - } else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); + + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (nodeView.getChildrenViews().size() != 1) { + return CommandError.ONE_CHILD.toString(); + } + } else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); + } + } } - } + return null; } - return null; - } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); - transition.setRule(oldRules.get(transition)); + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); + transition.setRule(oldRules.get(transition)); - if (addNode.get(transition) != null) { - final TreeNode childNode = transition.getChildNode(); - tree.removeTreeElement(childNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - } + if (addNode.get(transition) != null) { + final TreeNode childNode = transition.getChildNode(); + tree.removeTreeElement(childNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } + } - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/model/Puzzle.java b/src/main/java/edu/rpi/legup/model/Puzzle.java index ed39d0fe6..7971c95af 100644 --- a/src/main/java/edu/rpi/legup/model/Puzzle.java +++ b/src/main/java/edu/rpi/legup/model/Puzzle.java @@ -36,610 +36,615 @@ import org.xml.sax.SAXException; public abstract class Puzzle implements IBoardSubject, ITreeSubject { - private static final Logger LOGGER = LogManager.getLogger(Puzzle.class.getName()); - - protected String name; - protected Board currentBoard; - protected Tree tree; - protected BoardView boardView; - protected PuzzleImporter importer; - protected PuzzleExporter exporter; - protected ElementFactory factory; - - private List boardListeners; - private List treeListeners; - - protected List directRules; - protected List contradictionRules; - protected List caseRules; - protected List placeableElements; - protected List nonPlaceableElements; - - /** Puzzle Constructor - creates a new Puzzle */ - public Puzzle() { - this.boardListeners = new ArrayList<>(); - this.treeListeners = new ArrayList<>(); - - this.directRules = new ArrayList<>(); - this.contradictionRules = new ArrayList<>(); - this.caseRules = new ArrayList<>(); - - this.placeableElements = new ArrayList<>(); - this.nonPlaceableElements = new ArrayList<>(); - - registerRules(); - registerPuzzleElements(); - } - - private void registerPuzzleElements() { - String packageName = this.getClass().getPackage().toString().replace("package ", ""); - - try { - Class[] possElements = LegupUtils.getClasses(packageName); - - for (Class c : possElements) { - - System.out.println("possible element: " + c.getName()); - - // check that the element is not abstract - if (Modifier.isAbstract(c.getModifiers())) continue; - - for (Annotation a : c.getAnnotations()) { - if (a.annotationType() == RegisterElement.class) { - RegisterElement registerElement = (RegisterElement) a; - Constructor cons = c.getConstructor(); - try { - Element element = (Element) cons.newInstance(); - - switch (element.getElementType()) { - case PLACEABLE: - this.addPlaceableElement((PlaceableElement) element); - break; - case NONPLACEABLE: - this.addNonPlaceableElement((NonPlaceableElement) element); - break; - default: - break; - } - } catch (InvocationTargetException e) { - System.out.println(" Failed "); - e.getTargetException().printStackTrace(); + private static final Logger LOGGER = LogManager.getLogger(Puzzle.class.getName()); + + protected String name; + protected Board currentBoard; + protected Tree tree; + protected BoardView boardView; + protected PuzzleImporter importer; + protected PuzzleExporter exporter; + protected ElementFactory factory; + + private List boardListeners; + private List treeListeners; + + protected List directRules; + protected List contradictionRules; + protected List caseRules; + protected List placeableElements; + protected List nonPlaceableElements; + + /** Puzzle Constructor - creates a new Puzzle */ + public Puzzle() { + this.boardListeners = new ArrayList<>(); + this.treeListeners = new ArrayList<>(); + + this.directRules = new ArrayList<>(); + this.contradictionRules = new ArrayList<>(); + this.caseRules = new ArrayList<>(); + + this.placeableElements = new ArrayList<>(); + this.nonPlaceableElements = new ArrayList<>(); + + registerRules(); + registerPuzzleElements(); + } + + private void registerPuzzleElements() { + String packageName = this.getClass().getPackage().toString().replace("package ", ""); + + try { + Class[] possElements = LegupUtils.getClasses(packageName); + + for (Class c : possElements) { + + System.out.println("possible element: " + c.getName()); + + // check that the element is not abstract + if (Modifier.isAbstract(c.getModifiers())) continue; + + for (Annotation a : c.getAnnotations()) { + if (a.annotationType() == RegisterElement.class) { + RegisterElement registerElement = (RegisterElement) a; + Constructor cons = c.getConstructor(); + try { + Element element = (Element) cons.newInstance(); + + switch (element.getElementType()) { + case PLACEABLE: + this.addPlaceableElement((PlaceableElement) element); + break; + case NONPLACEABLE: + this.addNonPlaceableElement((NonPlaceableElement) element); + break; + default: + break; + } + } catch (InvocationTargetException e) { + System.out.println(" Failed "); + e.getTargetException().printStackTrace(); + } + } + } + } + + // } catch (IOException | ClassNotFoundException | NoSuchMethodException | + // InstantiationException | IllegalAccessException | + // InvocationTargetException + // e) { + // LOGGER.error("Unable to find rules for " + + // this.getClass().getSimpleName(), e); + // } + } catch (Exception e) { + LOGGER.error("Unable to find elements for " + this.getClass().getSimpleName(), e); + } + } + + private void registerRules() { + String packageName = this.getClass().getPackage().toString().replace("package ", ""); + + try { + Class[] possRules = LegupUtils.getClasses(packageName); + + for (Class c : possRules) { + + System.out.println("possible rule: " + c.getName()); + + // check that the rule is not abstract + if (Modifier.isAbstract(c.getModifiers())) continue; + + for (Annotation a : c.getAnnotations()) { + if (a.annotationType() == RegisterRule.class) { + RegisterRule registerRule = (RegisterRule) a; + Constructor cons = c.getConstructor(); + try { + Rule rule = (Rule) cons.newInstance(); + + switch (rule.getRuleType()) { + case BASIC: + this.addDirectRule((DirectRule) rule); + break; + case CASE: + this.addCaseRule((CaseRule) rule); + break; + case CONTRADICTION: + this.addContradictionRule((ContradictionRule) rule); + break; + case MERGE: + break; + default: + break; + } + } catch (InvocationTargetException e) { + System.out.println(" Failed "); + e.getTargetException().printStackTrace(); + } + } + } } - } + + // } catch (IOException | ClassNotFoundException | NoSuchMethodException | + // InstantiationException | IllegalAccessException | + // InvocationTargetException + // e) { + // LOGGER.error("Unable to find rules for " + + // this.getClass().getSimpleName(), e); + // } + } catch (Exception e) { + LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); + } + } + + /** Initializes the view. Called by the invoker of the class */ + public abstract void initializeView(); + + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + public abstract Board generatePuzzle(int difficulty); + + /** + * Checks if the given height and width are valid board dimensions for the given puzzle + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @return true if the given dimensions are valid for the given puzzle, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows > 0 && columns > 0; + } + + /** + * Checks if the given array of statements is valid text input for the given puzzle + * + * @param statements + * @return + */ + public boolean isValidTextInput(String[] statements) { + return statements.length > 0; + } + + /** + * Determines if the edu.rpi.legup.puzzle was solves correctly + * + * @return true if the board was solved correctly, false otherwise + */ + public boolean isPuzzleComplete() { + if (tree == null) { + return false; } - } - - // } catch (IOException | ClassNotFoundException | NoSuchMethodException | - // InstantiationException | IllegalAccessException | InvocationTargetException - // e) { - // LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); - // } - } catch (Exception e) { - LOGGER.error("Unable to find elements for " + this.getClass().getSimpleName(), e); - } - } - - private void registerRules() { - String packageName = this.getClass().getPackage().toString().replace("package ", ""); - - try { - Class[] possRules = LegupUtils.getClasses(packageName); - - for (Class c : possRules) { - - System.out.println("possible rule: " + c.getName()); - - // check that the rule is not abstract - if (Modifier.isAbstract(c.getModifiers())) continue; - - for (Annotation a : c.getAnnotations()) { - if (a.annotationType() == RegisterRule.class) { - RegisterRule registerRule = (RegisterRule) a; - Constructor cons = c.getConstructor(); - try { - Rule rule = (Rule) cons.newInstance(); - - switch (rule.getRuleType()) { - case BASIC: - this.addDirectRule((DirectRule) rule); - break; - case CASE: - this.addCaseRule((CaseRule) rule); - break; - case CONTRADICTION: - this.addContradictionRule((ContradictionRule) rule); - break; - case MERGE: - break; - default: - break; - } - } catch (InvocationTargetException e) { - System.out.println(" Failed "); - e.getTargetException().printStackTrace(); + + boolean isComplete = tree.isValid(); + if (isComplete) { + for (TreeElement leaf : tree.getLeafTreeElements()) { + if (leaf.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) leaf; + if (!node.isRoot()) { + isComplete &= + node.getParent().isContradictoryBranch() + || isBoardComplete(node.getBoard()); + } else { + isComplete &= isBoardComplete(node.getBoard()); + } + } else { + isComplete = false; + } } - } } - } - - // } catch (IOException | ClassNotFoundException | NoSuchMethodException | - // InstantiationException | IllegalAccessException | InvocationTargetException - // e) { - // LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); - // } - } catch (Exception e) { - LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); - } - } - - /** Initializes the view. Called by the invoker of the class */ - public abstract void initializeView(); - - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - public abstract Board generatePuzzle(int difficulty); - - /** - * Checks if the given height and width are valid board dimensions for the given puzzle - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @return true if the given dimensions are valid for the given puzzle, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows > 0 && columns > 0; - } - - /** - * Checks if the given array of statements is valid text input for the given puzzle - * - * @param statements - * @return - */ - public boolean isValidTextInput(String[] statements) { - return statements.length > 0; - } - - /** - * Determines if the edu.rpi.legup.puzzle was solves correctly - * - * @return true if the board was solved correctly, false otherwise - */ - public boolean isPuzzleComplete() { - if (tree == null) { - return false; - } - - boolean isComplete = tree.isValid(); - if (isComplete) { - for (TreeElement leaf : tree.getLeafTreeElements()) { - if (leaf.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) leaf; - if (!node.isRoot()) { - isComplete &= - node.getParent().isContradictoryBranch() || isBoardComplete(node.getBoard()); - } else { - isComplete &= isBoardComplete(node.getBoard()); - } + return isComplete; + } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + public abstract boolean isBoardComplete(Board board); + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + public abstract void onBoardChange(Board board); + + /** + * Imports the board using the file stream + * + * @param fileName the file that is imported + * @throws InvalidFileFormatException if file is invalid + */ + public void importPuzzle(String fileName) throws InvalidFileFormatException { + try { + importPuzzle(new FileInputStream(fileName)); + } catch (IOException e) { + LOGGER.error("Importing puzzle error", e); + throw new InvalidFileFormatException("Could not find file"); + } + } + + /** + * Imports the board using the file stream + * + * @param inputStream the file stream that is imported + * @throws InvalidFileFormatException if file stream is invalid + */ + public void importPuzzle(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Importing puzzle error", e); + throw new InvalidFileFormatException("Could not find file"); + } + + org.w3c.dom.Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + if (importer == null) { + throw new InvalidFileFormatException("Puzzle importer null"); + } + importer.initializePuzzle(node); } else { - isComplete = false; + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - } - } - return isComplete; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - public abstract boolean isBoardComplete(Board board); - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - public abstract void onBoardChange(Board board); - - /** - * Imports the board using the file stream - * - * @param fileName the file that is imported - * @throws InvalidFileFormatException if file is invalid - */ - public void importPuzzle(String fileName) throws InvalidFileFormatException { - try { - importPuzzle(new FileInputStream(fileName)); - } catch (IOException e) { - LOGGER.error("Importing puzzle error", e); - throw new InvalidFileFormatException("Could not find file"); - } - } - - /** - * Imports the board using the file stream - * - * @param inputStream the file stream that is imported - * @throws InvalidFileFormatException if file stream is invalid - */ - public void importPuzzle(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Importing puzzle error", e); - throw new InvalidFileFormatException("Could not find file"); - } - - org.w3c.dom.Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - if (importer == null) { - throw new InvalidFileFormatException("Puzzle importer null"); - } - importer.initializePuzzle(node); - } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); - } - } - - /** - * Gets the edu.rpi.legup.puzzle importer for importing edu.rpi.legup.puzzle files - * - * @return edu.rpi.legup.puzzle importer - */ - public PuzzleImporter getImporter() { - return importer; - } - - /** - * Gets the edu.rpi.legup.puzzle exporter for exporting edu.rpi.legup.puzzle files - * - * @return edu.rpi.legup.puzzle exporter - */ - public PuzzleExporter getExporter() { - return exporter; - } - - /** - * Gets the name of the edu.rpi.legup.puzzle - * - * @return name of the edu.rpi.legup.puzzle - */ - public String getName() { - return name; - } - - /** - * Gets the list of direct rules - * - * @return list of basic rules - */ - public List getDirectRules() { - return directRules; - } - - public List getPlaceableElements() { - return placeableElements; - } - - public List getNonPlaceableElements() { - return nonPlaceableElements; - } - - /** - * Sets the list of direct rules - * - * @param directRules list of basic rules - */ - public void setDirectRules(List directRules) { - this.directRules = directRules; - } - - /** - * Adds a basic rule to this Puzzle - * - * @param rule basic rule to add - */ - public void addDirectRule(DirectRule rule) { - directRules.add(rule); - } - - public void addPlaceableElement(PlaceableElement element) { - placeableElements.add(element); - } - - public void addNonPlaceableElement(NonPlaceableElement element) { - nonPlaceableElements.add(element); - } - - /** - * Remove a basic rule from this Puzzle - * - * @param rule basic rule to remove - */ - public void removeDirectRule(DirectRule rule) { - directRules.remove(rule); - } - - /** - * Gets the list of contradiction rules - * - * @return list of contradiction rules - */ - public List getContradictionRules() { - return contradictionRules; - } - - /** - * Sets the list of contradiction rules - * - * @param contradictionRules list of contradiction rules - */ - public void setContradictionRules(List contradictionRules) { - this.contradictionRules = contradictionRules; - } - - /** - * Adds a contradiction rule to this Puzzle - * - * @param rule contradiction rule to add - */ - public void addContradictionRule(ContradictionRule rule) { - contradictionRules.add(rule); - } - - /** - * Remove a contradiction rule from this Puzzle - * - * @param rule contradiction rule to remove - */ - public void removeContradictionRule(ContradictionRule rule) { - contradictionRules.remove(rule); - } - - /** - * Gets the list of case rules - * - * @return list of case rules - */ - public List getCaseRules() { - return caseRules; - } - - /** - * Sets the list of case rules - * - * @param caseRules list of case rules - */ - public void setCaseRules(List caseRules) { - this.caseRules = caseRules; - } - - /** - * Adds a case rule to this Puzzle - * - * @param rule case rule to add - */ - public void addCaseRule(CaseRule rule) { - caseRules.add(rule); - } - - /** - * Removes a case rule from this Puzzle - * - * @param rule case rule to remove - */ - public void removeCaseRule(CaseRule rule) { - caseRules.remove(rule); - } - - /** - * Gets the rule using the specified name - * - * @param name name of the rule - * @return Rule - */ - public Rule getRuleByName(String name) { - for (Rule rule : directRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - for (Rule rule : contradictionRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - for (Rule rule : caseRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - Rule mergeRule = new MergeRule(); - if (mergeRule.getRuleName().equals(name)) { - return mergeRule; - } - return null; - } - - /** - * Gets the rule using the specified name - * - * @param id name of the rule - * @return Rule - */ - public Rule getRuleByID(String id) { - for (Rule rule : directRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - for (Rule rule : contradictionRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - for (Rule rule : caseRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - Rule mergeRule = new MergeRule(); - if (mergeRule.getRuleID().equals(id)) { - return mergeRule; - } - return null; - } - - /** - * Gets the current board - * - * @return current board - */ - public Board getCurrentBoard() { - return currentBoard; - } - - /** - * Sets the current board - * - * @param currentBoard the current board - */ - public void setCurrentBoard(Board currentBoard) { - this.currentBoard = currentBoard; - } - - /** - * Gets the Tree for keeping the board states - * - * @return Tree - */ - public Tree getTree() { - return tree; - } - - /** - * Sets the Tree for keeping the board states - * - * @param tree tree of board states - */ - public void setTree(Tree tree) { - this.tree = tree; - } - - /** - * Gets the board view that displays the board - * - * @return board view - */ - public BoardView getBoardView() { - return boardView; - } - - /** - * Sets the board view that displays the board - * - * @param boardView board view - */ - public void setBoardView(BoardView boardView) { - this.boardView = boardView; - } - - /** - * Gets the ElementFactory associated with this edu.rpi.legup.puzzle - * - * @return ElementFactory associated with this edu.rpi.legup.puzzle - */ - public ElementFactory getFactory() { - return factory; - } - - /** - * Sets the ElementFactory associated with this edu.rpi.legup.puzzle - * - * @param factory ElementFactory associated with this edu.rpi.legup.puzzle - */ - public void setFactory(ElementFactory factory) { - this.factory = factory; - } - - /** - * Adds a board listener - * - * @param listener listener to add - */ - @Override - public void addBoardListener(IBoardListener listener) { - boardListeners.add(listener); - } - - /** - * Removes a board listener - * - * @param listener listener to remove - */ - @Override - public void removeBoardListener(IBoardListener listener) { - boardListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyBoardListeners(Consumer algorithm) { - boardListeners.forEach(algorithm); - } - - /** - * Adds a board listener - * - * @param listener listener to add - */ - @Override - public void addTreeListener(ITreeListener listener) { - treeListeners.add(listener); - } - - /** - * Removes a tree listener - * - * @param listener listener to remove - */ - @Override - public void removeTreeListener(ITreeListener listener) { - treeListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyTreeListeners(Consumer algorithm) { - treeListeners.forEach(algorithm); - } - - /** - * Check if the puzzle is valid - * - * @return if the puzzle is valid - */ - public boolean checkValidity() { - return true; - } + } + + /** + * Gets the edu.rpi.legup.puzzle importer for importing edu.rpi.legup.puzzle files + * + * @return edu.rpi.legup.puzzle importer + */ + public PuzzleImporter getImporter() { + return importer; + } + + /** + * Gets the edu.rpi.legup.puzzle exporter for exporting edu.rpi.legup.puzzle files + * + * @return edu.rpi.legup.puzzle exporter + */ + public PuzzleExporter getExporter() { + return exporter; + } + + /** + * Gets the name of the edu.rpi.legup.puzzle + * + * @return name of the edu.rpi.legup.puzzle + */ + public String getName() { + return name; + } + + /** + * Gets the list of direct rules + * + * @return list of basic rules + */ + public List getDirectRules() { + return directRules; + } + + public List getPlaceableElements() { + return placeableElements; + } + + public List getNonPlaceableElements() { + return nonPlaceableElements; + } + + /** + * Sets the list of direct rules + * + * @param directRules list of basic rules + */ + public void setDirectRules(List directRules) { + this.directRules = directRules; + } + + /** + * Adds a basic rule to this Puzzle + * + * @param rule basic rule to add + */ + public void addDirectRule(DirectRule rule) { + directRules.add(rule); + } + + public void addPlaceableElement(PlaceableElement element) { + placeableElements.add(element); + } + + public void addNonPlaceableElement(NonPlaceableElement element) { + nonPlaceableElements.add(element); + } + + /** + * Remove a basic rule from this Puzzle + * + * @param rule basic rule to remove + */ + public void removeDirectRule(DirectRule rule) { + directRules.remove(rule); + } + + /** + * Gets the list of contradiction rules + * + * @return list of contradiction rules + */ + public List getContradictionRules() { + return contradictionRules; + } + + /** + * Sets the list of contradiction rules + * + * @param contradictionRules list of contradiction rules + */ + public void setContradictionRules(List contradictionRules) { + this.contradictionRules = contradictionRules; + } + + /** + * Adds a contradiction rule to this Puzzle + * + * @param rule contradiction rule to add + */ + public void addContradictionRule(ContradictionRule rule) { + contradictionRules.add(rule); + } + + /** + * Remove a contradiction rule from this Puzzle + * + * @param rule contradiction rule to remove + */ + public void removeContradictionRule(ContradictionRule rule) { + contradictionRules.remove(rule); + } + + /** + * Gets the list of case rules + * + * @return list of case rules + */ + public List getCaseRules() { + return caseRules; + } + + /** + * Sets the list of case rules + * + * @param caseRules list of case rules + */ + public void setCaseRules(List caseRules) { + this.caseRules = caseRules; + } + + /** + * Adds a case rule to this Puzzle + * + * @param rule case rule to add + */ + public void addCaseRule(CaseRule rule) { + caseRules.add(rule); + } + + /** + * Removes a case rule from this Puzzle + * + * @param rule case rule to remove + */ + public void removeCaseRule(CaseRule rule) { + caseRules.remove(rule); + } + + /** + * Gets the rule using the specified name + * + * @param name name of the rule + * @return Rule + */ + public Rule getRuleByName(String name) { + for (Rule rule : directRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + for (Rule rule : contradictionRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + for (Rule rule : caseRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + Rule mergeRule = new MergeRule(); + if (mergeRule.getRuleName().equals(name)) { + return mergeRule; + } + return null; + } + + /** + * Gets the rule using the specified name + * + * @param id name of the rule + * @return Rule + */ + public Rule getRuleByID(String id) { + for (Rule rule : directRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + for (Rule rule : contradictionRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + for (Rule rule : caseRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + Rule mergeRule = new MergeRule(); + if (mergeRule.getRuleID().equals(id)) { + return mergeRule; + } + return null; + } + + /** + * Gets the current board + * + * @return current board + */ + public Board getCurrentBoard() { + return currentBoard; + } + + /** + * Sets the current board + * + * @param currentBoard the current board + */ + public void setCurrentBoard(Board currentBoard) { + this.currentBoard = currentBoard; + } + + /** + * Gets the Tree for keeping the board states + * + * @return Tree + */ + public Tree getTree() { + return tree; + } + + /** + * Sets the Tree for keeping the board states + * + * @param tree tree of board states + */ + public void setTree(Tree tree) { + this.tree = tree; + } + + /** + * Gets the board view that displays the board + * + * @return board view + */ + public BoardView getBoardView() { + return boardView; + } + + /** + * Sets the board view that displays the board + * + * @param boardView board view + */ + public void setBoardView(BoardView boardView) { + this.boardView = boardView; + } + + /** + * Gets the ElementFactory associated with this edu.rpi.legup.puzzle + * + * @return ElementFactory associated with this edu.rpi.legup.puzzle + */ + public ElementFactory getFactory() { + return factory; + } + + /** + * Sets the ElementFactory associated with this edu.rpi.legup.puzzle + * + * @param factory ElementFactory associated with this edu.rpi.legup.puzzle + */ + public void setFactory(ElementFactory factory) { + this.factory = factory; + } + + /** + * Adds a board listener + * + * @param listener listener to add + */ + @Override + public void addBoardListener(IBoardListener listener) { + boardListeners.add(listener); + } + + /** + * Removes a board listener + * + * @param listener listener to remove + */ + @Override + public void removeBoardListener(IBoardListener listener) { + boardListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyBoardListeners(Consumer algorithm) { + boardListeners.forEach(algorithm); + } + + /** + * Adds a board listener + * + * @param listener listener to add + */ + @Override + public void addTreeListener(ITreeListener listener) { + treeListeners.add(listener); + } + + /** + * Removes a tree listener + * + * @param listener listener to remove + */ + @Override + public void removeTreeListener(ITreeListener listener) { + treeListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyTreeListeners(Consumer algorithm) { + treeListeners.forEach(algorithm); + } + + /** + * Check if the puzzle is valid + * + * @return if the puzzle is valid + */ + public boolean checkValidity() { + return true; + } } diff --git a/src/main/java/edu/rpi/legup/model/PuzzleExporter.java b/src/main/java/edu/rpi/legup/model/PuzzleExporter.java index cccf0155c..a052a736a 100644 --- a/src/main/java/edu/rpi/legup/model/PuzzleExporter.java +++ b/src/main/java/edu/rpi/legup/model/PuzzleExporter.java @@ -21,125 +21,126 @@ import org.w3c.dom.Element; public abstract class PuzzleExporter { - private static final Logger LOGGER = LogManager.getLogger(PuzzleExporter.class.getName()); - - protected Puzzle puzzle; - - /** - * PuzzleExporter Constructor exports the puzzle object to a file - * - * @param puzzle puzzle that is to be exported - */ - public PuzzleExporter(Puzzle puzzle) { - this.puzzle = puzzle; - } - - /** - * Exports the puzzle to an xml formatted file - * - * @param fileName name of file to be exported - * @throws ExportFileException if puzzle can not be exported - */ - public void exportPuzzle(String fileName) throws ExportFileException { - try { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document newDocument = docBuilder.newDocument(); - - org.w3c.dom.Element legupElement = newDocument.createElement("Legup"); - legupElement.setAttribute("version", "3.0.0"); - newDocument.appendChild(legupElement); - - org.w3c.dom.Element timeSavedElement = newDocument.createElement("saved"); - legupElement.appendChild(timeSavedElement); - - org.w3c.dom.Element puzzleElement = newDocument.createElement("puzzle"); - puzzleElement.setAttribute("name", puzzle.getName()); - legupElement.appendChild(puzzleElement); - - puzzleElement.appendChild(createBoardElement(newDocument)); - if (puzzle.getTree() != null && !puzzle.getTree().getRootNode().getChildren().isEmpty()) { - puzzleElement.appendChild(createProofElement(newDocument)); - } - - org.w3c.dom.Element statusElement = newDocument.createElement("solved"); - String isSolved = "false"; - if (puzzle.isPuzzleComplete()) { - isSolved = "true"; - } - statusElement.setAttribute("isSolved", isSolved); - LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/New_York")); - String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - statusElement.setAttribute("lastSaved", time); - legupElement.appendChild(statusElement); - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - DOMSource source = new DOMSource(newDocument); - StreamResult result = new StreamResult(new File(fileName)); - - transformer.transform(source, result); - } catch (ParserConfigurationException | TransformerException e) { - throw new ExportFileException("Puzzle Exporter: parser configuration exception"); - } catch (Exception e) { - throw e; - // throw new ExportFileException(e.getMessage()); + private static final Logger LOGGER = LogManager.getLogger(PuzzleExporter.class.getName()); + + protected Puzzle puzzle; + + /** + * PuzzleExporter Constructor exports the puzzle object to a file + * + * @param puzzle puzzle that is to be exported + */ + public PuzzleExporter(Puzzle puzzle) { + this.puzzle = puzzle; } - } - - protected abstract Element createBoardElement(Document newDocument); - - protected Element createProofElement(Document newDocument) { - org.w3c.dom.Element proofElement = newDocument.createElement("proof"); - org.w3c.dom.Element treeElement = createTreeElement(newDocument); - proofElement.appendChild(treeElement); - return proofElement; - } - - protected Element createTreeElement(Document newDocument) { - org.w3c.dom.Element treeElement = newDocument.createElement("tree"); - - Set visited = new HashSet<>(); - List nodes = new ArrayList<>(); - nodes.add(puzzle.getTree().getRootNode()); - while (!nodes.isEmpty()) { - TreeNode treeNode = nodes.get(nodes.size() - 1); - nodes.remove(treeNode); - if (!visited.contains(treeNode)) { - visited.add(treeNode); - - org.w3c.dom.Element nodeElement = newDocument.createElement("node"); - nodeElement.setAttribute("id", String.valueOf(treeNode.hashCode())); - if (treeNode.isRoot()) { - nodeElement.setAttribute("root", "true"); + + /** + * Exports the puzzle to an xml formatted file + * + * @param fileName name of file to be exported + * @throws ExportFileException if puzzle can not be exported + */ + public void exportPuzzle(String fileName) throws ExportFileException { + try { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + Document newDocument = docBuilder.newDocument(); + + org.w3c.dom.Element legupElement = newDocument.createElement("Legup"); + legupElement.setAttribute("version", "3.0.0"); + newDocument.appendChild(legupElement); + + org.w3c.dom.Element timeSavedElement = newDocument.createElement("saved"); + legupElement.appendChild(timeSavedElement); + + org.w3c.dom.Element puzzleElement = newDocument.createElement("puzzle"); + puzzleElement.setAttribute("name", puzzle.getName()); + legupElement.appendChild(puzzleElement); + + puzzleElement.appendChild(createBoardElement(newDocument)); + if (puzzle.getTree() != null + && !puzzle.getTree().getRootNode().getChildren().isEmpty()) { + puzzleElement.appendChild(createProofElement(newDocument)); + } + + org.w3c.dom.Element statusElement = newDocument.createElement("solved"); + String isSolved = "false"; + if (puzzle.isPuzzleComplete()) { + isSolved = "true"; + } + statusElement.setAttribute("isSolved", isSolved); + LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/New_York")); + String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + statusElement.setAttribute("lastSaved", time); + legupElement.appendChild(statusElement); + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + + DOMSource source = new DOMSource(newDocument); + StreamResult result = new StreamResult(new File(fileName)); + + transformer.transform(source, result); + } catch (ParserConfigurationException | TransformerException e) { + throw new ExportFileException("Puzzle Exporter: parser configuration exception"); + } catch (Exception e) { + throw e; + // throw new ExportFileException(e.getMessage()); } + } + + protected abstract Element createBoardElement(Document newDocument); + + protected Element createProofElement(Document newDocument) { + org.w3c.dom.Element proofElement = newDocument.createElement("proof"); + org.w3c.dom.Element treeElement = createTreeElement(newDocument); + proofElement.appendChild(treeElement); + return proofElement; + } - for (TreeTransition transition : treeNode.getChildren()) { - org.w3c.dom.Element transElement = newDocument.createElement("transition"); - transElement.setAttribute("id", String.valueOf(transition.hashCode())); - - TreeNode child = transition.getChildNode(); - if (child != null) { - transElement.setAttribute("child", String.valueOf(child.hashCode())); - nodes.add(child); - } - - if (transition.isJustified()) { - transElement.setAttribute("rule", transition.getRule().getRuleName()); - transElement.setAttribute("rule_id", transition.getRule().getRuleID()); - } - - for (PuzzleElement data : transition.getBoard().getModifiedData()) { - transElement.appendChild(puzzle.getFactory().exportCell(newDocument, data)); - } - nodeElement.appendChild(transElement); + protected Element createTreeElement(Document newDocument) { + org.w3c.dom.Element treeElement = newDocument.createElement("tree"); + + Set visited = new HashSet<>(); + List nodes = new ArrayList<>(); + nodes.add(puzzle.getTree().getRootNode()); + while (!nodes.isEmpty()) { + TreeNode treeNode = nodes.get(nodes.size() - 1); + nodes.remove(treeNode); + if (!visited.contains(treeNode)) { + visited.add(treeNode); + + org.w3c.dom.Element nodeElement = newDocument.createElement("node"); + nodeElement.setAttribute("id", String.valueOf(treeNode.hashCode())); + if (treeNode.isRoot()) { + nodeElement.setAttribute("root", "true"); + } + + for (TreeTransition transition : treeNode.getChildren()) { + org.w3c.dom.Element transElement = newDocument.createElement("transition"); + transElement.setAttribute("id", String.valueOf(transition.hashCode())); + + TreeNode child = transition.getChildNode(); + if (child != null) { + transElement.setAttribute("child", String.valueOf(child.hashCode())); + nodes.add(child); + } + + if (transition.isJustified()) { + transElement.setAttribute("rule", transition.getRule().getRuleName()); + transElement.setAttribute("rule_id", transition.getRule().getRuleID()); + } + + for (PuzzleElement data : transition.getBoard().getModifiedData()) { + transElement.appendChild(puzzle.getFactory().exportCell(newDocument, data)); + } + nodeElement.appendChild(transElement); + } + treeElement.appendChild(nodeElement); + } } - treeElement.appendChild(nodeElement); - } + return treeElement; } - return treeElement; - } } diff --git a/src/main/java/edu/rpi/legup/model/PuzzleImporter.java b/src/main/java/edu/rpi/legup/model/PuzzleImporter.java index 35a3cd6be..0cc163200 100644 --- a/src/main/java/edu/rpi/legup/model/PuzzleImporter.java +++ b/src/main/java/edu/rpi/legup/model/PuzzleImporter.java @@ -14,398 +14,402 @@ import org.w3c.dom.NodeList; public abstract class PuzzleImporter { - private static final Logger LOGGER = LogManager.getLogger(PuzzleImporter.class.getName()); - - protected Puzzle puzzle; - - /** - * PuzzleImporter Constructor creates the puzzle object - * - * @param puzzle puzzle that is imported - */ - public PuzzleImporter(Puzzle puzzle) { - this.puzzle = puzzle; - } - - public abstract boolean acceptsRowsAndColumnsInput(); - - public abstract boolean acceptsTextInput(); - - /** - * Initializes an empty puzzle - * - * @param rows number of rows on the puzzle - * @param columns number of columns on the puzzle - * @throws RuntimeException if puzzle can not be made - */ - public void initializePuzzle(int rows, int columns) throws RuntimeException { - if (this.puzzle.isValidDimensions(rows, columns)) { - initializeBoard(rows, columns); - } else { - throw new IllegalArgumentException("Invalid dimensions provided"); + private static final Logger LOGGER = LogManager.getLogger(PuzzleImporter.class.getName()); + + protected Puzzle puzzle; + + /** + * PuzzleImporter Constructor creates the puzzle object + * + * @param puzzle puzzle that is imported + */ + public PuzzleImporter(Puzzle puzzle) { + this.puzzle = puzzle; } - } - - public void initializePuzzle(String[] statements) - throws InputMismatchException, IllegalArgumentException { - // Note: Error checking for the statements will be left up to the puzzles that support - // text input. For example, some puzzles may be okay with "blank" statements (Strings with - // length = 0) while others may not. - initializeBoard(statements); - } - - /** - * Initializes the puzzle attributes - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public void initializePuzzle(Node node) throws InvalidFileFormatException { - if (node.getNodeName().equalsIgnoreCase("puzzle")) { - org.w3c.dom.Element puzzleElement = (org.w3c.dom.Element) node; - - boolean initBoard = false; - boolean initProof = false; - NodeList childNodes = puzzleElement.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - Node n = childNodes.item(i); - if (n.getNodeName().equalsIgnoreCase("board")) { - if (initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: duplicate board puzzleElement found"); - } - initializeBoard(n); - initBoard = true; + + public abstract boolean acceptsRowsAndColumnsInput(); + + public abstract boolean acceptsTextInput(); + + /** + * Initializes an empty puzzle + * + * @param rows number of rows on the puzzle + * @param columns number of columns on the puzzle + * @throws RuntimeException if puzzle can not be made + */ + public void initializePuzzle(int rows, int columns) throws RuntimeException { + if (this.puzzle.isValidDimensions(rows, columns)) { + initializeBoard(rows, columns); } else { - if (n.getNodeName().equalsIgnoreCase("proof")) { - if (initProof) { - throw new InvalidFileFormatException( - "Puzzle creation error: duplicate proof puzzleElement found"); + throw new IllegalArgumentException("Invalid dimensions provided"); + } + } + + public void initializePuzzle(String[] statements) + throws InputMismatchException, IllegalArgumentException { + // Note: Error checking for the statements will be left up to the puzzles that support + // text input. For example, some puzzles may be okay with "blank" statements (Strings with + // length = 0) while others may not. + initializeBoard(statements); + } + + /** + * Initializes the puzzle attributes + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public void initializePuzzle(Node node) throws InvalidFileFormatException { + if (node.getNodeName().equalsIgnoreCase("puzzle")) { + org.w3c.dom.Element puzzleElement = (org.w3c.dom.Element) node; + + boolean initBoard = false; + boolean initProof = false; + NodeList childNodes = puzzleElement.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node n = childNodes.item(i); + if (n.getNodeName().equalsIgnoreCase("board")) { + if (initBoard) { + throw new InvalidFileFormatException( + "Puzzle creation error: duplicate board puzzleElement found"); + } + initializeBoard(n); + initBoard = true; + } else { + if (n.getNodeName().equalsIgnoreCase("proof")) { + if (initProof) { + throw new InvalidFileFormatException( + "Puzzle creation error: duplicate proof puzzleElement found"); + } + if (!initBoard) { + throw new InvalidFileFormatException( + "Puzzle creation error: could not find board puzzleElement"); + } + initializeProof(n); + initProof = true; + } else { + if (!n.getNodeName().equalsIgnoreCase("#text")) { + throw new InvalidFileFormatException( + "Puzzle creation error: unknown node found in file"); + } + } + } } + if (!initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: could not find board puzzleElement"); + throw new InvalidFileFormatException( + "Puzzle creation error: could not find board puzzleElement"); } - initializeProof(n); - initProof = true; - } else { - if (!n.getNodeName().equalsIgnoreCase("#text")) { - throw new InvalidFileFormatException( - "Puzzle creation error: unknown node found in file"); + if (!initProof) { + createDefaultTree(); } - } + } else { + throw new InvalidFileFormatException( + "Invalid file format; does not contain \"puzzle\" node"); } - } - - if (!initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: could not find board puzzleElement"); - } - if (!initProof) { - createDefaultTree(); - } - } else { - throw new InvalidFileFormatException("Invalid file format; does not contain \"puzzle\" node"); } - } - - /** - * Creates the board for building - * - * @param rows number of rows on the puzzle - * @param columns number of columns on the puzzle - * @throws RuntimeException if board can not be created - */ - public abstract void initializeBoard(int rows, int columns); - - /** - * Creates an empty board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public abstract void initializeBoard(Node node) throws InvalidFileFormatException; - - public abstract void initializeBoard(String[] statements) - throws UnsupportedOperationException, IllegalArgumentException; - - /** - * Creates the proof for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public void initializeProof(Node node) throws InvalidFileFormatException { - if (node.getNodeName().equalsIgnoreCase("proof")) { - org.w3c.dom.Element proofElement = (org.w3c.dom.Element) node; - NodeList treeList = proofElement.getElementsByTagName("tree"); - - boolean initTree = false; - for (int i = 0; i < treeList.getLength(); i++) { - Node n = treeList.item(i); - if (n.getNodeName().equalsIgnoreCase("tree")) { - if (initTree) { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate tree puzzleElement"); - } - createTree(n); - initTree = true; + + /** + * Creates the board for building + * + * @param rows number of rows on the puzzle + * @param columns number of columns on the puzzle + * @throws RuntimeException if board can not be created + */ + public abstract void initializeBoard(int rows, int columns); + + /** + * Creates an empty board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public abstract void initializeBoard(Node node) throws InvalidFileFormatException; + + public abstract void initializeBoard(String[] statements) + throws UnsupportedOperationException, IllegalArgumentException; + + /** + * Creates the proof for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public void initializeProof(Node node) throws InvalidFileFormatException { + if (node.getNodeName().equalsIgnoreCase("proof")) { + org.w3c.dom.Element proofElement = (org.w3c.dom.Element) node; + NodeList treeList = proofElement.getElementsByTagName("tree"); + + boolean initTree = false; + for (int i = 0; i < treeList.getLength(); i++) { + Node n = treeList.item(i); + if (n.getNodeName().equalsIgnoreCase("tree")) { + if (initTree) { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate tree puzzleElement"); + } + createTree(n); + initTree = true; + } else { + throw new InvalidFileFormatException( + "Proof Tree construction error: unknown puzzleElement found"); + } + } + if (!initTree) { + createDefaultTree(); + } } else { - throw new InvalidFileFormatException( - "Proof Tree construction error: unknown puzzleElement found"); + throw new InvalidFileFormatException( + "Invalid file format; does not contain \"proof\" node"); } - } - if (!initTree) { - createDefaultTree(); - } - } else { - throw new InvalidFileFormatException("Invalid file format; does not contain \"proof\" node"); - } - } - - /** - * Sets the puzzleElement from the xml document node - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - protected void setCells(Node node) throws InvalidFileFormatException { - NodeList dataList = ((org.w3c.dom.Element) node).getElementsByTagName("cell"); - Board board = puzzle.getCurrentBoard(); - for (int i = 0; i < dataList.getLength(); i++) { - PuzzleElement data = - puzzle.getFactory().importCell(dataList.item(i), puzzle.getCurrentBoard()); - board.setPuzzleElement(data.getIndex(), data); } - } - - /** - * Creates the tree for the edu.rpi.legup.puzzle - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - protected void createTree(Node node) throws InvalidFileFormatException { - Element treeElement = (org.w3c.dom.Element) node; - - Tree tree = new Tree(); - puzzle.setTree(tree); - - NodeList nodeList = ((org.w3c.dom.Element) node).getElementsByTagName("node"); - - HashMap treeNodes = new HashMap<>(); - HashMap treeTransitions = new HashMap<>(); - HashMap nodeChanges = new HashMap<>(); - - for (int i = 0; i < nodeList.getLength(); i++) { - org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); - String nodeId = treeNodeElement.getAttribute("id"); - String isRoot = treeNodeElement.getAttribute("root"); - if (nodeId.isEmpty()) { - throw new InvalidFileFormatException("Proof Tree construction error: cannot find node ID"); - } - if (treeNodes.containsKey(nodeId)) { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate tree node ID found"); - } - TreeNode treeNode = new TreeNode(puzzle.getCurrentBoard().copy()); - if (isRoot.equalsIgnoreCase("true")) { - if (tree.getRootNode() != null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: multiple root nodes declared"); + + /** + * Sets the puzzleElement from the xml document node + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + protected void setCells(Node node) throws InvalidFileFormatException { + NodeList dataList = ((org.w3c.dom.Element) node).getElementsByTagName("cell"); + Board board = puzzle.getCurrentBoard(); + for (int i = 0; i < dataList.getLength(); i++) { + PuzzleElement data = + puzzle.getFactory().importCell(dataList.item(i), puzzle.getCurrentBoard()); + board.setPuzzleElement(data.getIndex(), data); } - treeNode.setRoot(true); - tree.setRootNode(treeNode); - } - treeNodes.put(nodeId, treeNode); } - for (int i = 0; i < nodeList.getLength(); i++) { - org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); - String nodeId = treeNodeElement.getAttribute("id"); - TreeNode treeNode = treeNodes.get(nodeId); - - NodeList transList = treeNodeElement.getElementsByTagName("transition"); - for (int k = 0; k < transList.getLength(); k++) { - org.w3c.dom.Element trans = (org.w3c.dom.Element) transList.item(k); - String transId = trans.getAttribute("id"); - TreeTransition transition = treeTransitions.get(transId); - if (transition != null) { - if (transition.getRule() instanceof MergeRule) { - transition.addParent(treeNode); - treeNode.addChild(transition); - continue; - } else { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate transition ID found"); - } + /** + * Creates the tree for the edu.rpi.legup.puzzle + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + protected void createTree(Node node) throws InvalidFileFormatException { + Element treeElement = (org.w3c.dom.Element) node; + + Tree tree = new Tree(); + puzzle.setTree(tree); + + NodeList nodeList = ((org.w3c.dom.Element) node).getElementsByTagName("node"); + + HashMap treeNodes = new HashMap<>(); + HashMap treeTransitions = new HashMap<>(); + HashMap nodeChanges = new HashMap<>(); + + for (int i = 0; i < nodeList.getLength(); i++) { + org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); + String nodeId = treeNodeElement.getAttribute("id"); + String isRoot = treeNodeElement.getAttribute("root"); + if (nodeId.isEmpty()) { + throw new InvalidFileFormatException( + "Proof Tree construction error: cannot find node ID"); + } + if (treeNodes.containsKey(nodeId)) { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate tree node ID found"); + } + TreeNode treeNode = new TreeNode(puzzle.getCurrentBoard().copy()); + if (isRoot.equalsIgnoreCase("true")) { + if (tree.getRootNode() != null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: multiple root nodes declared"); + } + treeNode.setRoot(true); + tree.setRootNode(treeNode); + } + treeNodes.put(nodeId, treeNode); } - String childId = trans.getAttribute("child"); - String ruleName = trans.getAttribute("rule"); - String ruleId = trans.getAttribute("rule_id"); - - TreeNode child = treeNodes.get(childId); - - transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - - Rule rule; - if (!ruleName.isEmpty()) { - rule = puzzle.getRuleByID(ruleId); - if (rule == null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: could not find rule by ID"); - } - transition.setRule(rule); + for (int i = 0; i < nodeList.getLength(); i++) { + org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); + String nodeId = treeNodeElement.getAttribute("id"); + TreeNode treeNode = treeNodes.get(nodeId); + + NodeList transList = treeNodeElement.getElementsByTagName("transition"); + for (int k = 0; k < transList.getLength(); k++) { + org.w3c.dom.Element trans = (org.w3c.dom.Element) transList.item(k); + String transId = trans.getAttribute("id"); + TreeTransition transition = treeTransitions.get(transId); + if (transition != null) { + if (transition.getRule() instanceof MergeRule) { + transition.addParent(treeNode); + treeNode.addChild(transition); + continue; + } else { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate transition ID found"); + } + } + + String childId = trans.getAttribute("child"); + String ruleName = trans.getAttribute("rule"); + String ruleId = trans.getAttribute("rule_id"); + + TreeNode child = treeNodes.get(childId); + + transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + + Rule rule; + if (!ruleName.isEmpty()) { + rule = puzzle.getRuleByID(ruleId); + if (rule == null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: could not find rule by ID"); + } + transition.setRule(rule); + } + + treeNode.addChild(transition); + if (child != null) { + child.setParent(transition); + transition.setChildNode(child); + } + + nodeChanges.put(transition, trans); + treeTransitions.put(transId, transition); + } } - treeNode.addChild(transition); - if (child != null) { - child.setParent(transition); - transition.setChildNode(child); + // validateTreeStructure(treeNodes, treeTransitions); + System.err.println("Tree Size: " + treeTransitions.size()); + for (Map.Entry entry : nodeChanges.entrySet()) { + makeTransitionChanges(entry.getKey(), entry.getValue()); } - - nodeChanges.put(transition, trans); - treeTransitions.put(transId, transition); - } } - // validateTreeStructure(treeNodes, treeTransitions); - System.err.println("Tree Size: " + treeTransitions.size()); - for (Map.Entry entry : nodeChanges.entrySet()) { - makeTransitionChanges(entry.getKey(), entry.getValue()); - } - } - - protected void validateTreeStructure( - HashMap nodes, HashMap transitions) - throws InvalidFileFormatException { - Tree tree = puzzle.getTree(); + protected void validateTreeStructure( + HashMap nodes, HashMap transitions) + throws InvalidFileFormatException { + Tree tree = puzzle.getTree(); - if (tree == null) { - throw new InvalidFileFormatException("Proof Tree construction error: invalid tree"); - } - - HashMap connectedNodes = new HashMap<>(); - HashMap connectedTransitions = new HashMap<>(); + if (tree == null) { + throw new InvalidFileFormatException("Proof Tree construction error: invalid tree"); + } - for (TreeNode node : nodes.values()) { - connectedNodes.put(node, false); - } + HashMap connectedNodes = new HashMap<>(); + HashMap connectedTransitions = new HashMap<>(); - for (TreeTransition trans : transitions.values()) { - connectedTransitions.put(trans, false); - } + for (TreeNode node : nodes.values()) { + connectedNodes.put(node, false); + } - ArrayList treeElements = new ArrayList<>(); - treeElements.add(tree.getRootNode()); - while (!treeElements.isEmpty()) { - TreeElement element = treeElements.get(treeElements.size() - 1); - treeElements.remove(element); - if (element.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) element; - - if (connectedNodes.get(treeNode)) { - // for(TreeTransition trans : treeNode.getParents()) - // { - // if(!(trans.getRule() instanceof MergeRule)) - // { - // throw new InvalidFileFormatException("Proof Tree structure - // validation error: cyclic tree detected"); - // } - // } + for (TreeTransition trans : transitions.values()) { + connectedTransitions.put(trans, false); } - connectedNodes.replace(treeNode, true); - for (TreeTransition trans : treeNode.getChildren()) { - treeElements.add(trans); + ArrayList treeElements = new ArrayList<>(); + treeElements.add(tree.getRootNode()); + while (!treeElements.isEmpty()) { + TreeElement element = treeElements.get(treeElements.size() - 1); + treeElements.remove(element); + if (element.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) element; + + if (connectedNodes.get(treeNode)) { + // for(TreeTransition trans : treeNode.getParents()) + // { + // if(!(trans.getRule() instanceof MergeRule)) + // { + // throw new InvalidFileFormatException("Proof Tree + // structure + // validation error: cyclic tree detected"); + // } + // } + } + connectedNodes.replace(treeNode, true); + + for (TreeTransition trans : treeNode.getChildren()) { + treeElements.add(trans); + } + } else { + TreeTransition treeTransition = (TreeTransition) element; + + if (connectedTransitions.get(treeTransition)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: cyclic tree detected"); + } + connectedTransitions.replace(treeTransition, true); + + if (treeTransition.getChildNode() != null) { + treeElements.add(treeTransition.getChildNode()); + } + } } - } else { - TreeTransition treeTransition = (TreeTransition) element; - if (connectedTransitions.get(treeTransition)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: cyclic tree detected"); + for (TreeNode node : nodes.values()) { + if (!connectedNodes.get(node)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: disjoint node detected"); + } } - connectedTransitions.replace(treeTransition, true); - if (treeTransition.getChildNode() != null) { - treeElements.add(treeTransition.getChildNode()); + for (TreeTransition trans : transitions.values()) { + if (!connectedTransitions.get(trans)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: disjoint transition detected"); + } } - } } - for (TreeNode node : nodes.values()) { - if (!connectedNodes.get(node)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: disjoint node detected"); - } - } + protected void makeTransitionChanges(TreeTransition transition, Node transElement) + throws InvalidFileFormatException { + if (transition.getRule() instanceof MergeRule) { + List mergingNodes = transition.getParents(); + List mergingBoards = new ArrayList<>(); + mergingNodes.forEach(n -> mergingBoards.add(n.getBoard())); + + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: unable to find merge node"); + } + Board lcaBoard = lca.getBoard(); - for (TreeTransition trans : transitions.values()) { - if (!connectedTransitions.get(trans)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: disjoint transition detected"); - } - } - } - - protected void makeTransitionChanges(TreeTransition transition, Node transElement) - throws InvalidFileFormatException { - if (transition.getRule() instanceof MergeRule) { - List mergingNodes = transition.getParents(); - List mergingBoards = new ArrayList<>(); - mergingNodes.forEach(n -> mergingBoards.add(n.getBoard())); - - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: unable to find merge node"); - } - Board lcaBoard = lca.getBoard(); - - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); - - transition.setBoard(mergedBoard); - TreeNode childNode = transition.getChildNode(); - if (childNode != null) { - childNode.setBoard(mergedBoard.copy()); - } - } else { - NodeList cellList = transElement.getChildNodes(); - for (int i = 0; i < cellList.getLength(); i++) { - Node node = cellList.item(i); - if (node.getNodeName().equalsIgnoreCase("cell")) { - Board board = transition.getBoard(); - PuzzleElement cell = puzzle.getFactory().importCell(node, board); - - board.setPuzzleElement(cell.getIndex(), cell); - board.addModifiedData(cell); - transition.propagateChange(cell); + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + transition.setBoard(mergedBoard); + TreeNode childNode = transition.getChildNode(); + if (childNode != null) { + childNode.setBoard(mergedBoard.copy()); + } } else { - if (!node.getNodeName().equalsIgnoreCase("#text")) { - throw new InvalidFileFormatException( - "Proof Tree construction error: unknown node in transition"); - } + NodeList cellList = transElement.getChildNodes(); + for (int i = 0; i < cellList.getLength(); i++) { + Node node = cellList.item(i); + if (node.getNodeName().equalsIgnoreCase("cell")) { + Board board = transition.getBoard(); + PuzzleElement cell = puzzle.getFactory().importCell(node, board); + + board.setPuzzleElement(cell.getIndex(), cell); + board.addModifiedData(cell); + transition.propagateChange(cell); + } else { + if (!node.getNodeName().equalsIgnoreCase("#text")) { + throw new InvalidFileFormatException( + "Proof Tree construction error: unknown node in transition"); + } + } + } } - } } - } - - protected void createDefaultTree() { - TreeNode root = new TreeNode(puzzle.getCurrentBoard()); - root.setRoot(true); - Tree tree = new Tree(); - tree.setRootNode(root); - puzzle.setTree(tree); - } - - /** - * Gets the result of building the Puzzle - * - * @return puzzle - */ - public Puzzle getPuzzle() { - return puzzle; - } + + protected void createDefaultTree() { + TreeNode root = new TreeNode(puzzle.getCurrentBoard()); + root.setRoot(true); + Tree tree = new Tree(); + tree.setRootNode(root); + puzzle.setTree(tree); + } + + /** + * Gets the result of building the Puzzle + * + * @return puzzle + */ + public Puzzle getPuzzle() { + return puzzle; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/Element.java b/src/main/java/edu/rpi/legup/model/elements/Element.java index 5ad31782a..8b75d075d 100644 --- a/src/main/java/edu/rpi/legup/model/elements/Element.java +++ b/src/main/java/edu/rpi/legup/model/elements/Element.java @@ -6,71 +6,72 @@ @RegisterElement public abstract class Element { - protected String elementID; - protected String elementName; - protected String description; + protected String elementID; + protected String elementName; + protected String description; - protected String imageName; - protected ImageIcon image; + protected String imageName; + protected ImageIcon image; - protected ElementType elementType; + protected ElementType elementType; - private final String INVALID_USE_MESSAGE; + private final String INVALID_USE_MESSAGE; - public Element(String elementID, String elementName, String description, String imageName) { - this.elementID = elementID; - this.elementName = elementName; - this.description = description; - this.imageName = imageName; - this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.elementName; - loadImage(); - } + public Element(String elementID, String elementName, String description, String imageName) { + this.elementID = elementID; + this.elementName = elementName; + this.description = description; + this.imageName = imageName; + this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.elementName; + loadImage(); + } - private void loadImage() { - if (imageName != null) { - this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(imageName)); - // Resize images to be 100px wide - Image image = this.image.getImage(); - if (this.image.getIconWidth() < 120) return; - int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); - if (height == 0) { - System.out.println("height is 0 error"); - System.out.println("height: " + this.image.getIconHeight()); - System.out.println("width: " + this.image.getIconWidth()); - return; - } - BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = bimage.createGraphics(); - g.drawImage(image, 0, 0, 100, height, null); - this.image = new ImageIcon(bimage); + private void loadImage() { + if (imageName != null) { + this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(imageName)); + // Resize images to be 100px wide + Image image = this.image.getImage(); + if (this.image.getIconWidth() < 120) return; + int height = + (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); + if (height == 0) { + System.out.println("height is 0 error"); + System.out.println("height: " + this.image.getIconHeight()); + System.out.println("width: " + this.image.getIconWidth()); + return; + } + BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = bimage.createGraphics(); + g.drawImage(image, 0, 0, 100, height, null); + this.image = new ImageIcon(bimage); + } } - } - public String getElementName() { - return elementName; - } + public String getElementName() { + return elementName; + } - public void setElementName(String elementName) { - this.elementName = elementName; - } + public void setElementName(String elementName) { + this.elementName = elementName; + } - public String getElementID() { - return elementID; - } + public String getElementID() { + return elementID; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public ImageIcon getImageIcon() { - return image; - } + public ImageIcon getImageIcon() { + return image; + } - public ElementType getElementType() { - return elementType; - } + public ElementType getElementType() { + return elementType; + } - public String getInvalidUseOfRuleMessage() { - return this.INVALID_USE_MESSAGE; - } + public String getInvalidUseOfRuleMessage() { + return this.INVALID_USE_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/ElementType.java b/src/main/java/edu/rpi/legup/model/elements/ElementType.java index 1e32e6adf..dff4fe04f 100644 --- a/src/main/java/edu/rpi/legup/model/elements/ElementType.java +++ b/src/main/java/edu/rpi/legup/model/elements/ElementType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.model.elements; public enum ElementType { - PLACEABLE, - NONPLACEABLE + PLACEABLE, + NONPLACEABLE } diff --git a/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java b/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java index 94d14c4b5..4ab0ab509 100644 --- a/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java @@ -1,9 +1,9 @@ package edu.rpi.legup.model.elements; public abstract class NonPlaceableElement extends Element { - public NonPlaceableElement( - String elementID, String elementName, String description, String imageName) { - super(elementID, elementName, description, imageName); - this.elementType = ElementType.NONPLACEABLE; - } + public NonPlaceableElement( + String elementID, String elementName, String description, String imageName) { + super(elementID, elementName, description, imageName); + this.elementType = ElementType.NONPLACEABLE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java b/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java index b79fbf407..133658700 100644 --- a/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java @@ -1,9 +1,9 @@ package edu.rpi.legup.model.elements; public abstract class PlaceableElement extends Element { - public PlaceableElement( - String elementID, String elementName, String description, String imageName) { - super(elementID, elementName, description, imageName); - this.elementType = ElementType.PLACEABLE; - } + public PlaceableElement( + String elementID, String elementName, String description, String imageName) { + super(elementID, elementName, description, imageName); + this.elementType = ElementType.PLACEABLE; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/Board.java b/src/main/java/edu/rpi/legup/model/gameboard/Board.java index 453f698b4..d8bdf5199 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/Board.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/Board.java @@ -7,209 +7,209 @@ public abstract class Board { - protected List puzzleElements; - protected Set modifiedData; - protected boolean isModifiable; - - /** Board Constructor creates an empty board. */ - public Board() { - this.puzzleElements = new ArrayList<>(); - this.modifiedData = new HashSet<>(); - this.isModifiable = true; - } - - /** - * Board Constructor creates a board with null elements. - * - * @param size number of elements for the board - */ - public Board(int size) { - this(); - for (int i = 0; i < size; i++) { - puzzleElements.add(null); - } - } - - /** - * Gets a specific {@link PuzzleElement} on this board. - * - * @param puzzleElement equivalent puzzleElement - * @return equivalent puzzleElement on this board - */ - public PuzzleElement getPuzzleElement(PuzzleElement puzzleElement) { - int index = puzzleElement.getIndex(); - return index < puzzleElements.size() ? puzzleElements.get(index) : null; - } - - /** - * Sets a specific {@link PuzzleElement} on the board. - * - * @param index index of the puzzleElement - * @param puzzleElement new puzzleElement at the index - */ - public void setPuzzleElement(int index, PuzzleElement puzzleElement) { - if (index < puzzleElements.size()) { - puzzleElements.set(index, puzzleElement); - } - } - - /** - * Gets the number of elements on the board. - * - * @return number of elements on the board - */ - public int getElementCount() { - return puzzleElements.size(); - } - - /** - * Gets the {@link PuzzleElement} on the board. - * - * @return puzzle elements on the board - */ - public List getPuzzleElements() { - return puzzleElements; - } - - /** - * Sets the {@link PuzzleElement} on the board. - * - * @param puzzleElements elements on the board - */ - public void setPuzzleElements(List puzzleElements) { - this.puzzleElements = puzzleElements; - } - - /** - * Gets the modifiable attribute for the board. - * - * @return true if the board is modifiable, false otherwise - */ - public boolean isModifiable() { - return isModifiable; - } - - /** - * Sets the modifiable attribute for the board. - * - * @param isModifiable true if the board is modifiable, false otherwise - */ - public void setModifiable(boolean isModifiable) { - this.isModifiable = isModifiable; - } - - /** - * Gets whether any of {@link PuzzleElement} of this board has been modified by the user. - * - * @return true if the board has been modified, false otherwise - */ - public boolean isModified() { - return !modifiedData.isEmpty(); - } - - /** - * Gets the set of modified {@link PuzzleElement} of the board. - * - * @return set of modified puzzle element of the board - */ - public Set getModifiedData() { - return modifiedData; - } - - /** - * Adds a {@link PuzzleElement} that has been modified to the list. - * - * @param puzzleElement puzzleElement that has been modified - */ - public void addModifiedData(PuzzleElement puzzleElement) { - modifiedData.add(puzzleElement); - puzzleElement.setModified(true); - } - - /** - * Removes a {@link PuzzleElement} that is no longer modified. - * - * @param data puzzleElement that is no longer modified - */ - public void removeModifiedData(PuzzleElement data) { - modifiedData.remove(data); - data.setModified(false); - } - - /** - * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent - * puzzle element with the new data. - * - * @param puzzleElement equivalent puzzle element with the new data. - */ - @SuppressWarnings("unchecked") - public void notifyChange(PuzzleElement puzzleElement) { - puzzleElements.set(puzzleElement.getIndex(), puzzleElement); - } - - /** - * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element - * with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - public void notifyAddition(PuzzleElement puzzleElement) {} - - /** - * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle - * element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - public void notifyDeletion(PuzzleElement puzzleElement) {} - - @SuppressWarnings("unchecked") - public Board mergedBoard(Board lca, List boards) { - if (lca == null || boards.isEmpty()) { - return null; - } - - Board mergedBoard = lca.copy(); - - Board firstBoard = boards.get(0); - for (PuzzleElement lcaData : lca.getPuzzleElements()) { - PuzzleElement mData = firstBoard.getPuzzleElement(lcaData); - - boolean isSame = true; - for (Board board : boards) { - isSame &= mData.equalsData(board.getPuzzleElement(lcaData)); - } - - if (isSame && !lcaData.equalsData(mData)) { - PuzzleElement mergedData = mergedBoard.getPuzzleElement(lcaData); - mergedData.setData(mData.getData()); - mergedBoard.addModifiedData(mergedData); - } - } - - return mergedBoard; - } - - /** - * Determines if this board contains the equivalent puzzle elements as the one specified - * - * @param board board to check equivalence - * @return true if the boards are equivalent, false otherwise - */ - @SuppressWarnings("unchecked") - public boolean equalsBoard(Board board) { - for (PuzzleElement element : puzzleElements) { - if (!element.equalsData(board.getPuzzleElement(element))) { - return false; - } - } - return true; - } - - /** - * Performs a deep copy of this board. - * - * @return a new copy of the board that is independent of this one - */ - public abstract Board copy(); + protected List puzzleElements; + protected Set modifiedData; + protected boolean isModifiable; + + /** Board Constructor creates an empty board. */ + public Board() { + this.puzzleElements = new ArrayList<>(); + this.modifiedData = new HashSet<>(); + this.isModifiable = true; + } + + /** + * Board Constructor creates a board with null elements. + * + * @param size number of elements for the board + */ + public Board(int size) { + this(); + for (int i = 0; i < size; i++) { + puzzleElements.add(null); + } + } + + /** + * Gets a specific {@link PuzzleElement} on this board. + * + * @param puzzleElement equivalent puzzleElement + * @return equivalent puzzleElement on this board + */ + public PuzzleElement getPuzzleElement(PuzzleElement puzzleElement) { + int index = puzzleElement.getIndex(); + return index < puzzleElements.size() ? puzzleElements.get(index) : null; + } + + /** + * Sets a specific {@link PuzzleElement} on the board. + * + * @param index index of the puzzleElement + * @param puzzleElement new puzzleElement at the index + */ + public void setPuzzleElement(int index, PuzzleElement puzzleElement) { + if (index < puzzleElements.size()) { + puzzleElements.set(index, puzzleElement); + } + } + + /** + * Gets the number of elements on the board. + * + * @return number of elements on the board + */ + public int getElementCount() { + return puzzleElements.size(); + } + + /** + * Gets the {@link PuzzleElement} on the board. + * + * @return puzzle elements on the board + */ + public List getPuzzleElements() { + return puzzleElements; + } + + /** + * Sets the {@link PuzzleElement} on the board. + * + * @param puzzleElements elements on the board + */ + public void setPuzzleElements(List puzzleElements) { + this.puzzleElements = puzzleElements; + } + + /** + * Gets the modifiable attribute for the board. + * + * @return true if the board is modifiable, false otherwise + */ + public boolean isModifiable() { + return isModifiable; + } + + /** + * Sets the modifiable attribute for the board. + * + * @param isModifiable true if the board is modifiable, false otherwise + */ + public void setModifiable(boolean isModifiable) { + this.isModifiable = isModifiable; + } + + /** + * Gets whether any of {@link PuzzleElement} of this board has been modified by the user. + * + * @return true if the board has been modified, false otherwise + */ + public boolean isModified() { + return !modifiedData.isEmpty(); + } + + /** + * Gets the set of modified {@link PuzzleElement} of the board. + * + * @return set of modified puzzle element of the board + */ + public Set getModifiedData() { + return modifiedData; + } + + /** + * Adds a {@link PuzzleElement} that has been modified to the list. + * + * @param puzzleElement puzzleElement that has been modified + */ + public void addModifiedData(PuzzleElement puzzleElement) { + modifiedData.add(puzzleElement); + puzzleElement.setModified(true); + } + + /** + * Removes a {@link PuzzleElement} that is no longer modified. + * + * @param data puzzleElement that is no longer modified + */ + public void removeModifiedData(PuzzleElement data) { + modifiedData.remove(data); + data.setModified(false); + } + + /** + * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent + * puzzle element with the new data. + * + * @param puzzleElement equivalent puzzle element with the new data. + */ + @SuppressWarnings("unchecked") + public void notifyChange(PuzzleElement puzzleElement) { + puzzleElements.set(puzzleElement.getIndex(), puzzleElement); + } + + /** + * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + public void notifyAddition(PuzzleElement puzzleElement) {} + + /** + * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + public void notifyDeletion(PuzzleElement puzzleElement) {} + + @SuppressWarnings("unchecked") + public Board mergedBoard(Board lca, List boards) { + if (lca == null || boards.isEmpty()) { + return null; + } + + Board mergedBoard = lca.copy(); + + Board firstBoard = boards.get(0); + for (PuzzleElement lcaData : lca.getPuzzleElements()) { + PuzzleElement mData = firstBoard.getPuzzleElement(lcaData); + + boolean isSame = true; + for (Board board : boards) { + isSame &= mData.equalsData(board.getPuzzleElement(lcaData)); + } + + if (isSame && !lcaData.equalsData(mData)) { + PuzzleElement mergedData = mergedBoard.getPuzzleElement(lcaData); + mergedData.setData(mData.getData()); + mergedBoard.addModifiedData(mergedData); + } + } + + return mergedBoard; + } + + /** + * Determines if this board contains the equivalent puzzle elements as the one specified + * + * @param board board to check equivalence + * @return true if the boards are equivalent, false otherwise + */ + @SuppressWarnings("unchecked") + public boolean equalsBoard(Board board) { + for (PuzzleElement element : puzzleElements) { + if (!element.equalsData(board.getPuzzleElement(element))) { + return false; + } + } + return true; + } + + /** + * Performs a deep copy of this board. + * + * @return a new copy of the board that is independent of this one + */ + public abstract Board copy(); } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java b/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java index 93176b941..fa3625a43 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java @@ -6,49 +6,49 @@ import java.util.Set; public class CaseBoard extends Board { - protected Board baseBoard; - protected CaseRule caseRule; - protected Set pickablePuzzleElements; - - public CaseBoard(Board baseBoard, CaseRule caseRule) { - this.baseBoard = baseBoard; - this.caseRule = caseRule; - this.pickablePuzzleElements = new HashSet<>(); - } - - public void addPickableElement(PuzzleElement puzzleElement) { - pickablePuzzleElements.add(puzzleElement); - } - - public void removePickableElement(PuzzleElement puzzleElement) { - pickablePuzzleElements.remove(puzzleElement); - } - - public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { - return pickablePuzzleElements.contains(baseBoard.getPuzzleElement(puzzleElement)); - } - - public Board getBaseBoard() { - return baseBoard; - } - - public void setBaseBoard(Board baseBoard) { - this.baseBoard = baseBoard; - } - - public CaseRule getCaseRule() { - return caseRule; - } - - public void setCaseRule(CaseRule caseRule) { - this.caseRule = caseRule; - } - - public int getCount() { - return pickablePuzzleElements.size(); - } - - public CaseBoard copy() { - return null; - } + protected Board baseBoard; + protected CaseRule caseRule; + protected Set pickablePuzzleElements; + + public CaseBoard(Board baseBoard, CaseRule caseRule) { + this.baseBoard = baseBoard; + this.caseRule = caseRule; + this.pickablePuzzleElements = new HashSet<>(); + } + + public void addPickableElement(PuzzleElement puzzleElement) { + pickablePuzzleElements.add(puzzleElement); + } + + public void removePickableElement(PuzzleElement puzzleElement) { + pickablePuzzleElements.remove(puzzleElement); + } + + public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { + return pickablePuzzleElements.contains(baseBoard.getPuzzleElement(puzzleElement)); + } + + public Board getBaseBoard() { + return baseBoard; + } + + public void setBaseBoard(Board baseBoard) { + this.baseBoard = baseBoard; + } + + public CaseRule getCaseRule() { + return caseRule; + } + + public void setCaseRule(CaseRule caseRule) { + this.caseRule = caseRule; + } + + public int getCount() { + return pickablePuzzleElements.size(); + } + + public CaseBoard copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java b/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java index f0ea22dbe..bfc785bdd 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java @@ -7,24 +7,24 @@ public abstract class ElementFactory { - /** - * Creates a {@link PuzzleElement} based on the xml document Node and adds it to the board. - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException thrown if the xml node is invalid for the specific puzzle - * element - */ - public abstract PuzzleElement importCell(Node node, Board board) - throws InvalidFileFormatException; + /** + * Creates a {@link PuzzleElement} based on the xml document Node and adds it to the board. + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException thrown if the xml node is invalid for the specific puzzle + * element + */ + public abstract PuzzleElement importCell(Node node, Board board) + throws InvalidFileFormatException; - /** - * Creates a xml document {@link PuzzleElement} from a cell for exporting. - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public abstract Element exportCell(Document document, PuzzleElement puzzleElement); + /** + * Creates a xml document {@link PuzzleElement} from a cell for exporting. + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public abstract Element exportCell(Document document, PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java b/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java index 5c66250ce..9593690ce 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java @@ -8,160 +8,162 @@ public class GridBoard extends Board { - protected Dimension dimension; + protected Dimension dimension; - /** - * GridBoard Constructor creates a board for grid using puzzles from a width and height. - * - * @param width width of the board - * @param height height of the board - */ - public GridBoard(int width, int height) { - this.dimension = new Dimension(width, height); + /** + * GridBoard Constructor creates a board for grid using puzzles from a width and height. + * + * @param width width of the board + * @param height height of the board + */ + public GridBoard(int width, int height) { + this.dimension = new Dimension(width, height); - for (int i = 0; i < width * height; i++) { - puzzleElements.add(null); + for (int i = 0; i < width * height; i++) { + puzzleElements.add(null); + } } - } - - /** - * GridBoard Constructor creates a board for grid using puzzles from a size. - * - * @param size width and height of the GridBoard - */ - public GridBoard(int size) { - this(size, size); - } - /** - * Gets a {@link GridCell} from the board. - * - * @param x x location of the cell - * @param y y location of the cell - * @return grid cell at location (x, y) - */ - public GridCell getCell(int x, int y) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - System.err.printf("not in bounds, bounds are %dx%d\n", dimension.width, dimension.height); - return null; + /** + * GridBoard Constructor creates a board for grid using puzzles from a size. + * + * @param size width and height of the GridBoard + */ + public GridBoard(int size) { + this(size, size); } - return (GridCell) puzzleElements.get(y * dimension.width + x); - } - /** - * Sets the {@link GridCell} at the location (x,y). This method does not set the cell if the - * location specified is out of bounds. - * - * @param x x location of the cell - * @param y y location of the cell - * @param cell grid cell to set at location (x,y) - */ - public void setCell(int x, int y, GridCell cell) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return; + /** + * Gets a {@link GridCell} from the board. + * + * @param x x location of the cell + * @param y y location of the cell + * @return grid cell at location (x, y) + */ + public GridCell getCell(int x, int y) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + System.err.printf( + "not in bounds, bounds are %dx%d\n", dimension.width, dimension.height); + return null; + } + return (GridCell) puzzleElements.get(y * dimension.width + x); } - puzzleElements.set(y * dimension.width + x, cell); - } - public void setCell(int x, int y, Element e, MouseEvent m) { - if (this instanceof TreeTentBoard - && ((y == dimension.height && 0 <= x && x < dimension.width) - || (x == dimension.width && 0 <= y && y < dimension.height))) { - TreeTentBoard treeTentBoard = ((TreeTentBoard) this); - TreeTentClue clue = treeTentBoard.getClue(x, y); - if (y == dimension.height) { - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.height) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } - } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } else { - clue.setData(dimension.height); - } + /** + * Sets the {@link GridCell} at the location (x,y). This method does not set the cell if the + * location specified is out of bounds. + * + * @param x x location of the cell + * @param y y location of the cell + * @param cell grid cell to set at location (x,y) + */ + public void setCell(int x, int y, GridCell cell) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return; } - } else { // x == dimension.width - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.width) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } + puzzleElements.set(y * dimension.width + x, cell); + } + + public void setCell(int x, int y, Element e, MouseEvent m) { + if (this instanceof TreeTentBoard + && ((y == dimension.height && 0 <= x && x < dimension.width) + || (x == dimension.width && 0 <= y && y < dimension.height))) { + TreeTentBoard treeTentBoard = ((TreeTentBoard) this); + TreeTentClue clue = treeTentBoard.getClue(x, y); + if (y == dimension.height) { + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.height) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.height); + } + } + } else { // x == dimension.width + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.width) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.width); + } + } + } } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } else { - clue.setData(dimension.width); - } + if (e != null && y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return; + } else { + if (e != null) { + puzzleElements.get(y * dimension.width + x).setType(e, m); + } + } } - } - } else { - if (e != null && y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return; - } else { - if (e != null) { - puzzleElements.get(y * dimension.width + x).setType(e, m); - } - } + // puzzleElements.set(y * dimension.width + x, puzzleElements.get(y * dimension.width + // + + // x)); } - // puzzleElements.set(y * dimension.width + x, puzzleElements.get(y * dimension.width + - // x)); - } - /** - * Gets the width of the board. - * - * @return width of the board - */ - public int getWidth() { - return dimension.width; - } + /** + * Gets the width of the board. + * + * @return width of the board + */ + public int getWidth() { + return dimension.width; + } - /** - * Gets the height of the board. - * - * @return height of the board - */ - public int getHeight() { - return dimension.height; - } + /** + * Gets the height of the board. + * + * @return height of the board + */ + public int getHeight() { + return dimension.height; + } - /** - * Gets the dimension of the grid board - * - * @return the dimension of the grid board - */ - public Dimension getDimension() { - return dimension; - } + /** + * Gets the dimension of the grid board + * + * @return the dimension of the grid board + */ + public Dimension getDimension() { + return dimension; + } - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - public GridBoard copy() { - GridBoard newGridBoard = new GridBoard(this.dimension.width, this.dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - newGridBoard.setCell(x, y, getCell(x, y).copy()); - } + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + public GridBoard copy() { + GridBoard newGridBoard = new GridBoard(this.dimension.width, this.dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + newGridBoard.setCell(x, y, getCell(x, y).copy()); + } + } + return newGridBoard; } - return newGridBoard; - } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java b/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java index 9cc3d0768..a33c3ec80 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java @@ -3,59 +3,59 @@ import java.awt.*; public class GridCell extends PuzzleElement { - protected Point location; + protected Point location; - /** - * GridCell Constructor creates a grid cell at the specified location given as a {@link Point} - * - * @param value data value that represents the grid cell - * @param location location on the board - */ - public GridCell(T value, Point location) { - super(value); - this.location = location; - } + /** + * GridCell Constructor creates a grid cell at the specified location given as a {@link Point} + * + * @param value data value that represents the grid cell + * @param location location on the board + */ + public GridCell(T value, Point location) { + super(value); + this.location = location; + } - /** - * GridCell Constructor creates a grid cell at the specified location given as x,y pair - * - * @param value data value that represents the grid cell - * @param x x location - * @param y y location - */ - public GridCell(T value, int x, int y) { - this(value, new Point(x, y)); - } + /** + * GridCell Constructor creates a grid cell at the specified location given as x,y pair + * + * @param value data value that represents the grid cell + * @param x x location + * @param y y location + */ + public GridCell(T value, int x, int y) { + this(value, new Point(x, y)); + } - /** - * Gets the location of the grid cell on the board - * - * @return location of the grid cell - */ - public Point getLocation() { - return location; - } + /** + * Gets the location of the grid cell on the board + * + * @return location of the grid cell + */ + public Point getLocation() { + return location; + } - /** - * Sets the location of the grid cell on the board - * - * @param location location of the grid cell - */ - public void setLocation(Point location) { - this.location = location; - } + /** + * Sets the location of the grid cell on the board + * + * @param location location of the grid cell + */ + public void setLocation(Point location) { + this.location = location; + } - /** - * Performs a deep copy on the grid cell - * - * @return a new copy of the grid cell that is independent of this one - */ - public GridCell copy() { - GridCell copy = new GridCell<>(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setModified(isModified); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the grid cell + * + * @return a new copy of the grid cell that is independent of this one + */ + public GridCell copy() { + GridCell copy = new GridCell<>(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setModified(isModified); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java b/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java index 215419d54..4ce030a04 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java @@ -4,181 +4,181 @@ import java.awt.event.MouseEvent; public abstract class PuzzleElement { - protected int index; - protected T data; - protected boolean isModifiable; - protected boolean isModified; - protected boolean isGiven; - protected boolean isValid; - protected int casesDepended; - - /** PuzzleElement Constructor creates a new puzzle element. */ - public PuzzleElement() { - this.index = -1; - this.data = null; - this.isModifiable = true; - this.isModified = false; - this.isGiven = false; - this.isValid = true; - this.casesDepended = 0; - } - - /** - * PuzzleElement Constructor creates a new puzzle element from the specified data. - * - * @param data data used to create the puzzle element - */ - public PuzzleElement(T data) { - this(); - this.data = data; - } - - /** - * Gets the data that represents this puzzle element. - * - * @return data value - */ - public T getData() { - return data; - } - - /** - * Sets the data value that represents this puzzle element. - * - * @param data data value that represents this puzzle element - */ - public void setData(T data) { - this.data = data; - } - - public void setType(Element e, MouseEvent m) { - return; - } - - /** - * Gets whether this puzzle element is modifiable. - * - * @return true if this puzzle element is modifiable, false otherwise - */ - public boolean isModifiable() { - return isModifiable; - } - - /** - * Sets whether this puzzle element is modifiable. - * - * @param isModifiable true if this puzzle element is modifiable, false otherwise - */ - public void setModifiable(boolean isModifiable) { - this.isModifiable = isModifiable; - } - - /** - * Gets whether the puzzle element has been modified. - * - * @return true if the puzzle element has been modified, false otherwise - */ - public boolean isModified() { - return isModified; - } - - /** - * Sets whether the puzzle element has been modified. - * - * @param isModified true if the puzzle element has been modified, false otherwise - */ - public void setModified(boolean isModified) { - this.isModified = isModified; - } - - /** - * Gets the index of this puzzle element - * - * @return index of this puzzle element - */ - public int getIndex() { - return index; - } - - /** - * Sets the index of this puzzle element - * - * @param index index of this puzzle element - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Gets whether this puzzle element is given - * - * @return true if the puzzle element is given, false otherwise - */ - public boolean isGiven() { - return isGiven; - } - - /** - * Sets whether this puzzle element is given - * - * @param given true if the puzzle element is given, false otherwise - */ - public void setGiven(boolean given) { - isGiven = given; - } - - /** - * Get whether this puzzle element data is a valid change according to the rule applied to the - * transition that this puzzle element is contained in. - * - * @return true if the puzzle element logically follows from the rule, otherwise false. - */ - public boolean isValid() { - return this.isValid; - } - - /** - * Sets whether this puzzle element data is a valid change according to the rule applied to the - * transition that this puzzle element is contained in. - * - * @param isValid true if the puzzle element logically follows from the rule, otherwise false. - */ - public void setValid(boolean isValid) { - this.isValid = isValid; - } - - /** - * Get the number of case rules that depend upon the state of this element - * - * @return number of cases - */ - public int getCasesDepended() { - return this.casesDepended; - } - - /** - * Sets the number of case rules that depend upon the state of this element - * - * @param cases number of cases - */ - public void setCasesDepended(int cases) { - this.casesDepended = cases; - } - - /** - * Tests whether two puzzle elements objects have the same puzzle element - * - * @param puzzleElement puzzle element to check for equality - * @return true if the puzzle element are equal, false otherwise - */ - public boolean equalsData(PuzzleElement puzzleElement) { - return data.equals(puzzleElement.data); - } - - /** - * Copies this puzzle element to a new puzzle element object - * - * @return copied puzzle element object - */ - public abstract PuzzleElement copy(); + protected int index; + protected T data; + protected boolean isModifiable; + protected boolean isModified; + protected boolean isGiven; + protected boolean isValid; + protected int casesDepended; + + /** PuzzleElement Constructor creates a new puzzle element. */ + public PuzzleElement() { + this.index = -1; + this.data = null; + this.isModifiable = true; + this.isModified = false; + this.isGiven = false; + this.isValid = true; + this.casesDepended = 0; + } + + /** + * PuzzleElement Constructor creates a new puzzle element from the specified data. + * + * @param data data used to create the puzzle element + */ + public PuzzleElement(T data) { + this(); + this.data = data; + } + + /** + * Gets the data that represents this puzzle element. + * + * @return data value + */ + public T getData() { + return data; + } + + /** + * Sets the data value that represents this puzzle element. + * + * @param data data value that represents this puzzle element + */ + public void setData(T data) { + this.data = data; + } + + public void setType(Element e, MouseEvent m) { + return; + } + + /** + * Gets whether this puzzle element is modifiable. + * + * @return true if this puzzle element is modifiable, false otherwise + */ + public boolean isModifiable() { + return isModifiable; + } + + /** + * Sets whether this puzzle element is modifiable. + * + * @param isModifiable true if this puzzle element is modifiable, false otherwise + */ + public void setModifiable(boolean isModifiable) { + this.isModifiable = isModifiable; + } + + /** + * Gets whether the puzzle element has been modified. + * + * @return true if the puzzle element has been modified, false otherwise + */ + public boolean isModified() { + return isModified; + } + + /** + * Sets whether the puzzle element has been modified. + * + * @param isModified true if the puzzle element has been modified, false otherwise + */ + public void setModified(boolean isModified) { + this.isModified = isModified; + } + + /** + * Gets the index of this puzzle element + * + * @return index of this puzzle element + */ + public int getIndex() { + return index; + } + + /** + * Sets the index of this puzzle element + * + * @param index index of this puzzle element + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Gets whether this puzzle element is given + * + * @return true if the puzzle element is given, false otherwise + */ + public boolean isGiven() { + return isGiven; + } + + /** + * Sets whether this puzzle element is given + * + * @param given true if the puzzle element is given, false otherwise + */ + public void setGiven(boolean given) { + isGiven = given; + } + + /** + * Get whether this puzzle element data is a valid change according to the rule applied to the + * transition that this puzzle element is contained in. + * + * @return true if the puzzle element logically follows from the rule, otherwise false. + */ + public boolean isValid() { + return this.isValid; + } + + /** + * Sets whether this puzzle element data is a valid change according to the rule applied to the + * transition that this puzzle element is contained in. + * + * @param isValid true if the puzzle element logically follows from the rule, otherwise false. + */ + public void setValid(boolean isValid) { + this.isValid = isValid; + } + + /** + * Get the number of case rules that depend upon the state of this element + * + * @return number of cases + */ + public int getCasesDepended() { + return this.casesDepended; + } + + /** + * Sets the number of case rules that depend upon the state of this element + * + * @param cases number of cases + */ + public void setCasesDepended(int cases) { + this.casesDepended = cases; + } + + /** + * Tests whether two puzzle elements objects have the same puzzle element + * + * @param puzzleElement puzzle element to check for equality + * @return true if the puzzle element are equal, false otherwise + */ + public boolean equalsData(PuzzleElement puzzleElement) { + return data.equals(puzzleElement.data); + } + + /** + * Copies this puzzle element to a new puzzle element object + * + * @return copied puzzle element object + */ + public abstract PuzzleElement copy(); } diff --git a/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java b/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java index b5c712ead..461128562 100644 --- a/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java +++ b/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java @@ -5,24 +5,24 @@ import edu.rpi.legup.model.tree.TreeElement; public interface IBoardListener { - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - void onTreeElementChanged(TreeElement treeElement); + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + void onTreeElementChanged(TreeElement treeElement); - /** - * Called when the a case board has been added to the view. - * - * @param caseBoard case board to be added - */ - void onCaseBoardAdded(CaseBoard caseBoard); + /** + * Called when the a case board has been added to the view. + * + * @param caseBoard case board to be added + */ + void onCaseBoardAdded(CaseBoard caseBoard); - /** - * Called when a {@link PuzzleElement}'s data on the board has changed. - * - * @param puzzleElement puzzleElement that has changed - */ - void onBoardDataChanged(PuzzleElement puzzleElement); + /** + * Called when a {@link PuzzleElement}'s data on the board has changed. + * + * @param puzzleElement puzzleElement that has changed + */ + void onBoardDataChanged(PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java b/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java index 73bd2b6f8..c7bf13141 100644 --- a/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java +++ b/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface IBoardSubject { - /** - * Adds a board listener. - * - * @param listener listener to add - */ - void addBoardListener(IBoardListener listener); + /** + * Adds a board listener. + * + * @param listener listener to add + */ + void addBoardListener(IBoardListener listener); - /** - * Removes a board listener. - * - * @param listener listener to remove - */ - void removeBoardListener(IBoardListener listener); + /** + * Removes a board listener. + * + * @param listener listener to remove + */ + void removeBoardListener(IBoardListener listener); - /** - * Notifies all of the listeners using the specified algorithm. - * - * @param algorithm algorithm used to notify the listeners - */ - void notifyBoardListeners(Consumer algorithm); + /** + * Notifies all of the listeners using the specified algorithm. + * + * @param algorithm algorithm used to notify the listeners + */ + void notifyBoardListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java b/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java index 915b0adc9..d5e7fdb2d 100644 --- a/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java +++ b/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java @@ -4,27 +4,27 @@ import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; public interface ITreeListener { - /** - * Called when a {@link TreeElement} is added to the tree. - * - * @param treeElement tree element that was added to the tree - */ - void onTreeElementAdded(TreeElement treeElement); + /** + * Called when a {@link TreeElement} is added to the tree. + * + * @param treeElement tree element that was added to the tree + */ + void onTreeElementAdded(TreeElement treeElement); - /** - * Called when a {@link TreeElement} is removed from the tree. - * - * @param element TreeElement that was removed to the tree - */ - void onTreeElementRemoved(TreeElement element); + /** + * Called when a {@link TreeElement} is removed from the tree. + * + * @param element TreeElement that was removed to the tree + */ + void onTreeElementRemoved(TreeElement element); - /** - * Called when the {@link TreeViewSelection} was changed. - * - * @param selection tree view selection that was changed - */ - void onTreeSelectionChanged(TreeViewSelection selection); + /** + * Called when the {@link TreeViewSelection} was changed. + * + * @param selection tree view selection that was changed + */ + void onTreeSelectionChanged(TreeViewSelection selection); - /** Called when the model has finished updating the tree. */ - void onUpdateTree(); + /** Called when the model has finished updating the tree. */ + void onUpdateTree(); } diff --git a/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java b/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java index 7cf1bb1ef..66d5d9a5e 100644 --- a/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java +++ b/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface ITreeSubject { - /** - * Adds a board listener. - * - * @param listener listener to add - */ - void addTreeListener(ITreeListener listener); + /** + * Adds a board listener. + * + * @param listener listener to add + */ + void addTreeListener(ITreeListener listener); - /** - * Removes a tree listener. - * - * @param listener listener to remove - */ - void removeTreeListener(ITreeListener listener); + /** + * Removes a tree listener. + * + * @param listener listener to remove + */ + void removeTreeListener(ITreeListener listener); - /** - * Notifies all of the listeners using the specified algorithm. - * - * @param algorithm algorithm used to notify the listeners - */ - void notifyTreeListeners(Consumer algorithm); + /** + * Notifies all of the listeners using the specified algorithm. + * + * @param algorithm algorithm used to notify the listeners + */ + void notifyTreeListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/model/rules/CaseRule.java b/src/main/java/edu/rpi/legup/model/rules/CaseRule.java index 4fcd69065..e87896fcc 100644 --- a/src/main/java/edu/rpi/legup/model/rules/CaseRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/CaseRule.java @@ -13,135 +13,135 @@ public abstract class CaseRule extends Rule { - private final String INVALID_USE_MESSAGE; - - /** - * CaseRule Constructor creates a new case rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public CaseRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = CASE; - this.INVALID_USE_MESSAGE = "Invalid use of the case rule " + this.ruleName; - } - - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - public abstract CaseBoard getCaseBoard(Board board); - - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - public abstract List getCases(Board board, PuzzleElement puzzleElement); - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - List parentNodes = transition.getParents(); - if (parentNodes.size() != 1) { - return "Must not have multiple parent nodes"; + private final String INVALID_USE_MESSAGE; + + /** + * CaseRule Constructor creates a new case rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public CaseRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = CASE; + this.INVALID_USE_MESSAGE = "Invalid use of the case rule " + this.ruleName; } - for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { - if (childTrans.getRule() == null - || !childTrans.getRule().getClass().equals(this.getClass())) { - return "All children nodes must be justified with the same case rule."; - } - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + public abstract CaseBoard getCaseBoard(Board board); + + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + public abstract List getCases(Board board, PuzzleElement puzzleElement); + + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + List parentNodes = transition.getParents(); + if (parentNodes.size() != 1) { + return "Must not have multiple parent nodes"; + } - String check = checkRuleRaw(transition); + for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { + if (childTrans.getRule() == null + || !childTrans.getRule().getClass().equals(this.getClass())) { + return "All children nodes must be justified with the same case rule."; + } + } - // Mark transition and new data as valid or not - boolean isCorrect = (check == null); - for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { - childTrans.setCorrect(isCorrect); - for (PuzzleElement element : childTrans.getBoard().getModifiedData()) { - element.setValid(isCorrect); - } - } + String check = checkRuleRaw(transition); - return check; - } - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public abstract String checkRuleRaw(TreeTransition transition); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return this.INVALID_USE_MESSAGE; - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - List cases = getCases(board, puzzleElement); - for (Board caseBoard : cases) { - Set data = caseBoard.getModifiedData(); - for (PuzzleElement element : data) { - if (!elements.contains(board.getPuzzleElement(element))) { - elements.add(board.getPuzzleElement(element)); + // Mark transition and new data as valid or not + boolean isCorrect = (check == null); + for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { + childTrans.setCorrect(isCorrect); + for (PuzzleElement element : childTrans.getBoard().getModifiedData()) { + element.setValid(isCorrect); + } } - } + + return check; } - return elements; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public abstract String checkRuleRaw(TreeTransition transition); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return this.INVALID_USE_MESSAGE; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + List cases = getCases(board, puzzleElement); + for (Board caseBoard : cases) { + Set data = caseBoard.getModifiedData(); + for (PuzzleElement element : data) { + if (!elements.contains(board.getPuzzleElement(element))) { + elements.add(board.getPuzzleElement(element)); + } + } + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java b/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java index 8ae3f02c6..b38a95fd2 100644 --- a/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java @@ -8,102 +8,102 @@ public abstract class ContradictionRule extends Rule { - private final String NO_CONTRADICTION_MESSAGE = - "No instance of the contradiction " + this.ruleName + " here"; + private final String NO_CONTRADICTION_MESSAGE = + "No instance of the contradiction " + this.ruleName + " here"; - /** - * ContradictionRule Constructor creates a new contradiction rule - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public ContradictionRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - ruleType = CONTRADICTION; - } + /** + * ContradictionRule Constructor creates a new contradiction rule + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public ContradictionRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + ruleType = CONTRADICTION; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - return checkContradiction(transition.getBoard()); - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + return checkContradiction(transition.getBoard()); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkContradictionAt(transition.getBoard(), puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkContradictionAt(transition.getBoard(), puzzleElement); + } - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return checkContradiction(transition.getBoard()); - } + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return checkContradiction(transition.getBoard()); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkContradictionAt(transition.getBoard(), puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkContradictionAt(transition.getBoard(), puzzleElement); + } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - public String checkContradiction(Board board) { - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - String checkStr = checkContradictionAt(board, puzzleElement); - if (checkStr == null) { - return checkStr; - } + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + public String checkContradiction(Board board) { + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + String checkStr = checkContradictionAt(board, puzzleElement); + if (checkStr == null) { + return checkStr; + } + } + return this.NO_CONTRADICTION_MESSAGE; } - return this.NO_CONTRADICTION_MESSAGE; - } - public String getNoContradictionMessage() { - return this.NO_CONTRADICTION_MESSAGE; - } + public String getNoContradictionMessage() { + return this.NO_CONTRADICTION_MESSAGE; + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - public abstract String checkContradictionAt(Board board, PuzzleElement puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + public abstract String checkContradictionAt(Board board, PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java index 1ce44318a..d550bc02c 100644 --- a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java @@ -8,96 +8,97 @@ import edu.rpi.legup.model.tree.TreeTransition; public abstract class DirectRule extends Rule { - /** - * DirectRule Constructor creates a new basic rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public DirectRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = BASIC; - } + /** + * DirectRule Constructor creates a new basic rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public DirectRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = BASIC; + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRule(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - // System.out.println(finalBoard.getModifiedData().size()); - if (transition.getParents().size() != 1 - || transition.getParents().get(0).getChildren().size() != 1) { - return "State must have only 1 parent and 1 child"; - } else if (finalBoard.getModifiedData().isEmpty()) { - // null transition - return null; - } else { - return checkRuleRaw(transition); + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRule(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + // System.out.println(finalBoard.getModifiedData().size()); + if (transition.getParents().size() != 1 + || transition.getParents().get(0).getChildren().size() != 1) { + return "State must have only 1 parent and 1 child"; + } else if (finalBoard.getModifiedData().isEmpty()) { + // null transition + return null; + } else { + return checkRuleRaw(transition); + } } - } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRuleRaw(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - String checkStr = null; + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRuleRaw(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + String checkStr = null; - // Go directly to specific direct rule's judgement if no cell's are edited - if (finalBoard.getModifiedData().size() == 0) { - checkStr = checkRuleRawAt(transition, null); - } - for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { - String tempStr = checkRuleAt(transition, puzzleElement); - if (tempStr != null) { - checkStr = tempStr; - } + // Go directly to specific direct rule's judgement if no cell's are edited + if (finalBoard.getModifiedData().size() == 0) { + checkStr = checkRuleRawAt(transition, null); + } + for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { + String tempStr = checkRuleAt(transition, puzzleElement); + if (tempStr != null) { + checkStr = tempStr; + } + } + return checkStr; } - return checkStr; - } - /** - * Checks whether the child node logically follows from the parent node at the specific {@link - * PuzzleElement} using this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - Board finalBoard = transition.getBoard(); - puzzleElement = finalBoard.getPuzzleElement(puzzleElement); - String checkStr; - if (!puzzleElement.isModified()) { - checkStr = "PuzzleElement must be modified"; - } else { - if (transition.getParents().size() != 1 - || transition.getParents().get(0).getChildren().size() != 1) { - checkStr = "State must have only 1 parent and 1 child"; - } else { - checkStr = checkRuleRawAt(transition, puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific {@link + * PuzzleElement} using this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + Board finalBoard = transition.getBoard(); + puzzleElement = finalBoard.getPuzzleElement(puzzleElement); + String checkStr; + if (!puzzleElement.isModified()) { + checkStr = "PuzzleElement must be modified"; + } else { + if (transition.getParents().size() != 1 + || transition.getParents().get(0).getChildren().size() != 1) { + checkStr = "State must have only 1 parent and 1 child"; + } else { + checkStr = checkRuleRawAt(transition, puzzleElement); + } + } + puzzleElement.setValid(checkStr == null); + return checkStr; } - puzzleElement.setValid(checkStr == null); - return checkStr; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - public abstract Board getDefaultBoard(TreeNode node); + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + public abstract Board getDefaultBoard(TreeNode node); } diff --git a/src/main/java/edu/rpi/legup/model/rules/MergeRule.java b/src/main/java/edu/rpi/legup/model/rules/MergeRule.java index 25c543abb..f7badcd8b 100644 --- a/src/main/java/edu/rpi/legup/model/rules/MergeRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/MergeRule.java @@ -11,88 +11,88 @@ import java.util.List; public class MergeRule extends Rule { - /** MergeRule Constructor merges to board states together */ - public MergeRule() { - super( - "MERGE", - "Merge Rule", - "Merge any number of nodes into one", - "edu/rpi/legup/images/Legup/MergeRule.png"); - this.ruleType = MERGE; - } - - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @SuppressWarnings("unchecked") - @Override - public String checkRuleRaw(TreeTransition transition) { - Board board = transition.getBoard(); - List mergingNodes = new ArrayList<>(); - List mergingBoards = new ArrayList<>(); - for (TreeNode treeNode : transition.getParents()) { - mergingNodes.add(treeNode); - mergingBoards.add(treeNode.getBoard()); + /** MergeRule Constructor merges to board states together */ + public MergeRule() { + super( + "MERGE", + "Merge Rule", + "Merge any number of nodes into one", + "edu/rpi/legup/images/Legup/MergeRule.png"); + this.ruleType = MERGE; } - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - return "Merge was not correctly created."; - } - Board lcaBoard = lca.getBoard(); + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @SuppressWarnings("unchecked") + @Override + public String checkRuleRaw(TreeTransition transition) { + Board board = transition.getBoard(); + List mergingNodes = new ArrayList<>(); + List mergingBoards = new ArrayList<>(); + for (TreeNode treeNode : transition.getParents()) { + mergingNodes.add(treeNode); + mergingBoards.add(treeNode.getBoard()); + } - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + return "Merge was not correctly created."; + } + Board lcaBoard = lca.getBoard(); - for (PuzzleElement m : mergedBoard.getPuzzleElements()) { - if (!m.equalsData(board.getPuzzleElement(m))) { - return "Merge was not correctly created."; - } - } + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + for (PuzzleElement m : mergedBoard.getPuzzleElements()) { + if (!m.equalsData(board.getPuzzleElement(m))) { + return "Merge was not correctly created."; + } + } - return null; - } + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRule(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRule(transition); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - return checkRuleRaw(transition); - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + return checkRuleRaw(transition); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRawAt(transition, puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRawAt(transition, puzzleElement); + } } diff --git a/src/main/java/edu/rpi/legup/model/rules/Rule.java b/src/main/java/edu/rpi/legup/model/rules/Rule.java index d15b79e5e..f70bb2889 100644 --- a/src/main/java/edu/rpi/legup/model/rules/Rule.java +++ b/src/main/java/edu/rpi/legup/model/rules/Rule.java @@ -10,154 +10,156 @@ @RegisterRule public abstract class Rule { - protected String ruleID; - protected String ruleName; - protected String description; - protected String imageName; - protected ImageIcon image; - protected RuleType ruleType; - - private final String INVALID_USE_MESSAGE; - - /** - * Rule Constructor creates a new rule - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public Rule(String ruleID, String ruleName, String description, String imageName) { - this.ruleID = ruleID; - this.ruleName = ruleName; - this.description = description; - this.imageName = imageName; - this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.ruleName; - loadImage(); - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public abstract String checkRule(TreeTransition transition); - - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - protected abstract String checkRuleRaw(TreeTransition transition); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public abstract String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - protected abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** Loads the image file */ - public void loadImage() { - if (imageName != null) { - String name = imageName; - LegupPreferences prefs = LegupPreferences.getInstance(); - if (name.contains("shorttruthtable") - && prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - name = name.replace("ruleimages", "ruleimages_cb"); - } - this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(name)); - // Resize images to be 100px wide - Image image = this.image.getImage(); - if (this.image.getIconWidth() < 120) return; - int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); - if (height == 0) { - System.out.println("height is 0 error"); - System.out.println("height: " + this.image.getIconHeight()); - System.out.println("width: " + this.image.getIconWidth()); - return; - } - BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = bimage.createGraphics(); - g.drawImage(image, 0, 0, 100, height, null); - this.image = new ImageIcon(bimage); + protected String ruleID; + protected String ruleName; + protected String description; + protected String imageName; + protected ImageIcon image; + protected RuleType ruleType; + + private final String INVALID_USE_MESSAGE; + + /** + * Rule Constructor creates a new rule + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public Rule(String ruleID, String ruleName, String description, String imageName) { + this.ruleID = ruleID; + this.ruleName = ruleName; + this.description = description; + this.imageName = imageName; + this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.ruleName; + loadImage(); + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public abstract String checkRule(TreeTransition transition); + + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + protected abstract String checkRuleRaw(TreeTransition transition); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public abstract String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + protected abstract String checkRuleRawAt( + TreeTransition transition, PuzzleElement puzzleElement); + + /** Loads the image file */ + public void loadImage() { + if (imageName != null) { + String name = imageName; + LegupPreferences prefs = LegupPreferences.getInstance(); + if (name.contains("shorttruthtable") + && prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + name = name.replace("ruleimages", "ruleimages_cb"); + } + this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(name)); + // Resize images to be 100px wide + Image image = this.image.getImage(); + if (this.image.getIconWidth() < 120) return; + int height = + (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); + if (height == 0) { + System.out.println("height is 0 error"); + System.out.println("height: " + this.image.getIconHeight()); + System.out.println("width: " + this.image.getIconWidth()); + return; + } + BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = bimage.createGraphics(); + g.drawImage(image, 0, 0, 100, height, null); + this.image = new ImageIcon(bimage); + } + } + + /** + * Gets the name of the rule + * + * @return name of the rule + */ + public String getRuleName() { + return ruleName; + } + + /** + * Gets the name of the rule + * + * @return name of the rule + */ + public String getRuleID() { + return ruleID; + } + + /** + * Sets the rule name + * + * @param ruleName new name of the rule + */ + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + + /** + * Gets the description of the rule + * + * @return the description of the rule + */ + public String getDescription() { + return description; + } + + /** + * Gets the image icon of the rule + * + * @return image icon of the rule + */ + public ImageIcon getImageIcon() { + return image; + } + + /** + * Gets the rule type + * + * @return rule type + */ + public RuleType getRuleType() { + return ruleType; + } + + public String getInvalidUseOfRuleMessage() { + return this.INVALID_USE_MESSAGE; } - } - - /** - * Gets the name of the rule - * - * @return name of the rule - */ - public String getRuleName() { - return ruleName; - } - - /** - * Gets the name of the rule - * - * @return name of the rule - */ - public String getRuleID() { - return ruleID; - } - - /** - * Sets the rule name - * - * @param ruleName new name of the rule - */ - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - - /** - * Gets the description of the rule - * - * @return the description of the rule - */ - public String getDescription() { - return description; - } - - /** - * Gets the image icon of the rule - * - * @return image icon of the rule - */ - public ImageIcon getImageIcon() { - return image; - } - - /** - * Gets the rule type - * - * @return rule type - */ - public RuleType getRuleType() { - return ruleType; - } - - public String getInvalidUseOfRuleMessage() { - return this.INVALID_USE_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/model/rules/RuleType.java b/src/main/java/edu/rpi/legup/model/rules/RuleType.java index 48589e836..06aa1844b 100644 --- a/src/main/java/edu/rpi/legup/model/rules/RuleType.java +++ b/src/main/java/edu/rpi/legup/model/rules/RuleType.java @@ -1,8 +1,8 @@ package edu.rpi.legup.model.rules; public enum RuleType { - BASIC, - CASE, - CONTRADICTION, - MERGE + BASIC, + CASE, + CONTRADICTION, + MERGE } diff --git a/src/main/java/edu/rpi/legup/model/tree/Tree.java b/src/main/java/edu/rpi/legup/model/tree/Tree.java index 2e5604a2c..a0746db87 100644 --- a/src/main/java/edu/rpi/legup/model/tree/Tree.java +++ b/src/main/java/edu/rpi/legup/model/tree/Tree.java @@ -7,185 +7,186 @@ import java.util.Set; public class Tree { - private TreeNode rootNode; - - /** - * Tree Constructor creates the tree structure from the initial {@link Board} - * - * @param initBoard initial board - */ - public Tree(Board initBoard) { - this.rootNode = new TreeNode(initBoard); - this.rootNode.setRoot(true); - } - - /** Tree Constructor creates the tree structure with null root node */ - public Tree() { - this.rootNode = null; - } - - public TreeTransition addNewTransition(TreeNode treeNode) { - TreeTransition transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - treeNode.addChild(transition); - treeNode.getChildren().forEach(TreeTransition::reverify); - return transition; - } - - public TreeNode addNode(TreeTransition transition) { - TreeNode treeNode = new TreeNode(transition.getBoard().copy()); - transition.setChildNode(treeNode); - treeNode.setParent(transition); - return treeNode; - } - - public TreeElement addTreeElement(TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) element; - return addTreeElement(treeNode, new TreeTransition(treeNode, treeNode.getBoard().copy())); - } else { - TreeTransition transition = (TreeTransition) element; - Board copyBoard = transition.board.copy(); - copyBoard.setModifiable(false); - return addTreeElement(transition, new TreeNode(copyBoard)); + private TreeNode rootNode; + + /** + * Tree Constructor creates the tree structure from the initial {@link Board} + * + * @param initBoard initial board + */ + public Tree(Board initBoard) { + this.rootNode = new TreeNode(initBoard); + this.rootNode.setRoot(true); } - } - - public TreeElement addTreeElement(TreeNode treeNode, TreeTransition transition) { - treeNode.addChild(transition); - treeNode.getChildren().forEach(TreeTransition::reverify); - return transition; - } - - public TreeElement addTreeElement(TreeTransition transition, TreeNode treeNode) { - transition.setChildNode(treeNode); - treeNode.setParent(transition); - return treeNode; - } - - public void removeTreeElement(TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getParent().setChildNode(null); - } else { - TreeTransition transition = (TreeTransition) element; - transition.getParents().forEach(n -> n.removeChild(transition)); - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + + /** Tree Constructor creates the tree structure with null root node */ + public Tree() { + this.rootNode = null; + } + + public TreeTransition addNewTransition(TreeNode treeNode) { + TreeTransition transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + treeNode.addChild(transition); + treeNode.getChildren().forEach(TreeTransition::reverify); + return transition; + } + + public TreeNode addNode(TreeTransition transition) { + TreeNode treeNode = new TreeNode(transition.getBoard().copy()); + transition.setChildNode(treeNode); + treeNode.setParent(transition); + return treeNode; + } + + public TreeElement addTreeElement(TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) element; + return addTreeElement( + treeNode, new TreeTransition(treeNode, treeNode.getBoard().copy())); + } else { + TreeTransition transition = (TreeTransition) element; + Board copyBoard = transition.board.copy(); + copyBoard.setModifiable(false); + return addTreeElement(transition, new TreeNode(copyBoard)); + } + } + + public TreeElement addTreeElement(TreeNode treeNode, TreeTransition transition) { + treeNode.addChild(transition); + treeNode.getChildren().forEach(TreeTransition::reverify); + return transition; } - } - - /** - * Determines if the tree is valid by checking whether this tree puzzleElement and all descendants - * of this tree puzzleElement is justified and justified correctly - * - * @return true if tree is valid, false otherwise - */ - public boolean isValid() { - return rootNode.isValidBranch(); - } - - /** - * Gets a Set of TreeNodes that are leaf nodes - * - * @return Set of TreeNodes that are leaf nodes - */ - public Set getLeafTreeElements() { - Set leafs = new HashSet<>(); - getLeafTreeElements(leafs, rootNode); - return leafs; - } - - /** - * Gets a Set of TreeNodes that are leaf nodes from the sub tree rooted at the specified node - * - * @param node node that is input - * @return Set of TreeNodes that are leaf nodes from the sub tree - */ - public Set getLeafTreeElements(TreeNode node) { - Set leafs = new HashSet<>(); - getLeafTreeElements(leafs, node); - return leafs; - } - - /** - * Recursively gets a Set of TreeNodes that are leaf nodes - * - * @param leafs Set of TreeNodes that are leaf nodes - * @param element current TreeNode being evaluated - */ - private void getLeafTreeElements(Set leafs, TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - List childTrans = node.getChildren(); - if (childTrans.isEmpty()) { - leafs.add(node); - } else { - childTrans.forEach(t -> getLeafTreeElements(leafs, t)); - } - } else { - TreeTransition transition = (TreeTransition) element; - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - leafs.add(transition); - } else { - getLeafTreeElements(leafs, childNode); - } + + public TreeElement addTreeElement(TreeTransition transition, TreeNode treeNode) { + transition.setChildNode(treeNode); + treeNode.setParent(transition); + return treeNode; } - } - - /** - * Gets the lowest common ancestor (LCA) among the list of {@link TreeNode} passed into the - * function. This lowest common ancestor is the most immediate ancestor node such that the list of - * tree nodes specified are descendants of the node. This will return null if no such ancestor - * exists - * - * @param nodes list of tree nodes to find the LCA - * @return the first ancestor node that all tree nodes have in common, otherwise null if none - * exists - */ - public static TreeNode getLowestCommonAncestor(List nodes) { - if (nodes.isEmpty()) { - return null; - } else { - if (nodes.size() == 1) { - return nodes.get(0); - } else { - List> ancestors = new ArrayList<>(); - for (TreeNode node : nodes) { - ancestors.add(node.getAncestors()); + + public void removeTreeElement(TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getParent().setChildNode(null); + } else { + TreeTransition transition = (TreeTransition) element; + transition.getParents().forEach(n -> n.removeChild(transition)); + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); } + } + + /** + * Determines if the tree is valid by checking whether this tree puzzleElement and all + * descendants of this tree puzzleElement is justified and justified correctly + * + * @return true if tree is valid, false otherwise + */ + public boolean isValid() { + return rootNode.isValidBranch(); + } - List first = ancestors.get(0); + /** + * Gets a Set of TreeNodes that are leaf nodes + * + * @return Set of TreeNodes that are leaf nodes + */ + public Set getLeafTreeElements() { + Set leafs = new HashSet<>(); + getLeafTreeElements(leafs, rootNode); + return leafs; + } + + /** + * Gets a Set of TreeNodes that are leaf nodes from the sub tree rooted at the specified node + * + * @param node node that is input + * @return Set of TreeNodes that are leaf nodes from the sub tree + */ + public Set getLeafTreeElements(TreeNode node) { + Set leafs = new HashSet<>(); + getLeafTreeElements(leafs, node); + return leafs; + } - for (TreeNode node : first) { - boolean isCommon = true; - for (List nList : ancestors) { - isCommon &= nList.contains(node); - } + /** + * Recursively gets a Set of TreeNodes that are leaf nodes + * + * @param leafs Set of TreeNodes that are leaf nodes + * @param element current TreeNode being evaluated + */ + private void getLeafTreeElements(Set leafs, TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + List childTrans = node.getChildren(); + if (childTrans.isEmpty()) { + leafs.add(node); + } else { + childTrans.forEach(t -> getLeafTreeElements(leafs, t)); + } + } else { + TreeTransition transition = (TreeTransition) element; + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + leafs.add(transition); + } else { + getLeafTreeElements(leafs, childNode); + } + } + } - if (isCommon) { - return node; - } + /** + * Gets the lowest common ancestor (LCA) among the list of {@link TreeNode} passed into the + * function. This lowest common ancestor is the most immediate ancestor node such that the list + * of tree nodes specified are descendants of the node. This will return null if no such + * ancestor exists + * + * @param nodes list of tree nodes to find the LCA + * @return the first ancestor node that all tree nodes have in common, otherwise null if none + * exists + */ + public static TreeNode getLowestCommonAncestor(List nodes) { + if (nodes.isEmpty()) { + return null; + } else { + if (nodes.size() == 1) { + return nodes.get(0); + } else { + List> ancestors = new ArrayList<>(); + for (TreeNode node : nodes) { + ancestors.add(node.getAncestors()); + } + + List first = ancestors.get(0); + + for (TreeNode node : first) { + boolean isCommon = true; + for (List nList : ancestors) { + isCommon &= nList.contains(node); + } + + if (isCommon) { + return node; + } + } + } } - } + return null; + } + + /** + * Gets the root node of this tree + * + * @return the root node of the tree + */ + public TreeNode getRootNode() { + return rootNode; + } + + /** + * Sets the root node of this tree + * + * @param rootNode the root node of the tree + */ + public void setRootNode(TreeNode rootNode) { + this.rootNode = rootNode; } - return null; - } - - /** - * Gets the root node of this tree - * - * @return the root node of the tree - */ - public TreeNode getRootNode() { - return rootNode; - } - - /** - * Sets the root node of this tree - * - * @param rootNode the root node of the tree - */ - public void setRootNode(TreeNode rootNode) { - this.rootNode = rootNode; - } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeElement.java b/src/main/java/edu/rpi/legup/model/tree/TreeElement.java index d7f21c3b7..59f75acf3 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeElement.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeElement.java @@ -3,61 +3,61 @@ import edu.rpi.legup.model.gameboard.Board; public abstract class TreeElement { - protected TreeElementType type; - protected Board board; - - /** - * TreeElement Constructor creates a tree puzzleElement that is part of a tree - * - * @param type type of tree puzzleElement (NODE or TRANSITION) - */ - public TreeElement(TreeElementType type) { - this.type = type; - } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must lead - * to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - public abstract boolean isContradictoryBranch(); - - /** - * Recursively determines if the sub-tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and - * justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - public abstract boolean isValidBranch(); - - /** - * Gets the type of tree puzzleElement - * - * @return NODE if this tree puzzleElement is a tree node, TRANSITION, if this tree puzzleElement - * is a transition - */ - public TreeElementType getType() { - return type; - } - - /** - * Gets the board at this TreeElement - * - * @return the board at this TreeElement - */ - public Board getBoard() { - return board; - } - - /** - * Sets the board at this TreeElement - * - * @param board the board at this TreeElement - */ - public void setBoard(Board board) { - this.board = board; - } + protected TreeElementType type; + protected Board board; + + /** + * TreeElement Constructor creates a tree puzzleElement that is part of a tree + * + * @param type type of tree puzzleElement (NODE or TRANSITION) + */ + public TreeElement(TreeElementType type) { + this.type = type; + } + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must + * lead to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + public abstract boolean isContradictoryBranch(); + + /** + * Recursively determines if the sub-tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified + * and justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + public abstract boolean isValidBranch(); + + /** + * Gets the type of tree puzzleElement + * + * @return NODE if this tree puzzleElement is a tree node, TRANSITION, if this tree + * puzzleElement is a transition + */ + public TreeElementType getType() { + return type; + } + + /** + * Gets the board at this TreeElement + * + * @return the board at this TreeElement + */ + public Board getBoard() { + return board; + } + + /** + * Sets the board at this TreeElement + * + * @param board the board at this TreeElement + */ + public void setBoard(Board board) { + this.board = board; + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java b/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java index 42eeb6c34..67437a535 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.model.tree; public enum TreeElementType { - NODE, - TRANSITION + NODE, + TRANSITION } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeNode.java b/src/main/java/edu/rpi/legup/model/tree/TreeNode.java index 4d1652a3c..a2ac7cb21 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeNode.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeNode.java @@ -5,328 +5,328 @@ import java.util.*; public class TreeNode extends TreeElement { - private TreeTransition parent; - private List children; - private boolean isRoot; - - /** - * TreeNode Constructor creates a tree node whenever a rule has been made - * - * @param board board associated with this tree node - */ - public TreeNode(Board board) { - super(TreeElementType.NODE); - this.board = board; - this.parent = null; - this.children = new ArrayList<>(); - this.isRoot = false; - } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must lead - * to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - @Override - public boolean isContradictoryBranch() { - boolean leadsToContra = true; - for (TreeTransition child : children) { - leadsToContra &= child.isContradictoryBranch(); + private TreeTransition parent; + private List children; + private boolean isRoot; + + /** + * TreeNode Constructor creates a tree node whenever a rule has been made + * + * @param board board associated with this tree node + */ + public TreeNode(Board board) { + super(TreeElementType.NODE); + this.board = board; + this.parent = null; + this.children = new ArrayList<>(); + this.isRoot = false; } - return leadsToContra && !children.isEmpty(); - } - - /** - * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and - * justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - @Override - public boolean isValidBranch() { - for (TreeTransition transition : children) { - if (!transition.isValidBranch()) { - return false; - } - } - return true; - } - - /** - * Gets all of the ancestors of this node - * - * @return list of all of the ancestors for this node - */ - public List getAncestors() { - List ancestors = new ArrayList<>(); - Queue it = new LinkedList<>(); - it.add(this); - - while (!it.isEmpty()) { - TreeNode next = it.poll(); - if (next.getParent() != null) { - for (TreeNode treeNode : next.getParent().getParents()) { - if (!it.contains(treeNode)) { - it.add(treeNode); - } - } - } - if (!ancestors.contains(next)) { - ancestors.add(next); - } + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must + * lead to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + @Override + public boolean isContradictoryBranch() { + boolean leadsToContra = true; + for (TreeTransition child : children) { + leadsToContra &= child.isContradictoryBranch(); + } + return leadsToContra && !children.isEmpty(); } - return ancestors; - } - - /** - * Gets a list of the descendants of this node - * - * @return list of all the descendants for this node - */ - public List getDescendants() { - List descendants = new ArrayList<>(); - Queue it = new LinkedList<>(); - it.add(this); - - while (!it.isEmpty()) { - TreeElement next = it.poll(); - - if (next.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) next; - for (TreeTransition transition : node.getChildren()) { - if (!descendants.contains(transition)) { - descendants.add(transition); - it.add(transition); - } + + /** + * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified + * and justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + @Override + public boolean isValidBranch() { + for (TreeTransition transition : children) { + if (!transition.isValidBranch()) { + return false; + } } - } else { - TreeTransition trans = (TreeTransition) next; - TreeNode childNode = trans.getChildNode(); - if (childNode != null && !descendants.contains(childNode)) { - descendants.add(childNode); - it.add(childNode); + return true; + } + + /** + * Gets all of the ancestors of this node + * + * @return list of all of the ancestors for this node + */ + public List getAncestors() { + List ancestors = new ArrayList<>(); + Queue it = new LinkedList<>(); + it.add(this); + + while (!it.isEmpty()) { + TreeNode next = it.poll(); + if (next.getParent() != null) { + for (TreeNode treeNode : next.getParent().getParents()) { + if (!it.contains(treeNode)) { + it.add(treeNode); + } + } + } + + if (!ancestors.contains(next)) { + ancestors.add(next); + } } - } + return ancestors; } - return descendants; - } - - /** - * Gets a DisjointSets containing the children of this node such that the sets contained within - * the DisjointSets are such that elements in the same set are branches of this tree node that - * will eventually merge. This could mean that multiple merges take place before this happens. - * - * @return DisjointSets of tree transitions containing unique non-merging branches - */ - public DisjointSets findMergingBranches() { - DisjointSets branches = new DisjointSets<>(); - children.forEach(branches::createSet); - - for (TreeTransition tran : children) { - branches.createSet(tran); - - TreeNode child = tran.getChildNode(); - if (child != null) { - List nodes = new ArrayList<>(); - nodes.add(child); - while (!nodes.isEmpty()) { - TreeElement element = nodes.get(0); - branches.createSet(element); - branches.union(tran, element); - - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - nodes.addAll(node.getChildren()); - } else { - TreeTransition childTran = (TreeTransition) element; - if (childTran.getChildNode() != null) { - nodes.add(childTran.getChildNode()); + + /** + * Gets a list of the descendants of this node + * + * @return list of all the descendants for this node + */ + public List getDescendants() { + List descendants = new ArrayList<>(); + Queue it = new LinkedList<>(); + it.add(this); + + while (!it.isEmpty()) { + TreeElement next = it.poll(); + + if (next.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) next; + for (TreeTransition transition : node.getChildren()) { + if (!descendants.contains(transition)) { + descendants.add(transition); + it.add(transition); + } + } + } else { + TreeTransition trans = (TreeTransition) next; + TreeNode childNode = trans.getChildNode(); + if (childNode != null && !descendants.contains(childNode)) { + descendants.add(childNode); + it.add(childNode); + } } - } - nodes.remove(element); } - } + return descendants; } - DisjointSets mergingBranches = new DisjointSets<>(); - children.forEach(mergingBranches::createSet); + /** + * Gets a DisjointSets containing the children of this node such that the sets contained within + * the DisjointSets are such that elements in the same set are branches of this tree node that + * will eventually merge. This could mean that multiple merges take place before this happens. + * + * @return DisjointSets of tree transitions containing unique non-merging branches + */ + public DisjointSets findMergingBranches() { + DisjointSets branches = new DisjointSets<>(); + children.forEach(branches::createSet); + + for (TreeTransition tran : children) { + branches.createSet(tran); + + TreeNode child = tran.getChildNode(); + if (child != null) { + List nodes = new ArrayList<>(); + nodes.add(child); + while (!nodes.isEmpty()) { + TreeElement element = nodes.get(0); + branches.createSet(element); + branches.union(tran, element); + + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + nodes.addAll(node.getChildren()); + } else { + TreeTransition childTran = (TreeTransition) element; + if (childTran.getChildNode() != null) { + nodes.add(childTran.getChildNode()); + } + } + nodes.remove(element); + } + } + } + + DisjointSets mergingBranches = new DisjointSets<>(); + children.forEach(mergingBranches::createSet); - for (TreeTransition tran : children) { - for (TreeTransition tran1 : children) { - if (branches.find(tran) == branches.find(tran1)) { - mergingBranches.union(tran, tran1); + for (TreeTransition tran : children) { + for (TreeTransition tran1 : children) { + if (branches.find(tran) == branches.find(tran1)) { + mergingBranches.union(tran, tran1); + } + } } - } + return mergingBranches; } - return mergingBranches; - } - - /** - * Finds the point at which the set of tree elements passed in will merge. This must be a set - * gotten from findMergingBranches method DisjointSets - * - * @param branches tree elements to find the merging point - * @return tree transition of the merging point or null if no such point exists - */ - @SuppressWarnings("unchecked") - public static TreeTransition findMergingPoint(Set branches) { - DisjointSets mergeSet = new DisjointSets<>(); - Set branchesCopy = new HashSet<>(branches); - TreeElement headBranch = branchesCopy.iterator().next(); - branchesCopy.remove(headBranch); - - for (TreeElement element : branchesCopy) { - mergeSet.createSet(element); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getDescendants() - .forEach( - (TreeElement e) -> { - if (!mergeSet.contains(e)) { - mergeSet.createSet(e); - } - mergeSet.union(element, e); - }); - } else { - TreeTransition transition = (TreeTransition) element; - TreeNode childNode = transition.getChildNode(); - if (childNode != null) { - List des = childNode.getDescendants(); - for (TreeElement e : des) { - if (!mergeSet.contains(e)) { - mergeSet.createSet(e); + + /** + * Finds the point at which the set of tree elements passed in will merge. This must be a set + * gotten from findMergingBranches method DisjointSets + * + * @param branches tree elements to find the merging point + * @return tree transition of the merging point or null if no such point exists + */ + @SuppressWarnings("unchecked") + public static TreeTransition findMergingPoint(Set branches) { + DisjointSets mergeSet = new DisjointSets<>(); + Set branchesCopy = new HashSet<>(branches); + TreeElement headBranch = branchesCopy.iterator().next(); + branchesCopy.remove(headBranch); + + for (TreeElement element : branchesCopy) { + mergeSet.createSet(element); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getDescendants() + .forEach( + (TreeElement e) -> { + if (!mergeSet.contains(e)) { + mergeSet.createSet(e); + } + mergeSet.union(element, e); + }); + } else { + TreeTransition transition = (TreeTransition) element; + TreeNode childNode = transition.getChildNode(); + if (childNode != null) { + List des = childNode.getDescendants(); + for (TreeElement e : des) { + if (!mergeSet.contains(e)) { + mergeSet.createSet(e); + } + mergeSet.union(element, e); + } + } } - mergeSet.union(element, e); - } } - } - } - Queue next = new LinkedList<>(); - next.add(headBranch); + Queue next = new LinkedList<>(); + next.add(headBranch); - while (!next.isEmpty()) { - TreeElement element = next.poll(); - if (!mergeSet.contains(element)) { - mergeSet.createSet(element); - } - mergeSet.union(headBranch, element); + while (!next.isEmpty()) { + TreeElement element = next.poll(); + if (!mergeSet.contains(element)) { + mergeSet.createSet(element); + } + mergeSet.union(headBranch, element); + + if (mergeSet.setCount() == 1) { + if (element.getType() == TreeElementType.TRANSITION) { + return (TreeTransition) element; + } + return null; + } - if (mergeSet.setCount() == 1) { - if (element.getType() == TreeElementType.TRANSITION) { - return (TreeTransition) element; + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + next.addAll(node.getChildren()); + } else { + TreeTransition tran = (TreeTransition) element; + next.add(tran.getChildNode()); + } } return null; - } - - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - next.addAll(node.getChildren()); - } else { - TreeTransition tran = (TreeTransition) element; - next.add(tran.getChildNode()); - } } - return null; - } - - /** - * Determines if the specified tree transition is a parent of this node - * - * @param parent tree transition that could be a parent - * @return true if the specified tree transition is a parent of this node, false otherwise - */ - public boolean isParent(TreeTransition parent) { - return this.parent == parent; - } - - /** - * Adds a child to this tree node - * - * @param child child to add - */ - public void addChild(TreeTransition child) { - children.add(child); - } - - /** - * Removes a child to this tree node - * - * @param child child to remove - */ - public void removeChild(TreeTransition child) { - children.remove(child); - } - - /** - * Determines if the specified tree node is a child of this node - * - * @param child tree node that could be a child - * @return true if the specified tree node is a child of this node, false otherwise - */ - public boolean isChild(TreeNode child) { - return children.contains(child); - } - - /** - * Gets the TreeNode's parent - * - * @return the TreeNode's parent - */ - public TreeTransition getParent() { - return parent; - } - - /** - * Sets the TreeNode's parent - * - * @param parent the TreeNode's parent - */ - public void setParent(TreeTransition parent) { - this.parent = parent; - } - - /** - * Gets the TreeNode's children - * - * @return the TreeNode's children - */ - public List getChildren() { - return children; - } - - /** - * Sets the TreeNode's children - * - * @param children the TreeNode's children - */ - public void setChildren(List children) { - this.children = children; - } - - /** - * Is this node the root of the tree - * - * @return true if this node is the root of the tree, false otherwise - */ - public boolean isRoot() { - return isRoot; - } - - /** - * Sets the root of the tree - * - * @param isRoot true if this node is the root of the tree, false otherwise - */ - public void setRoot(boolean isRoot) { - this.isRoot = isRoot; - } - - public void clearChildren() { - this.children.clear(); - } + + /** + * Determines if the specified tree transition is a parent of this node + * + * @param parent tree transition that could be a parent + * @return true if the specified tree transition is a parent of this node, false otherwise + */ + public boolean isParent(TreeTransition parent) { + return this.parent == parent; + } + + /** + * Adds a child to this tree node + * + * @param child child to add + */ + public void addChild(TreeTransition child) { + children.add(child); + } + + /** + * Removes a child to this tree node + * + * @param child child to remove + */ + public void removeChild(TreeTransition child) { + children.remove(child); + } + + /** + * Determines if the specified tree node is a child of this node + * + * @param child tree node that could be a child + * @return true if the specified tree node is a child of this node, false otherwise + */ + public boolean isChild(TreeNode child) { + return children.contains(child); + } + + /** + * Gets the TreeNode's parent + * + * @return the TreeNode's parent + */ + public TreeTransition getParent() { + return parent; + } + + /** + * Sets the TreeNode's parent + * + * @param parent the TreeNode's parent + */ + public void setParent(TreeTransition parent) { + this.parent = parent; + } + + /** + * Gets the TreeNode's children + * + * @return the TreeNode's children + */ + public List getChildren() { + return children; + } + + /** + * Sets the TreeNode's children + * + * @param children the TreeNode's children + */ + public void setChildren(List children) { + this.children = children; + } + + /** + * Is this node the root of the tree + * + * @return true if this node is the root of the tree, false otherwise + */ + public boolean isRoot() { + return isRoot; + } + + /** + * Sets the root of the tree + * + * @param isRoot true if this node is the root of the tree, false otherwise + */ + public void setRoot(boolean isRoot) { + this.isRoot = isRoot; + } + + public void clearChildren() { + this.children.clear(); + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java b/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java index e20ba8b6a..e79cd4b96 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java @@ -9,413 +9,412 @@ import java.util.List; public class TreeTransition extends TreeElement { - private ArrayList parents; - private TreeNode childNode; - private Rule rule; - - private PuzzleElement selection; - private boolean isCorrect; - private boolean isVerified; - - /** - * TreeTransition Constructor create a transition from one node to another - * - * @param board board state of the transition - */ - public TreeTransition(Board board) { - super(TreeElementType.TRANSITION); - this.parents = new ArrayList<>(); - this.childNode = null; - this.board = board; - this.rule = null; - this.selection = null; - this.isCorrect = false; - this.isVerified = false; - } - - /** - * TreeTransition Constructor - create a transition from one node to another - * - * @param parent parent tree node associated with the transition - * @param board board state of the transition - */ - public TreeTransition(TreeNode parent, Board board) { - this(board); - this.parents.add(parent); - } - - /** - * Recursively propagates the change of puzzleElement down the tree - * - * @param element puzzleElement of the change made - */ - @SuppressWarnings("unchecked") - public void propagateChange(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyChange(element); - changed = true; - } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyChange(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyChange(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - PuzzleElement copy = element.copy(); - copy.setModifiable(false); - child.propagateChange(copy); - } - } - } - } else { - // Overwrite previous modifications to this element - board.removeModifiedData(board.getPuzzleElement(element)); - - // apply changes to tranistion - board.notifyChange(element); - - // mark first transition as modified - if (!board - .getPuzzleElement(element) - .equalsData(parents.get(0).getBoard().getPuzzleElement(element))) { - board.addModifiedData(element); - } - - // propagate to children - if (childNode != null) { - - // find starting board - TreeNode head = childNode; - while (head.getParent() != null) { - head = head.getParent().getParents().get(0); - } - Board headBoard = head.getBoard(); + private ArrayList parents; + private TreeNode childNode; + private Rule rule; + + private PuzzleElement selection; + private boolean isCorrect; + private boolean isVerified; + + /** + * TreeTransition Constructor create a transition from one node to another + * + * @param board board state of the transition + */ + public TreeTransition(Board board) { + super(TreeElementType.TRANSITION); + this.parents = new ArrayList<>(); + this.childNode = null; + this.board = board; + this.rule = null; + this.selection = null; + this.isCorrect = false; + this.isVerified = false; + } - PuzzleElement copy = element.copy(); - // Set as modifiable if reverted to starting value (and started modifiable) - if (headBoard.getPuzzleElement(element).equalsData(element)) { - copy.setModifiable(headBoard.getPuzzleElement(element).isModifiable()); + /** + * TreeTransition Constructor - create a transition from one node to another + * + * @param parent parent tree node associated with the transition + * @param board board state of the transition + */ + public TreeTransition(TreeNode parent, Board board) { + this(board); + this.parents.add(parent); + } + + /** + * Recursively propagates the change of puzzleElement down the tree + * + * @param element puzzleElement of the change made + */ + @SuppressWarnings("unchecked") + public void propagateChange(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyChange(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyChange(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyChange(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + PuzzleElement copy = element.copy(); + copy.setModifiable(false); + child.propagateChange(copy); + } + } + } } else { - copy.setModifiable(false); - } + // Overwrite previous modifications to this element + board.removeModifiedData(board.getPuzzleElement(element)); - // apply changes to result node - childNode.getBoard().notifyChange(copy); + // apply changes to tranistion + board.notifyChange(element); - // apply to all child transitions - for (TreeTransition child : childNode.getChildren()) { - child.propagateChange(copy.copy()); + // mark first transition as modified + if (!board.getPuzzleElement(element) + .equalsData(parents.get(0).getBoard().getPuzzleElement(element))) { + board.addModifiedData(element); + } + + // propagate to children + if (childNode != null) { + + // find starting board + TreeNode head = childNode; + while (head.getParent() != null) { + head = head.getParent().getParents().get(0); + } + Board headBoard = head.getBoard(); + + PuzzleElement copy = element.copy(); + // Set as modifiable if reverted to starting value (and started modifiable) + if (headBoard.getPuzzleElement(element).equalsData(element)) { + copy.setModifiable(headBoard.getPuzzleElement(element).isModifiable()); + } else { + copy.setModifiable(false); + } + + // apply changes to result node + childNode.getBoard().notifyChange(copy); + + // apply to all child transitions + for (TreeTransition child : childNode.getChildren()) { + child.propagateChange(copy.copy()); + } + } } - } + reverify(); } - reverify(); - } - - /** - * Recursively propagates the addition of puzzleElement down the tree - * - * @param element puzzleElement of the addition made - */ - @SuppressWarnings("unchecked") - public void propagateAddition(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyDeletion(element); - changed = true; + + /** + * Recursively propagates the addition of puzzleElement down the tree + * + * @param element puzzleElement of the addition made + */ + @SuppressWarnings("unchecked") + public void propagateAddition(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyDeletion(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyAddition(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyAddition(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateAddition(element.copy()); + } + } + } } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyAddition(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyAddition(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateAddition(element.copy()); - } + if (childNode != null) { + board.notifyAddition(element); + childNode.getBoard().notifyAddition(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateAddition(element.copy()); + } + } } - } - } else { - if (childNode != null) { - board.notifyAddition(element); - childNode.getBoard().notifyAddition(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateAddition(element.copy()); + reverify(); + } + + /** + * Recursively propagates the change of puzzleElement down the tree + * + * @param element puzzleElement of the change made + */ + @SuppressWarnings("unchecked") + public void propagateDeletion(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyDeletion(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyAddition(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyDeletion(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateDeletion(element.copy()); + } + } + } + } else { + if (childNode != null) { + board.notifyDeletion(element); + childNode.getBoard().notifyDeletion(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateDeletion(element.copy()); + } + } } - } + reverify(); } - reverify(); - } - - /** - * Recursively propagates the change of puzzleElement down the tree - * - * @param element puzzleElement of the change made - */ - @SuppressWarnings("unchecked") - public void propagateDeletion(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyDeletion(element); - changed = true; + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must + * lead to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + @Override + public boolean isContradictoryBranch() { + if (isJustified() && isCorrect() && rule.getRuleType() == RuleType.CONTRADICTION) { + return true; } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyAddition(element); - changed = true; - } + if (childNode == null) { + return false; + } else { + return childNode.isContradictoryBranch() && isJustified() && isCorrect(); + } } - if (changed && childNode != null) { - childNode.getBoard().notifyDeletion(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateDeletion(element.copy()); - } + } + + /** + * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified + * and justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + @Override + public boolean isValidBranch() { + return isJustified() && isCorrect() && childNode != null && childNode.isValidBranch(); + } + + /** + * Gets the parent tree nodes of this transition + * + * @return parent tree nodes of this tree transition + */ + public ArrayList getParents() { + return parents; + } + + /** + * Sets the parent tree nodes of this transition + * + * @param parents parents tree nodes of this tree transition + */ + public void setParents(ArrayList parents) { + this.parents = parents; + } + + /** + * Adds a parent tree node to this tree transition + * + * @param parent parent tree node to add + */ + public void addParent(TreeNode parent) { + parents.add(parent); + } + + /** + * Removes a parent tree node to this tree transition + * + * @param parent parent tree node to remove + */ + public void removeParent(TreeNode parent) { + parents.remove(parent); + } + + /** + * Determines if the specified tree node is a parent of this transition + * + * @param parent tree node that could be a parent + * @return true if the specified tree node is a parent of this transition, false otherwise + */ + public boolean isParent(TreeNode parent) { + return parents.contains(parent); + } + + /** + * Gets the childNode tree node of this transition + * + * @return childNode tree node + */ + public TreeNode getChildNode() { + return childNode; + } + + /** + * Sets the childNode tree node of this transition + * + * @param childNode childNode tree node + */ + public void setChildNode(TreeNode childNode) { + this.childNode = childNode; + } + + /** + * Gets the rule associated with this transition + * + * @return rule of this transition + */ + public Rule getRule() { + return rule; + } + + /** + * Sets the rule associated with this transition + * + * @param rule rule of this transition + */ + public void setRule(Rule rule) { + this.rule = rule; + isVerified = false; + } + + /** + * Gets he selected element associated with this transition + * + * @return If this is a case rule, the selected element for that rule, null otherwise + */ + public PuzzleElement getSelection() { + if (this.rule instanceof CaseRule) { + return selection; } - } - } else { - if (childNode != null) { - board.notifyDeletion(element); - childNode.getBoard().notifyDeletion(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateDeletion(element.copy()); + return null; + } + + /** + * Sets the selected element associated with this transition + * + * @param selection selected element for this transition + */ + public void setSelection(PuzzleElement selection) { + this.selection = selection; + } + + /** + * Gets whether this transition is correctly justified + * + * @return true if this transition is correctly justified, false otherwise + */ + public boolean isCorrect() { + if (isJustified() && !isVerified) { + isCorrect = rule.checkRule(this) == null; + isVerified = true; } - } + return isJustified() && isCorrect; } - reverify(); - } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must lead - * to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - @Override - public boolean isContradictoryBranch() { - if (isJustified() && isCorrect() && rule.getRuleType() == RuleType.CONTRADICTION) { - return true; - } else { - if (childNode == null) { - return false; - } else { - return childNode.isContradictoryBranch() && isJustified() && isCorrect(); - } + + /** + * Sets whether this transition is correctly justified + * + * @param isCorrect true if this transition is correctly justified, false otherwise + */ + public void setCorrect(boolean isCorrect) { + this.isCorrect = isCorrect; + this.isVerified = true; } - } - - /** - * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and - * justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - @Override - public boolean isValidBranch() { - return isJustified() && isCorrect() && childNode != null && childNode.isValidBranch(); - } - - /** - * Gets the parent tree nodes of this transition - * - * @return parent tree nodes of this tree transition - */ - public ArrayList getParents() { - return parents; - } - - /** - * Sets the parent tree nodes of this transition - * - * @param parents parents tree nodes of this tree transition - */ - public void setParents(ArrayList parents) { - this.parents = parents; - } - - /** - * Adds a parent tree node to this tree transition - * - * @param parent parent tree node to add - */ - public void addParent(TreeNode parent) { - parents.add(parent); - } - - /** - * Removes a parent tree node to this tree transition - * - * @param parent parent tree node to remove - */ - public void removeParent(TreeNode parent) { - parents.remove(parent); - } - - /** - * Determines if the specified tree node is a parent of this transition - * - * @param parent tree node that could be a parent - * @return true if the specified tree node is a parent of this transition, false otherwise - */ - public boolean isParent(TreeNode parent) { - return parents.contains(parent); - } - - /** - * Gets the childNode tree node of this transition - * - * @return childNode tree node - */ - public TreeNode getChildNode() { - return childNode; - } - - /** - * Sets the childNode tree node of this transition - * - * @param childNode childNode tree node - */ - public void setChildNode(TreeNode childNode) { - this.childNode = childNode; - } - - /** - * Gets the rule associated with this transition - * - * @return rule of this transition - */ - public Rule getRule() { - return rule; - } - - /** - * Sets the rule associated with this transition - * - * @param rule rule of this transition - */ - public void setRule(Rule rule) { - this.rule = rule; - isVerified = false; - } - - /** - * Gets he selected element associated with this transition - * - * @return If this is a case rule, the selected element for that rule, null otherwise - */ - public PuzzleElement getSelection() { - if (this.rule instanceof CaseRule) { - return selection; + + /** + * Forces check of rule on this transition regardless if it has been cached already + * + * @return true if this transition is correctly justified, false otherwise + */ + public boolean reverify() { + isVerified = false; + return isCorrect(); } - return null; - } - - /** - * Sets the selected element associated with this transition - * - * @param selection selected element for this transition - */ - public void setSelection(PuzzleElement selection) { - this.selection = selection; - } - - /** - * Gets whether this transition is correctly justified - * - * @return true if this transition is correctly justified, false otherwise - */ - public boolean isCorrect() { - if (isJustified() && !isVerified) { - isCorrect = rule.checkRule(this) == null; - isVerified = true; + + /** + * Gets whether this transition is justified + * + * @return true if this transition is justified, false otherwise + */ + public boolean isJustified() { + return rule != null; } - return isJustified() && isCorrect; - } - - /** - * Sets whether this transition is correctly justified - * - * @param isCorrect true if this transition is correctly justified, false otherwise - */ - public void setCorrect(boolean isCorrect) { - this.isCorrect = isCorrect; - this.isVerified = true; - } - - /** - * Forces check of rule on this transition regardless if it has been cached already - * - * @return true if this transition is correctly justified, false otherwise - */ - public boolean reverify() { - isVerified = false; - return isCorrect(); - } - - /** - * Gets whether this transition is justified - * - * @return true if this transition is justified, false otherwise - */ - public boolean isJustified() { - return rule != null; - } - - /*public int modifiedData_size(){ - return board.getModifiedData().size(); - }*/ + + /*public int modifiedData_size(){ + return board.getModifiedData().size(); + }*/ } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java b/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java index fcfa70cd4..41af3f626 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java @@ -6,164 +6,164 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Battleship extends Puzzle { - public Battleship() { - super(); + public Battleship() { + super(); - this.name = "Battleship"; + this.name = "Battleship"; - this.importer = new BattleshipImporter(this); - this.exporter = new BattleshipExporter(this); + this.importer = new BattleshipImporter(this); + this.exporter = new BattleshipExporter(this); - this.factory = new BattleshipCellFactory(); - } + this.factory = new BattleshipCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new BattleshipView((BattleshipBoard) currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new BattleshipView((BattleshipBoard) currentBoard); + addBoardListener(boardView); + } - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Battleship - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Battleship, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for Battleship + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Battleship, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - BattleshipBoard battleShipBoard = (BattleshipBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + BattleshipBoard battleShipBoard = (BattleshipBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(battleShipBoard) == null) { - return false; - } + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(battleShipBoard) == null) { + return false; + } + } + for (PuzzleElement data : battleShipBoard.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) data; + if (cell.getType() == BattleshipType.UNKNOWN) { + return false; + } + } + return true; } - for (PuzzleElement data : battleShipBoard.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) data; - if (cell.getType() == BattleshipType.UNKNOWN) { - return false; - } - } - return true; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} - // - // @Override - // public void onTreeSelectionChange(ArrayList newSelection) - // { - // - // } + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} - @Override - public void importPuzzle(String fileName) { - // if(fileName != null) - // { - // InputStream inputStream = new FileInputStream(fileName); - // DocumentBuilder builder = null;//factory.newDocumentBuilder(); - // Document document = builder.parse(inputStream); - // - // BattleShipBoard battleShipBoard; - // - // PuzzleElement rootNode = document.getDocumentElement(); - // PuzzleElement puzzleElement = (PuzzleElement) - // rootNode.getElementsByTagName("edu.rpi.legup.puzzle").item(0); - // PuzzleElement boardElement = (PuzzleElement) - // puzzleElement.getElementsByTagName("board").item(0); - // PuzzleElement axesElement = (PuzzleElement) - // boardElement.getElementsByTagName("axes").item(0); - // PuzzleElement shipElement = (PuzzleElement) - // boardElement.getElementsByTagName("ships").item(0); - // PuzzleElement cellElement = (PuzzleElement) - // boardElement.getElementsByTagName("cells").item(0); - // PuzzleElement rightElement = (PuzzleElement) - // axesElement.getElementsByTagName("right").item(0); - // PuzzleElement bottomElement = (PuzzleElement) - // axesElement.getElementsByTagName("bottom").item(0); - // NodeList rightClueList = rightElement.getElementsByTagName("clue"); - // NodeList bottomClueList = bottomElement.getElementsByTagName("clue"); - // NodeList shipList = shipElement.getElementsByTagName("ship"); - // NodeList cells = cellElement.getElementsByTagName("cell"); // - // int size = Integer.valueOf(boardElement.getAttribute("size")); - // battleShipBoard = new BattleShipBoard(size); + // @Override + // public void onTreeSelectionChange(ArrayList newSelection) + // { // - // ArrayList battleShipData = new ArrayList<>(); - // for(int i = 0; i < size * size; i++) - // { - // battleShipData.add(null); - // } - // - // for (int i = 0; i < rightClueList.getLength(); i++) { - // battleShipBoard.getRight()[i] = - // Integer.valueOf(rightClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); - // } - // - // for (int i = 0; i < bottomClueList.getLength(); i++) { - // battleShipBoard.getBottom()[i] = - // Integer.valueOf(bottomClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); - // } - // - // for (int i = 0; i < shipList.getLength(); i++) { - // int length = - // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("length").getNodeValue()); - // int count = - // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("count").getNodeValue()); - // battleShipBoard.getShips().add(new Ship(length, count)); - // } - // - // for (int i = 0; i < cells.getLength(); i++) { - // int x = - // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("x").getNodeValue()); - // int y = - // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("y").getNodeValue()); - // String value = - // cells.item(i).getAttributes().getNamedItem("value").getNodeValue().toUpperCase(); - // - // BattleShipCell cell = new - // BattleShipCell(BattleShipType.valueOf(value).ordinal(), new Point(x, y)); - // battleShipBoard.setCell(x, y, cell); - // cell.setModifiable(false); - // cell.setGiven(true); - // } - // - // for (int x = 0; x < size; x++) { - // for (int y = 0; y < size; y++) { - // if (battleShipBoard.getCell(x, y) == null) { - // BattleShipCell cell = new BattleShipCell(9, new Point(x, y)); - // cell.setModifiable(true); - // battleShipBoard.setCell(x, y, cell); - // } - // } - // } - // this.currentBoard = battleShipBoard; - // this.tree = new Tree(currentBoard); - // } - } + // } + + @Override + public void importPuzzle(String fileName) { + // if(fileName != null) + // { + // InputStream inputStream = new FileInputStream(fileName); + // DocumentBuilder builder = null;//factory.newDocumentBuilder(); + // Document document = builder.parse(inputStream); + // + // BattleShipBoard battleShipBoard; + // + // PuzzleElement rootNode = document.getDocumentElement(); + // PuzzleElement puzzleElement = (PuzzleElement) + // rootNode.getElementsByTagName("edu.rpi.legup.puzzle").item(0); + // PuzzleElement boardElement = (PuzzleElement) + // puzzleElement.getElementsByTagName("board").item(0); + // PuzzleElement axesElement = (PuzzleElement) + // boardElement.getElementsByTagName("axes").item(0); + // PuzzleElement shipElement = (PuzzleElement) + // boardElement.getElementsByTagName("ships").item(0); + // PuzzleElement cellElement = (PuzzleElement) + // boardElement.getElementsByTagName("cells").item(0); + // PuzzleElement rightElement = (PuzzleElement) + // axesElement.getElementsByTagName("right").item(0); + // PuzzleElement bottomElement = (PuzzleElement) + // axesElement.getElementsByTagName("bottom").item(0); + // NodeList rightClueList = rightElement.getElementsByTagName("clue"); + // NodeList bottomClueList = bottomElement.getElementsByTagName("clue"); + // NodeList shipList = shipElement.getElementsByTagName("ship"); + // NodeList cells = cellElement.getElementsByTagName("cell"); + // + // int size = Integer.valueOf(boardElement.getAttribute("size")); + // battleShipBoard = new BattleShipBoard(size); + // + // ArrayList battleShipData = new ArrayList<>(); + // for(int i = 0; i < size * size; i++) + // { + // battleShipData.add(null); + // } + // + // for (int i = 0; i < rightClueList.getLength(); i++) { + // battleShipBoard.getRight()[i] = + // Integer.valueOf(rightClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); + // } + // + // for (int i = 0; i < bottomClueList.getLength(); i++) { + // battleShipBoard.getBottom()[i] = + // Integer.valueOf(bottomClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); + // } + // + // for (int i = 0; i < shipList.getLength(); i++) { + // int length = + // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("length").getNodeValue()); + // int count = + // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("count").getNodeValue()); + // battleShipBoard.getShips().add(new Ship(length, count)); + // } + // + // for (int i = 0; i < cells.getLength(); i++) { + // int x = + // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("x").getNodeValue()); + // int y = + // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("y").getNodeValue()); + // String value = + // cells.item(i).getAttributes().getNamedItem("value").getNodeValue().toUpperCase(); + // + // BattleShipCell cell = new + // BattleShipCell(BattleShipType.valueOf(value).ordinal(), new Point(x, y)); + // battleShipBoard.setCell(x, y, cell); + // cell.setModifiable(false); + // cell.setGiven(true); + // } + // + // for (int x = 0; x < size; x++) { + // for (int y = 0; y < size; y++) { + // if (battleShipBoard.getCell(x, y) == null) { + // BattleShipCell cell = new BattleShipCell(9, new Point(x, y)); + // cell.setModifiable(true); + // battleShipBoard.setCell(x, y, cell); + // } + // } + // } + // this.currentBoard = battleShipBoard; + // this.tree = new Tree(currentBoard); + // } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java index cbf7ffbcd..555c8471f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java @@ -8,148 +8,148 @@ public class BattleshipBoard extends GridBoard { - private List east; - private List south; + private List east; + private List south; - /** - * Constructor for creating a rectangular battleship board. - * - * @param width width of the board - * @param height height of the board - */ - public BattleshipBoard(int width, int height) { - super(width, height); + /** + * Constructor for creating a rectangular battleship board. + * + * @param width width of the board + * @param height height of the board + */ + public BattleshipBoard(int width, int height) { + super(width, height); - this.east = new ArrayList<>(); - this.south = new ArrayList<>(); + this.east = new ArrayList<>(); + this.south = new ArrayList<>(); - for (int i = 0; i < height; i++) { - east.add(null); + for (int i = 0; i < height; i++) { + east.add(null); + } + for (int i = 0; i < width; i++) { + south.add(null); + } } - for (int i = 0; i < width; i++) { - south.add(null); - } - } - - /** - * Constructor for creating a square-sized battleship board. - * - * @param size size of the board - */ - public BattleshipBoard(int size) { - this(size, size); - } - /** - * Gets the east {@link BattleshipClue} - * - * @return List of BattleShipClue objects on the east side of the board - */ - public List getEast() { - return east; - } + /** + * Constructor for creating a square-sized battleship board. + * + * @param size size of the board + */ + public BattleshipBoard(int size) { + this(size, size); + } - /** - * Gets the east {@link BattleshipClue} - * - * @return east battle ship clues - */ - public List getSouth() { - return south; - } + /** + * Gets the east {@link BattleshipClue} + * + * @return List of BattleShipClue objects on the east side of the board + */ + public List getEast() { + return east; + } - @Override - public BattleshipCell getCell(int x, int y) { - return (BattleshipCell) super.getCell(x, y); - } + /** + * Gets the east {@link BattleshipClue} + * + * @return east battle ship clues + */ + public List getSouth() { + return south; + } - @Override - /** - * Creates a copy of the current board - * - * @return the copy of the board - */ - public BattleshipBoard copy() { - BattleshipBoard copy = new BattleshipBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + @Override + public BattleshipCell getCell(int x, int y) { + return (BattleshipCell) super.getCell(x, y); } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + @Override + /** + * Creates a copy of the current board + * + * @return the copy of the board + */ + public BattleshipBoard copy() { + BattleshipBoard copy = new BattleshipBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.east = this.east; + copy.south = this.south; + return copy; } - copy.east = this.east; - copy.south = this.south; - return copy; - } - /** - * Get a list of all orthogonally adjacent cells. - * - * @param cell The cell to get adjacent cells from. - * @return List of adjacent cells in clockwise order: { up, right, down, left } - */ - public List getAdjOrthogonals(BattleshipCell cell) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - BattleshipCell up = getCell(loc.x, loc.y - 1); - BattleshipCell right = getCell(loc.x + 1, loc.y); - BattleshipCell down = getCell(loc.x, loc.y + 1); - BattleshipCell left = getCell(loc.x - 1, loc.y); - adj.add(up); - adj.add(right); - adj.add(down); - adj.add(left); - return adj; - } + /** + * Get a list of all orthogonally adjacent cells. + * + * @param cell The cell to get adjacent cells from. + * @return List of adjacent cells in clockwise order: { up, right, down, left } + */ + public List getAdjOrthogonals(BattleshipCell cell) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + BattleshipCell up = getCell(loc.x, loc.y - 1); + BattleshipCell right = getCell(loc.x + 1, loc.y); + BattleshipCell down = getCell(loc.x, loc.y + 1); + BattleshipCell left = getCell(loc.x - 1, loc.y); + adj.add(up); + adj.add(right); + adj.add(down); + adj.add(left); + return adj; + } - /** - * Get a list of all diagonally adjacent cells. - * - * @param cell The cell to get diagonally adjacent cells from. - * @return List of diagonally adjacent cells in clockwise order: - * { upRight, downRight, downLeft, upLeft } - */ - public List getAdjDiagonals(BattleshipCell cell) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - BattleshipCell upRight = getCell(loc.x + 1, loc.y - 1); - BattleshipCell downRight = getCell(loc.x + 1, loc.y + 1); - BattleshipCell downLeft = getCell(loc.x - 1, loc.y + 1); - BattleshipCell upLeft = getCell(loc.x - 1, loc.y - 1); - dia.add(upRight); - dia.add(downRight); - dia.add(downLeft); - dia.add(upLeft); - return dia; - } + /** + * Get a list of all diagonally adjacent cells. + * + * @param cell The cell to get diagonally adjacent cells from. + * @return List of diagonally adjacent cells in clockwise order: + * { upRight, downRight, downLeft, upLeft } + */ + public List getAdjDiagonals(BattleshipCell cell) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + BattleshipCell upRight = getCell(loc.x + 1, loc.y - 1); + BattleshipCell downRight = getCell(loc.x + 1, loc.y + 1); + BattleshipCell downLeft = getCell(loc.x - 1, loc.y + 1); + BattleshipCell upLeft = getCell(loc.x - 1, loc.y - 1); + dia.add(upRight); + dia.add(downRight); + dia.add(downLeft); + dia.add(upLeft); + return dia; + } - /** - * Get a list of cells in a row. - * - * @param y The y-coordinate of the row. - * @return List of cells in the row in increasing x-coordinate order. - */ - public List getRow(int y) { - List row = new ArrayList<>(); - for (int x = 0; x < dimension.width; x++) { - row.add(getCell(x, y)); + /** + * Get a list of cells in a row. + * + * @param y The y-coordinate of the row. + * @return List of cells in the row in increasing x-coordinate order. + */ + public List getRow(int y) { + List row = new ArrayList<>(); + for (int x = 0; x < dimension.width; x++) { + row.add(getCell(x, y)); + } + return row; } - return row; - } - /** - * Get a list of cells in a column. - * - * @param x The x-coordinate of the column. - * @return List of cells in the column in increasing y-coordinate order. - */ - public List getColumn(int x) { - List column = new ArrayList<>(); - for (int y = 0; y < dimension.height; y++) { - column.add(getCell(x, y)); + /** + * Get a list of cells in a column. + * + * @param x The x-coordinate of the column. + * @return List of cells in the column in increasing y-coordinate order. + */ + public List getColumn(int x) { + List column = new ArrayList<>(); + for (int y = 0; y < dimension.height; y++) { + column.add(getCell(x, y)); + } + return column; } - return column; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java index 1e902633e..5a5b86094 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java @@ -5,35 +5,35 @@ public class BattleshipCell extends GridCell { - /** - * BattleShipCell Constructor - creates a BattleShipCell from the specified value and location - * - * @param value value of the BattleShipCell - * @param location position of the BattleShipCell - */ - public BattleshipCell(BattleshipType value, Point location) { - super(value, location); - } + /** + * BattleShipCell Constructor - creates a BattleShipCell from the specified value and location + * + * @param value value of the BattleShipCell + * @param location position of the BattleShipCell + */ + public BattleshipCell(BattleshipType value, Point location) { + super(value, location); + } - /** - * Gets the type of this BattleShipCell - * - * @return type of BattleShipCell - */ - public BattleshipType getType() { - return data; - } + /** + * Gets the type of this BattleShipCell + * + * @return type of BattleShipCell + */ + public BattleshipType getType() { + return data; + } - /** - * Performs a deep copy on the BattleShipCell - * - * @return a new copy of the BattleShipCell that is independent of this one - */ - public BattleshipCell copy() { - BattleshipCell copy = new BattleshipCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the BattleShipCell + * + * @return a new copy of the BattleShipCell that is independent of this one + */ + public BattleshipCell copy() { + BattleshipCell copy = new BattleshipCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java index d97a44034..9db0cca84 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java @@ -5,39 +5,39 @@ import java.awt.event.MouseEvent; public class BattleshipCellController extends ElementController { - /** - * Controller class for the Battleship puzzle - receives user mouse input and changes what's shown - * on the GUI - * - * @param data the PuzzleElement to be changed - * @param e the user mouse input - */ - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - BattleshipCell cell = (BattleshipCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == BattleshipType.SHIP_MIDDLE) { - cell.setData(BattleshipType.UNKNOWN); + /** + * Controller class for the Battleship puzzle - receives user mouse input and changes what's + * shown on the GUI + * + * @param data the PuzzleElement to be changed + * @param e the user mouse input + */ + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + BattleshipCell cell = (BattleshipCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == BattleshipType.SHIP_MIDDLE) { + cell.setData(BattleshipType.UNKNOWN); + } else { + cell.setData(BattleshipType.getType(cell.getData().value + 1)); + } + } } else { - cell.setData(BattleshipType.getType(cell.getData().value + 1)); + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == BattleshipType.UNKNOWN) { + cell.setData(BattleshipType.SHIP_MIDDLE); + } else { + cell.setData(BattleshipType.getType(cell.getData().value - 1)); + } + } } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == BattleshipType.UNKNOWN) { - cell.setData(BattleshipType.SHIP_MIDDLE); - } else { - cell.setData(BattleshipType.getType(cell.getData().value - 1)); - } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java index f967a677e..1b3b6c427 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java @@ -10,66 +10,68 @@ import org.w3c.dom.Node; public class BattleshipCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) - throws InvalidFileFormatException { - try { - BattleshipBoard battleShipBoard = (BattleshipBoard) board; - int width = battleShipBoard.getWidth(); - int height = battleShipBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - if (node.getNodeName().equalsIgnoreCase("cell")) { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) + throws InvalidFileFormatException { + try { + BattleshipBoard battleShipBoard = (BattleshipBoard) board; + int width = battleShipBoard.getWidth(); + int height = battleShipBoard.getHeight(); + NamedNodeMap attributeList = node.getAttributes(); + if (node.getNodeName().equalsIgnoreCase("cell")) { - int value = Integer.parseInt(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.parseInt(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.parseInt(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("BattleShip Factory: cell location out of bounds"); - } - if (value < 0 || value > 3) { - throw new InvalidFileFormatException("BattleShip Factory: cell unknown value"); - } + int value = Integer.parseInt(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.parseInt(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.parseInt(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "BattleShip Factory: cell location out of bounds"); + } + if (value < 0 || value > 3) { + throw new InvalidFileFormatException("BattleShip Factory: cell unknown value"); + } - BattleshipCell cell = new BattleshipCell(BattleshipType.getType(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } else { - throw new InvalidFileFormatException( - "BattleShip Factory: unknown puzzleElement puzzleElement"); - } - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "BattleShip Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("BattleShip Factory: could not find attribute(s)"); + BattleshipCell cell = + new BattleshipCell(BattleshipType.getType(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } else { + throw new InvalidFileFormatException( + "BattleShip Factory: unknown puzzleElement puzzleElement"); + } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "BattleShip Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("BattleShip Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - BattleshipCell cell = (BattleshipCell) puzzleElement; - Point loc = cell.getLocation(); + BattleshipCell cell = (BattleshipCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java index 1ed0face1..6b5856639 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java @@ -4,75 +4,75 @@ public class BattleshipClue extends PuzzleElement { - private BattleshipType type; + private BattleshipType type; - public BattleshipClue(int value, int index, BattleshipType type) { - super(value); - this.index = index; - this.type = type; - } + public BattleshipClue(int value, int index, BattleshipType type) { + super(value); + this.index = index; + this.type = type; + } - /** - * Returns the column number as a string - * - * @param col the column number that is to be converted and returned - * @return int value - */ - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; + /** + * Returns the column number as a string + * + * @param col the column number that is to be converted and returned + * @return int value + */ + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; + } + return sb.reverse().toString(); } - return sb.reverse().toString(); - } - /** - * Returns the column string as an integer - * - * @param col the column number as a string that is to be converted and returned - * @return string value - */ - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; + /** + * Returns the column string as an integer + * + * @param col the column number as a string that is to be converted and returned + * @return string value + */ + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; + } + return result; } - return result; - } - /** - * Gets the int value that represents this puzzleElement - * - * @return int value - */ - @Override - public Integer getData() { - return (Integer) super.getData(); - } + /** + * Gets the int value that represents this puzzleElement + * + * @return int value + */ + @Override + public Integer getData() { + return (Integer) super.getData(); + } - /** - * Returns the type of the battleship object (ship or clue) - * - * @return BattleshipType type - */ - public BattleshipType getType() { - return type; - } + /** + * Returns the type of the battleship object (ship or clue) + * + * @return BattleshipType type + */ + public BattleshipType getType() { + return type; + } - /** - * Sets the type of the battleship object (ship or clue) to the given type - * - * @param type given Battleship type - */ - public void setType(BattleshipType type) { - this.type = type; - } + /** + * Sets the type of the battleship object (ship or clue) to the given type + * + * @param type given Battleship type + */ + public void setType(BattleshipType type) { + this.type = type; + } - public BattleshipClue copy() { - return null; - } + public BattleshipClue copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java index e2ad8b863..788c860f3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java @@ -5,55 +5,55 @@ public class BattleshipClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public BattleshipClueView(BattleshipClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public BattleshipClue getPuzzleElement() { - return (BattleshipClue) super.getPuzzleElement(); - } - - @Override - /** - * Draws the clue from the PuzzleElement associated with this view on the given frame - * - * @param graphics2D the frame the clue is to be drawn on - */ - public void draw(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - BattleshipClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - value = String.valueOf(clue.getData() + 1); - break; - case CLUE_EAST: - value = String.valueOf(clue.getData()); - break; - case CLUE_SOUTH: - value = String.valueOf(clue.getData()); - break; - case CLUE_WEST: - value = BattleshipClue.colNumToString(clue.getData() + 1); - break; - default: - value = ""; + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public BattleshipClueView(BattleshipClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public BattleshipClue getPuzzleElement() { + return (BattleshipClue) super.getPuzzleElement(); } - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + @Override + /** + * Draws the clue from the PuzzleElement associated with this view on the given frame + * + * @param graphics2D the frame the clue is to be drawn on + */ + public void draw(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + BattleshipClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + value = String.valueOf(clue.getData() + 1); + break; + case CLUE_EAST: + value = String.valueOf(clue.getData()); + break; + case CLUE_SOUTH: + value = String.valueOf(clue.getData()); + break; + case CLUE_WEST: + value = BattleshipClue.colNumToString(clue.getData() + 1); + break; + default: + value = ""; + } + + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java index fed0afaf3..1898468ce 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java @@ -4,94 +4,107 @@ import java.awt.*; public class BattleshipElementView extends GridElementView { - private static final Stroke OUTLINE_STROKE = new BasicStroke(1); - private static final Color OUTLINE_COLOR = new Color(0x212121); + private static final Stroke OUTLINE_STROKE = new BasicStroke(1); + private static final Color OUTLINE_COLOR = new Color(0x212121); - private static final Color UNKNOWN_COLOR = new Color(0xE0E0E0); - private static final Color WATER_COLOR = new Color(0x1565C0); - private static final Color SHIP_COLOR = new Color(0x757575); + private static final Color UNKNOWN_COLOR = new Color(0xE0E0E0); + private static final Color WATER_COLOR = new Color(0x1565C0); + private static final Color SHIP_COLOR = new Color(0x757575); - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 10); - private static final Color FONT_COLOR = new Color(0xFFEB3B); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 10); + private static final Color FONT_COLOR = new Color(0xFFEB3B); - public BattleshipElementView(BattleshipCell cell) { - super(cell); - } + public BattleshipElementView(BattleshipCell cell) { + super(cell); + } - @Override - /** - * Draws on the given frame based on the type of the cell of the current puzzleElement - * - * @param graphics2D the frame to be drawn on - */ - public void drawElement(Graphics2D graphics2D) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - BattleshipType type = cell.getType(); + @Override + /** + * Draws on the given frame based on the type of the cell of the current puzzleElement + * + * @param graphics2D the frame to be drawn on + */ + public void drawElement(Graphics2D graphics2D) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + BattleshipType type = cell.getType(); - switch (type) { - case UNKNOWN: - graphics2D.setColor(UNKNOWN_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - case WATER: - graphics2D.setColor(WATER_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - case SHIP_UNKNOWN: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillRect( - location.x + 3 * size.width / 8, - location.y + 3 * size.height / 8, - size.width / 4, - size.height / 4); + switch (type) { + case UNKNOWN: + graphics2D.setColor(UNKNOWN_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + case WATER: + graphics2D.setColor(WATER_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + case SHIP_UNKNOWN: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillRect( + location.x + 3 * size.width / 8, + location.y + 3 * size.height / 8, + size.width / 4, + size.height / 4); - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = "?"; - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - break; - case SUBMARINE: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillOval( - location.x + size.width / 4, - location.y + size.width / 4, - size.width / 2, - size.height / 2); - break; - case SHIP_TOP: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x, location.y - size.height / 2, size.width, size.height, 180, 180); - break; - case SHIP_RIGHT: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x + size.height / 2, location.y, size.width, size.height, 90, 180); - break; - case SHIP_BOTTOM: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x, location.y + size.height / 2, size.width, size.height, 0, 180); - break; - case SHIP_LEFT: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x - size.height / 2, location.y, size.width, size.height, 270, 180); - break; - case SHIP_MIDDLE: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - default: - graphics2D.setColor(new Color(0xE040FB)); - break; - } + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = "?"; + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + + ((size.height - metrics.getHeight()) / 2) + + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + break; + case SUBMARINE: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillOval( + location.x + size.width / 4, + location.y + size.width / 4, + size.width / 2, + size.height / 2); + break; + case SHIP_TOP: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x, + location.y - size.height / 2, + size.width, + size.height, + 180, + 180); + break; + case SHIP_RIGHT: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x + size.height / 2, location.y, size.width, size.height, 90, 180); + break; + case SHIP_BOTTOM: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x, location.y + size.height / 2, size.width, size.height, 0, 180); + break; + case SHIP_LEFT: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x - size.height / 2, + location.y, + size.width, + size.height, + 270, + 180); + break; + case SHIP_MIDDLE: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + default: + graphics2D.setColor(new Color(0xE040FB)); + break; + } - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.setStroke(OUTLINE_STROKE); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.setStroke(OUTLINE_STROKE); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java index d9ec97a58..cbc364842 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java @@ -6,60 +6,60 @@ public class BattleshipExporter extends PuzzleExporter { - public BattleshipExporter(Battleship battleShip) { - super(battleShip); - } - - /** - * Creates and returns a new board element in the XML document specified - * - * @param newDocument the XML document to append to - * @return the new board element - */ - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - BattleshipBoard board; - if (puzzle.getTree() != null) { - board = (BattleshipBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (BattleshipBoard) puzzle.getBoardView().getBoard(); + public BattleshipExporter(Battleship battleShip) { + super(battleShip); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + /** + * Creates and returns a new board element in the XML document specified + * + * @param newDocument the XML document to append to + * @return the new board element + */ + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + BattleshipBoard board; + if (puzzle.getTree() != null) { + board = (BattleshipBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (BattleshipBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - if (cell.getData() != BattleshipType.getType(0)) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (BattleshipClue clue : board.getEast()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", BattleshipClue.colNumToString(clue.getIndex())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + if (cell.getData() != BattleshipType.getType(0)) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (BattleshipClue clue : board.getEast()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", String.valueOf(clue.getIndex())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (BattleshipClue clue : board.getEast()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", BattleshipClue.colNumToString(clue.getIndex())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); + + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (BattleshipClue clue : board.getEast()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", String.valueOf(clue.getIndex())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); - return boardElement; - } + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java index 012bf9b5c..cbc1dd02b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java @@ -8,176 +8,183 @@ import org.w3c.dom.NodeList; public class BattleshipImporter extends PuzzleImporter { - public BattleshipImporter(Battleship battleShip) { - super(battleShip); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } - - @Override - public boolean acceptsTextInput() { - return false; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - BattleshipBoard battleShipBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - battleShipBoard = new BattleshipBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - battleShipBoard = new BattleshipBoard(width, height); - } - } - - if (battleShipBoard == null) { - throw new InvalidFileFormatException("BattleShip Importer: " + "invalid board dimensions"); - } - - int width = battleShipBoard.getWidth(); - int height = battleShipBoard.getHeight(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - BattleshipCell cell = - (BattleshipCell) - puzzle.getFactory().importCell(elementDataList.item(i), battleShipBoard); - Point loc = cell.getLocation(); - if (cell.getData() != BattleshipType.getType(0)) { - cell.setModifiable(false); - cell.setGiven(true); - } - battleShipBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (battleShipBoard.getCell(x, y) == null) { - BattleshipCell cell = new BattleshipCell(BattleshipType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - battleShipBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("BattleShip Importer: " + "cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis2.hasAttribute("side")) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != battleShipBoard.getHeight() - || southClues.getLength() != battleShipBoard.getWidth()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " - + "there must be same number of clues as the dimension " - + "of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = BattleshipClue.colStringToColNum(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > battleShipBoard.getHeight()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "clue index out of bounds"); - } + public BattleshipImporter(Battleship battleShip) { + super(battleShip); + } - if (battleShipBoard.getEast().get(index - 1) != null) { - throw new InvalidFileFormatException("BattleShip Importer: " + "duplicate clue index"); - } - battleShipBoard - .getEast() - .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > battleShipBoard.getWidth()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "clue index out of bounds"); - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - if (battleShipBoard.getSouth().get(index - 1) != null) { - throw new InvalidFileFormatException("BattleShip Importer: " + "duplicate clue index"); + @Override + public boolean acceptsTextInput() { + return false; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + BattleshipBoard battleShipBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + battleShipBoard = new BattleshipBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + battleShipBoard = new BattleshipBoard(width, height); + } + } + + if (battleShipBoard == null) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "invalid board dimensions"); + } + + int width = battleShipBoard.getWidth(); + int height = battleShipBoard.getHeight(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + BattleshipCell cell = + (BattleshipCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), battleShipBoard); + Point loc = cell.getLocation(); + if (cell.getData() != BattleshipType.getType(0)) { + cell.setModifiable(false); + cell.setGiven(true); + } + battleShipBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (battleShipBoard.getCell(x, y) == null) { + BattleshipCell cell = + new BattleshipCell(BattleshipType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + battleShipBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("BattleShip Importer: " + "cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis2.hasAttribute("side")) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != battleShipBoard.getHeight() + || southClues.getLength() != battleShipBoard.getWidth()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + + "there must be same number of clues as the dimension " + + "of the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = BattleshipClue.colStringToColNum(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > battleShipBoard.getHeight()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "clue index out of bounds"); + } + + if (battleShipBoard.getEast().get(index - 1) != null) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "duplicate clue index"); + } + battleShipBoard + .getEast() + .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > battleShipBoard.getWidth()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "clue index out of bounds"); + } + + if (battleShipBoard.getSouth().get(index - 1) != null) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "duplicate clue index"); + } + battleShipBoard + .getSouth() + .set( + index - 1, + new BattleshipClue(value, index, BattleshipType.CLUE_SOUTH)); + } + + puzzle.setCurrentBoard(battleShipBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "unknown value where integer expected"); } - battleShipBoard - .getSouth() - .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_SOUTH)); - } - - puzzle.setCurrentBoard(battleShipBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Battleship cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Battleship cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java index 2cee10469..0d505f43c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java @@ -1,52 +1,52 @@ package edu.rpi.legup.puzzle.battleship; public enum BattleshipType { - UNKNOWN, - WATER, - SUBMARINE, - SHIP_UNKNOWN, - SHIP_TOP, - SHIP_RIGHT, - SHIP_BOTTOM, - SHIP_LEFT, - SHIP_MIDDLE, - CLUE_NORTH, - CLUE_EAST, - CLUE_SOUTH, - CLUE_WEST; + UNKNOWN, + WATER, + SUBMARINE, + SHIP_UNKNOWN, + SHIP_TOP, + SHIP_RIGHT, + SHIP_BOTTOM, + SHIP_LEFT, + SHIP_MIDDLE, + CLUE_NORTH, + CLUE_EAST, + CLUE_SOUTH, + CLUE_WEST; - public int value; + public int value; - BattleshipType() { - this.value = this.ordinal(); - } + BattleshipType() { + this.value = this.ordinal(); + } - /** - * Gets the enum of this BattleShipType - * - * @param value the integer value input - * @return enum equivalent BattleShipType of integer value - */ - public static BattleshipType getType(int value) { - BattleshipType[] vals = values(); - if (value >= 0 && value < vals.length) { - return vals[value]; + /** + * Gets the enum of this BattleShipType + * + * @param value the integer value input + * @return enum equivalent BattleShipType of integer value + */ + public static BattleshipType getType(int value) { + BattleshipType[] vals = values(); + if (value >= 0 && value < vals.length) { + return vals[value]; + } + return null; } - return null; - } - /** - * Checks if the type is a ship. - * - * @param type the {@link BattleshipType} to check - * @return true if the type is a ship, false otherwise - */ - public static boolean isShip(BattleshipType type) { - return type == SHIP_UNKNOWN - || type == SHIP_TOP - || type == SHIP_RIGHT - || type == SHIP_BOTTOM - || type == SHIP_LEFT - || type == SHIP_MIDDLE; - } + /** + * Checks if the type is a ship. + * + * @param type the {@link BattleshipType} to check + * @return true if the type is a ship, false otherwise + */ + public static boolean isShip(BattleshipType type) { + return type == SHIP_UNKNOWN + || type == SHIP_TOP + || type == SHIP_RIGHT + || type == SHIP_BOTTOM + || type == SHIP_LEFT + || type == SHIP_MIDDLE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java index b82828fb8..4095db54a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java @@ -7,22 +7,23 @@ public class BattleshipView extends GridBoardView { - public BattleshipView(BattleshipBoard board) { - super(new BoardController(), new BattleshipCellController(), board.getDimension()); + public BattleshipView(BattleshipBoard board) { + super(new BoardController(), new BattleshipCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - Point loc = cell.getLocation(); - BattleshipElementView elementView = new BattleshipElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + Point loc = cell.getLocation(); + BattleshipElementView elementView = new BattleshipElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); - } + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java index 41abeabe1..f1ecd6685 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java @@ -10,79 +10,79 @@ public class AdjacentShipsContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "No instance of the contradiction " + this.ruleName + " here"; + private final String NO_CONTRADICTION_MESSAGE = + "No instance of the contradiction " + this.ruleName + " here"; - public AdjacentShipsContradictionRule() { - super( - "BTSP-CONT-0001", - "Adjacent Ships", - "Cells next to the battleship must be water.", - "edu/rpi/legup/images/battleship/contradictions" + "/AdjacentShips.png"); - } + public AdjacentShipsContradictionRule() { + super( + "BTSP-CONT-0001", + "Adjacent Ships", + "Cells next to the battleship must be water.", + "edu/rpi/legup/images/battleship/contradictions" + "/AdjacentShips.png"); + } - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule. - * - * @param board board to check contradiction - * @param puzzleElement equivalent {@link PuzzleElement} - * @return null if the transition contains a contradiction at the specified {@link - * PuzzleElement}, otherwise return a no contradiction message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - BattleshipBoard bsBoard = (BattleshipBoard) board; - BattleshipCell cell = (BattleshipCell) bsBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule. + * + * @param board board to check contradiction + * @param puzzleElement equivalent {@link PuzzleElement} + * @return null if the transition contains a contradiction at the specified {@link + * PuzzleElement}, otherwise return a no contradiction message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + BattleshipBoard bsBoard = (BattleshipBoard) board; + BattleshipCell cell = (BattleshipCell) bsBoard.getPuzzleElement(puzzleElement); - // rule only applies to battleship cells - if (!BattleshipType.isShip(cell.getType())) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } + // rule only applies to battleship cells + if (!BattleshipType.isShip(cell.getType())) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } - // check orthogonally adjacent cells - List orthoAdjCells = bsBoard.getAdjOrthogonals(cell); + // check orthogonally adjacent cells + List orthoAdjCells = bsBoard.getAdjOrthogonals(cell); - BattleshipCell up = orthoAdjCells.get(0); - BattleshipCell right = orthoAdjCells.get(1); - BattleshipCell down = orthoAdjCells.get(2); - BattleshipCell left = orthoAdjCells.get(3); + BattleshipCell up = orthoAdjCells.get(0); + BattleshipCell right = orthoAdjCells.get(1); + BattleshipCell down = orthoAdjCells.get(2); + BattleshipCell left = orthoAdjCells.get(3); - boolean isVertical = - (up != null && BattleshipType.isShip(up.getData())) - || (down != null && BattleshipType.isShip(down.getData())); + boolean isVertical = + (up != null && BattleshipType.isShip(up.getData())) + || (down != null && BattleshipType.isShip(down.getData())); - boolean isHorizontal = - (left != null && BattleshipType.isShip(left.getData())) - || (right != null && BattleshipType.isShip(right.getData())); + boolean isHorizontal = + (left != null && BattleshipType.isShip(left.getData())) + || (right != null && BattleshipType.isShip(right.getData())); - // ships cannot be both vertical and horizontal - if (isVertical && isHorizontal) { - return null; - } + // ships cannot be both vertical and horizontal + if (isVertical && isHorizontal) { + return null; + } - // check diagonally adjacent cells - List diagAdjCells = bsBoard.getAdjDiagonals(cell); + // check diagonally adjacent cells + List diagAdjCells = bsBoard.getAdjDiagonals(cell); - BattleshipCell upRight = diagAdjCells.get(0); - BattleshipCell downRight = diagAdjCells.get(1); - BattleshipCell downLeft = diagAdjCells.get(2); - BattleshipCell upLeft = diagAdjCells.get(3); + BattleshipCell upRight = diagAdjCells.get(0); + BattleshipCell downRight = diagAdjCells.get(1); + BattleshipCell downLeft = diagAdjCells.get(2); + BattleshipCell upLeft = diagAdjCells.get(3); - // diagonally adjacent cells must be water - if (upRight != null && BattleshipType.isShip(upRight.getData())) { - return null; - } - if (downRight != null && BattleshipType.isShip(downRight.getData())) { - return null; - } - if (downLeft != null && BattleshipType.isShip(downLeft.getData())) { - return null; - } - if (upLeft != null && BattleshipType.isShip(upLeft.getData())) { - return null; - } + // diagonally adjacent cells must be water + if (upRight != null && BattleshipType.isShip(upRight.getData())) { + return null; + } + if (downRight != null && BattleshipType.isShip(downRight.getData())) { + return null; + } + if (downLeft != null && BattleshipType.isShip(downLeft.getData())) { + return null; + } + if (upLeft != null && BattleshipType.isShip(upLeft.getData())) { + return null; + } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java index ab9a88525..670a136a4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java @@ -8,37 +8,38 @@ public class ContinueShipDirectRule extends DirectRule { - public ContinueShipDirectRule() { - super( - "BTSP-BASC-0001", - "Continue Ship", - "", - "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); - } + public ContinueShipDirectRule() { + super( + "BTSP-BASC-0001", + "Continue Ship", + "", + "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should be overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should be overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java index c4f4432d7..9bc4065aa 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java @@ -14,94 +14,95 @@ public class FinishWithShipsDirectRule extends DirectRule { - public FinishWithShipsDirectRule() { - super( - "BTSP-BASC-0002", - "Finish with Ships", - "The number of undetermined squares is equal to the number " - + "of segments remaining for each clue.", - "edu/rpi/legup/images/battleship/rules/finishShip.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should be overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message. - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - BattleshipBoard initBoard = (BattleshipBoard) transition.getParents().get(0).getBoard(); - BattleshipCell initCell = (BattleshipCell) initBoard.getPuzzleElement(puzzleElement); - BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); - BattleshipCell finalCell = (BattleshipCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == BattleshipType.UNKNOWN - && BattleshipType.isShip(finalCell.getType()))) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; - } - - if (isForced(initBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() - + ": This cell is not forced to" - + "be a ship segment."; + public FinishWithShipsDirectRule() { + super( + "BTSP-BASC-0002", + "Finish with Ships", + "The number of undetermined squares is equal to the number " + + "of segments remaining for each clue.", + "edu/rpi/legup/images/battleship/rules/finishShip.png"); } - } - private boolean isForced(BattleshipBoard board, BattleshipCell cell) { - Point loc = cell.getLocation(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should be overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message. + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + BattleshipBoard initBoard = (BattleshipBoard) transition.getParents().get(0).getBoard(); + BattleshipCell initCell = (BattleshipCell) initBoard.getPuzzleElement(puzzleElement); + BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); + BattleshipCell finalCell = (BattleshipCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == BattleshipType.UNKNOWN + && BattleshipType.isShip(finalCell.getType()))) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; + } - // count the number of ship segments and unknowns in the row - List row = board.getRow(loc.y); - int rowCount = 0; - for (BattleshipCell c : row) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { - rowCount++; - } + if (isForced(initBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This cell is not forced to" + + "be a ship segment."; + } } - // count the number of ship segments and unknowns in the column - List col = board.getColumn(loc.x); - int colCount = 0; - for (BattleshipCell c : col) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { - colCount++; - } - } + private boolean isForced(BattleshipBoard board, BattleshipCell cell) { + Point loc = cell.getLocation(); + + // count the number of ship segments and unknowns in the row + List row = board.getRow(loc.y); + int rowCount = 0; + for (BattleshipCell c : row) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { + rowCount++; + } + } - // compare the counts with the clues - BattleshipClue east = board.getEast().get(loc.y); - BattleshipClue south = board.getSouth().get(loc.x); + // count the number of ship segments and unknowns in the column + List col = board.getColumn(loc.x); + int colCount = 0; + for (BattleshipCell c : col) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { + colCount++; + } + } - return rowCount <= east.getData() && colCount <= south.getData(); - } + // compare the counts with the clues + BattleshipClue east = board.getEast().get(loc.y); + BattleshipClue south = board.getSouth().get(loc.x); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board. - * @return default board or null if this rule cannot be applied to this tree node. - */ - @Override - public Board getDefaultBoard(TreeNode node) { - BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); - for (PuzzleElement element : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) element; - if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { - cell.setData(BattleshipType.SHIP_UNKNOWN); - board.addModifiedData(cell); - } + return rowCount <= east.getData() && colCount <= south.getData(); } - if (board.getModifiedData().isEmpty()) { - return null; - } else { - return board; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board. + * @return default board or null if this rule cannot be applied to this tree node. + */ + @Override + public Board getDefaultBoard(TreeNode node) { + BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); + for (PuzzleElement element : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) element; + if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { + cell.setData(BattleshipType.SHIP_UNKNOWN); + board.addModifiedData(cell); + } + } + + if (board.getModifiedData().isEmpty()) { + return null; + } else { + return board; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java index 6f32b35a6..99e5925e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java @@ -8,37 +8,38 @@ public class FinishWithWaterDirectRule extends DirectRule { - public FinishWithWaterDirectRule() { - super( - "BTSP-BASC-0003", - "Finish with Water", - "", - "edu/rpi/legup/images/battleship/rules/finishWater.png"); - } + public FinishWithWaterDirectRule() { + super( + "BTSP-BASC-0003", + "Finish with Water", + "", + "edu/rpi/legup/images/battleship/rules/finishWater.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java index 05ed95fbd..e8cfebb90 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java @@ -6,25 +6,25 @@ public class IncompleteShipContradictionRule extends ContradictionRule { - public IncompleteShipContradictionRule() { - super( - "BTSP-CONT-0002", - "Incomplete Ship", - "", - "edu/rpi/legup/images/battleship/contradictions/IncompleteShip.png"); - } + public IncompleteShipContradictionRule() { + super( + "BTSP-CONT-0002", + "Incomplete Ship", + "", + "edu/rpi/legup/images/battleship/contradictions/IncompleteShip.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java index afc4f8fc0..93079fb71 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java @@ -8,63 +8,63 @@ import java.util.List; public class SegmentTypeCaseRule extends CaseRule { - public SegmentTypeCaseRule() { - super( - "BTSP-CASE-0001", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/cases/SegmentType.png"); - } + public SegmentTypeCaseRule() { + super( + "BTSP-CASE-0001", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/cases/SegmentType.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java index f95625e5e..8576ef722 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java @@ -8,37 +8,38 @@ public class SegmentTypeDirectRule extends DirectRule { - public SegmentTypeDirectRule() { - super( - "BTSP-BASC-0004", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); - } + public SegmentTypeDirectRule() { + super( + "BTSP-BASC-0004", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java index 3033bafbd..da8f33cc2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java @@ -9,63 +9,63 @@ public class ShipLocationCaseRule extends CaseRule { - public ShipLocationCaseRule() { - super( - "BTSP-CASE-0002", - "Ship Location", - "", - "edu/rpi/legup/images/battleship/cases/ShipLocations.png"); - } + public ShipLocationCaseRule() { + super( + "BTSP-CASE-0002", + "Ship Location", + "", + "edu/rpi/legup/images/battleship/cases/ShipLocations.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java index 3696049eb..3c123d7c1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java @@ -9,63 +9,63 @@ public class ShipOrWaterCaseRule extends CaseRule { - public ShipOrWaterCaseRule() { - super( - "BTSP-CASE-0003", - "Ship or Water", - "", - "edu/rpi/legup/images/battleship/cases/ShipOrWater.png"); - } + public ShipOrWaterCaseRule() { + super( + "BTSP-CASE-0003", + "Ship or Water", + "", + "edu/rpi/legup/images/battleship/cases/ShipOrWater.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java index 5a1821be0..d26c3ed29 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java @@ -8,37 +8,38 @@ public class SurroundShipDirectRule extends DirectRule { - public SurroundShipDirectRule() { - super( - "BTSP-BASC-0005", - "Surround Ship", - "", - "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); - } + public SurroundShipDirectRule() { + super( + "BTSP-BASC-0005", + "Surround Ship", + "", + "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java index a3dbba9c4..d10e086d2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java @@ -6,25 +6,25 @@ public class TooFewInFleetContradictionRule extends ContradictionRule { - public TooFewInFleetContradictionRule() { - super( - "BTSP-CONT-0003", - "Too Few in Fleet", - "", - "edu/rpi/legup/images/battleship/contradictions/too_few_in_fleet.png"); - } + public TooFewInFleetContradictionRule() { + super( + "BTSP-CONT-0003", + "Too Few in Fleet", + "", + "edu/rpi/legup/images/battleship/contradictions/too_few_in_fleet.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java index b4814796d..382ba6e39 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java @@ -6,25 +6,25 @@ public class TooFewRowColContradictionRule extends ContradictionRule { - public TooFewRowColContradictionRule() { - super( - "BTSP-CONT-0004", - "Too few in row/col", - "", - "edu/rpi/legup/images/battleship/contradictions/too_few_segments.png"); - } + public TooFewRowColContradictionRule() { + super( + "BTSP-CONT-0004", + "Too few in row/col", + "", + "edu/rpi/legup/images/battleship/contradictions/too_few_segments.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java index a375b63e2..d58701c0b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java @@ -6,25 +6,25 @@ public class TooManyInFleetContradictionRule extends ContradictionRule { - public TooManyInFleetContradictionRule() { - super( - "BTSP-CONT-0005", - "Too Many in Fleet", - "", - "edu/rpi/legup/images/battleship/contradictions/too_many_in_fleet.png"); - } + public TooManyInFleetContradictionRule() { + super( + "BTSP-CONT-0005", + "Too Many in Fleet", + "", + "edu/rpi/legup/images/battleship/contradictions/too_many_in_fleet.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java index abb72b5ca..27caa0524 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java @@ -6,25 +6,25 @@ public class TooManyRowColContradiction extends ContradictionRule { - public TooManyRowColContradiction() { - super( - "BTSP-CONT-0006", - "Too Many row/col", - "", - "edu/rpi/legup/images/battleship/contradictions/too_many_segments.png"); - } + public TooManyRowColContradiction() { + super( + "BTSP-CONT-0006", + "Too Many row/col", + "", + "edu/rpi/legup/images/battleship/contradictions/too_many_segments.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java index 28d2a2790..79574caa6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java @@ -6,60 +6,60 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Fillapix extends Puzzle { - /** Fillapix Constructor */ - public Fillapix() { - super(); + /** Fillapix Constructor */ + public Fillapix() { + super(); - this.name = "Fillapix"; + this.name = "Fillapix"; - this.importer = new FillapixImporter(this); - this.exporter = new FillapixExporter(this); + this.importer = new FillapixImporter(this); + this.exporter = new FillapixExporter(this); - this.factory = new FillapixCellFactory(); - } - - /** Initializes the game board */ - @Override - public void initializeView() { - boardView = new FillapixView((FillapixBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + this.factory = new FillapixCellFactory(); + } - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** Initializes the game board */ + @Override + public void initializeView() { + boardView = new FillapixView((FillapixBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - @Override - /** - * Determines if the given dimensions are valid for Fillapix - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Fillapix, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return super.isValidDimensions(rows, columns); - } + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - public boolean isBoardComplete(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(fillapixBoard) == null) { - return false; - } + @Override + /** + * Determines if the given dimensions are valid for Fillapix + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Fillapix, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return super.isValidDimensions(rows, columns); } - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN) { - return false; - } + + @Override + public boolean isBoardComplete(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(fillapixBoard) == null) { + return false; + } + } + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN) { + return false; + } + } + return true; } - return true; - } - @Override - public void onBoardChange(Board board) {} + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java index eaf408fcd..a6672bd4f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java @@ -6,62 +6,62 @@ import java.util.logging.Logger; public class FillapixBoard extends GridBoard { - private static final Logger LOGGER = Logger.getLogger(FillapixBoard.class.getName()); + private static final Logger LOGGER = Logger.getLogger(FillapixBoard.class.getName()); - public FillapixBoard(int width, int height) { - super(width, height); - } - - public FillapixBoard(int size) { - this(size, size); - } - - public FillapixCell getCell(int x, int y) { - return (FillapixCell) super.getCell(x, y); - } - - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - @Override - public FillapixBoard copy() { - FillapixBoard copy = new FillapixBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + public FillapixBoard(int width, int height) { + super(width, height); } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + public FillapixBoard(int size) { + this(size, size); } - return copy; - } - /** - * Finds the number of cells that match the specified type around and on a particular cell - * - * @param cell the cell we're looking around - * @param type the CellState whether it's black, white, or unknown - * @return integer number of cells that match specified type - */ - public int getNumCells(FillapixCell cell, FillapixCellType type) { - Point loc = cell.getLocation(); + public FillapixCell getCell(int x, int y) { + return (FillapixCell) super.getCell(x, y); + } - int numCells = 0; - for (int i = -1; i < 2; i++) { - for (int j = -1; j < 2; j++) { - if (loc.x + i > dimension.width || loc.y + j > dimension.height) { - continue; + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + @Override + public FillapixBoard copy() { + FillapixBoard copy = new FillapixBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } - FillapixCell c = getCell(loc.x + i, loc.y + j); - if (c != null && c.getType() == type) { - numCells++; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } - } + return copy; } - return numCells; - } + /** + * Finds the number of cells that match the specified type around and on a particular cell + * + * @param cell the cell we're looking around + * @param type the CellState whether it's black, white, or unknown + * @return integer number of cells that match specified type + */ + public int getNumCells(FillapixCell cell, FillapixCellType type) { + Point loc = cell.getLocation(); + + int numCells = 0; + for (int i = -1; i < 2; i++) { + for (int j = -1; j < 2; j++) { + if (loc.x + i > dimension.width || loc.y + j > dimension.height) { + continue; + } + FillapixCell c = getCell(loc.x + i, loc.y + j); + if (c != null && c.getType() == type) { + numCells++; + } + } + } + + return numCells; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java index 5051eecdf..a9e5aa2df 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java @@ -8,97 +8,98 @@ public class FillapixCell extends GridCell implements Comparable { - public static final int DEFAULT_VALUE = 10; + public static final int DEFAULT_VALUE = 10; - public FillapixCell(int value, Point location) { - super(value, location); - } + public FillapixCell(int value, Point location) { + super(value, location); + } - public int getNumber() { - int temp = (data % 100); - return temp == 10 ? -1 : temp; - } + public int getNumber() { + int temp = (data % 100); + return temp == 10 ? -1 : temp; + } - public void setNumber(int number) { - int temp = number == -1 ? 10 : number; - data = (data / 100) * 100 + temp; - } + public void setNumber(int number) { + int temp = number == -1 ? 10 : number; + data = (data / 100) * 100 + temp; + } - public FillapixCellType getType() { - switch (data / 100) { - case 0: - return FillapixCellType.UNKNOWN; - case 1: - return FillapixCellType.BLACK; - default: - return FillapixCellType.WHITE; + public FillapixCellType getType() { + switch (data / 100) { + case 0: + return FillapixCellType.UNKNOWN; + case 1: + return FillapixCellType.BLACK; + default: + return FillapixCellType.WHITE; + } } - } - public void setCellType(FillapixCellType type) { - data = type.value * 100 + (data % 100); - } + public void setCellType(FillapixCellType type) { + data = type.value * 100 + (data % 100); + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "FPIX-PLAC-0001": - this.setCellType(FillapixCellType.BLACK); - break; - case "FPIX-PLAC-0002": - this.setCellType(FillapixCellType.WHITE); - break; - case "FPIX-UNPL-0001": - int n = this.getNumber(); - switch (m.getButton()) { - case MouseEvent.BUTTON1: - n++; - break; - case MouseEvent.BUTTON3: - n--; - break; - } - if (n > 9) { - n = 0; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "FPIX-PLAC-0001": + this.setCellType(FillapixCellType.BLACK); + break; + case "FPIX-PLAC-0002": + this.setCellType(FillapixCellType.WHITE); + break; + case "FPIX-UNPL-0001": + int n = this.getNumber(); + switch (m.getButton()) { + case MouseEvent.BUTTON1: + n++; + break; + case MouseEvent.BUTTON3: + n--; + break; + } + if (n > 9) { + n = 0; + } + if (n < 0) { + n = 9; + } + this.setNumber(n); + break; + default: + this.setCellType(FillapixCellType.UNKNOWN); + this.data = -1; + break; } - if (n < 0) { - n = 9; - } - this.setNumber(n); - break; - default: - this.setCellType(FillapixCellType.UNKNOWN); - this.data = -1; - break; } - } - /** - * Performs a deep copy on the FillapixCell - * - * @return a new copy of the FillapixCell that is independent of this one - */ - @Override - public FillapixCell copy() { - FillapixCell cell = new FillapixCell(data, (Point) location.clone()); - cell.setIndex(index); - cell.setModifiable(isModifiable); - return cell; - } + /** + * Performs a deep copy on the FillapixCell + * + * @return a new copy of the FillapixCell that is independent of this one + */ + @Override + public FillapixCell copy() { + FillapixCell cell = new FillapixCell(data, (Point) location.clone()); + cell.setIndex(index); + cell.setModifiable(isModifiable); + return cell; + } - public boolean equals(FillapixCell otherCell) { - // return this.location.equals(otherCell.location) && this.index == otherCell.index && - // this.data == otherCell.data; - // return this.index == otherCell.index && this.data == otherCell.data; - // return this.index == otherCell.index; - return this.location.x == otherCell.location.x && this.location.y == otherCell.location.y; - } + public boolean equals(FillapixCell otherCell) { + // return this.location.equals(otherCell.location) && this.index == otherCell.index + // && + // this.data == otherCell.data; + // return this.index == otherCell.index && this.data == otherCell.data; + // return this.index == otherCell.index; + return this.location.x == otherCell.location.x && this.location.y == otherCell.location.y; + } - public int compareTo(FillapixCell otherCell) { - return this.index - otherCell.index; - } + public int compareTo(FillapixCell otherCell) { + return this.index - otherCell.index; + } - public int hashCode() { - return Objects.hash(this.index); - } + public int hashCode() { + return Objects.hash(this.index); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java index 45182c88f..f59c0df47 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java @@ -5,44 +5,44 @@ import java.awt.event.MouseEvent; public class FillapixCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement puzzleElement) { - FillapixCell cell = (FillapixCell) puzzleElement; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getType() == FillapixCellType.UNKNOWN) { - cell.setCellType(FillapixCellType.BLACK); - } else { - if (cell.getType() == FillapixCellType.BLACK) { - cell.setCellType(FillapixCellType.WHITE); - } else { - if (cell.getType() == FillapixCellType.WHITE) { - cell.setCellType(FillapixCellType.UNKNOWN); + @Override + public void changeCell(MouseEvent e, PuzzleElement puzzleElement) { + FillapixCell cell = (FillapixCell) puzzleElement; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getType() == FillapixCellType.UNKNOWN) { + cell.setCellType(FillapixCellType.BLACK); + } else { + if (cell.getType() == FillapixCellType.BLACK) { + cell.setCellType(FillapixCellType.WHITE); + } else { + if (cell.getType() == FillapixCellType.WHITE) { + cell.setCellType(FillapixCellType.UNKNOWN); + } + } + } } - } - } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getType() == FillapixCellType.UNKNOWN) { - cell.setCellType(FillapixCellType.WHITE); } else { - if (cell.getType() == FillapixCellType.BLACK) { - cell.setCellType(FillapixCellType.UNKNOWN); - } else { - if (cell.getType() == FillapixCellType.WHITE) { - cell.setCellType(FillapixCellType.BLACK); + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getType() == FillapixCellType.UNKNOWN) { + cell.setCellType(FillapixCellType.WHITE); + } else { + if (cell.getType() == FillapixCellType.BLACK) { + cell.setCellType(FillapixCellType.UNKNOWN); + } else { + if (cell.getType() == FillapixCellType.WHITE) { + cell.setCellType(FillapixCellType.BLACK); + } + } + } } - } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java index 37b4130b2..9f689bc96 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java @@ -10,65 +10,66 @@ import org.w3c.dom.Node; public class FillapixCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public FillapixCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Fillapix Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public FillapixCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Fillapix Factory: unknown puzzleElement puzzleElement"); + } - FillapixBoard fillapixBoard = (FillapixBoard) board; - int width = fillapixBoard.getWidth(); - int height = fillapixBoard.getHeight(); + FillapixBoard fillapixBoard = (FillapixBoard) board; + int width = fillapixBoard.getWidth(); + int height = fillapixBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Fillapix Factory: cell location out of bounds"); - } - if (value / 100 > 2 || value % 100 > 10) { - throw new InvalidFileFormatException("Fillapix Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "Fillapix Factory: cell location out of bounds"); + } + if (value / 100 > 2 || value % 100 > 10) { + throw new InvalidFileFormatException("Fillapix Factory: cell unknown value"); + } - FillapixCell cell = new FillapixCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Fillapix Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Fillapix Factory: could not find attribute(s)"); + FillapixCell cell = new FillapixCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Fillapix Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Fillapix Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - FillapixCell cell = (FillapixCell) puzzleElement; - Point loc = cell.getLocation(); + FillapixCell cell = (FillapixCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java index 659cebb1b..28a263467 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java @@ -1,17 +1,17 @@ package edu.rpi.legup.puzzle.fillapix; public enum FillapixCellType { - UNKNOWN(0), - BLACK(1), - WHITE(2); + UNKNOWN(0), + BLACK(1), + WHITE(2); - public int value; + public int value; - FillapixCellType(int value) { - this.value = value; - } + FillapixCellType(int value) { + this.value = value; + } - public String toString() { - return super.toString().toLowerCase(); - } + public String toString() { + return super.toString().toLowerCase(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java index 97b864bc9..47465a522 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java @@ -4,58 +4,59 @@ import java.awt.*; public class FillapixElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); - public FillapixElementView(FillapixCell cell) { - super(cell); - } + public FillapixElementView(FillapixCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public FillapixCell getPuzzleElement() { - return (FillapixCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public FillapixCell getPuzzleElement() { + return (FillapixCell) super.getPuzzleElement(); + } - /** - * Draws the fillapix puzzleElement to the screen - * - * @param graphics2D graphics object - */ - @Override - public void drawElement(Graphics2D graphics2D) { - FillapixCell cell = (FillapixCell) puzzleElement; - FillapixCellType type = cell.getType(); - graphics2D.setStroke(new BasicStroke(1)); - switch (type) { - case UNKNOWN: - graphics2D.setColor(GRAY_COLOR); - break; - case BLACK: + /** + * Draws the fillapix puzzleElement to the screen + * + * @param graphics2D graphics object + */ + @Override + public void drawElement(Graphics2D graphics2D) { + FillapixCell cell = (FillapixCell) puzzleElement; + FillapixCellType type = cell.getType(); + graphics2D.setStroke(new BasicStroke(1)); + switch (type) { + case UNKNOWN: + graphics2D.setColor(GRAY_COLOR); + break; + case BLACK: + graphics2D.setColor(BLACK_COLOR); + break; + default: + graphics2D.setColor(WHITE_COLOR); + break; + } + graphics2D.fillRect(location.x, location.y, size.width, size.height); + if (cell.getNumber() >= 0 && cell.getNumber() < 10) { + graphics2D.setColor(type == FillapixCellType.WHITE ? BLACK_COLOR : WHITE_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getNumber()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } graphics2D.setColor(BLACK_COLOR); - break; - default: - graphics2D.setColor(WHITE_COLOR); - break; - } - graphics2D.fillRect(location.x, location.y, size.width, size.height); - if (cell.getNumber() >= 0 && cell.getNumber() < 10) { - graphics2D.setColor(type == FillapixCellType.WHITE ? BLACK_COLOR : WHITE_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getNumber()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); + graphics2D.drawRect(location.x, location.y, size.width, size.height); } - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java index 1df8157cf..ffabd8762 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java @@ -6,34 +6,34 @@ public class FillapixExporter extends PuzzleExporter { - public FillapixExporter(Fillapix fillapix) { - super(fillapix); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - FillapixBoard board; - if (puzzle.getTree() != null) { - board = (FillapixBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (FillapixBoard) puzzle.getBoardView().getBoard(); + public FillapixExporter(Fillapix fillapix) { + super(fillapix); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + FillapixBoard board; + if (puzzle.getTree() != null) { + board = (FillapixBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (FillapixBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) puzzleElement; - if (cell.getNumber() != -1 || cell.getType() != FillapixCellType.UNKNOWN) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) puzzleElement; + if (cell.getNumber() != -1 || cell.getType() != FillapixCellType.UNKNOWN) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java index 5877fd25b..d16bc8219 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java @@ -8,110 +8,116 @@ import org.w3c.dom.NodeList; public class FillapixImporter extends PuzzleImporter { - public FillapixImporter(Fillapix fillapix) { - super(fillapix); - } + public FillapixImporter(Fillapix fillapix) { + super(fillapix); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be made - */ - @Override - public void initializeBoard(int rows, int columns) { - FillapixBoard fillapixBoard = new FillapixBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be made + */ + @Override + public void initializeBoard(int rows, int columns) { + FillapixBoard fillapixBoard = new FillapixBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - FillapixCell cell = new FillapixCell(FillapixCellType.UNKNOWN.value, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setNumber(FillapixCell.DEFAULT_VALUE); - cell.setModifiable(true); - fillapixBoard.setCell(x, y, cell); - } + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + FillapixCell cell = + new FillapixCell(FillapixCellType.UNKNOWN.value, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setNumber(FillapixCell.DEFAULT_VALUE); + cell.setModifiable(true); + fillapixBoard.setCell(x, y, cell); + } + } + puzzle.setCurrentBoard(fillapixBoard); } - puzzle.setCurrentBoard(fillapixBoard); - } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Fillapix Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Fillapix Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Fillapix Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Fillapix Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - FillapixBoard fillapixBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - fillapixBoard = new FillapixBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - fillapixBoard = new FillapixBoard(width, height); - } - } + FillapixBoard fillapixBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + fillapixBoard = new FillapixBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + fillapixBoard = new FillapixBoard(width, height); + } + } - if (fillapixBoard == null) { - throw new InvalidFileFormatException("Fillapix Importer: invalid board dimensions"); - } + if (fillapixBoard == null) { + throw new InvalidFileFormatException("Fillapix Importer: invalid board dimensions"); + } - int width = fillapixBoard.getWidth(); - int height = fillapixBoard.getHeight(); + int width = fillapixBoard.getWidth(); + int height = fillapixBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - FillapixCell cell = - (FillapixCell) puzzle.getFactory().importCell(elementDataList.item(i), fillapixBoard); - Point loc = cell.getLocation(); - cell.setModifiable(true); - cell.setGiven(true); - fillapixBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + FillapixCell cell = + (FillapixCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), fillapixBoard); + Point loc = cell.getLocation(); + cell.setModifiable(true); + cell.setGiven(true); + fillapixBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (fillapixBoard.getCell(x, y) == null) { - FillapixCell cell = new FillapixCell(FillapixCell.DEFAULT_VALUE, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - fillapixBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (fillapixBoard.getCell(x, y) == null) { + FillapixCell cell = + new FillapixCell(FillapixCell.DEFAULT_VALUE, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + fillapixBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(fillapixBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Fillapix Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(fillapixBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Fillapix Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Fillapix cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Fillapix cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java index 6eeb4bd25..571a0c7f7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java @@ -8,231 +8,234 @@ public class FillapixUtilities { - public static boolean isForcedBlack(FillapixBoard board, FillapixCell cell) { - TooFewBlackCellsContradictionRule tooManyBlackCells = new TooFewBlackCellsContradictionRule(); - FillapixBoard whiteCaseBoard = board.copy(); - FillapixCell whiteCell = (FillapixCell) whiteCaseBoard.getPuzzleElement(cell); - whiteCell.setCellType(FillapixCellType.WHITE); - ArrayList adjCells = getAdjacentCells(whiteCaseBoard, whiteCell); - for (FillapixCell adjCell : adjCells) { - if (tooManyBlackCells.checkContradictionAt(whiteCaseBoard, adjCell) == null) { - return true; - } - } - return false; - } - - public static boolean isForcedWhite(FillapixBoard board, FillapixCell cell) { - TooManyBlackCellsContradictionRule tooManyBlackCells = new TooManyBlackCellsContradictionRule(); - FillapixBoard blackCaseBoard = board.copy(); - FillapixCell blackCell = (FillapixCell) blackCaseBoard.getPuzzleElement(cell); - blackCell.setCellType(FillapixCellType.BLACK); - ArrayList adjCells = getAdjacentCells(blackCaseBoard, blackCell); - for (FillapixCell adjCell : adjCells) { - if (tooManyBlackCells.checkContradictionAt(blackCaseBoard, adjCell) == null) { - return true; - } + public static boolean isForcedBlack(FillapixBoard board, FillapixCell cell) { + TooFewBlackCellsContradictionRule tooManyBlackCells = + new TooFewBlackCellsContradictionRule(); + FillapixBoard whiteCaseBoard = board.copy(); + FillapixCell whiteCell = (FillapixCell) whiteCaseBoard.getPuzzleElement(cell); + whiteCell.setCellType(FillapixCellType.WHITE); + ArrayList adjCells = getAdjacentCells(whiteCaseBoard, whiteCell); + for (FillapixCell adjCell : adjCells) { + if (tooManyBlackCells.checkContradictionAt(whiteCaseBoard, adjCell) == null) { + return true; + } + } + return false; } - return false; - } - public static boolean isComplete(FillapixBoard board, FillapixCell cell) { - int cellNum = cell.getNumber(); - int cellTouchBlack = 0; - ArrayList adjCells = getAdjacentCells(board, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - cellTouchBlack++; - } + public static boolean isForcedWhite(FillapixBoard board, FillapixCell cell) { + TooManyBlackCellsContradictionRule tooManyBlackCells = + new TooManyBlackCellsContradictionRule(); + FillapixBoard blackCaseBoard = board.copy(); + FillapixCell blackCell = (FillapixCell) blackCaseBoard.getPuzzleElement(cell); + blackCell.setCellType(FillapixCellType.BLACK); + ArrayList adjCells = getAdjacentCells(blackCaseBoard, blackCell); + for (FillapixCell adjCell : adjCells) { + if (tooManyBlackCells.checkContradictionAt(blackCaseBoard, adjCell) == null) { + return true; + } + } + return false; } - return cellNum == cellTouchBlack; - } - public static boolean hasEmptyAdjacent(FillapixBoard board, FillapixCell cell) { - ArrayList adjCells = getAdjacentCells(board, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - return true; - } + public static boolean isComplete(FillapixBoard board, FillapixCell cell) { + int cellNum = cell.getNumber(); + int cellTouchBlack = 0; + ArrayList adjCells = getAdjacentCells(board, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + cellTouchBlack++; + } + } + return cellNum == cellTouchBlack; } - return false; - } - /** Gets all cells adjacent to a specific cell. The cell itself will be included. */ - public static ArrayList getAdjacentCells(FillapixBoard board, FillapixCell cell) { - ArrayList adjCells = new ArrayList(); - Point cellLoc = cell.getLocation(); - for (int i = -1; i <= 1; i++) { - for (int j = -1; j <= 1; j++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; + public static boolean hasEmptyAdjacent(FillapixBoard board, FillapixCell cell) { + ArrayList adjCells = getAdjacentCells(board, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + return true; + } } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } + return false; } - return adjCells; - } - /** - * Gets all cells that are contained in the square defined as having 'distance' cells between the - * center and the outer wall. For example, distance = 1: - * - *

|X|X|X|X|X| - * - *

|X| | | |X| - * - *

|X| |O| |X| - * - *

|X| | | |X| - * - *

|X|X|X|X|X| - * - *

O is 'cell', and all 'X' will be returned in the ArrayList - */ - public static ArrayList getCellsAtDistance( - FillapixBoard board, FillapixCell cell, int distance) { - ArrayList adjCells = new ArrayList(); - Point cellLoc = cell.getLocation(); - int i = 0, j = 0; - // top line - for (i = cellLoc.x - (distance), j = cellLoc.y - (distance + 1); - i <= cellLoc.x + (distance + 1); - i++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // right line - for (i = cellLoc.x + (distance + 1), j = cellLoc.y - (distance); - j <= cellLoc.y + (distance + 1); - j++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // bottom line - for (i = cellLoc.x + (distance), j = cellLoc.y + (distance + 1); - i <= cellLoc.x - (distance + 1); - i--) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // left line - for (i = cellLoc.x - (distance + 1), j = cellLoc.y + (distance); - j <= cellLoc.y - (distance + 1); - j--) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); + /** Gets all cells adjacent to a specific cell. The cell itself will be included. */ + public static ArrayList getAdjacentCells(FillapixBoard board, FillapixCell cell) { + ArrayList adjCells = new ArrayList(); + Point cellLoc = cell.getLocation(); + for (int i = -1; i <= 1; i++) { + for (int j = -1; j <= 1; j++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + } + return adjCells; } - return adjCells; - } + /** + * Gets all cells that are contained in the square defined as having 'distance' cells between + * the center and the outer wall. For example, distance = 1: + * + *

|X|X|X|X|X| + * + *

|X| | | |X| + * + *

|X| |O| |X| + * + *

|X| | | |X| + * + *

|X|X|X|X|X| + * + *

O is 'cell', and all 'X' will be returned in the ArrayList + */ + public static ArrayList getCellsAtDistance( + FillapixBoard board, FillapixCell cell, int distance) { + ArrayList adjCells = new ArrayList(); + Point cellLoc = cell.getLocation(); + int i = 0, j = 0; + // top line + for (i = cellLoc.x - (distance), j = cellLoc.y - (distance + 1); + i <= cellLoc.x + (distance + 1); + i++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // right line + for (i = cellLoc.x + (distance + 1), j = cellLoc.y - (distance); + j <= cellLoc.y + (distance + 1); + j++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // bottom line + for (i = cellLoc.x + (distance), j = cellLoc.y + (distance + 1); + i <= cellLoc.x - (distance + 1); + i--) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // left line + for (i = cellLoc.x - (distance + 1), j = cellLoc.y + (distance); + j <= cellLoc.y - (distance + 1); + j--) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } - /** - * Finds all possible combinations of chosenNumObj items can be chosen from - * totalNumObj total items. For example, if 1 item is chosen from 2 possible items, the - * combinations are: - * - *

[ [true,false], [false,true] ]
- * - * @param totalNumItems the total number of items that can possibly be chosen - * @param chosenNumItems the number of items to be chosen - * @return an ArrayList of Boolean arrays. Each index in the ArrayList represents a distinct - * combination. Each Boolean array will be totalNumItems long and each index will - * be true if the corresponding item is included in that combination, and - * false otherwise. - */ - public static ArrayList getCombinations(int chosenNumItems, int totalNumItems) { - ArrayList combinations = new ArrayList(); + return adjCells; + } - // calculate all combinations - boolean[] array = new boolean[totalNumItems]; - recurseCombinations(combinations, 0, chosenNumItems, 0, totalNumItems, array); + /** + * Finds all possible combinations of chosenNumObj items can be chosen from + * totalNumObj total items. For example, if 1 item is chosen from 2 possible items, the + * combinations are: + * + *
[ [true,false], [false,true] ]
+ * + * @param totalNumItems the total number of items that can possibly be chosen + * @param chosenNumItems the number of items to be chosen + * @return an ArrayList of Boolean arrays. Each index in the ArrayList represents a distinct + * combination. Each Boolean array will be totalNumItems long and each index + * will be true if the corresponding item is included in that combination, and + * + * false otherwise. + */ + public static ArrayList getCombinations(int chosenNumItems, int totalNumItems) { + ArrayList combinations = new ArrayList(); - return combinations; - } + // calculate all combinations + boolean[] array = new boolean[totalNumItems]; + recurseCombinations(combinations, 0, chosenNumItems, 0, totalNumItems, array); - private static void recurseCombinations( - ArrayList result, - int curIndex, - int maxBlack, - int numBlack, - int len, - boolean[] workingArray) { - if (curIndex == len) { - // complete, but not valid solution - if (numBlack != maxBlack) { - return; - } - // complete and valid solution - result.add(workingArray.clone()); - return; - } - // there is no chance of completing the required number of solutions, so quit - if (len - curIndex < maxBlack - numBlack) { - return; + return combinations; } - if (numBlack < maxBlack) { - workingArray[curIndex] = true; - recurseCombinations(result, curIndex + 1, maxBlack, numBlack + 1, len, workingArray); + private static void recurseCombinations( + ArrayList result, + int curIndex, + int maxBlack, + int numBlack, + int len, + boolean[] workingArray) { + if (curIndex == len) { + // complete, but not valid solution + if (numBlack != maxBlack) { + return; + } + // complete and valid solution + result.add(workingArray.clone()); + return; + } + // there is no chance of completing the required number of solutions, so quit + if (len - curIndex < maxBlack - numBlack) { + return; + } + + if (numBlack < maxBlack) { + workingArray[curIndex] = true; + recurseCombinations(result, curIndex + 1, maxBlack, numBlack + 1, len, workingArray); + } + workingArray[curIndex] = false; + recurseCombinations(result, curIndex + 1, maxBlack, numBlack, len, workingArray); } - workingArray[curIndex] = false; - recurseCombinations(result, curIndex + 1, maxBlack, numBlack, len, workingArray); - } - public static boolean checkBoardForContradiction(FillapixBoard board) { - ContradictionRule tooManyBlack = new TooManyBlackCellsContradictionRule(); - ContradictionRule tooManyWhite = new TooFewBlackCellsContradictionRule(); - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - if (tooManyBlack.checkContradictionAt(board, board.getCell(i, j)) == null - || tooManyWhite.checkContradictionAt(board, board.getCell(i, j)) == null) { - return true; + public static boolean checkBoardForContradiction(FillapixBoard board) { + ContradictionRule tooManyBlack = new TooManyBlackCellsContradictionRule(); + ContradictionRule tooManyWhite = new TooFewBlackCellsContradictionRule(); + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + if (tooManyBlack.checkContradictionAt(board, board.getCell(i, j)) == null + || tooManyWhite.checkContradictionAt(board, board.getCell(i, j)) == null) { + return true; + } + } } - } + return false; } - return false; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java index eea7c7a4d..55332e47d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java @@ -6,17 +6,18 @@ import java.awt.*; public class FillapixView extends GridBoardView { - public FillapixView(FillapixBoard board) { - super(new BoardController(), new FillapixCellController(), board.getDimension()); + public FillapixView(FillapixBoard board) { + super(new BoardController(), new FillapixCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) puzzleElement; - Point loc = cell.getLocation(); - FillapixElementView elementView = new FillapixElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) puzzleElement; + Point loc = cell.getLocation(); + FillapixElementView elementView = new FillapixElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java index ce4ba520c..1d7c038a3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BlackTile extends PlaceableElement { - public BlackTile() { - super( - "FPIX-PLAC-0001", - "Black Tile", - "The black tile", - "edu/rpi/legup/images/fillapix/tiles/BlackTile.png"); - } + public BlackTile() { + super( + "FPIX-PLAC-0001", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/fillapix/tiles/BlackTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java index 0b76b1b57..e869aeaf9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java @@ -3,28 +3,28 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super( - "FPIX-UNPL-0001", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/fillapix/tiles/NumberTile.png"); - object_num = 0; - } + public NumberTile() { + super( + "FPIX-UNPL-0001", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/fillapix/tiles/NumberTile.png"); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java index 25104eb60..6778c1758 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "FPIX-UNPL-0002", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/fillapix/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "FPIX-UNPL-0002", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/fillapix/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java index 935c9bc1b..67065a7e9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class WhiteTile extends PlaceableElement { - public WhiteTile() { - super( - "FPIX-PLAC-0002", - "White Tile", - "The white tile", - "edu/rpi/legup/images/fillapix/tiles/WhiteTile.png"); - } + public WhiteTile() { + super( + "FPIX-PLAC-0002", + "White Tile", + "The white tile", + "edu/rpi/legup/images/fillapix/tiles/WhiteTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java index 02699327e..860a6c011 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java @@ -12,81 +12,81 @@ import java.util.List; public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "FPIX-CASE-0001", - "Black or White", - "Each cell is either black or white.", - "edu/rpi/legup/images/fillapix/cases/BlackOrWhite.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); - fillapixBoard.setModifiable(false); - for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) data; - if (cell.getType() == FillapixCellType.UNKNOWN) { - caseBoard.addPickableElement(data); - } + public BlackOrWhiteCaseRule() { + super( + "FPIX-CASE-0001", + "Black or White", + "Each cell is either black or white.", + "edu/rpi/legup/images/fillapix/cases/BlackOrWhite.png"); } - return caseBoard; - } - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); + @Override + public CaseBoard getCaseBoard(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); + fillapixBoard.setModifiable(false); + for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) data; + if (cell.getType() == FillapixCellType.UNKNOWN) { + caseBoard.addPickableElement(data); + } + } + return caseBoard; + } - Board case1 = board.copy(); - FillapixCell cell1 = (FillapixCell) case1.getPuzzleElement(puzzleElement); - cell1.setCellType(FillapixCellType.BLACK); - case1.addModifiedData(cell1); - cases.add(case1); + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); - Board case2 = board.copy(); - FillapixCell cell2 = (FillapixCell) case2.getPuzzleElement(puzzleElement); - cell2.setCellType(FillapixCellType.WHITE); - case2.addModifiedData(cell2); - cases.add(case2); + Board case1 = board.copy(); + FillapixCell cell1 = (FillapixCell) case1.getPuzzleElement(puzzleElement); + cell1.setCellType(FillapixCellType.BLACK); + case1.addModifiedData(cell1); + cases.add(case1); - return cases; - } + Board case2 = board.copy(); + FillapixCell cell2 = (FillapixCell) case2.getPuzzleElement(puzzleElement); + cell2.setCellType(FillapixCellType.WHITE); + case2.addModifiedData(cell2); + cases.add(case2); - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + return cases; } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - FillapixCell mod1 = (FillapixCell) case1.getBoard().getModifiedData().iterator().next(); - FillapixCell mod2 = (FillapixCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - if (!((mod1.getType() == FillapixCellType.BLACK && mod2.getType() == FillapixCellType.WHITE) - || (mod2.getType() == FillapixCellType.BLACK - && mod1.getType() == FillapixCellType.WHITE))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty cell and a lit cell."; - } + FillapixCell mod1 = (FillapixCell) case1.getBoard().getModifiedData().iterator().next(); + FillapixCell mod2 = (FillapixCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } + + if (!((mod1.getType() == FillapixCellType.BLACK && mod2.getType() == FillapixCellType.WHITE) + || (mod2.getType() == FillapixCellType.BLACK + && mod1.getType() == FillapixCellType.WHITE))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty cell and a lit cell."; + } - return null; - } + return null; + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java index da0ccb057..ccc002f46 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java @@ -11,55 +11,56 @@ import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; public class FinishWithBlackDirectRule extends DirectRule { - public FinishWithBlackDirectRule() { - super( - "FPIX-BASC-0001", - "Finish with Black", - "The remaining unknowns around and on a cell must be black to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); - } + public FinishWithBlackDirectRule() { + super( + "FPIX-BASC-0001", + "Finish with Black", + "The remaining unknowns around and on a cell must be black to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == FillapixCellType.UNKNOWN - && cell.getType() == FillapixCellType.BLACK)) { - return super.getInvalidUseOfRuleMessage() - + ": This cell must be black to be applicable with this rule."; - } + if (!(parentCell.getType() == FillapixCellType.UNKNOWN + && cell.getType() == FillapixCellType.BLACK)) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must be black to be applicable with this rule."; + } - if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; + if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; + } } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN - && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.BLACK); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } else { - return fillapixBoard; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN + && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.BLACK); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } else { + return fillapixBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java index 0d8423c0c..6735fb8f4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java @@ -11,55 +11,56 @@ import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; public class FinishWithWhiteDirectRule extends DirectRule { - public FinishWithWhiteDirectRule() { - super( - "FPIX-BASC-0002", - "Finish with White", - "The remaining unknowns around and on a cell must be white to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); - } + public FinishWithWhiteDirectRule() { + super( + "FPIX-BASC-0002", + "Finish with White", + "The remaining unknowns around and on a cell must be white to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == FillapixCellType.UNKNOWN - && cell.getType() == FillapixCellType.WHITE)) { - return super.getInvalidUseOfRuleMessage() - + ": This cell must be white to be applicable with this rule"; - } + if (!(parentCell.getType() == FillapixCellType.UNKNOWN + && cell.getType() == FillapixCellType.WHITE)) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must be white to be applicable with this rule"; + } - if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; + if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; + } } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN - && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.WHITE); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } else { - return fillapixBoard; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN + && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.WHITE); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } else { + return fillapixBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java index f38c8179e..e91931bd4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java @@ -15,88 +15,93 @@ import java.util.List; public class MirrorDirectRule extends DirectRule { - public MirrorDirectRule() { - super( - "FPIX-BASC-0003", - "Mirror", - "Two adjacent clues with the same value must have the same number of black squares in their unshared regions", - "edu/rpi/legup/images/fillapix/rules/Mirror.png"); - } + public MirrorDirectRule() { + super( + "FPIX-BASC-0003", + "Mirror", + "Two adjacent clues with the same value must have the same number of black squares" + + " in their unshared regions", + "edu/rpi/legup/images/fillapix/rules/Mirror.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = + (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // find all cells adjacent to cell that are numbered - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - ArrayList adjNums = new ArrayList(); - for (int i = 0; i < adjCells.size(); i++) { - if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { - adjNums.add(adjCells.get(i)); - } - } - // the numbered cells must be next to another numbered cell of the same value - Iterator itr = adjNums.iterator(); - while (itr.hasNext()) { - FillapixCell adjNum = itr.next(); - adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); - boolean found = false; - for (FillapixCell adjCell : adjCells) { - if (adjCell.getNumber() == adjNum.getNumber() && adjCell.getIndex() != adjNum.getIndex()) { - found = true; + // find all cells adjacent to cell that are numbered + ArrayList adjCells = + FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + ArrayList adjNums = new ArrayList(); + for (int i = 0; i < adjCells.size(); i++) { + if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { + adjNums.add(adjCells.get(i)); + } + } + // the numbered cells must be next to another numbered cell of the same value + Iterator itr = adjNums.iterator(); + while (itr.hasNext()) { + FillapixCell adjNum = itr.next(); + adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); + boolean found = false; + for (FillapixCell adjCell : adjCells) { + if (adjCell.getNumber() == adjNum.getNumber() + && adjCell.getIndex() != adjNum.getIndex()) { + found = true; + } + } + if (!found) { + itr.remove(); + } } - } - if (!found) { - itr.remove(); - } - } - // change the color of the parentCell, and check if there exists a valid board - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); - } - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjNum : adjNums) { - caseBoards = completeClue.getCases(parentBoard, adjNum); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; + // change the color of the parentCell, and check if there exists a valid board + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjNum : adjNums) { + caseBoards = completeClue.getCases(parentBoard, adjNum); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } } - } - if (found) { - return null; - } - } - return super.getInvalidUseOfRuleMessage(); - } + return super.getInvalidUseOfRuleMessage(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java index 09930825e..71a85a95b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java @@ -15,85 +15,89 @@ import java.util.List; public class NonTouchingSharedDirectRule extends DirectRule { - public NonTouchingSharedDirectRule() { - super( - "FPIX-BASC-0005", - "NonTouching Shared", - "Clues with shared cells have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } + public NonTouchingSharedDirectRule() { + super( + "FPIX-BASC-0005", + "NonTouching Shared", + "Clues with shared cells have the same difference in black cells in their unshared" + + " regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = + (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell not - * touching, but sharing cells */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - ArrayList sharingCells = - FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); - boolean found = false; - for (FillapixCell sharingCell : sharingCells) { - if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { - found = true; + // get all adjCells that have a number + ArrayList adjCells = + FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell not + * touching, but sharing cells */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + ArrayList sharingCells = + FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); + boolean found = false; + for (FillapixCell sharingCell : sharingCells) { + if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { + found = true; + } + } + if (!found) { + itr.remove(); + } } - } - if (!found) { - itr.remove(); - } - } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } } - } - if (found) { - return null; - } - } - return super.getInvalidUseOfRuleMessage(); - } + return super.getInvalidUseOfRuleMessage(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java index fdfe2e765..7db833f76 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java @@ -18,215 +18,216 @@ import java.util.TreeSet; public class SatisfyClueCaseRule extends CaseRule { - public SatisfyClueCaseRule() { - super( - "FPIX-CASE-0002", - "Satisfy Clue", - "Each clue must touch that number of squares.", - "edu/rpi/legup/images/fillapix/cases/SatisfyClue.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); - fillapixBoard.setModifiable(false); - for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) data; - if (cell.getNumber() >= 0 - && cell.getNumber() <= 9 - && FillapixUtilities.hasEmptyAdjacent(fillapixBoard, cell)) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; - } - - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - - // get value of cell - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellMaxBlack = cell.getNumber(); - if (cellMaxBlack < 0 || cellMaxBlack > 9) { // cell is not valid cell - return null; + public SatisfyClueCaseRule() { + super( + "FPIX-CASE-0002", + "Satisfy Clue", + "Each clue must touch that number of squares.", + "edu/rpi/legup/images/fillapix/cases/SatisfyClue.png"); } - // find number of black & empty squares - int cellNumBlack = 0; - int cellNumEmpty = 0; - ArrayList emptyCells = new ArrayList(); - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - cellNumBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - cellNumEmpty++; - emptyCells.add(adjCell); - } - } - // no cases if no empty or if too many black already - if (cellNumBlack > cellMaxBlack || cellNumEmpty == 0) { - return cases; + @Override + public CaseBoard getCaseBoard(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); + fillapixBoard.setModifiable(false); + for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) data; + if (cell.getNumber() >= 0 + && cell.getNumber() <= 9 + && FillapixUtilities.hasEmptyAdjacent(fillapixBoard, cell)) { + caseBoard.addPickableElement(data); + } + } + return caseBoard; } - // generate all cases as boolean expressions - ArrayList combinations; - combinations = FillapixUtilities.getCombinations(cellMaxBlack - cellNumBlack, cellNumEmpty); - - for (int i = 0; i < combinations.size(); i++) { - Board case_ = board.copy(); - for (int j = 0; j < combinations.get(i).length; j++) { - cell = (FillapixCell) case_.getPuzzleElement(emptyCells.get(j)); - if (combinations.get(i)[j]) { - cell.setCellType(FillapixCellType.BLACK); - } else { - cell.setCellType(FillapixCellType.WHITE); + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + + // get value of cell + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + int cellMaxBlack = cell.getNumber(); + if (cellMaxBlack < 0 || cellMaxBlack > 9) { // cell is not valid cell + return null; } - case_.addModifiedData(cell); - } - cases.add(case_); - } - return cases; - } - - @Override - public String checkRuleRaw(TreeTransition transition) { - TreeNode parent = transition.getParents().get(0); - List childTransitions = parent.getChildren(); - - /* - * In order for the transition to be valid, it can only be applied to - * one cell, thus: - * * there must be modified cells - * * all modified cells must share at least one common adjacent - * cell - * * all modified cells must fit within a 3X3 square - * * the center of one of the possible squaress must be a cell - * with a number - * * that cells possible combinations must match the transitions - * If all the above is verified, then the transition is valid - */ - - /* ensure there are modified cells */ - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() <= 0) { - return super.getInvalidUseOfRuleMessage(); - } + // find number of black & empty squares + int cellNumBlack = 0; + int cellNumEmpty = 0; + ArrayList emptyCells = new ArrayList(); + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + cellNumBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + cellNumEmpty++; + emptyCells.add(adjCell); + } + } + // no cases if no empty or if too many black already + if (cellNumBlack > cellMaxBlack || cellNumEmpty == 0) { + return cases; + } - /* ensure modified cells occur within a 3X3 square */ - int minVertLoc = Integer.MAX_VALUE, maxVertLoc = Integer.MIN_VALUE; - int minHorzLoc = Integer.MAX_VALUE, maxHorzLoc = Integer.MIN_VALUE; - for (PuzzleElement modCell : modCells) { - Point loc = ((FillapixCell) modCell).getLocation(); - if (loc.x < minHorzLoc) { - minHorzLoc = loc.x; - } - if (loc.x > maxHorzLoc) { - maxHorzLoc = loc.x; - } - if (loc.y < minVertLoc) { - minVertLoc = loc.y; - } - if (loc.y > maxVertLoc) { - maxVertLoc = loc.y; - } - } - if (maxVertLoc - minVertLoc > 3 || maxHorzLoc - minHorzLoc > 3) { - return super.getInvalidUseOfRuleMessage(); - } + // generate all cases as boolean expressions + ArrayList combinations; + combinations = FillapixUtilities.getCombinations(cellMaxBlack - cellNumBlack, cellNumEmpty); + + for (int i = 0; i < combinations.size(); i++) { + Board case_ = board.copy(); + for (int j = 0; j < combinations.get(i).length; j++) { + cell = (FillapixCell) case_.getPuzzleElement(emptyCells.get(j)); + if (combinations.get(i)[j]) { + cell.setCellType(FillapixCellType.BLACK); + } else { + cell.setCellType(FillapixCellType.WHITE); + } + case_.addModifiedData(cell); + } + cases.add(case_); + } - /* get the center of all possible 3X3 squares, - * and collect all that have numbers */ - FillapixBoard board = (FillapixBoard) transition.getParents().get(0).getBoard(); - Set possibleCenters = new TreeSet(); - possibleCenters.addAll( - FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCells.iterator().next())); - for (PuzzleElement modCell : modCells) { - possibleCenters.retainAll( - (FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCell))); - } - // removing all elements without a valid number - possibleCenters.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - if (possibleCenters.isEmpty()) { - return super.getInvalidUseOfRuleMessage(); + return cases; } - /* Now go through the remaining centers, and check if their combinations - * match the transitions */ - for (FillapixCell possibleCenter : possibleCenters) { - int numBlack = 0; - int numEmpty = 0; - int maxBlack = possibleCenter.getNumber(); - for (FillapixCell adjCell : FillapixUtilities.getAdjacentCells(board, possibleCenter)) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - numEmpty++; + @Override + public String checkRuleRaw(TreeTransition transition) { + TreeNode parent = transition.getParents().get(0); + List childTransitions = parent.getChildren(); + + /* + * In order for the transition to be valid, it can only be applied to + * one cell, thus: + * * there must be modified cells + * * all modified cells must share at least one common adjacent + * cell + * * all modified cells must fit within a 3X3 square + * * the center of one of the possible squaress must be a cell + * with a number + * * that cells possible combinations must match the transitions + * If all the above is verified, then the transition is valid + */ + + /* ensure there are modified cells */ + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() <= 0) { + return super.getInvalidUseOfRuleMessage(); } - } - if (numEmpty <= 0 || numBlack > maxBlack) { - // this cell has no cases (no empty) or is already broken (too many black) - continue; - } - - ArrayList combinations = - FillapixUtilities.getCombinations(maxBlack - numBlack, numEmpty); - if (combinations.size() != childTransitions.size()) { - // not this center because combinations do not match transitions - continue; - } - boolean quitEarly = false; - for (TreeTransition trans : childTransitions) { - /* convert the transition board into boolean format, so that it - * can be compared to the combinations */ - FillapixBoard transBoard = (FillapixBoard) trans.getBoard(); - ArrayList transModCells = new ArrayList(); + + /* ensure modified cells occur within a 3X3 square */ + int minVertLoc = Integer.MAX_VALUE, maxVertLoc = Integer.MIN_VALUE; + int minHorzLoc = Integer.MAX_VALUE, maxHorzLoc = Integer.MIN_VALUE; for (PuzzleElement modCell : modCells) { - transModCells.add((FillapixCell) transBoard.getPuzzleElement(modCell)); + Point loc = ((FillapixCell) modCell).getLocation(); + if (loc.x < minHorzLoc) { + minHorzLoc = loc.x; + } + if (loc.x > maxHorzLoc) { + maxHorzLoc = loc.x; + } + if (loc.y < minVertLoc) { + minVertLoc = loc.y; + } + if (loc.y > maxVertLoc) { + maxVertLoc = loc.y; + } } - - boolean[] translatedModCells = new boolean[transModCells.size()]; - for (int i = 0; i < transModCells.size(); i++) { - if (transModCells.get(i).getType() == FillapixCellType.BLACK) { - translatedModCells[i] = true; - } else { - translatedModCells[i] = false; - } + if (maxVertLoc - minVertLoc > 3 || maxHorzLoc - minHorzLoc > 3) { + return super.getInvalidUseOfRuleMessage(); } - // try to find the above state in the combinations, remove if found - boolean removed = false; - for (boolean[] combination : combinations) { - if (Arrays.equals(combination, translatedModCells)) { - combinations.remove(combination); - removed = true; - break; - } + /* get the center of all possible 3X3 squares, + * and collect all that have numbers */ + FillapixBoard board = (FillapixBoard) transition.getParents().get(0).getBoard(); + Set possibleCenters = new TreeSet(); + possibleCenters.addAll( + FillapixUtilities.getAdjacentCells( + board, (FillapixCell) modCells.iterator().next())); + for (PuzzleElement modCell : modCells) { + possibleCenters.retainAll( + (FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCell))); } - // if combination not found, no need to check further, just quit - if (!removed) { - quitEarly = true; - break; + // removing all elements without a valid number + possibleCenters.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + if (possibleCenters.isEmpty()) { + return super.getInvalidUseOfRuleMessage(); } - } - /* we found a center that is valid */ - if (combinations.isEmpty() && !quitEarly) { - return null; - } - } + /* Now go through the remaining centers, and check if their combinations + * match the transitions */ + for (FillapixCell possibleCenter : possibleCenters) { + int numBlack = 0; + int numEmpty = 0; + int maxBlack = possibleCenter.getNumber(); + for (FillapixCell adjCell : FillapixUtilities.getAdjacentCells(board, possibleCenter)) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + numEmpty++; + } + } + if (numEmpty <= 0 || numBlack > maxBlack) { + // this cell has no cases (no empty) or is already broken (too many black) + continue; + } + + ArrayList combinations = + FillapixUtilities.getCombinations(maxBlack - numBlack, numEmpty); + if (combinations.size() != childTransitions.size()) { + // not this center because combinations do not match transitions + continue; + } + boolean quitEarly = false; + for (TreeTransition trans : childTransitions) { + /* convert the transition board into boolean format, so that it + * can be compared to the combinations */ + FillapixBoard transBoard = (FillapixBoard) trans.getBoard(); + ArrayList transModCells = new ArrayList(); + for (PuzzleElement modCell : modCells) { + transModCells.add((FillapixCell) transBoard.getPuzzleElement(modCell)); + } + + boolean[] translatedModCells = new boolean[transModCells.size()]; + for (int i = 0; i < transModCells.size(); i++) { + if (transModCells.get(i).getType() == FillapixCellType.BLACK) { + translatedModCells[i] = true; + } else { + translatedModCells[i] = false; + } + } + + // try to find the above state in the combinations, remove if found + boolean removed = false; + for (boolean[] combination : combinations) { + if (Arrays.equals(combination, translatedModCells)) { + combinations.remove(combination); + removed = true; + break; + } + } + // if combination not found, no need to check further, just quit + if (!removed) { + quitEarly = true; + break; + } + } + + /* we found a center that is valid */ + if (combinations.isEmpty() && !quitEarly) { + return null; + } + } - return super.getInvalidUseOfRuleMessage(); - } + return super.getInvalidUseOfRuleMessage(); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java index 09d031421..df5954d63 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java @@ -11,46 +11,46 @@ public class TooFewBlackCellsContradictionRule extends ContradictionRule { - public TooFewBlackCellsContradictionRule() { - super( - "FPIX-CONT-0001", - "Too Few Black Cells", - "There may not be fewer black cells than the number.", - "edu/rpi/legup/images/fillapix/contradictions/TooFewBlackCells.png"); - } + public TooFewBlackCellsContradictionRule() { + super( + "FPIX-CONT-0001", + "Too Few Black Cells", + "There may not be fewer black cells than the number.", + "edu/rpi/legup/images/fillapix/contradictions/TooFewBlackCells.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellNum = cell.getNumber(); - if (cellNum < 0 || cellNum >= 10) { - return super.getNoContradictionMessage(); - } - int numBlack = 0, numEmpty = 0; - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - numEmpty++; - } - } - if (numBlack + numEmpty < cellNum) { - return null; - } + int cellNum = cell.getNumber(); + if (cellNum < 0 || cellNum >= 10) { + return super.getNoContradictionMessage(); + } + int numBlack = 0, numEmpty = 0; + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + numEmpty++; + } + } + if (numBlack + numEmpty < cellNum) { + return null; + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java index 9184212bb..38b47c972 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java @@ -11,43 +11,43 @@ public class TooManyBlackCellsContradictionRule extends ContradictionRule { - public TooManyBlackCellsContradictionRule() { - super( - "FPIX-CONT-0002", - "Too Many Black Cells", - "There may not be more black cells than the number", - "edu/rpi/legup/images/fillapix/contradictions/TooManyBlackCells.png"); - } + public TooManyBlackCellsContradictionRule() { + super( + "FPIX-CONT-0002", + "Too Many Black Cells", + "There may not be more black cells than the number", + "edu/rpi/legup/images/fillapix/contradictions/TooManyBlackCells.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellNum = cell.getNumber(); - if (cellNum < 0 || cellNum >= 10) { - return super.getNoContradictionMessage(); - } - int numBlack = 0; - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - } - if (numBlack > cellNum) { - return null; - } + int cellNum = cell.getNumber(); + if (cellNum < 0 || cellNum >= 10) { + return super.getNoContradictionMessage(); + } + int numBlack = 0; + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } + } + if (numBlack > cellNum) { + return null; + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java index 34051f06f..72e2def47 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java @@ -15,95 +15,99 @@ import java.util.List; public class TouchingCornersDirectRule extends DirectRule { - public TouchingCornersDirectRule() { - super( - "FPIX-BASC-0005", - "Touching Corners", - "Clues with touching corners have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); - } + public TouchingCornersDirectRule() { + super( + "FPIX-BASC-0005", + "Touching Corners", + "Clues with touching corners have the same difference in black cells in their" + + " unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = + (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } + + // get all adjCells that have a number + ArrayList adjCells = + FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell diagonally + * adjacent to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + FillapixCell adjCell = itr.next(); - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell diagonally - * adjacent to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - FillapixCell adjCell = itr.next(); + boolean found = false; + ArrayList adjAdjCells = + FillapixUtilities.getAdjacentCells(parentBoard, adjCell); + for (FillapixCell adjAdjCell : adjAdjCells) { + if (adjAdjCell.getLocation().x != adjCell.getLocation().x + && adjAdjCell.getLocation().y != adjCell.getLocation().y + && adjAdjCell.getNumber() >= 0 + && adjAdjCell.getNumber() < 10 + && adjAdjCell.getIndex() != parentCell.getIndex()) { + // adjAdjCell is diagonally adjacent to adjCell && it has a + // number && it is not parentCell + found = true; + } + } - boolean found = false; - ArrayList adjAdjCells = - FillapixUtilities.getAdjacentCells(parentBoard, adjCell); - for (FillapixCell adjAdjCell : adjAdjCells) { - if (adjAdjCell.getLocation().x != adjCell.getLocation().x - && adjAdjCell.getLocation().y != adjCell.getLocation().y - && adjAdjCell.getNumber() >= 0 - && adjAdjCell.getNumber() < 10 - && adjAdjCell.getIndex() != parentCell.getIndex()) { - // adjAdjCell is diagonally adjacent to adjCell && it has a - // number && it is not parentCell - found = true; + // does not qualify for this rule + if (!found) { + itr.remove(); + } } - } - // does not qualify for this rule - if (!found) { - itr.remove(); - } - } + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } + } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); + return super.getInvalidUseOfRuleMessage(); } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { return null; - } } - - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java index ea6b84c69..281dd5392 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java @@ -15,108 +15,112 @@ import java.util.List; public class TouchingSidesDirectRule extends DirectRule { - public TouchingSidesDirectRule() { - super( - "FPIX-BASC-0004", - "Touching Sides", - "Clues with touching sides have the same difference in black cells in their unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } + public TouchingSidesDirectRule() { + super( + "FPIX-BASC-0004", + "Touching Sides", + "Clues with touching sides have the same difference in black cells in their" + + " unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = + (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } + + // get all adjCells that have a number + ArrayList adjCells = + FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell adjacent + * to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + // calculate x and y offset of adjCell from cell + FillapixCell adjCell = itr.next(); + int xOffset = adjCell.getLocation().x - cell.getLocation().x; + int yOffset = adjCell.getLocation().y - cell.getLocation().y; - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell adjacent - * to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - // calculate x and y offset of adjCell from cell - FillapixCell adjCell = itr.next(); - int xOffset = adjCell.getLocation().x - cell.getLocation().x; - int yOffset = adjCell.getLocation().y - cell.getLocation().y; + boolean found = false; + // check vertically for numbered cell in opposite direction of cell + if (adjCell.getLocation().x + xOffset >= 0 + && adjCell.getLocation().x < parentBoard.getWidth()) { + int adjNum = + parentBoard + .getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y) + .getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; + } + } + // check horizontally for numbered cell in opposite direction of cell + if (adjCell.getLocation().y + yOffset >= 0 + && adjCell.getLocation().y < parentBoard.getHeight()) { + int adjNum = + parentBoard + .getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset) + .getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; + } + } - boolean found = false; - // check vertically for numbered cell in opposite direction of cell - if (adjCell.getLocation().x + xOffset >= 0 - && adjCell.getLocation().x < parentBoard.getWidth()) { - int adjNum = - parentBoard - .getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y) - .getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; + // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, + // then adjCell is not valid, so should be removed + if (!found) { + itr.remove(); + } } - } - // check horizontally for numbered cell in opposite direction of cell - if (adjCell.getLocation().y + yOffset >= 0 - && adjCell.getLocation().y < parentBoard.getHeight()) { - int adjNum = - parentBoard - .getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset) - .getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; + + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } } - } - // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, - // then adjCell is not valid, so should be removed - if (!found) { - itr.remove(); - } + return super.getInvalidUseOfRuleMessage(); } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { return null; - } } - - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java index 119362a88..afe3dd652 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java @@ -5,63 +5,63 @@ public class Heyawake extends Puzzle { - public Heyawake() { - super(); + public Heyawake() { + super(); - this.name = "Heyawake"; + this.name = "Heyawake"; - this.factory = new HeyawakeFactory(); + this.factory = new HeyawakeFactory(); - this.exporter = new HeyawakeExporter(this); - this.importer = new HeyawakeImporter(this); - } + this.exporter = new HeyawakeExporter(this); + this.importer = new HeyawakeImporter(this); + } - /** Initializes the view. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new HeyawakeView((HeyawakeBoard) currentBoard); - } + /** Initializes the view. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new HeyawakeView((HeyawakeBoard) currentBoard); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for HeyAwake - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for HeyAwake, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for HeyAwake + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for HeyAwake, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java index 2dfe35138..cedb3a91b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java @@ -10,46 +10,46 @@ public class HeyawakeBoard extends GridBoard { - private Map> regions; - - public HeyawakeBoard(int width, int height) { - super(width, height); - this.regions = new HashMap<>(); - } - - public HeyawakeBoard(int size) { - this(size, size); - } - - @Override - public HeyawakeCell getCell(int x, int y) { - return (HeyawakeCell) super.getCell(x, y); - } - - public List getRegion(int regionIndex) { - return this.regions.get(regionIndex); - } - - public Map> getRegions() { - return this.regions; - } - - @Override - public HeyawakeBoard copy() { - HeyawakeBoard copy = new HeyawakeBoard(dimension.width, dimension.height); - for (List region : regions.values()) { - List newCpy = new ArrayList<>(); - for (HeyawakeCell cell : region) { - Point point = cell.getLocation(); - HeyawakeCell cellCpy = cell.copy(); - copy.setCell(point.x, point.y, cellCpy); - newCpy.add(cellCpy); - } - copy.regions.put(region.get(0).getRegionIndex(), newCpy); + private Map> regions; + + public HeyawakeBoard(int width, int height) { + super(width, height); + this.regions = new HashMap<>(); + } + + public HeyawakeBoard(int size) { + this(size, size); + } + + @Override + public HeyawakeCell getCell(int x, int y) { + return (HeyawakeCell) super.getCell(x, y); } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + public List getRegion(int regionIndex) { + return this.regions.get(regionIndex); + } + + public Map> getRegions() { + return this.regions; + } + + @Override + public HeyawakeBoard copy() { + HeyawakeBoard copy = new HeyawakeBoard(dimension.width, dimension.height); + for (List region : regions.values()) { + List newCpy = new ArrayList<>(); + for (HeyawakeCell cell : region) { + Point point = cell.getLocation(); + HeyawakeCell cellCpy = cell.copy(); + copy.setCell(point.x, point.y, cellCpy); + newCpy.add(cellCpy); + } + copy.regions.put(region.get(0).getRegionIndex(), newCpy); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; } - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java index e75271355..480e2e39b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java @@ -5,23 +5,23 @@ public class HeyawakeCell extends GridCell { - private int regionIndex; + private int regionIndex; - public HeyawakeCell(int valueInt, Point location, int regionIndex) { - super(valueInt, location); - this.regionIndex = regionIndex; - } + public HeyawakeCell(int valueInt, Point location, int regionIndex) { + super(valueInt, location); + this.regionIndex = regionIndex; + } - public int getRegionIndex() { - return this.regionIndex; - } + public int getRegionIndex() { + return this.regionIndex; + } - @Override - public HeyawakeCell copy() { - HeyawakeCell copy = new HeyawakeCell(data, (Point) location.clone(), regionIndex); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public HeyawakeCell copy() { + HeyawakeCell copy = new HeyawakeCell(data, (Point) location.clone(), regionIndex); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java index f1ca1c79e..d30159856 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java @@ -5,41 +5,42 @@ public class HeyawakeElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); - - public HeyawakeElementView(HeyawakeCell cell) { - super(cell); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public HeyawakeCell getPuzzleElement() { - return (HeyawakeCell) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - - if (cell.getData() >= 0) { - graphics2D.setColor(BLACK_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); + + public HeyawakeElementView(HeyawakeCell cell) { + super(cell); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public HeyawakeCell getPuzzleElement() { + return (HeyawakeCell) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + + if (cell.getData() >= 0) { + graphics2D.setColor(BLACK_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java index 0856bf0de..4470d77be 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java @@ -6,34 +6,34 @@ public class HeyawakeExporter extends PuzzleExporter { - public HeyawakeExporter(Heyawake heyawake) { - super(heyawake); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - HeyawakeBoard board; - if (puzzle.getTree() != null) { - board = (HeyawakeBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (HeyawakeBoard) puzzle.getBoardView().getBoard(); + public HeyawakeExporter(Heyawake heyawake) { + super(heyawake); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + HeyawakeBoard board; + if (puzzle.getTree() != null) { + board = (HeyawakeBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (HeyawakeBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java index f6853d75f..8ecf24135 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java @@ -10,68 +10,69 @@ import org.w3c.dom.Node; public class HeyawakeFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public HeyawakeCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Heyawake Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public HeyawakeCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Heyawake Factory: unknown puzzleElement puzzleElement"); + } - HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; - int width = heyawakeBoard.getWidth(); - int height = heyawakeBoard.getHeight(); + HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; + int width = heyawakeBoard.getWidth(); + int height = heyawakeBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - int regionIndex = Integer.valueOf(attributeList.getNamedItem("region").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Heyawake Factory: cell location out of bounds"); - } - if (value < -4 || value > 4) { - throw new InvalidFileFormatException("Heyawake Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + int regionIndex = Integer.valueOf(attributeList.getNamedItem("region").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "Heyawake Factory: cell location out of bounds"); + } + if (value < -4 || value > 4) { + throw new InvalidFileFormatException("Heyawake Factory: cell unknown value"); + } - HeyawakeCell cell = new HeyawakeCell(value, new Point(x, y), regionIndex); - cell.setIndex(y * height + x); - heyawakeBoard.getRegions(); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Heyawake Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Heyawake Factory: could not find attribute(s)"); + HeyawakeCell cell = new HeyawakeCell(value, new Point(x, y), regionIndex); + cell.setIndex(y * height + x); + heyawakeBoard.getRegions(); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Heyawake Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Heyawake Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - Point loc = cell.getLocation(); + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); - cellElement.setAttribute("region", String.valueOf(cell.getRegionIndex())); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("region", String.valueOf(cell.getRegionIndex())); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java index f85a0b46d..6bbabd54d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java @@ -9,99 +9,103 @@ public class HeyawakeImporter extends PuzzleImporter { - public HeyawakeImporter(Heyawake heyawake) { - super(heyawake); - } + public HeyawakeImporter(Heyawake heyawake) { + super(heyawake); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Heyawake Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Heyawake Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Heyawake Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Heyawake Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - HeyawakeBoard heyawakeBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - heyawakeBoard = new HeyawakeBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - heyawakeBoard = new HeyawakeBoard(width, height); - } - } + HeyawakeBoard heyawakeBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + heyawakeBoard = new HeyawakeBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + heyawakeBoard = new HeyawakeBoard(width, height); + } + } - if (heyawakeBoard == null) { - throw new InvalidFileFormatException("Heyawake Importer: invalid board dimensions"); - } + if (heyawakeBoard == null) { + throw new InvalidFileFormatException("Heyawake Importer: invalid board dimensions"); + } - int width = heyawakeBoard.getWidth(); - int height = heyawakeBoard.getHeight(); + int width = heyawakeBoard.getWidth(); + int height = heyawakeBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - HeyawakeCell cell = - (HeyawakeCell) puzzle.getFactory().importCell(elementDataList.item(i), heyawakeBoard); - Point loc = cell.getLocation(); - if (cell.getData() != -2) { - cell.setModifiable(false); - cell.setGiven(true); - } - heyawakeBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + HeyawakeCell cell = + (HeyawakeCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), heyawakeBoard); + Point loc = cell.getLocation(); + if (cell.getData() != -2) { + cell.setModifiable(false); + cell.setGiven(true); + } + heyawakeBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (heyawakeBoard.getCell(x, y) == null) { - HeyawakeCell cell = new HeyawakeCell(0, new Point(x, y), -1); - cell.setIndex(y * height + x); - cell.setModifiable(false); - heyawakeBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (heyawakeBoard.getCell(x, y) == null) { + HeyawakeCell cell = new HeyawakeCell(0, new Point(x, y), -1); + cell.setIndex(y * height + x); + cell.setModifiable(false); + heyawakeBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(heyawakeBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Heyawake Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(heyawakeBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Heyawake Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Hey Awake cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Hey Awake cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java index 0c349ca87..fba5f0eb7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java @@ -11,43 +11,44 @@ public class HeyawakeView extends GridBoardView { - private Map regionsBoundaries; - - public HeyawakeView(HeyawakeBoard board) { - super(new BoardController(), new HeyawakeController(), board.getDimension()); - - this.regionsBoundaries = new HashMap<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - Point loc = cell.getLocation(); - HeyawakeElementView elementView = new HeyawakeElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - - int regionIndex = cell.getRegionIndex(); - if (regionsBoundaries.get(regionIndex) == null) { - regionsBoundaries.put(regionIndex, new Area(elementView.getBounds())); - } else { - regionsBoundaries.get(regionIndex).add(new Area(elementView.getBounds())); - } + private Map regionsBoundaries; + + public HeyawakeView(HeyawakeBoard board) { + super(new BoardController(), new HeyawakeController(), board.getDimension()); + + this.regionsBoundaries = new HashMap<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + Point loc = cell.getLocation(); + HeyawakeElementView elementView = new HeyawakeElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + + int regionIndex = cell.getRegionIndex(); + if (regionsBoundaries.get(regionIndex) == null) { + regionsBoundaries.put(regionIndex, new Area(elementView.getBounds())); + } else { + regionsBoundaries.get(regionIndex).add(new Area(elementView.getBounds())); + } + } } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; + @Override + public void drawBoard(Graphics2D graphics2D) { + HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; - for (ElementView elementView : elementViews) { - elementView.draw(graphics2D); - } + for (ElementView elementView : elementViews) { + elementView.draw(graphics2D); + } - graphics2D.setColor(Color.BLACK); - graphics2D.setStroke(new BasicStroke(3)); - for (Area s : regionsBoundaries.values()) { - graphics2D.draw(s); + graphics2D.setColor(Color.BLACK); + graphics2D.setStroke(new BasicStroke(3)); + for (Area s : regionsBoundaries.values()) { + graphics2D.draw(s); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java index 1a46e5265..88d293f5e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java @@ -6,25 +6,25 @@ public class AdjacentBlacksContradictionRule extends ContradictionRule { - public AdjacentBlacksContradictionRule() { - super( - "HEYA-CONT-0001", - "Adjacent Blacks", - "", - "edu/rpi/legup/images/heyawake/contradictions/adjacentBlacks.png"); - } + public AdjacentBlacksContradictionRule() { + super( + "HEYA-CONT-0001", + "Adjacent Blacks", + "", + "edu/rpi/legup/images/heyawake/contradictions/adjacentBlacks.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java index 882372372..251be46ee 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java @@ -9,63 +9,63 @@ public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "HEYA-CASE-0001", - "Black or White", - "", - "edu/rpi/legup/images/heyawake/cases/BlackOrWhite.png"); - } + public BlackOrWhiteCaseRule() { + super( + "HEYA-CASE-0001", + "Black or White", + "", + "edu/rpi/legup/images/heyawake/cases/BlackOrWhite.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java index d687569ff..1fc3d0776 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class BlackPathDirectRule { - public BlackPathDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public BlackPathDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java index 033bce643..41d950378 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class BottleNeckDirectRule { - public BottleNeckDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public BottleNeckDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java index 8fe0f66e5..aee1ae4bf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java @@ -8,37 +8,38 @@ public class FillRoomBlackDirectRule extends DirectRule { - public FillRoomBlackDirectRule() { - super( - "HEYA-BASC-0003", - "Fill Room Black", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); - } + public FillRoomBlackDirectRule() { + super( + "HEYA-BASC-0003", + "Fill Room Black", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java index 95473aa9c..c4609b239 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java @@ -8,37 +8,38 @@ public class FillRoomWhiteDirectRule extends DirectRule { - public FillRoomWhiteDirectRule() { - super( - "HEYA-BASC-0004", - "Fill Room White", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); - } + public FillRoomWhiteDirectRule() { + super( + "HEYA-BASC-0004", + "Fill Room White", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java index 233136061..8b6f21564 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class OneRowDirectRule { - public OneRowDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public OneRowDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java index 14b3ef0a2..f5d4e78b7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class PreventWhiteLineDirectRule { - public PreventWhiteLineDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public PreventWhiteLineDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java index af2448b13..762b435a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java @@ -6,25 +6,25 @@ public class RoomTooEmptyContradictionRule extends ContradictionRule { - public RoomTooEmptyContradictionRule() { - super( - "HEYA-CONT-0002", - "Room too Empty", - "", - "edu/rpi/legup/images/heyawake/contradictions/RoomTooEmpty.png"); - } + public RoomTooEmptyContradictionRule() { + super( + "HEYA-CONT-0002", + "Room too Empty", + "", + "edu/rpi/legup/images/heyawake/contradictions/RoomTooEmpty.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java index d46ae27a0..643f75f13 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java @@ -6,25 +6,25 @@ public class RoomTooFullContradictionRule extends ContradictionRule { - public RoomTooFullContradictionRule() { - super( - "HEYA-CONT-0003", - "Room too Full", - "", - "edu/rpi/legup/images/heyawake/contradictions/RoomTooFull.png"); - } + public RoomTooFullContradictionRule() { + super( + "HEYA-CONT-0003", + "Room too Full", + "", + "edu/rpi/legup/images/heyawake/contradictions/RoomTooFull.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java index b6782e380..cf2c241e3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ThreeByThreeDirectRule { - public ThreeByThreeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ThreeByThreeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java index 0af7fbc15..83f1ca72f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class TwoInCornerDirectRule { - public TwoInCornerDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public TwoInCornerDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java index 377ba5911..c0987d4f9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java @@ -6,25 +6,25 @@ public class WhiteAreaContradictionRule extends ContradictionRule { - public WhiteAreaContradictionRule() { - super( - "HEYA-CONT-0004", - "White Area", - "", - "edu/rpi/legup/images/heyawake/contradictions/WhiteArea.png"); - } + public WhiteAreaContradictionRule() { + super( + "HEYA-CONT-0004", + "White Area", + "", + "edu/rpi/legup/images/heyawake/contradictions/WhiteArea.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java index c6c7b7d6b..2e3bc1812 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java @@ -8,37 +8,38 @@ public class WhiteAroundBlackDirectRule extends DirectRule { - public WhiteAroundBlackDirectRule() { - super( - "HEYA-BASC-0009", - "White Around Black", - "", - "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); - } + public WhiteAroundBlackDirectRule() { + super( + "HEYA-BASC-0009", + "White Around Black", + "", + "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java index d4d547677..f151ec12a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class WhiteEscapeDirectRule { - public WhiteEscapeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public WhiteEscapeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java index 813dd45ed..b695b8206 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java @@ -6,25 +6,25 @@ public class WhiteLineContradictionRule extends ContradictionRule { - public WhiteLineContradictionRule() { - super( - "HEYA-CONT-0005", - "White Line", - "", - "edu/rpi/legup/images/heyawake/contradictions/WhiteLine.png"); - } + public WhiteLineContradictionRule() { + super( + "HEYA-CONT-0005", + "White Line", + "", + "edu/rpi/legup/images/heyawake/contradictions/WhiteLine.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java index 9f9212861..d44491a6e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ZigZagCaseRule { - public ZigZagCaseRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ZigZagCaseRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java index 531cf030e..9df735b0b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ZigZagWhiteDirectRule { - public ZigZagWhiteDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ZigZagWhiteDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java index 73878706f..ab95c4658 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java @@ -9,79 +9,80 @@ @RegisterPuzzle public class LightUp extends Puzzle { - public LightUp() { - super(); - this.name = "LightUp"; + public LightUp() { + super(); + this.name = "LightUp"; - this.importer = new LightUpImporter(this); - this.exporter = new LightUpExporter(this); + this.importer = new LightUpImporter(this); + this.exporter = new LightUpExporter(this); - this.factory = new LightUpCellFactory(); - } + this.factory = new LightUpCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new LightUpView((LightUpBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new LightUpView((LightUpBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Light Up - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Light Up, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows > 0 && columns > 0; - } + @Override + /** + * Determines if the given dimensions are valid for Light Up + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Light Up, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows > 0 && columns > 0; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - lightUpBoard.fillWithLight(); + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + lightUpBoard.fillWithLight(); - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(lightUpBoard) == null) { - System.out.println(rule.getRuleName()); - return false; - } - } - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) data; - if ((cell.getType() == LightUpCellType.UNKNOWN || cell.getType() == LightUpCellType.EMPTY) - && !cell.isLite()) { - return false; - } + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(lightUpBoard) == null) { + System.out.println(rule.getRuleName()); + return false; + } + } + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) data; + if ((cell.getType() == LightUpCellType.UNKNOWN + || cell.getType() == LightUpCellType.EMPTY) + && !cell.isLite()) { + return false; + } + } + return true; } - return true; - } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java index 5d0d66648..217ef79a8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java @@ -7,168 +7,172 @@ import java.util.Set; public class LightUpBoard extends GridBoard { - public LightUpBoard(int width, int height) { - super(width, height); - } - - public LightUpBoard(int size) { - super(size, size); - } + public LightUpBoard(int width, int height) { + super(width, height); + } - /** - * Sets cells in board to lite depending on whether there is a bulb cell in the current row or - * column - */ - public void fillWithLight() { - for (int y = 0; y < this.dimension.height; y++) { - for (int x = 0; x < this.dimension.width; x++) { - getCell(x, y).setLite(false); - } + public LightUpBoard(int size) { + super(size, size); } - for (int y = 0; y < this.dimension.height; y++) { - for (int x = 0; x < this.dimension.width; x++) { - LightUpCell cell = getCell(x, y); - if (cell.getType() == LightUpCellType.BULB) { - cell.setLite(true); - for (int i = x + 1; i < this.dimension.width; i++) { - LightUpCell c = getCell(i, y); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = x - 1; i >= 0; i--) { - LightUpCell c = getCell(i, y); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = y + 1; i < this.dimension.height; i++) { - LightUpCell c = getCell(x, i); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; + /** + * Sets cells in board to lite depending on whether there is a bulb cell in the current row or + * column + */ + public void fillWithLight() { + for (int y = 0; y < this.dimension.height; y++) { + for (int x = 0; x < this.dimension.width; x++) { + getCell(x, y).setLite(false); } - c.setLite(true); - } - for (int i = y - 1; i >= 0; i--) { - LightUpCell c = getCell(x, i); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; + } + + for (int y = 0; y < this.dimension.height; y++) { + for (int x = 0; x < this.dimension.width; x++) { + LightUpCell cell = getCell(x, y); + if (cell.getType() == LightUpCellType.BULB) { + cell.setLite(true); + for (int i = x + 1; i < this.dimension.width; i++) { + LightUpCell c = getCell(i, y); + if (c.getType() == LightUpCellType.NUMBER + || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = x - 1; i >= 0; i--) { + LightUpCell c = getCell(i, y); + if (c.getType() == LightUpCellType.NUMBER + || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = y + 1; i < this.dimension.height; i++) { + LightUpCell c = getCell(x, i); + if (c.getType() == LightUpCellType.NUMBER + || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = y - 1; i >= 0; i--) { + LightUpCell c = getCell(x, i); + if (c.getType() == LightUpCellType.NUMBER + || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + } } - c.setLite(true); - } } - } } - } - /** - * Gets adjancent cells to the specified cell - * - * @param cell LightUpCell - * @return Set of adjacent LightUpCells - */ - public Set getAdj(LightUpCell cell) { - Set adjCells = new HashSet<>(); - cell = (LightUpCell) getPuzzleElement(cell); + /** + * Gets adjancent cells to the specified cell + * + * @param cell LightUpCell + * @return Set of adjacent LightUpCells + */ + public Set getAdj(LightUpCell cell) { + Set adjCells = new HashSet<>(); + cell = (LightUpCell) getPuzzleElement(cell); - Point loc = cell.getLocation(); - LightUpCell up = getCell(loc.x, loc.y + 1); - if (up != null) { - adjCells.add(up); - } - LightUpCell down = getCell(loc.x, loc.y - 1); - if (down != null) { - adjCells.add(down); - } - LightUpCell right = getCell(loc.x + 1, loc.y); - if (right != null) { - adjCells.add(right); - } - LightUpCell left = getCell(loc.x - 1, loc.y); - if (left != null) { - adjCells.add(left); + Point loc = cell.getLocation(); + LightUpCell up = getCell(loc.x, loc.y + 1); + if (up != null) { + adjCells.add(up); + } + LightUpCell down = getCell(loc.x, loc.y - 1); + if (down != null) { + adjCells.add(down); + } + LightUpCell right = getCell(loc.x + 1, loc.y); + if (right != null) { + adjCells.add(right); + } + LightUpCell left = getCell(loc.x - 1, loc.y); + if (left != null) { + adjCells.add(left); + } + return adjCells; } - return adjCells; - } - /** - * Gets the number of adjacent cells of the specified type - * - * @param cell base cell - * @param type specified type - * @return the number of adjacent cells - */ - public int getNumAdj(LightUpCell cell, LightUpCellType type) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.getType() == type) { - num++; - } + /** + * Gets the number of adjacent cells of the specified type + * + * @param cell base cell + * @param type specified type + * @return the number of adjacent cells + */ + public int getNumAdj(LightUpCell cell, LightUpCellType type) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.getType() == type) { + num++; + } + } + return num; } - return num; - } - /** - * Gets the number of adjacent cells - * - * @param cell LightUpCell - * @return number of adjacent cells - */ - public int getNumAdjLite(LightUpCell cell) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.isLite()) { - num++; - } + /** + * Gets the number of adjacent cells + * + * @param cell LightUpCell + * @return number of adjacent cells + */ + public int getNumAdjLite(LightUpCell cell) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.isLite()) { + num++; + } + } + return num; } - return num; - } - /** - * Gets the number of adjacent cells that are placable - * - * @param cell specified cell - * @return number of adjacent cells that are placable - */ - public int getNumPlacble(LightUpCell cell) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - num++; - } + /** + * Gets the number of adjacent cells that are placable + * + * @param cell specified cell + * @return number of adjacent cells that are placable + */ + public int getNumPlacble(LightUpCell cell) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + num++; + } + } + return num; } - return num; - } - @Override - public LightUpCell getCell(int x, int y) { - return (LightUpCell) super.getCell(x, y); - } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - super.notifyChange(puzzleElement); - fillWithLight(); - } + @Override + public LightUpCell getCell(int x, int y) { + return (LightUpCell) super.getCell(x, y); + } - @Override - public LightUpBoard copy() { - LightUpBoard copy = new LightUpBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + @Override + public void notifyChange(PuzzleElement puzzleElement) { + super.notifyChange(puzzleElement); + fillWithLight(); } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + @Override + public LightUpBoard copy() { + LightUpBoard copy = new LightUpBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.fillWithLight(); + return copy; } - copy.fillWithLight(); - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java index f21f42fd6..8adf84cb4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java @@ -6,78 +6,78 @@ import java.awt.event.MouseEvent; public class LightUpCell extends GridCell { - private boolean isLite; + private boolean isLite; - public LightUpCell(int valueInt, Point location) { - super(valueInt, location); - this.isLite = false; - } + public LightUpCell(int valueInt, Point location) { + super(valueInt, location); + this.isLite = false; + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "LTUP-PLAC-0001": - this.data = -4; - break; - case "LTUP-UNPL-0002": - this.data = -1; - break; - case "LTUP-UNPL-0003": - this.data = -2; - break; - case "LTUP-UNPL-0001": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data < 0 || this.data > 3) { - this.data = 0; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 0) { - this.data = this.data - 1; - } else { - this.data = 4; - } - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "LTUP-PLAC-0001": + this.data = -4; + break; + case "LTUP-UNPL-0002": + this.data = -1; + break; + case "LTUP-UNPL-0003": + this.data = -2; + break; + case "LTUP-UNPL-0001": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data < 0 || this.data > 3) { + this.data = 0; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 0) { + this.data = this.data - 1; + } else { + this.data = 4; + } + break; + } + break; } - break; } - } - public LightUpCellType getType() { - switch (data) { - case -4: - return LightUpCellType.BULB; - case -3: - return LightUpCellType.EMPTY; - case -2: - return LightUpCellType.UNKNOWN; - case -1: - return LightUpCellType.BLACK; - default: - if (data >= 0) { - return LightUpCellType.NUMBER; + public LightUpCellType getType() { + switch (data) { + case -4: + return LightUpCellType.BULB; + case -3: + return LightUpCellType.EMPTY; + case -2: + return LightUpCellType.UNKNOWN; + case -1: + return LightUpCellType.BLACK; + default: + if (data >= 0) { + return LightUpCellType.NUMBER; + } } + return null; } - return null; - } - public boolean isLite() { - return isLite; - } + public boolean isLite() { + return isLite; + } - public void setLite(boolean isLite) { - this.isLite = isLite; - } + public void setLite(boolean isLite) { + this.isLite = isLite; + } - @Override - public LightUpCell copy() { - LightUpCell copy = new LightUpCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public LightUpCell copy() { + LightUpCell copy = new LightUpCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java index 07217869e..d4049897d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java @@ -5,40 +5,40 @@ import java.awt.event.MouseEvent; public class LightUpCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - LightUpCell cell = (LightUpCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == -2) { - data.setData(-4); + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + LightUpCell cell = (LightUpCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == -2) { + data.setData(-4); + } else { + if (cell.getData() == -4) { + data.setData(-3); + } else { + data.setData(-2); + } + } + } } else { - if (cell.getData() == -4) { - data.setData(-3); - } else { - data.setData(-2); - } + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == -4) { + data.setData(-2); + } else { + if (cell.getData() == -2) { + data.setData(-3); + } else { + data.setData(-4); + } + } + } } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == -4) { - data.setData(-2); - } else { - if (cell.getData() == -2) { - data.setData(-3); - } else { - data.setData(-4); - } - } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java index 10a44ca85..384aa2b74 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java @@ -10,64 +10,66 @@ import org.w3c.dom.Node; public class LightUpCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public LightUpCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "lightup Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public LightUpCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "lightup Factory: unknown puzzleElement puzzleElement"); + } - LightUpBoard lightUpBoard = (LightUpBoard) board; - int width = lightUpBoard.getWidth(); - int height = lightUpBoard.getHeight(); + LightUpBoard lightUpBoard = (LightUpBoard) board; + int width = lightUpBoard.getWidth(); + int height = lightUpBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("lightup Factory: cell location out of bounds"); - } - if (value < -4 || value > 4) { - throw new InvalidFileFormatException("lightup Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "lightup Factory: cell location out of bounds"); + } + if (value < -4 || value > 4) { + throw new InvalidFileFormatException("lightup Factory: cell unknown value"); + } - LightUpCell cell = new LightUpCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("lightup Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("lightup Factory: could not find attribute(s)"); + LightUpCell cell = new LightUpCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "lightup Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("lightup Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java index 3d28a0604..8472be7a6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java @@ -1,15 +1,15 @@ package edu.rpi.legup.puzzle.lightup; public enum LightUpCellType { - BULB(-4), - EMPTY(-3), - UNKNOWN(-2), - BLACK(-1), - NUMBER(0); + BULB(-4), + EMPTY(-3), + UNKNOWN(-2), + BLACK(-1), + NUMBER(0); - public int value; + public int value; - LightUpCellType(int value) { - this.value = value; - } + LightUpCellType(int value) { + this.value = value; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java index 6805d9d29..1b00b007d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java @@ -4,85 +4,86 @@ import java.awt.*; public class LightUpElementView extends GridElementView { - private static final Color LITE = new Color(0xFFF176); - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color LITE = new Color(0xFFF176); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); - public LightUpElementView(LightUpCell cell) { - super(cell); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public LightUpCell getPuzzleElement() { - return (LightUpCell) super.getPuzzleElement(); - } + public LightUpElementView(LightUpCell cell) { + super(cell); + } - @Override - public void drawElement(Graphics2D graphics2D) { - LightUpCell cell = (LightUpCell) puzzleElement; - LightUpCellType type = cell.getType(); - if (type == LightUpCellType.NUMBER) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public LightUpCell getPuzzleElement() { + return (LightUpCell) super.getPuzzleElement(); + } - graphics2D.setColor(WHITE_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } else { - if (type == LightUpCellType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.EMPTY) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(cell.isLite() ? LITE : WHITE_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect( - location.x + size.width * 7 / 16, - location.y + size.height * 7 / 16, - size.width / 8, - size.height / 8); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.UNKNOWN) { + @Override + public void drawElement(Graphics2D graphics2D) { + LightUpCell cell = (LightUpCell) puzzleElement; + LightUpCellType type = cell.getType(); + if (type == LightUpCellType.NUMBER) { graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(cell.isLite() ? LITE : Color.LIGHT_GRAY); + graphics2D.setColor(BLACK_COLOR); graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.BULB) { - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.drawImage( - LightUpView.lightImage, - location.x, - location.y, - size.width, - size.height, - LITE, - null); - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + + graphics2D.setColor(WHITE_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } else { + if (type == LightUpCellType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.EMPTY) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(cell.isLite() ? LITE : WHITE_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect( + location.x + size.width * 7 / 16, + location.y + size.height * 7 / 16, + size.width / 8, + size.height / 8); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(cell.isLite() ? LITE : Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.BULB) { + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.drawImage( + LightUpView.lightImage, + location.x, + location.y, + size.width, + size.height, + LITE, + null); + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } + } + } } - } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java index d632879d5..0e8987020 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java @@ -6,34 +6,34 @@ public class LightUpExporter extends PuzzleExporter { - public LightUpExporter(LightUp lightUp) { - super(lightUp); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - LightUpBoard board; - if (puzzle.getTree() != null) { - board = (LightUpBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (LightUpBoard) puzzle.getBoardView().getBoard(); + public LightUpExporter(LightUp lightUp) { + super(lightUp); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + LightUpBoard board; + if (puzzle.getTree() != null) { + board = (LightUpBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (LightUpBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java index bce9f10ee..336b063f6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java @@ -8,113 +8,117 @@ import org.w3c.dom.NodeList; public class LightUpImporter extends PuzzleImporter { - public LightUpImporter(LightUp lightUp) { - super(lightUp); - } + public LightUpImporter(LightUp lightUp) { + super(lightUp); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - LightUpBoard lightUpBoard = new LightUpBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + LightUpBoard lightUpBoard = new LightUpBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - if (lightUpBoard.getCell(x, y) == null) { - LightUpCell cell = new LightUpCell(-2, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - lightUpBoard.setCell(x, y, cell); + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + if (lightUpBoard.getCell(x, y) == null) { + LightUpCell cell = new LightUpCell(-2, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + lightUpBoard.setCell(x, y, cell); + } + } } - } + puzzle.setCurrentBoard(lightUpBoard); } - puzzle.setCurrentBoard(lightUpBoard); - } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("lightup Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("lightup Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "lightup Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "lightup Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - LightUpBoard lightUpBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - lightUpBoard = new LightUpBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - lightUpBoard = new LightUpBoard(width, height); - } - } + LightUpBoard lightUpBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + lightUpBoard = new LightUpBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + lightUpBoard = new LightUpBoard(width, height); + } + } - if (lightUpBoard == null) { - throw new InvalidFileFormatException("lightup Importer: invalid board dimensions"); - } + if (lightUpBoard == null) { + throw new InvalidFileFormatException("lightup Importer: invalid board dimensions"); + } - int width = lightUpBoard.getWidth(); - int height = lightUpBoard.getHeight(); + int width = lightUpBoard.getWidth(); + int height = lightUpBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - LightUpCell cell = - (LightUpCell) puzzle.getFactory().importCell(elementDataList.item(i), lightUpBoard); - Point loc = cell.getLocation(); - if (cell.getData() != -2) { - cell.setModifiable(false); - cell.setGiven(true); - } - lightUpBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + LightUpCell cell = + (LightUpCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), lightUpBoard); + Point loc = cell.getLocation(); + if (cell.getData() != -2) { + cell.setModifiable(false); + cell.setGiven(true); + } + lightUpBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (lightUpBoard.getCell(x, y) == null) { - LightUpCell cell = new LightUpCell(-2, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - lightUpBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (lightUpBoard.getCell(x, y) == null) { + LightUpCell cell = new LightUpCell(-2, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + lightUpBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(lightUpBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "lightup Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(lightUpBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "lightup Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Light Up cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Light Up cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java index b8122ffff..ebce6a682 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java @@ -15,86 +15,90 @@ import org.apache.logging.log4j.Logger; public class LightUpView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(LightUpView.class.getName()); - static Image lightImage; + private static final Logger LOGGER = LogManager.getLogger(LightUpView.class.getName()); + static Image lightImage; - static { - try { - lightImage = - ImageIO.read( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/lightup/light.png")); - } catch (IOException e) { - LOGGER.error("Failed to open TreeTent images"); + static { + try { + lightImage = + ImageIO.read( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/lightup/light.png")); + } catch (IOException e) { + LOGGER.error("Failed to open TreeTent images"); + } } - } - public LightUpView(LightUpBoard board) { - super(new BoardController(), new LightUpCellController(), board.getDimension()); + public LightUpView(LightUpBoard board) { + super(new BoardController(), new LightUpCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); - LightUpElementView elementView = new LightUpElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); + LightUpElementView elementView = new LightUpElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - super.onTreeElementChanged(treeElement); - LightUpBoard lightUpBoard = - board instanceof CaseBoard - ? (LightUpBoard) ((CaseBoard) board).getBaseBoard() - : (LightUpBoard) board; - lightUpBoard.fillWithLight(); - repaint(); - } + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + super.onTreeElementChanged(treeElement); + LightUpBoard lightUpBoard = + board instanceof CaseBoard + ? (LightUpBoard) ((CaseBoard) board).getBaseBoard() + : (LightUpBoard) board; + lightUpBoard.fillWithLight(); + repaint(); + } - /** Returns a DataSelectionView popup menu */ - public DataSelectionView getSelectionPopupMenu() { - DataSelectionView selectionView = new DataSelectionView(elementController); - GridLayout layout = new GridLayout(3, 1); - selectionView.setLayout(layout); + /** Returns a DataSelectionView popup menu */ + public DataSelectionView getSelectionPopupMenu() { + DataSelectionView selectionView = new DataSelectionView(elementController); + GridLayout layout = new GridLayout(3, 1); + selectionView.setLayout(layout); - Dimension iconSize = new Dimension(32, 32); - Point loc = new Point(0, 0); + Dimension iconSize = new Dimension(32, 32); + Point loc = new Point(0, 0); - LightUpElementView element1 = new LightUpElementView(new LightUpCell(-2, null)); - element1.setSize(iconSize); - element1.setLocation(loc); - SelectionItemView item1 = - new SelectionItemView(element1.getPuzzleElement(), new ImageIcon(element1.getImage())); - item1.addActionListener(elementController); - item1.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item1); + LightUpElementView element1 = new LightUpElementView(new LightUpCell(-2, null)); + element1.setSize(iconSize); + element1.setLocation(loc); + SelectionItemView item1 = + new SelectionItemView( + element1.getPuzzleElement(), new ImageIcon(element1.getImage())); + item1.addActionListener(elementController); + item1.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item1); - LightUpElementView element2 = new LightUpElementView(new LightUpCell(-4, null)); - element2.setSize(iconSize); - element2.setLocation(loc); - SelectionItemView item2 = - new SelectionItemView(element2.getPuzzleElement(), new ImageIcon(element2.getImage())); - item2.addActionListener(elementController); - item2.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item2); + LightUpElementView element2 = new LightUpElementView(new LightUpCell(-4, null)); + element2.setSize(iconSize); + element2.setLocation(loc); + SelectionItemView item2 = + new SelectionItemView( + element2.getPuzzleElement(), new ImageIcon(element2.getImage())); + item2.addActionListener(elementController); + item2.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item2); - LightUpElementView element3 = new LightUpElementView(new LightUpCell(-3, null)); - element3.setSize(iconSize); - element3.setLocation(loc); - SelectionItemView item3 = - new SelectionItemView(element3.getPuzzleElement(), new ImageIcon(element3.getImage())); - item3.addActionListener(elementController); - item3.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item3); + LightUpElementView element3 = new LightUpElementView(new LightUpCell(-3, null)); + element3.setSize(iconSize); + element3.setLocation(loc); + SelectionItemView item3 = + new SelectionItemView( + element3.getPuzzleElement(), new ImageIcon(element3.getImage())); + item3.addActionListener(elementController); + item3.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item3); - return selectionView; - } + return selectionView; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java index bac5aa4ba..2ddb4f754 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java @@ -3,8 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class BlackTile extends NonPlaceableElement { - public BlackTile() { - super( - "LTUP-UNPL-0002", "Black Tile", "The black tile", "edu/rpi/legup/images/lightup/black.gif"); - } + public BlackTile() { + super( + "LTUP-UNPL-0002", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/lightup/black.gif"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java index ce0629fbe..d238baa56 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BulbTile extends PlaceableElement { - public BulbTile() { - super("LTUP-PLAC-0001", "Bulb Tile", "The bulb tile", "edu/rpi/legup/images/lightup/light.png"); - } + public BulbTile() { + super( + "LTUP-PLAC-0001", + "Bulb Tile", + "The bulb tile", + "edu/rpi/legup/images/lightup/light.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java index 9a2fba5c7..ae314a4cf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java @@ -4,20 +4,24 @@ public class NumberTile extends NonPlaceableElement { - int object_number; + int object_number; - // Follow the default format and resolves the NoSuchMethod error - public NumberTile() { - super("LTUP-UNPL-0001", "Number Tile", "The number tile", "edu/rpi/legup/images/lightup/1.gif"); - } + // Follow the default format and resolves the NoSuchMethod error + public NumberTile() { + super( + "LTUP-UNPL-0001", + "Number Tile", + "The number tile", + "edu/rpi/legup/images/lightup/1.gif"); + } - public NumberTile(int num) { - super( - "LTUP-UNPL-0001", - "Number Tile", - "The number tile", - "edu/rpi/legup/images/lightup/" + num + ".gif"); - if (num > 3 || num < 1) num = 1; - object_number = num; - } + public NumberTile(int num) { + super( + "LTUP-UNPL-0001", + "Number Tile", + "The number tile", + "edu/rpi/legup/images/lightup/" + num + ".gif"); + if (num > 3 || num < 1) num = 1; + object_number = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java index 4e17c6b37..24d420fe8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "LTUP-UNPL-0003", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/lightup/UnknownTile.png"); - } + public UnknownTile() { + super( + "LTUP-UNPL-0003", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/lightup/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java index 1adf449d0..90652888c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java @@ -10,72 +10,72 @@ public class BulbsInPathContradictionRule extends ContradictionRule { - public BulbsInPathContradictionRule() { - super( - "LTUP-CONT-0001", - "Bulbs In Path", - "A bulb cannot be placed in another bulb's path.", - "edu/rpi/legup/images/lightup/contradictions/BulbsInPath.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.BULB) { - return super.getNoContradictionMessage(); + public BulbsInPathContradictionRule() { + super( + "LTUP-CONT-0001", + "Bulbs In Path", + "A bulb cannot be placed in another bulb's path.", + "edu/rpi/legup/images/lightup/contradictions/BulbsInPath.png"); } - Point location = cell.getLocation(); - for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.BULB) { + return super.getNoContradictionMessage(); } - } - } - for (int i = location.x - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; + + Point location = cell.getLocation(); + for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; + } + } } - } - } - for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; + for (int i = location.x - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; + } + } } - } - } - for (int i = location.y - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; + for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; + } + } + } + for (int i = location.y - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; + } + } } - } + return super.getNoContradictionMessage(); } - return super.getNoContradictionMessage(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java index b9b93620a..0ed88636c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java @@ -10,80 +10,80 @@ public class CannotLightACellContradictionRule extends ContradictionRule { - public CannotLightACellContradictionRule() { - super( - "LTUP-CONT-0002", - "Cannot Light A Cell", - "All cells must be able to be lit.", - "edu/rpi/legup/images/lightup/contradictions/CannotLightACell.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - /*if (cell.getType() == LightUpCellType.BLACK || cell.getType() == LightUpCellType.NUMBER || cell.isLite()) { - return "This cell does not contain a contradiction"; - }*/ - if (cell.getType() != LightUpCellType.EMPTY || cell.isLite()) { - return super.getNoContradictionMessage(); + public CannotLightACellContradictionRule() { + super( + "LTUP-CONT-0002", + "Cannot Light A Cell", + "All cells must be able to be lit.", + "edu/rpi/legup/images/lightup/contradictions/CannotLightACell.png"); } - Point location = cell.getLocation(); - int ver_count = 0; - int hor_count = 0; - for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - hor_count += 1; + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + /*if (cell.getType() == LightUpCellType.BLACK || cell.getType() == LightUpCellType.NUMBER || cell.isLite()) { + return "This cell does not contain a contradiction"; + }*/ + if (cell.getType() != LightUpCellType.EMPTY || cell.isLite()) { + return super.getNoContradictionMessage(); } - } - } - for (int i = location.x - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - hor_count += 1; + Point location = cell.getLocation(); + int ver_count = 0; + int hor_count = 0; + for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + hor_count += 1; + } + } } - } - } - for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - ver_count += 1; + for (int i = location.x - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + hor_count += 1; + } + } } - } - } - for (int i = location.y - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - ver_count += 1; + for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + ver_count += 1; + } + } } - } - } - System.out.printf("%d, %d, %d, %d\n", location.x, location.y, hor_count, ver_count); - if (hor_count == 0 && ver_count == 0) { - return null; + for (int i = location.y - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + ver_count += 1; + } + } + } + System.out.printf("%d, %d, %d, %d\n", location.x, location.y, hor_count, ver_count); + if (hor_count == 0 && ver_count == 0) { + return null; + } + return super.getNoContradictionMessage(); } - return super.getNoContradictionMessage(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java index 857d2333d..269ef0ad5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java @@ -11,57 +11,58 @@ public class EmptyCellinLightDirectRule extends DirectRule { - public EmptyCellinLightDirectRule() { - super( - "LTUP-BASC-0002", - "Empty Cells in Light", - "Cells in light must be empty.", - "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - initialBoard.fillWithLight(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); - if (finalCell.getType() == LightUpCellType.EMPTY - && initCell.getType() == LightUpCellType.UNKNOWN - && initCell.isLite()) { - return null; + public EmptyCellinLightDirectRule() { + super( + "LTUP-BASC-0002", + "Empty Cells in Light", + "Cells in light must be empty.", + "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + initialBoard.fillWithLight(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); + if (finalCell.getType() == LightUpCellType.EMPTY + && initCell.getType() == LightUpCellType.UNKNOWN + && initCell.isLite()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java index e0e22b5f4..702c116c1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java @@ -14,101 +14,104 @@ public class EmptyCornersDirectRule extends DirectRule { - public EmptyCornersDirectRule() { - super( - "LTUP-BASC-0003", - "Empty Corners", - "Cells on the corners of a number must be empty if placing bulbs would prevent the number from being satisfied.", - "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); - } + public EmptyCornersDirectRule() { + super( + "LTUP-BASC-0003", + "Empty Corners", + "Cells on the corners of a number must be empty if placing bulbs would prevent the" + + " number from being satisfied.", + "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(cell.getType() == LightUpCellType.UNKNOWN - && finalCell.getType() == LightUpCellType.EMPTY)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; - } + if (!(cell.getType() == LightUpCellType.UNKNOWN + && finalCell.getType() == LightUpCellType.EMPTY)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; + } - Point loc = finalCell.getLocation(); - List numberedCells = new ArrayList<>(); - LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); - if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperRight); - } - LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); - if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperLeft); - } - LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); - if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerRight); - } - LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); - if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerLeft); - } - if (numberedCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() + ": This cell must diagonal to a numbered cell"; - } + Point loc = finalCell.getLocation(); + List numberedCells = new ArrayList<>(); + LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); + if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperRight); + } + LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); + if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperLeft); + } + LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); + if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerRight); + } + LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); + if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerLeft); + } + if (numberedCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must diagonal to a numbered cell"; + } - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - LightUpBoard bulbCaseBoard = finalBoard.copy(); - LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); - bulbCaseCell.setData(LightUpCellType.BULB.value); - bulbCaseBoard.fillWithLight(); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + LightUpBoard bulbCaseBoard = finalBoard.copy(); + LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); + bulbCaseCell.setData(LightUpCellType.BULB.value); + bulbCaseBoard.fillWithLight(); - boolean createsContra = false; - for (LightUpCell c : numberedCells) { - createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; + boolean createsContra = false; + for (LightUpCell c : numberedCells) { + createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; + } + if (createsContra) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; + } } - if (createsContra) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; - } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); - TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); - for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - int temp = cell.getData(); - cell.setData(LightUpCellType.EMPTY.value); - if (checkRuleRawAt(transition, cell) == null) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(modCell); - } else { - cell.setData(temp); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); + TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); + for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + int temp = cell.getData(); + cell.setData(LightUpCellType.EMPTY.value); + if (checkRuleRawAt(transition, cell) == null) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(modCell); + } else { + cell.setData(temp); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java index b2ae63788..3f884d459 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java @@ -12,97 +12,99 @@ public class FinishWithBulbsDirectRule extends DirectRule { - public FinishWithBulbsDirectRule() { - super( - "LTUP-BASC-0004", - "Finish with Bulbs", - "The remaining unknowns around a block must be bulbs to satisfy the number.", - "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == LightUpCellType.UNKNOWN - && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + public FinishWithBulbsDirectRule() { + super( + "LTUP-BASC-0004", + "Finish with Bulbs", + "The remaining unknowns around a block must be bulbs to satisfy the number.", + "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); } - Set adjCells = finalBoard.getAdj(finalCell); - adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() + ": This cell is not adjacent to a numbered cell"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == LightUpCellType.UNKNOWN + && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } - LightUpBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return null; - } - } - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; - } + Set adjCells = finalBoard.getAdj(finalCell); + adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + + ": This cell is not adjacent to a numbered cell"; + } - /** - * Determines whether the specified cell is forced to be a bulb or not - * - * @param board the entire board - * @param cell specified cell - * @return whether cell is forced to be a bulb or not - */ - private boolean isForced(LightUpBoard board, LightUpCell cell) { - Set adjCells = board.getAdj(cell); - adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return false; + LightUpBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return null; + } + } + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; } - LightUpBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return true; - } - } - return false; - } + /** + * Determines whether the specified cell is forced to be a bulb or not + * + * @param board the entire board + * @param cell specified cell + * @return whether cell is forced to be a bulb or not + */ + private boolean isForced(LightUpBoard board, LightUpCell cell) { + Set adjCells = board.getAdj(cell); + adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { - cell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + LightUpBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return true; + } + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { + cell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java index dc2647eb9..678ee67a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java @@ -12,108 +12,111 @@ public class FinishWithEmptyDirectRule extends DirectRule { - public FinishWithEmptyDirectRule() { - super( - "LTUP-BASC-0005", - "Finish with Empty", - "The remaining unknowns around a block must be empty if the number is satisfied.", - "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.EMPTY) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; - } - - if (isForced(initialBoard, cell.getLocation())) { - return null; + public FinishWithEmptyDirectRule() { + super( + "LTUP-BASC-0005", + "Finish with Empty", + "The remaining unknowns around a block must be empty if the number is satisfied.", + "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); } - return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; - } - /** - * Checks whether a certain cell is forced to not be a bulb - * - * @param board specified board - * @param location location of cell to check - * @return boolean value based on whether a certain cell has an adjacent cell that has the - * required amount of adjacent bulbs - */ - private boolean isForced(LightUpBoard board, Point location) { - return isForcedEmpty(board, new Point(location.x + 1, location.y)) - || isForcedEmpty(board, new Point(location.x, location.y + 1)) - || isForcedEmpty(board, new Point(location.x - 1, location.y)) - || isForcedEmpty(board, new Point(location.x, location.y - 1)); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.EMPTY) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; + } - /** - * Checks whether a certain cell has the required amount of adjacent bulbs - * - * @param board specified board - * @param loc location of cell to check - * @return boolean value based on whether a certain cell has the required amount of adjacent bulbs - */ - private boolean isForcedEmpty(LightUpBoard board, Point loc) { - LightUpCell cell = board.getCell(loc.x, loc.y); - if (cell == null || cell.getType() != LightUpCellType.NUMBER) { - return false; + if (isForced(initialBoard, cell.getLocation())) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; } - int bulbs = 0; - int bulbsNeeded = cell.getData(); - cell = board.getCell(loc.x + 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y + 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; + /** + * Checks whether a certain cell is forced to not be a bulb + * + * @param board specified board + * @param location location of cell to check + * @return boolean value based on whether a certain cell has an adjacent cell that has the + * required amount of adjacent bulbs + */ + private boolean isForced(LightUpBoard board, Point location) { + return isForcedEmpty(board, new Point(location.x + 1, location.y)) + || isForcedEmpty(board, new Point(location.x, location.y + 1)) + || isForcedEmpty(board, new Point(location.x - 1, location.y)) + || isForcedEmpty(board, new Point(location.x, location.y - 1)); } - cell = board.getCell(loc.x - 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y - 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - return bulbs == bulbsNeeded; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell.getLocation())) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } + /** + * Checks whether a certain cell has the required amount of adjacent bulbs + * + * @param board specified board + * @param loc location of cell to check + * @return boolean value based on whether a certain cell has the required amount of adjacent + * bulbs + */ + private boolean isForcedEmpty(LightUpBoard board, Point loc) { + LightUpCell cell = board.getCell(loc.x, loc.y); + if (cell == null || cell.getType() != LightUpCellType.NUMBER) { + return false; + } + + int bulbs = 0; + int bulbsNeeded = cell.getData(); + cell = board.getCell(loc.x + 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y + 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x - 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y - 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + return bulbs == bulbsNeeded; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN + && isForced(initialBoard, cell.getLocation())) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java index 39ad146a7..4ba754731 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java @@ -13,100 +13,101 @@ public class LightOrEmptyCaseRule extends CaseRule { - public LightOrEmptyCaseRule() { - super( - "LTUP-CASE-0001", - "Light or Empty", - "Each blank cell is either a light or empty.", - "edu/rpi/legup/images/lightup/cases/LightOrEmpty.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); - lightUpBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((LightUpCell) data).getType() == LightUpCellType.UNKNOWN) { - caseBoard.addPickableElement(data); - } + public LightOrEmptyCaseRule() { + super( + "LTUP-CASE-0001", + "Light or Empty", + "Each blank cell is either a light or empty.", + "edu/rpi/legup/images/lightup/cases/LightOrEmpty.png"); } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(-4); - case1.addModifiedData(data1); - cases.add(case1); + @Override + public CaseBoard getCaseBoard(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); + lightUpBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((LightUpCell) data).getType() == LightUpCellType.UNKNOWN) { + caseBoard.addPickableElement(data); + } + } + return caseBoard; + } - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(-3); - case2.addModifiedData(data2); - cases.add(case2); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(-4); + case1.addModifiedData(data1); + cases.add(case1); - return cases; - } + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(-3); + case2.addModifiedData(data2); + cases.add(case2); - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children"; + return cases; } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children"; + } - LightUpCell mod1 = (LightUpCell) case1.getBoard().getModifiedData().iterator().next(); - LightUpCell mod2 = (LightUpCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case"; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; + } - if (!((mod1.getType() == LightUpCellType.EMPTY && mod2.getType() == LightUpCellType.BULB) - || (mod2.getType() == LightUpCellType.EMPTY && mod1.getType() == LightUpCellType.BULB))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty cell and a bulb cell"; - } + LightUpCell mod1 = (LightUpCell) case1.getBoard().getModifiedData().iterator().next(); + LightUpCell mod2 = (LightUpCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case"; + } + + if (!((mod1.getType() == LightUpCellType.EMPTY && mod2.getType() == LightUpCellType.BULB) + || (mod2.getType() == LightUpCellType.EMPTY + && mod1.getType() == LightUpCellType.BULB))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty cell and a bulb cell"; + } - return null; - } + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java index 272450959..bf1843728 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java @@ -12,141 +12,142 @@ public class MustLightDirectRule extends DirectRule { - public MustLightDirectRule() { - super( - "LTUP-BASC-0006", - "Must Light", - "A cell must be a bulb if it is the only cell to be able to light another.", - "edu/rpi/legup/images/lightup/rules/MustLight.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == LightUpCellType.UNKNOWN - && !parentCell.isLite() - && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + public MustLightDirectRule() { + super( + "LTUP-BASC-0006", + "Must Light", + "A cell must be a bulb if it is the only cell to be able to light another.", + "edu/rpi/legup/images/lightup/rules/MustLight.png"); } - finalBoard.fillWithLight(); - boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); - finalCell.setData(LightUpCellType.BULB.value); - finalBoard.fillWithLight(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(parentCell.getType() == LightUpCellType.UNKNOWN + && !parentCell.isLite() + && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } - if (isForced) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; - } - } + finalBoard.fillWithLight(); + boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); + finalCell.setData(LightUpCellType.BULB.value); + finalBoard.fillWithLight(); - private boolean isForcedBulb(LightUpBoard board, Point loc) { - CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); - LightUpBoard modifiedBoard = board.copy(); - LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); - modifiedCell.setData(LightUpCellType.EMPTY.value); - // Check if this cell itself (the one with the bulb) has no other lighting option - if ((modifiedCell.getType() == LightUpCellType.EMPTY - || modifiedCell.getType() == LightUpCellType.UNKNOWN) - && !modifiedCell.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { - return true; - } - // Look right - for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; + if (isForced) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; } - } } - // Look left - for (int i = loc.x - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; + + private boolean isForcedBulb(LightUpBoard board, Point loc) { + CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); + LightUpBoard modifiedBoard = board.copy(); + LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); + modifiedCell.setData(LightUpCellType.EMPTY.value); + // Check if this cell itself (the one with the bulb) has no other lighting option + if ((modifiedCell.getType() == LightUpCellType.EMPTY + || modifiedCell.getType() == LightUpCellType.UNKNOWN) + && !modifiedCell.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { + return true; } - } - } - // Look down - for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; + // Look right + for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } } - } - } - // Look up - for (int i = loc.y - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; + // Look left + for (int i = loc.x - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } + } + // Look down + for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } + } + // Look up + for (int i = loc.y - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } } - } + return false; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : tempBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - if (isForcedBulb(initialBoard, cell.getLocation())) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(modCell); + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : tempBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + if (isForcedBulb(initialBoard, cell.getLocation())) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(modCell); + } + cell.setData(LightUpCellType.UNKNOWN.value); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } - cell.setData(LightUpCellType.UNKNOWN.value); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java index 7e9f258a3..ac656721d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java @@ -17,337 +17,341 @@ public class SatisfyNumberCaseRule extends CaseRule { - public SatisfyNumberCaseRule() { - super( - "LTUP-CASE-0002", - "Satisfy Number", - "The different ways a blocks number can be satisfied.", - "edu/rpi/legup/images/lightup/cases/SatisfyNumber.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - lightUpBoard.setModifiable(false); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((LightUpCell) data).getType() == LightUpCellType.NUMBER) { - caseBoard.addPickableElement(data); - } + public SatisfyNumberCaseRule() { + super( + "LTUP-CASE-0002", + "Satisfy Number", + "The different ways a blocks number can be satisfied.", + "edu/rpi/legup/images/lightup/cases/SatisfyNumber.png"); } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); - - List openSpots = new ArrayList<>(); - - int numNeeded = cell.getData(); - - LightUpCell checkCell = lightUpBoard.getCell(loc.x + 1, loc.y); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; + + @Override + public CaseBoard getCaseBoard(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + lightUpBoard.setModifiable(false); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((LightUpCell) data).getType() == LightUpCellType.NUMBER) { + caseBoard.addPickableElement(data); + } } - } + return caseBoard; } - checkCell = lightUpBoard.getCell(loc.x, loc.y + 1); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); + + List openSpots = new ArrayList<>(); + + int numNeeded = cell.getData(); + + LightUpCell checkCell = lightUpBoard.getCell(loc.x + 1, loc.y); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; + } + } } - } - } - checkCell = lightUpBoard.getCell(loc.x - 1, loc.y); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; + checkCell = lightUpBoard.getCell(loc.x, loc.y + 1); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; + } + } } - } - } - checkCell = lightUpBoard.getCell(loc.x, loc.y - 1); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; + checkCell = lightUpBoard.getCell(loc.x - 1, loc.y); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; + } + } + } + checkCell = lightUpBoard.getCell(loc.x, loc.y - 1); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; + } + } } - } - } - - ArrayList cases = new ArrayList<>(); - if (numNeeded == 0) { - return cases; - } - generateCases(lightUpBoard, numNeeded, openSpots, cases); + ArrayList cases = new ArrayList<>(); + if (numNeeded == 0) { + return cases; + } - return cases; - } + generateCases(lightUpBoard, numNeeded, openSpots, cases); - private void generateCases( - final LightUpBoard board, final int num, List openSpots, List cases) { - if (num > openSpots.size()) { - return; + return cases; } - for (int i = 0; i < openSpots.size(); i++) { - LightUpCell c = openSpots.get(i); - LightUpBoard newCase = board.copy(); - LightUpCell newCell = c.copy(); - Point loc = c.getLocation(); + private void generateCases( + final LightUpBoard board, + final int num, + List openSpots, + List cases) { + if (num > openSpots.size()) { + return; + } - newCell.setData(-4); - newCase.setCell(loc.x, loc.y, newCell); - newCase.addModifiedData(newCell); + for (int i = 0; i < openSpots.size(); i++) { + LightUpCell c = openSpots.get(i); + LightUpBoard newCase = board.copy(); + LightUpCell newCell = c.copy(); + Point loc = c.getLocation(); - generateCases(board, num, openSpots, cases, newCase, i); - } - } - - private void generateCases( - final LightUpBoard board, - final int num, - List openSpots, - List cases, - LightUpBoard curBoard, - int index) { - if (num <= curBoard.getModifiedData().size()) { - cases.add(curBoard); - return; + newCell.setData(-4); + newCase.setCell(loc.x, loc.y, newCell); + newCase.addModifiedData(newCell); + + generateCases(board, num, openSpots, cases, newCase, i); + } } - for (int i = index + 1; i < openSpots.size(); i++) { - LightUpCell c = openSpots.get(i); - Point loc = c.getLocation(); - LightUpCell cc = curBoard.getCell(loc.x, loc.y); - if (!curBoard.getModifiedData().contains(cc)) { - LightUpBoard newCase = board.copy(); - LightUpCell newCell = c.copy(); + private void generateCases( + final LightUpBoard board, + final int num, + List openSpots, + List cases, + LightUpBoard curBoard, + int index) { + if (num <= curBoard.getModifiedData().size()) { + cases.add(curBoard); + return; + } - for (PuzzleElement mod : curBoard.getModifiedData()) { - LightUpCell modCell = (LightUpCell) mod.copy(); - Point modLoc = modCell.getLocation(); + for (int i = index + 1; i < openSpots.size(); i++) { + LightUpCell c = openSpots.get(i); + Point loc = c.getLocation(); + LightUpCell cc = curBoard.getCell(loc.x, loc.y); + if (!curBoard.getModifiedData().contains(cc)) { + LightUpBoard newCase = board.copy(); + LightUpCell newCell = c.copy(); - modCell.setData(-4); + for (PuzzleElement mod : curBoard.getModifiedData()) { + LightUpCell modCell = (LightUpCell) mod.copy(); + Point modLoc = modCell.getLocation(); - newCase.setCell(modLoc.x, modLoc.y, modCell); - newCase.addModifiedData(modCell); - } + modCell.setData(-4); - newCell.setData(-4); + newCase.setCell(modLoc.x, modLoc.y, modCell); + newCase.addModifiedData(modCell); + } - newCase.setCell(loc.x, loc.y, newCell); - newCase.addModifiedData(newCell); + newCell.setData(-4); - generateCases(board, num, openSpots, cases, newCase, i); - } - } - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - TreeNode parent = transition.getParents().get(0); - List childTransitions = parent.getChildren(); - - List spots = getPossibleSpots(transition); - if (spots == null) { - return super.getInvalidUseOfRuleMessage(); + newCase.setCell(loc.x, loc.y, newCell); + newCase.addModifiedData(newCell); + + generateCases(board, num, openSpots, cases, newCase, i); + } + } } - for (LightUpCell c : spots) { - ArrayList cases = getCases(parent.getBoard(), c); - - // We will allow case rules to have only one option - if (cases.size() == childTransitions.size() && cases.size() >= 1) { - boolean foundSpot = true; - for (TreeTransition childTrans : childTransitions) { - LightUpBoard actCase = (LightUpBoard) childTrans.getBoard(); - boolean foundBoard = false; - for (Board b : cases) { - LightUpBoard posCase = (LightUpBoard) b; - boolean foundAllCells = false; - if (posCase.getModifiedData().size() == actCase.getModifiedData().size()) { - foundAllCells = true; - for (PuzzleElement actEle : actCase.getModifiedData()) { - LightUpCell actCell = (LightUpCell) actEle; - boolean foundCell = false; - for (PuzzleElement posEle : posCase.getModifiedData()) { - LightUpCell posCell = (LightUpCell) posEle; - if (actCell.getType() == posCell.getType() - && actCell.getLocation().equals(posCell.getLocation())) { - foundCell = true; - break; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + TreeNode parent = transition.getParents().get(0); + List childTransitions = parent.getChildren(); + + List spots = getPossibleSpots(transition); + if (spots == null) { + return super.getInvalidUseOfRuleMessage(); + } + + for (LightUpCell c : spots) { + ArrayList cases = getCases(parent.getBoard(), c); + + // We will allow case rules to have only one option + if (cases.size() == childTransitions.size() && cases.size() >= 1) { + boolean foundSpot = true; + for (TreeTransition childTrans : childTransitions) { + LightUpBoard actCase = (LightUpBoard) childTrans.getBoard(); + boolean foundBoard = false; + for (Board b : cases) { + LightUpBoard posCase = (LightUpBoard) b; + boolean foundAllCells = false; + if (posCase.getModifiedData().size() == actCase.getModifiedData().size()) { + foundAllCells = true; + for (PuzzleElement actEle : actCase.getModifiedData()) { + LightUpCell actCell = (LightUpCell) actEle; + boolean foundCell = false; + for (PuzzleElement posEle : posCase.getModifiedData()) { + LightUpCell posCell = (LightUpCell) posEle; + if (actCell.getType() == posCell.getType() + && actCell.getLocation() + .equals(posCell.getLocation())) { + foundCell = true; + break; + } + } + if (!foundCell) { + foundAllCells = false; + break; + } + } + } + if (foundAllCells) { + foundBoard = true; + break; + } + } + if (!foundBoard) { + foundSpot = false; + break; + } } - if (!foundCell) { - foundAllCells = false; - break; + if (foundSpot) { + return null; } - } - } - if (foundAllCells) { - foundBoard = true; - break; } - } - if (!foundBoard) { - foundSpot = false; - break; - } } - if (foundSpot) { - return null; - } - } - } - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Gets all cells in the TreeTransition board that are adjacent to all modified cells - * - * @param transition TreeTransition object - * @return list of cells that are adjacent to all modified cells, returns null if the number of - * modified cells is =0 || >4 - */ - private List getPossibleSpots(TreeTransition transition) { - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Set modCells = transition.getBoard().getModifiedData(); - - int size = modCells.size(); - if (size == 0 || size > 4) { - return null; - } else { - Iterator it = modCells.iterator(); - List spots = getAdjacentCells(board, (LightUpCell) it.next()); - - while (it.hasNext()) { - spots.retainAll(getAdjacentCells(board, (LightUpCell) it.next())); - } - return spots; - } - } - - private List getAdjacentCells(LightUpBoard board, LightUpCell cell) { - List cells = new ArrayList<>(); - Point point = cell.getLocation(); - LightUpCell right = board.getCell(point.x + 1, point.y); - if (right != null) { - cells.add(right); + return super.getInvalidUseOfRuleMessage(); } - LightUpCell down = board.getCell(point.x, point.y + 1); - if (down != null) { - cells.add(down); - } - LightUpCell left = board.getCell(point.x - 1, point.y); - if (left != null) { - cells.add(left); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; } - LightUpCell up = board.getCell(point.x, point.y - 1); - if (up != null) { - cells.add(up); + + /** + * Gets all cells in the TreeTransition board that are adjacent to all modified cells + * + * @param transition TreeTransition object + * @return list of cells that are adjacent to all modified cells, returns null if the number of + * modified cells is =0 || >4 + */ + private List getPossibleSpots(TreeTransition transition) { + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Set modCells = transition.getBoard().getModifiedData(); + + int size = modCells.size(); + if (size == 0 || size > 4) { + return null; + } else { + Iterator it = modCells.iterator(); + List spots = getAdjacentCells(board, (LightUpCell) it.next()); + + while (it.hasNext()) { + spots.retainAll(getAdjacentCells(board, (LightUpCell) it.next())); + } + return spots; + } } - return cells; - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - LightUpBoard puzzleBoard = (LightUpBoard) board; - LightUpCell point = (LightUpCell) puzzleBoard.getPuzzleElement(puzzleElement); - - List cells = getAdjacentCells(puzzleBoard, point); - - for (LightUpCell cell : cells) { - // add cells that can light adjacents from any direction - Point location = cell.getLocation(); - for (int i = location.x; i < puzzleBoard.getWidth(); i++) { - System.out.println(i); - LightUpCell c = puzzleBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); + + private List getAdjacentCells(LightUpBoard board, LightUpCell cell) { + List cells = new ArrayList<>(); + Point point = cell.getLocation(); + LightUpCell right = board.getCell(point.x + 1, point.y); + if (right != null) { + cells.add(right); } - } - for (int i = location.x; i >= 0; i--) { - LightUpCell c = puzzleBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); + LightUpCell down = board.getCell(point.x, point.y + 1); + if (down != null) { + cells.add(down); } - } - for (int i = location.y; i < puzzleBoard.getHeight(); i++) { - LightUpCell c = puzzleBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); + LightUpCell left = board.getCell(point.x - 1, point.y); + if (left != null) { + cells.add(left); } - } - for (int i = location.y; i >= 0; i--) { - LightUpCell c = puzzleBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); + LightUpCell up = board.getCell(point.x, point.y - 1); + if (up != null) { + cells.add(up); } - } + return cells; } - return elements; - } + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + LightUpBoard puzzleBoard = (LightUpBoard) board; + LightUpCell point = (LightUpCell) puzzleBoard.getPuzzleElement(puzzleElement); + + List cells = getAdjacentCells(puzzleBoard, point); + + for (LightUpCell cell : cells) { + // add cells that can light adjacents from any direction + Point location = cell.getLocation(); + for (int i = location.x; i < puzzleBoard.getWidth(); i++) { + System.out.println(i); + LightUpCell c = puzzleBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); + } + } + for (int i = location.x; i >= 0; i--) { + LightUpCell c = puzzleBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); + } + } + for (int i = location.y; i < puzzleBoard.getHeight(); i++) { + LightUpCell c = puzzleBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); + } + } + for (int i = location.y; i >= 0; i--) { + LightUpCell c = puzzleBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); + } + } + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java index 8b00e537e..8cf68e570 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java @@ -10,37 +10,37 @@ public class TooFewBulbsContradictionRule extends ContradictionRule { - public TooFewBulbsContradictionRule() { - super( - "LTUP-CONT-0003", - "Too Few Bulbs", - "There cannot be less bulbs around a block than its number states.", - "edu/rpi/legup/images/lightup/contradictions/TooFewBulbs.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.NUMBER) { - return super.getNoContradictionMessage(); + public TooFewBulbsContradictionRule() { + super( + "LTUP-CONT-0003", + "Too Few Bulbs", + "There cannot be less bulbs around a block than its number states.", + "edu/rpi/legup/images/lightup/contradictions/TooFewBulbs.png"); } - int bulbs = lightUpBoard.getNumAdj(cell, LightUpCellType.BULB); - int placeable = lightUpBoard.getNumPlacble(cell); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.NUMBER) { + return super.getNoContradictionMessage(); + } + + int bulbs = lightUpBoard.getNumAdj(cell, LightUpCellType.BULB); + int placeable = lightUpBoard.getNumPlacble(cell); - if (bulbs + placeable < cell.getData()) { - return null; + if (bulbs + placeable < cell.getData()) { + return null; + } + return super.getNoContradictionMessage(); } - return super.getNoContradictionMessage(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java index 8d1403663..64cd4adcb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java @@ -10,55 +10,55 @@ public class TooManyBulbsContradictionRule extends ContradictionRule { - public TooManyBulbsContradictionRule() { - super( - "LTUP-CONT-0004", - "Too Many Bulbs", - "There cannot be more bulbs around a block than its number states.", - "edu/rpi/legup/images/lightup/contradictions/TooManyBulbs.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.NUMBER) { - return super.getNoContradictionMessage(); + public TooManyBulbsContradictionRule() { + super( + "LTUP-CONT-0004", + "Too Many Bulbs", + "There cannot be more bulbs around a block than its number states.", + "edu/rpi/legup/images/lightup/contradictions/TooManyBulbs.png"); } - Point location = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.NUMBER) { + return super.getNoContradictionMessage(); + } - int bulbs = 0; + Point location = cell.getLocation(); - LightUpCell up = lightUpBoard.getCell(location.x, location.y + 1); - if (up != null && up.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell down = lightUpBoard.getCell(location.x, location.y - 1); - if (down != null && down.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell right = lightUpBoard.getCell(location.x + 1, location.y); - if (right != null && right.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell left = lightUpBoard.getCell(location.x - 1, location.y); - if (left != null && left.getType() == LightUpCellType.BULB) { - bulbs++; - } + int bulbs = 0; + + LightUpCell up = lightUpBoard.getCell(location.x, location.y + 1); + if (up != null && up.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell down = lightUpBoard.getCell(location.x, location.y - 1); + if (down != null && down.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell right = lightUpBoard.getCell(location.x + 1, location.y); + if (right != null && right.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell left = lightUpBoard.getCell(location.x - 1, location.y); + if (left != null && left.getType() == LightUpCellType.BULB) { + bulbs++; + } - if (bulbs > cell.getData()) { - return null; + if (bulbs > cell.getData()) { + return null; + } + return super.getNoContradictionMessage(); } - return super.getNoContradictionMessage(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java b/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java index 98e22173e..9986a1eda 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java @@ -17,154 +17,157 @@ import java.awt.event.MouseEvent; public class EditLineCommand extends PuzzleCommand { - private TreeTransition transition; - private PuzzleElement oldData; - private PuzzleElement newData; - - private ElementView elementView; - private TreeElementView selectedView; - private TreeElementView newSelectedView; - private MouseEvent event; - - private TreeTransitionView transitionView; - - public EditLineCommand( - ElementView elementView, TreeElementView selectedView, MouseEvent event, MasyuLine line) { - this.elementView = elementView; - this.selectedView = selectedView; - this.event = event; - this.newData = line; - this.oldData = newData.copy(); - this.transition = null; - } - - /** Executes a command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - Puzzle puzzle = getInstance().getPuzzleModule(); - - MasyuBoard board = (MasyuBoard) selectedView.getTreeElement().getBoard(); - int index = elementView.getIndex(); - - if (selectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); - - if (transition == null) { - transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - } - - treeNode.getChildren().add(transition); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeElementAdded(transition)); - transitionView = (TreeTransitionView) treeView.getElementView(transition); - - selection.newSelection(transitionView); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeSelectionChanged(selection)); - - getInstance().getLegupUI().repaintTree(); - board = (MasyuBoard) transition.getBoard(); - getInstance().getPuzzleModule().setCurrentBoard(board); - oldData = newData.copy(); - } else { - transitionView = (TreeTransitionView) selectedView; - transition = transitionView.getTreeElement(); + private TreeTransition transition; + private PuzzleElement oldData; + private PuzzleElement newData; + + private ElementView elementView; + private TreeElementView selectedView; + private TreeElementView newSelectedView; + private MouseEvent event; + + private TreeTransitionView transitionView; + + public EditLineCommand( + ElementView elementView, + TreeElementView selectedView, + MouseEvent event, + MasyuLine line) { + this.elementView = elementView; + this.selectedView = selectedView; + this.event = event; + this.newData = line; + this.oldData = newData.copy(); + this.transition = null; } - newSelectedView = transitionView; - PuzzleElement dup_line = null; - boolean mod_contains = false; - boolean contains = false; - final MasyuBoard editBoard = board; - System.out.println("Size: " + board.getModifiedData().size()); - for (PuzzleElement puzzleElement : board.getModifiedData()) { - if (puzzleElement instanceof MasyuLine) { - if (((MasyuLine) newData).compare((MasyuLine) puzzleElement)) { - System.out.println("contains"); - dup_line = puzzleElement; - mod_contains = true; + + /** Executes a command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + Puzzle puzzle = getInstance().getPuzzleModule(); + + MasyuBoard board = (MasyuBoard) selectedView.getTreeElement().getBoard(); + int index = elementView.getIndex(); + + if (selectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); + + if (transition == null) { + transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + } + + treeNode.getChildren().add(transition); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeElementAdded(transition)); + transitionView = (TreeTransitionView) treeView.getElementView(transition); + + selection.newSelection(transitionView); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeSelectionChanged(selection)); + + getInstance().getLegupUI().repaintTree(); + board = (MasyuBoard) transition.getBoard(); + getInstance().getPuzzleModule().setCurrentBoard(board); + oldData = newData.copy(); + } else { + transitionView = (TreeTransitionView) selectedView; + transition = transitionView.getTreeElement(); } - } - } - for (int i = 0; i < board.getLines().size(); i++) { - if (board.getLines().get(i).compare((MasyuLine) newData)) { - contains = true; - } - } - if (contains || mod_contains) { - System.out.println("delete"); - board.getModifiedData().remove(dup_line); - board.getLines().remove(dup_line); - // puzzle.notifyBoardListeners((IBoardListener listener) -> - // listener.onTreeElementChanged(editBoard)); - } else { - System.out.println("adding"); - board.getModifiedData().add(newData); - board.getLines().add((MasyuLine) newData); - // puzzle.notifyBoardListeners((IBoardListener listener) -> - // listener.onTreeElementChanged(editBoard)); + newSelectedView = transitionView; + PuzzleElement dup_line = null; + boolean mod_contains = false; + boolean contains = false; + final MasyuBoard editBoard = board; + System.out.println("Size: " + board.getModifiedData().size()); + for (PuzzleElement puzzleElement : board.getModifiedData()) { + if (puzzleElement instanceof MasyuLine) { + if (((MasyuLine) newData).compare((MasyuLine) puzzleElement)) { + System.out.println("contains"); + dup_line = puzzleElement; + mod_contains = true; + } + } + } + for (int i = 0; i < board.getLines().size(); i++) { + if (board.getLines().get(i).compare((MasyuLine) newData)) { + contains = true; + } + } + if (contains || mod_contains) { + System.out.println("delete"); + board.getModifiedData().remove(dup_line); + board.getLines().remove(dup_line); + // puzzle.notifyBoardListeners((IBoardListener listener) -> + // listener.onTreeElementChanged(editBoard)); + } else { + System.out.println("adding"); + board.getModifiedData().add(newData); + board.getLines().add((MasyuLine) newData); + // puzzle.notifyBoardListeners((IBoardListener listener) -> + // listener.onTreeElementChanged(editBoard)); + } + + transition.propagateChange(newData); } - transition.propagateChange(newData); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - Board board = selectedView.getTreeElement().getBoard(); - if (!board.isModifiable()) { - return "Board is not modifiable"; - } else { - if (!board.getPuzzleElement(elementView.getPuzzleElement()).isModifiable()) { - return "Data is not modifiable"; - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + Board board = selectedView.getTreeElement().getBoard(); + if (!board.isModifiable()) { + return "Board is not modifiable"; + } else { + if (!board.getPuzzleElement(elementView.getPuzzleElement()).isModifiable()) { + return "Data is not modifiable"; + } + } + return null; } - return null; - } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); - Board board = transition.getBoard(); + Board board = transition.getBoard(); - if (selectedView.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); + if (selectedView.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); - tree.removeTreeElement(transition); - treeView.removeTreeElement(newSelectedView); + tree.removeTreeElement(transition); + treeView.removeTreeElement(newSelectedView); - selection.newSelection(selectedView); + selection.newSelection(selectedView); - getInstance().getLegupUI().repaintTree(); - getInstance().getPuzzleModule().setCurrentBoard(treeNode.getBoard()); - } + getInstance().getLegupUI().repaintTree(); + getInstance().getPuzzleModule().setCurrentBoard(treeNode.getBoard()); + } - Board prevBoard = null; // transition.getParentNode().getBoard(); + Board prevBoard = null; // transition.getParentNode().getBoard(); - newData.setData(oldData.getData()); - board.notifyChange(newData); + newData.setData(oldData.getData()); + board.notifyChange(newData); - // System.err.println(newData.getData() + " : " + oldData.getData()); + // System.err.println(newData.getData() + " : " + oldData.getData()); - if (prevBoard.getPuzzleElement(elementView.getPuzzleElement()).equalsData(newData)) { - board.removeModifiedData(newData); - } else { - board.addModifiedData(newData); + if (prevBoard.getPuzzleElement(elementView.getPuzzleElement()).equalsData(newData)) { + board.removeModifiedData(newData); + } else { + board.addModifiedData(newData); + } + transition.propagateChange(newData); } - transition.propagateChange(newData); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java b/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java index 1c5d19e08..1ab74d56b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java @@ -5,63 +5,63 @@ public class Masyu extends Puzzle { - public Masyu() { - super(); + public Masyu() { + super(); - this.name = "Masyu"; + this.name = "Masyu"; - this.importer = new MasyuImporter(this); - this.exporter = new MasyuExporter(this); + this.importer = new MasyuImporter(this); + this.exporter = new MasyuExporter(this); - this.factory = new MasyuCellFactory(); - } + this.factory = new MasyuCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new MasyuView((MasyuBoard) currentBoard); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new MasyuView((MasyuBoard) currentBoard); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Masyu - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Masyu, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for Masyu + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Masyu, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java index 554408dd3..f347ff4c4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java @@ -7,53 +7,53 @@ public class MasyuBoard extends GridBoard { - private List lines; - - public MasyuBoard(int width, int height) { - super(width, height); - this.lines = new ArrayList<>(); - } - - public MasyuBoard(int size) { - this(size, size); - } - - @Override - public MasyuCell getCell(int x, int y) { - return (MasyuCell) super.getCell(x, y); - } - - public List getLines() { - return lines; - } - - public void setLines(List lines) { - this.lines = lines; - } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - if (puzzleElement instanceof MasyuLine) { - lines.add((MasyuLine) puzzleElement); - } else { - super.notifyChange(puzzleElement); + private List lines; + + public MasyuBoard(int width, int height) { + super(width, height); + this.lines = new ArrayList<>(); + } + + public MasyuBoard(int size) { + this(size, size); + } + + @Override + public MasyuCell getCell(int x, int y) { + return (MasyuCell) super.getCell(x, y); } - } - - @Override - public MasyuBoard copy() { - MasyuBoard copy = new MasyuBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + + public List getLines() { + return lines; } - for (MasyuLine line : lines) { - copy.lines.add(line.copy()); + + public void setLines(List lines) { + this.lines = lines; } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + if (puzzleElement instanceof MasyuLine) { + lines.add((MasyuLine) puzzleElement); + } else { + super.notifyChange(puzzleElement); + } + } + + @Override + public MasyuBoard copy() { + MasyuBoard copy = new MasyuBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (MasyuLine line : lines) { + copy.lines.add(line.copy()); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; } - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java index 7d23cdf37..af0811c55 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java @@ -5,20 +5,20 @@ public class MasyuCell extends GridCell { - public MasyuCell(MasyuType value, Point location) { - super(value, location); - } + public MasyuCell(MasyuType value, Point location) { + super(value, location); + } - public MasyuType getType() { - return data; - } + public MasyuType getType() { + return data; + } - @Override - public MasyuCell copy() { - MasyuCell copy = new MasyuCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public MasyuCell copy() { + MasyuCell copy = new MasyuCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java index 803edfbea..50e3c4cc0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java @@ -10,63 +10,65 @@ import org.w3c.dom.Node; public class MasyuCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public MasyuCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Masyu Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public MasyuCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Masyu Factory: unknown puzzleElement puzzleElement"); + } - MasyuBoard masyuBoard = (MasyuBoard) board; - int width = masyuBoard.getWidth(); - int height = masyuBoard.getHeight(); + MasyuBoard masyuBoard = (MasyuBoard) board; + int width = masyuBoard.getWidth(); + int height = masyuBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Masyu Factory: cell location out of bounds"); - } - if (value < 0 || value > 2) { - throw new InvalidFileFormatException("Masyu Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("Masyu Factory: cell location out of bounds"); + } + if (value < 0 || value > 2) { + throw new InvalidFileFormatException("Masyu Factory: cell unknown value"); + } - MasyuCell cell = new MasyuCell(MasyuType.convertToMasyuType(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("Masyu Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Masyu Factory: could not find attribute(s)"); + MasyuCell cell = new MasyuCell(MasyuType.convertToMasyuType(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Masyu Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Masyu Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - MasyuCell cell = (MasyuCell) puzzleElement; - Point loc = cell.getLocation(); + MasyuCell cell = (MasyuCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java index 1644e4d11..202c43a1e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java @@ -14,89 +14,93 @@ public class MasyuController extends ElementController { - private MasyuElementView mousePressedCell; - private MasyuElementView mouseDraggedCell; - private List masyuLine; + private MasyuElementView mousePressedCell; + private MasyuElementView mouseDraggedCell; + private List masyuLine; - public MasyuController() { - super(); - this.mousePressedCell = null; - this.mouseDraggedCell = null; - this.masyuLine = new ArrayList<>(); - } + public MasyuController() { + super(); + this.mousePressedCell = null; + this.mouseDraggedCell = null; + this.masyuLine = new ArrayList<>(); + } - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e the event to be processed - */ - @Override - public void mousePressed(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - this.masyuLine.clear(); - mousePressedCell = (MasyuElementView) boardView.getElement(e.getPoint()); - masyuLine.add(mousePressedCell); - } + /** + * Invoked when a mouse button has been pressed on a component. + * + * @param e the event to be processed + */ + @Override + public void mousePressed(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + this.masyuLine.clear(); + mousePressedCell = (MasyuElementView) boardView.getElement(e.getPoint()); + masyuLine.add(mousePressedCell); + } - @Override - public void mouseDragged(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - MasyuElementView elementView = (MasyuElementView) boardView.getElement(e.getPoint()); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (mousePressedCell != null && elementView != null) { - if (mouseDraggedCell == null) { - mouseDraggedCell = elementView; - Point p1 = mousePressedCell.getPuzzleElement().getLocation(); - Point p2 = mouseDraggedCell.getPuzzleElement().getLocation(); + @Override + public void mouseDragged(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + MasyuElementView elementView = (MasyuElementView) boardView.getElement(e.getPoint()); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (mousePressedCell != null && elementView != null) { + if (mouseDraggedCell == null) { + mouseDraggedCell = elementView; + Point p1 = mousePressedCell.getPuzzleElement().getLocation(); + Point p2 = mouseDraggedCell.getPuzzleElement().getLocation(); - if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { - masyuLine.add(elementView); - MasyuLine newLine = - new MasyuLine( - mousePressedCell.getPuzzleElement(), mouseDraggedCell.getPuzzleElement()); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); - } - } else { - if (mouseDraggedCell != elementView) { - Point p1 = mouseDraggedCell.getPuzzleElement().getLocation(); - Point p2 = elementView.getPuzzleElement().getLocation(); + if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { + masyuLine.add(elementView); + MasyuLine newLine = + new MasyuLine( + mousePressedCell.getPuzzleElement(), + mouseDraggedCell.getPuzzleElement()); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); + } + } else { + if (mouseDraggedCell != elementView) { + Point p1 = mouseDraggedCell.getPuzzleElement().getLocation(); + Point p2 = elementView.getPuzzleElement().getLocation(); - if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { - masyuLine.add(elementView); - MasyuLine newLine = - new MasyuLine(mouseDraggedCell.getPuzzleElement(), elementView.getPuzzleElement()); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); - } - mouseDraggedCell = elementView; + if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { + masyuLine.add(elementView); + MasyuLine newLine = + new MasyuLine( + mouseDraggedCell.getPuzzleElement(), + elementView.getPuzzleElement()); + puzzle.notifyBoardListeners( + listener -> listener.onBoardDataChanged(newLine)); + } + mouseDraggedCell = elementView; + } + } } - } } - } - - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - mousePressedCell = null; - mouseDraggedCell = null; - masyuLine.clear(); - } - /** - * Alters the cells as they are being dragged over or clicked - * - * @param e Mouse event being used - * @param data Data of selected cell - */ - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - MasyuCell cell = (MasyuCell) data; - if (cell.getData() == MasyuType.BLACK || cell.getData() == MasyuType.WHITE) { - return; + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + mousePressedCell = null; + mouseDraggedCell = null; + masyuLine.clear(); } - if (cell.getData() == MasyuType.UNKNOWN) { - data.setData(3); - } else { - data.setData(0); + + /** + * Alters the cells as they are being dragged over or clicked + * + * @param e Mouse event being used + * @param data Data of selected cell + */ + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + MasyuCell cell = (MasyuCell) data; + if (cell.getData() == MasyuType.BLACK || cell.getData() == MasyuType.WHITE) { + return; + } + if (cell.getData() == MasyuType.UNKNOWN) { + data.setData(3); + } else { + data.setData(0); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java index d01e74033..942e1ffd2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java @@ -4,48 +4,48 @@ import java.awt.*; public class MasyuElementView extends GridElementView { - public MasyuElementView(MasyuCell masyuCell) { - super(masyuCell); - } + public MasyuElementView(MasyuCell masyuCell) { + super(masyuCell); + } - @Override - public MasyuCell getPuzzleElement() { - return (MasyuCell) super.getPuzzleElement(); - } + @Override + public MasyuCell getPuzzleElement() { + return (MasyuCell) super.getPuzzleElement(); + } - @Override - public void drawElement(Graphics2D graphics2D) { - MasyuCell cell = (MasyuCell) puzzleElement; - MasyuType type = cell.getType(); - if (type == MasyuType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == MasyuType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == MasyuType.WHITE) { - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.WHITE); - graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); - graphics2D.setColor(Color.BLACK); - graphics2D.drawOval(location.x + 6, location.y + 6, 18, 18); - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + MasyuCell cell = (MasyuCell) puzzleElement; + MasyuType type = cell.getType(); + if (type == MasyuType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == MasyuType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == MasyuType.WHITE) { + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.WHITE); + graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); + graphics2D.setColor(Color.BLACK); + graphics2D.drawOval(location.x + 6, location.y + 6, 18, 18); + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java index 0f8555ce0..0c692193a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java @@ -6,31 +6,32 @@ public class MasyuExporter extends PuzzleExporter { - public MasyuExporter(Masyu masyu) { - super(masyu); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - MasyuBoard board; - if (puzzle.getTree() != null) { - board = (MasyuBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (MasyuBoard) puzzle.getBoardView().getBoard(); + public MasyuExporter(Masyu masyu) { + super(masyu); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + MasyuBoard board; + if (puzzle.getTree() != null) { + board = (MasyuBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (MasyuBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - MasyuCell cell = (MasyuCell) puzzleElement; - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + MasyuCell cell = (MasyuCell) puzzleElement; + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java index b5db71234..2170da3ee 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java @@ -8,98 +8,102 @@ import org.w3c.dom.NodeList; public class MasyuImporter extends PuzzleImporter { - public MasyuImporter(Masyu masyu) { - super(masyu); - } + public MasyuImporter(Masyu masyu) { + super(masyu); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Masyu Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Masyu Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Masyu Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Masyu Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - MasyuBoard masyuBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - masyuBoard = new MasyuBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - masyuBoard = new MasyuBoard(width, height); - } - } + MasyuBoard masyuBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + masyuBoard = new MasyuBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + masyuBoard = new MasyuBoard(width, height); + } + } - if (masyuBoard == null) { - throw new InvalidFileFormatException("Masyu Importer: invalid board dimensions"); - } + if (masyuBoard == null) { + throw new InvalidFileFormatException("Masyu Importer: invalid board dimensions"); + } - int width = masyuBoard.getWidth(); - int height = masyuBoard.getHeight(); + int width = masyuBoard.getWidth(); + int height = masyuBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - MasyuCell cell = - (MasyuCell) puzzle.getFactory().importCell(elementDataList.item(i), masyuBoard); - Point loc = cell.getLocation(); - if (cell.getData() != MasyuType.UNKNOWN) { - cell.setModifiable(false); - cell.setGiven(true); - } - masyuBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + MasyuCell cell = + (MasyuCell) + puzzle.getFactory().importCell(elementDataList.item(i), masyuBoard); + Point loc = cell.getLocation(); + if (cell.getData() != MasyuType.UNKNOWN) { + cell.setModifiable(false); + cell.setGiven(true); + } + masyuBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (masyuBoard.getCell(x, y) == null) { - MasyuCell cell = new MasyuCell(MasyuType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - masyuBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (masyuBoard.getCell(x, y) == null) { + MasyuCell cell = new MasyuCell(MasyuType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + masyuBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(masyuBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Masyu Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(masyuBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("Masyu Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Masyu cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Masyu cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java index 30924ea57..eda51c839 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java @@ -4,40 +4,40 @@ import edu.rpi.legup.utility.Entry; public class MasyuLine extends PuzzleElement> { - public MasyuLine(MasyuCell c1, MasyuCell c2) { - this.data = new Entry<>(c1, c2); - } - - public MasyuCell getC1() { - return data.getKey(); - } - - public void setC1(MasyuCell c1) { - this.data.setKey(c1); - } - - public MasyuCell getC2() { - return data.getValue(); - } - - public void setC2(MasyuCell c2) { - this.data.setValue(c2); - } - - public boolean compare(MasyuLine line) { - return ((line.getC1().getLocation().equals(data.getKey().getLocation()) - && line.getC2().getLocation().equals(data.getValue().getLocation())) - || (line.getC1().getLocation().equals(data.getValue().getLocation()) - && line.getC2().getLocation().equals(data.getKey().getLocation()))); - } - - /** - * Copies this elements puzzleElement to a new PuzzleElement object - * - * @return copied PuzzleElement object - */ - @Override - public MasyuLine copy() { - return new MasyuLine(data.getKey().copy(), data.getValue().copy()); - } + public MasyuLine(MasyuCell c1, MasyuCell c2) { + this.data = new Entry<>(c1, c2); + } + + public MasyuCell getC1() { + return data.getKey(); + } + + public void setC1(MasyuCell c1) { + this.data.setKey(c1); + } + + public MasyuCell getC2() { + return data.getValue(); + } + + public void setC2(MasyuCell c2) { + this.data.setValue(c2); + } + + public boolean compare(MasyuLine line) { + return ((line.getC1().getLocation().equals(data.getKey().getLocation()) + && line.getC2().getLocation().equals(data.getValue().getLocation())) + || (line.getC1().getLocation().equals(data.getValue().getLocation()) + && line.getC2().getLocation().equals(data.getKey().getLocation()))); + } + + /** + * Copies this elements puzzleElement to a new PuzzleElement object + * + * @return copied PuzzleElement object + */ + @Override + public MasyuLine copy() { + return new MasyuLine(data.getKey().copy(), data.getValue().copy()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java index 54efc335f..c967f4865 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java @@ -4,27 +4,27 @@ import java.awt.*; public class MasyuLineView extends ElementView { - private final Color LINE_COLOR = Color.GREEN; + private final Color LINE_COLOR = Color.GREEN; - private final Stroke LINE_STROKE = new BasicStroke(3); + private final Stroke LINE_STROKE = new BasicStroke(3); - public MasyuLineView(MasyuLine line) { - super(line); - } + public MasyuLineView(MasyuLine line) { + super(line); + } - @Override - public void draw(Graphics2D graphics2D) { - MasyuLine line = (MasyuLine) puzzleElement; - Point p1 = line.getC1().getLocation(); - Point p2 = line.getC2().getLocation(); - int x1 = p1.x * size.width + size.width / 2; - int y1 = p1.y * size.height + size.height / 2; + @Override + public void draw(Graphics2D graphics2D) { + MasyuLine line = (MasyuLine) puzzleElement; + Point p1 = line.getC1().getLocation(); + Point p2 = line.getC2().getLocation(); + int x1 = p1.x * size.width + size.width / 2; + int y1 = p1.y * size.height + size.height / 2; - int x2 = p2.x * size.width + size.width / 2; - int y2 = p2.y * size.height + size.height / 2; + int x2 = p2.x * size.width + size.width / 2; + int y2 = p2.y * size.height + size.height / 2; - graphics2D.setColor(line.isModified() ? Color.GREEN : Color.BLACK); - graphics2D.setStroke(LINE_STROKE); - graphics2D.drawLine(x1, y1, x2, y2); - } + graphics2D.setColor(line.isModified() ? Color.GREEN : Color.BLACK); + graphics2D.setStroke(LINE_STROKE); + graphics2D.drawLine(x1, y1, x2, y2); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java index 114e4bf71..4029d259d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java @@ -1,21 +1,21 @@ package edu.rpi.legup.puzzle.masyu; public enum MasyuType { - UNKNOWN, - BLACK, - WHITE, - LINE; + UNKNOWN, + BLACK, + WHITE, + LINE; - public static MasyuType convertToMasyuType(int num) { - switch (num) { - case 1: - return BLACK; - case 2: - return WHITE; - case 3: - return LINE; - default: - return UNKNOWN; + public static MasyuType convertToMasyuType(int num) { + switch (num) { + case 1: + return BLACK; + case 2: + return WHITE; + case 3: + return LINE; + default: + return UNKNOWN; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java index dc81b24cd..e962a6ebf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java @@ -8,47 +8,49 @@ import java.util.List; public class MasyuView extends GridBoardView { - private List lineViews; + private List lineViews; - public MasyuView(MasyuBoard board) { - super(new BoardController(), new MasyuController(), board.getDimension()); + public MasyuView(MasyuBoard board) { + super(new BoardController(), new MasyuController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - MasyuCell cell = (MasyuCell) puzzleElement; - Point loc = cell.getLocation(); - MasyuElementView elementView = new MasyuElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + MasyuCell cell = (MasyuCell) puzzleElement; + Point loc = cell.getLocation(); + MasyuElementView elementView = new MasyuElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } + lineViews = new ArrayList<>(); + for (MasyuLine line : board.getLines()) { + MasyuLineView lineView = new MasyuLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } } - lineViews = new ArrayList<>(); - for (MasyuLine line : board.getLines()) { - MasyuLineView lineView = new MasyuLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - super.drawBoard(graphics2D); - lineViews.forEach(masyuLineView -> masyuLineView.draw(graphics2D)); - } + @Override + public void drawBoard(Graphics2D graphics2D) { + graphics2D.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + super.drawBoard(graphics2D); + lineViews.forEach(masyuLineView -> masyuLineView.draw(graphics2D)); + } - /** - * Called when the board puzzleElement changed - * - * @param puzzleElement puzzleElement of the puzzleElement that changed - */ - @Override - public void onBoardDataChanged(PuzzleElement puzzleElement) { - if (puzzleElement instanceof MasyuLine) { - MasyuLineView lineView = new MasyuLineView((MasyuLine) puzzleElement); - lineView.setSize(elementSize); - lineViews.add(lineView); + /** + * Called when the board puzzleElement changed + * + * @param puzzleElement puzzleElement of the puzzleElement that changed + */ + @Override + public void onBoardDataChanged(PuzzleElement puzzleElement) { + if (puzzleElement instanceof MasyuLine) { + MasyuLineView lineView = new MasyuLineView((MasyuLine) puzzleElement); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + repaint(); } - repaint(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java index f4dd95268..1681446cd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java @@ -6,25 +6,25 @@ public class BadLoopingContradictionRule extends ContradictionRule { - public BadLoopingContradictionRule() { - super( - "MASY-CONT-0001", - "Bad Looping", - "", - "edu/rpi/legup/images/masyu/ContradictionBadLooping.png"); - } + public BadLoopingContradictionRule() { + super( + "MASY-CONT-0001", + "Bad Looping", + "", + "edu/rpi/legup/images/masyu/ContradictionBadLooping.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java index f4e95eb14..c219eeaa3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java @@ -6,21 +6,21 @@ public class BlackContradictionRule extends ContradictionRule { - public BlackContradictionRule() { - super("MASY-CONT-0002", "Black", "", "edu/rpi/legup/images/masyu/ContradictionBlack.png"); - } + public BlackContradictionRule() { + super("MASY-CONT-0002", "Black", "", "edu/rpi/legup/images/masyu/ContradictionBlack.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java index 63b40d7f3..665a74204 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java @@ -8,33 +8,34 @@ public class BlackEdgeDirectRule extends DirectRule { - public BlackEdgeDirectRule() { - super("MASY-BASC-0001", "Black Edge", "", "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); - } + public BlackEdgeDirectRule() { + super("MASY-BASC-0001", "Black Edge", "", "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java index 2b598321c..c7e3ff500 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java @@ -9,59 +9,59 @@ public class BlackSplitCaseRule extends CaseRule { - public BlackSplitCaseRule() { - super("MASY-CASE-0001", "Black Split", "", "edu/rpi/legup/images/masyu/CaseBlackSplit.png"); - } + public BlackSplitCaseRule() { + super("MASY-CASE-0001", "Black Split", "", "edu/rpi/legup/images/masyu/CaseBlackSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java index faa311450..5c284eb45 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java @@ -8,33 +8,38 @@ public class BlockedBlackDirectRule extends DirectRule { - public BlockedBlackDirectRule() { - super("MASY-BASC-0002", "Blocked Black", "", "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); - } + public BlockedBlackDirectRule() { + super( + "MASY-BASC-0002", + "Blocked Black", + "", + "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java index 1a49b83a1..6aee8ba5f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java @@ -8,37 +8,38 @@ public class ConnectedCellsDirectRule extends DirectRule { - public ConnectedCellsDirectRule() { - super( - "MASY-BASC-0003", - "Connected Cells", - "", - "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); - } + public ConnectedCellsDirectRule() { + super( + "MASY-BASC-0003", + "Connected Cells", + "", + "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java index f6c95050b..27b39bc04 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java @@ -8,33 +8,38 @@ public class FinishPathDirectRule extends DirectRule { - public FinishPathDirectRule() { - super("MASY-BASC-0004", "Finished Path", "", "edu/rpi/legup/images/masyu/RuleFinishPath.png"); - } + public FinishPathDirectRule() { + super( + "MASY-BASC-0004", + "Finished Path", + "", + "edu/rpi/legup/images/masyu/RuleFinishPath.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java index 67ed25d64..6a565bc82 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java @@ -8,33 +8,34 @@ public class NearWhiteDirectRule extends DirectRule { - public NearWhiteDirectRule() { - super("MASY-BASC-0005", "Near White", "", "edu/rpi/legup/images/masyu/RuleNearWhite.png"); - } + public NearWhiteDirectRule() { + super("MASY-BASC-0005", "Near White", "", "edu/rpi/legup/images/masyu/RuleNearWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java index f068c6503..c41999b9c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java @@ -6,25 +6,25 @@ public class NoOptionsContradictionRule extends ContradictionRule { - public NoOptionsContradictionRule() { - super( - "MASY-CONT-0003", - "No Options", - "", - "edu/rpi/legup/images/masyu/ContradictionNoOptions.png"); - } + public NoOptionsContradictionRule() { + super( + "MASY-CONT-0003", + "No Options", + "", + "edu/rpi/legup/images/masyu/ContradictionNoOptions.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java index 015a7dcf9..382ac6466 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java @@ -9,59 +9,63 @@ public class NormalSplitCaseRule extends CaseRule { - public NormalSplitCaseRule() { - super("MASY-CASE-0002", "Normal Split", "", "edu/rpi/legup/images/masyu/CaseNormalSplit.png"); - } + public NormalSplitCaseRule() { + super( + "MASY-CASE-0002", + "Normal Split", + "", + "edu/rpi/legup/images/masyu/CaseNormalSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java index b25ac8c09..bc7353e5d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java @@ -8,37 +8,38 @@ public class OnlyOneChoiceDirectRule extends DirectRule { - public OnlyOneChoiceDirectRule() { - super( - "MASY-BASC-0006", - "Only One Choice", - "", - "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); - } + public OnlyOneChoiceDirectRule() { + super( + "MASY-BASC-0006", + "Only One Choice", + "", + "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java index bda563b2e..ee71ee2bc 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java @@ -6,21 +6,25 @@ public class OnlyTwoContradictionRule extends ContradictionRule { - public OnlyTwoContradictionRule() { - super("MASY-CONT-0004", "Only Two", "", "edu/rpi/legup/images/masyu/ContradictionOnly2.png"); - } + public OnlyTwoContradictionRule() { + super( + "MASY-CONT-0004", + "Only Two", + "", + "edu/rpi/legup/images/masyu/ContradictionOnly2.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java index 4ae418c36..efc523b8d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java @@ -6,21 +6,21 @@ public class WhiteContradictionRule extends ContradictionRule { - public WhiteContradictionRule() { - super("MASY-CONT-0005", "White", "", "edu/rpi/legup/images/masyu/ContradictionWhite.png"); - } + public WhiteContradictionRule() { + super("MASY-CONT-0005", "White", "", "edu/rpi/legup/images/masyu/ContradictionWhite.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java index e653c96b0..4d2982d00 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java @@ -7,33 +7,34 @@ import edu.rpi.legup.model.tree.TreeTransition; public class WhiteEdgeDirectRule extends DirectRule { - public WhiteEdgeDirectRule() { - super("MASY-BASC-0007", "White Edge", "", "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); - } + public WhiteEdgeDirectRule() { + super("MASY-BASC-0007", "White Edge", "", "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java index e8eb97cd8..d50ddacfa 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java @@ -9,59 +9,59 @@ public class WhiteSplitCaseRule extends CaseRule { - public WhiteSplitCaseRule() { - super("MASY-CASE-0003", "White Split", "", "edu/rpi/legup/images/masyu/CaseWhiteSplit.png"); - } + public WhiteSplitCaseRule() { + super("MASY-CASE-0003", "White Split", "", "edu/rpi/legup/images/masyu/CaseWhiteSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java index c8aa80012..8366d905f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java @@ -6,77 +6,77 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Nurikabe extends Puzzle { - public Nurikabe() { - super(); + public Nurikabe() { + super(); - this.name = "Nurikabe"; + this.name = "Nurikabe"; - this.importer = new NurikabeImporter(this); - this.exporter = new NurikabeExporter(this); + this.importer = new NurikabeImporter(this); + this.exporter = new NurikabeExporter(this); - this.factory = new NurikabeCellFactory(); - } + this.factory = new NurikabeCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new NurikabeView((NurikabeBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new NurikabeView((NurikabeBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Nurikabe - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Nurikabe, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows >= 2 && columns >= 2; - } + @Override + /** + * Determines if the given dimensions are valid for Nurikabe + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Nurikabe, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows >= 2 && columns >= 2; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(nurikabeBoard) == null) { - return false; - } - } - for (PuzzleElement data : nurikabeBoard.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.UNKNOWN) { - return false; - } + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(nurikabeBoard) == null) { + return false; + } + } + for (PuzzleElement data : nurikabeBoard.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.UNKNOWN) { + return false; + } + } + return true; } - return true; - } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java index 7be7813ac..1f80611e8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java @@ -4,53 +4,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class NurikabeBoard extends GridBoard { - public NurikabeBoard(int width, int height) { - super(width, height); - } - - public NurikabeBoard(int size) { - super(size, size); - } + public NurikabeBoard(int width, int height) { + super(width, height); + } - @Override - public NurikabeCell getCell(int x, int y) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return null; + public NurikabeBoard(int size) { + super(size, size); } - return (NurikabeCell) super.getCell(x, y); - } - /** - * Gets the cells as an int array - * - * @return int array of values - */ - public int[][] getIntArray() { - int[][] arr = new int[dimension.height][dimension.width]; - for (int i = 0; i < dimension.height; i++) { - for (int k = 0; k < dimension.width; k++) { - arr[i][k] = getCell(k, i).getData(); - } + @Override + public NurikabeCell getCell(int x, int y) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return null; + } + return (NurikabeCell) super.getCell(x, y); } - return arr; - } - @Override - public NurikabeBoard copy() { - // System.out.println("NurikabeBoard copy()"); - NurikabeBoard copy = new NurikabeBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + /** + * Gets the cells as an int array + * + * @return int array of values + */ + public int[][] getIntArray() { + int[][] arr = new int[dimension.height][dimension.width]; + for (int i = 0; i < dimension.height; i++) { + for (int k = 0; k < dimension.width; k++) { + arr[i][k] = getCell(k, i).getData(); + } + } + return arr; } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + @Override + public NurikabeBoard copy() { + // System.out.println("NurikabeBoard copy()"); + NurikabeBoard copy = new NurikabeBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; } - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java index 4f92c6227..c6cd2c64e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java @@ -7,86 +7,86 @@ public class NurikabeCell extends GridCell { - /** - * NurikabeCell Constructor - creates a NurikabeCell from the specified value and location - * - * @param value value of the NurikabeCell - * @param location position of the NurikabeCell - */ - public NurikabeCell(int value, Point location) { - super(value, location); - } + /** + * NurikabeCell Constructor - creates a NurikabeCell from the specified value and location + * + * @param value value of the NurikabeCell + * @param location position of the NurikabeCell + */ + public NurikabeCell(int value, Point location) { + super(value, location); + } - /** - * Gets the type of this NurikabeCell - * - * @return type of NurikabeCell - */ - public NurikabeType getType() { - switch (data) { - case -2: - return NurikabeType.UNKNOWN; - case -1: - return NurikabeType.BLACK; - case 0: - return NurikabeType.WHITE; - default: - if (data > 0) { - return NurikabeType.NUMBER; + /** + * Gets the type of this NurikabeCell + * + * @return type of NurikabeCell + */ + public NurikabeType getType() { + switch (data) { + case -2: + return NurikabeType.UNKNOWN; + case -1: + return NurikabeType.BLACK; + case 0: + return NurikabeType.WHITE; + default: + if (data > 0) { + return NurikabeType.NUMBER; + } } + return null; } - return null; - } - /** - * Sets the type of this NurikabeCell - * - * @param e element to set the type of this nurikabe cell to - */ - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "NURI-PLAC-0001": - this.data = -1; - break; - case "NURI-PLAC-0002": - this.data = 0; - break; - case "NURI-UNPL-0001": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data <= 0 || this.data > 8) { - this.data = 1; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 1) { - this.data = this.data - 1; - } else { - this.data = 9; - } - break; + /** + * Sets the type of this NurikabeCell + * + * @param e element to set the type of this nurikabe cell to + */ + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "NURI-PLAC-0001": + this.data = -1; + break; + case "NURI-PLAC-0002": + this.data = 0; + break; + case "NURI-UNPL-0001": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data <= 0 || this.data > 8) { + this.data = 1; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 1) { + this.data = this.data - 1; + } else { + this.data = 9; + } + break; + } + break; + default: + this.data = -2; + break; } - break; - default: - this.data = -2; - break; } - } - /** - * Performs a deep copy on the NurikabeCell - * - * @return a new copy of the NurikabeCell that is independent of this one - */ - @Override - public NurikabeCell copy() { - NurikabeCell copy = new NurikabeCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the NurikabeCell + * + * @return a new copy of the NurikabeCell that is independent of this one + */ + @Override + public NurikabeCell copy() { + NurikabeCell copy = new NurikabeCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java index 298acfb7b..7241608ac 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java @@ -10,65 +10,66 @@ import org.w3c.dom.Node; public class NurikabeCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public NurikabeCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public NurikabeCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown puzzleElement puzzleElement"); + } - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int width = nurikabeBoard.getWidth(); - int height = nurikabeBoard.getHeight(); + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("nurikabe Factory: cell location out of bounds"); - } - if (value < -2) { - throw new InvalidFileFormatException("nurikabe Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "nurikabe Factory: cell location out of bounds"); + } + if (value < -2) { + throw new InvalidFileFormatException("nurikabe Factory: cell unknown value"); + } - NurikabeCell cell = new NurikabeCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); + NurikabeCell cell = new NurikabeCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - NurikabeCell cell = (NurikabeCell) puzzleElement; - Point loc = cell.getLocation(); + NurikabeCell cell = (NurikabeCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java index e87f661eb..158abe7b4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java @@ -6,40 +6,40 @@ public class NurikabeController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - NurikabeCell cell = (NurikabeCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == -2) { - data.setData(0); + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + NurikabeCell cell = (NurikabeCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == -2) { + data.setData(0); + } else { + if (cell.getData() == 0) { + data.setData(-1); + } else { + data.setData(-2); + } + } + } } else { - if (cell.getData() == 0) { - data.setData(-1); - } else { - data.setData(-2); - } + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == -2) { + data.setData(-1); + } else { + if (cell.getData() == 0) { + data.setData(-2); + } else { + data.setData(0); + } + } + } } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == -2) { - data.setData(-1); - } else { - if (cell.getData() == 0) { - data.setData(-2); - } else { - data.setData(0); - } - } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java index 6569cfaf7..116b727d2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java @@ -5,64 +5,65 @@ public class NurikabeElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; - public NurikabeElementView(NurikabeCell cell) { - super(cell); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public NurikabeCell getPuzzleElement() { - return (NurikabeCell) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - NurikabeType type = cell.getType(); - if (type == NurikabeType.NUMBER) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.WHITE); - graphics2D.fillRect(location.x, location.y, size.width, size.height); + public NurikabeElementView(NurikabeCell cell) { + super(cell); + } - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public NurikabeCell getPuzzleElement() { + return (NurikabeCell) super.getPuzzleElement(); + } - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } else { - if (type == NurikabeType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.BLACK); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } else { - if (type == NurikabeType.WHITE) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.WHITE); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == NurikabeType.UNKNOWN) { + @Override + public void drawElement(Graphics2D graphics2D) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + NurikabeType type = cell.getType(); + if (type == NurikabeType.NUMBER) { graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.setColor(Color.WHITE); graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); graphics2D.drawRect(location.x, location.y, size.width, size.height); - } + + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } else { + if (type == NurikabeType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.BLACK); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } else { + if (type == NurikabeType.WHITE) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.WHITE); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == NurikabeType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java index 1a0f06bb2..23efd4724 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java @@ -6,34 +6,34 @@ public class NurikabeExporter extends PuzzleExporter { - public NurikabeExporter(Nurikabe nurikabe) { - super(nurikabe); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - NurikabeBoard board; - if (puzzle.getTree() != null) { - board = (NurikabeBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (NurikabeBoard) puzzle.getBoardView().getBoard(); + public NurikabeExporter(Nurikabe nurikabe) { + super(nurikabe); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + NurikabeBoard board; + if (puzzle.getTree() != null) { + board = (NurikabeBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (NurikabeBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java index 2be1ba899..ec4ed3ac1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java @@ -8,111 +8,117 @@ import org.w3c.dom.NodeList; public class NurikabeImporter extends PuzzleImporter { - public NurikabeImporter(Nurikabe nurikabe) { - super(nurikabe); - } + public NurikabeImporter(Nurikabe nurikabe) { + super(nurikabe); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - NurikabeBoard nurikabeBoard = new NurikabeBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + NurikabeBoard nurikabeBoard = new NurikabeBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - nurikabeBoard.setCell(x, y, cell); - } + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + NurikabeCell cell = + new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + nurikabeBoard.setCell(x, y, cell); + } + } + puzzle.setCurrentBoard(nurikabeBoard); } - puzzle.setCurrentBoard(nurikabeBoard); - } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("nurikabe Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("nurikabe Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "nurikabe Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "nurikabe Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - NurikabeBoard nurikabeBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - nurikabeBoard = new NurikabeBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - nurikabeBoard = new NurikabeBoard(width, height); - } - } + NurikabeBoard nurikabeBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + nurikabeBoard = new NurikabeBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + nurikabeBoard = new NurikabeBoard(width, height); + } + } - if (nurikabeBoard == null) { - throw new InvalidFileFormatException("nurikabe Importer: invalid board dimensions"); - } + if (nurikabeBoard == null) { + throw new InvalidFileFormatException("nurikabe Importer: invalid board dimensions"); + } - int width = nurikabeBoard.getWidth(); - int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - NurikabeCell cell = - (NurikabeCell) puzzle.getFactory().importCell(elementDataList.item(i), nurikabeBoard); - Point loc = cell.getLocation(); - if (cell.getData() != NurikabeType.UNKNOWN.toValue()) { - cell.setModifiable(false); - cell.setGiven(true); - } - nurikabeBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + NurikabeCell cell = + (NurikabeCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), nurikabeBoard); + Point loc = cell.getLocation(); + if (cell.getData() != NurikabeType.UNKNOWN.toValue()) { + cell.setModifiable(false); + cell.setGiven(true); + } + nurikabeBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (nurikabeBoard.getCell(x, y) == null) { - NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - nurikabeBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (nurikabeBoard.getCell(x, y) == null) { + NurikabeCell cell = + new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + nurikabeBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(nurikabeBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(nurikabeBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Nurikabe cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Nurikabe cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java index a692a27fe..8acf9fc02 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java @@ -1,12 +1,12 @@ package edu.rpi.legup.puzzle.nurikabe; public enum NurikabeType { - UNKNOWN, - BLACK, - WHITE, - NUMBER; + UNKNOWN, + BLACK, + WHITE, + NUMBER; - public int toValue() { - return this.ordinal() - 2; - } + public int toValue() { + return this.ordinal() - 2; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java index f6b1a02a4..71ffa08e5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java @@ -10,303 +10,305 @@ public class NurikabeUtilities { - /** - * Gets all of the numbered cells in the Nurikabe board - * - * @param board nurikabe board - * @return a list of all of the numbered cells - */ - public static Set getNurikabeNumberedCells(NurikabeBoard board) { - Set numberedCells = new HashSet<>(); + /** + * Gets all of the numbered cells in the Nurikabe board + * + * @param board nurikabe board + * @return a list of all of the numbered cells + */ + public static Set getNurikabeNumberedCells(NurikabeBoard board) { + Set numberedCells = new HashSet<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.NUMBER) { - numberedCells.add(cell); - } + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.NUMBER) { + numberedCells.add(cell); + } + } + return numberedCells; } - return numberedCells; - } - /** - * Gets nurikabe regions of black, white, and unknown cells - * - * @param board nurikabe board - * @return a disjoint set of the regions - */ - public static DisjointSets getNurikabeRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets nurikabe regions of black, white, and unknown cells + * + * @param board nurikabe board + * @return a disjoint set of the regions + */ + public static DisjointSets getNurikabeRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets regions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - regions.createSet((NurikabeCell) data); - } + DisjointSets regions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + regions.createSet((NurikabeCell) data); + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.NUMBER || cell.getType() == NurikabeType.WHITE) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.NUMBER - || rightCell.getType() == NurikabeType.WHITE)) { - regions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.NUMBER - || downCell.getType() == NurikabeType.WHITE)) { - regions.union(cell, downCell); - } - } else { - if (cell.getType() == NurikabeType.BLACK) { - if (rightCell != null && rightCell.getType() == NurikabeType.BLACK) { - regions.union(cell, rightCell); + if (cell.getType() == NurikabeType.NUMBER || cell.getType() == NurikabeType.WHITE) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.NUMBER + || rightCell.getType() == NurikabeType.WHITE)) { + regions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.NUMBER + || downCell.getType() == NurikabeType.WHITE)) { + regions.union(cell, downCell); + } + } else { + if (cell.getType() == NurikabeType.BLACK) { + if (rightCell != null && rightCell.getType() == NurikabeType.BLACK) { + regions.union(cell, rightCell); + } + if (downCell != null && downCell.getType() == NurikabeType.BLACK) { + regions.union(cell, downCell); + } + } else { + if (cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null && rightCell.getType() == NurikabeType.UNKNOWN) { + regions.union(cell, rightCell); + } + if (downCell != null && downCell.getType() == NurikabeType.UNKNOWN) { + regions.union(cell, downCell); + } + } + } + } } - if (downCell != null && downCell.getType() == NurikabeType.BLACK) { - regions.union(cell, downCell); - } - } else { - if (cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null && rightCell.getType() == NurikabeType.UNKNOWN) { - regions.union(cell, rightCell); - } - if (downCell != null && downCell.getType() == NurikabeType.UNKNOWN) { - regions.union(cell, downCell); - } - } - } } - } + return regions; } - return regions; - } - /** - * Gets the disjoint set containing the possible black regions be interpreting all unknown cells - * as black cells - * - * @param board nurikabe board - * @return the disjoint set containing the possible black regions - */ - public static DisjointSets getPossibleBlackRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets the disjoint set containing the possible black regions be interpreting all unknown cells + * as black cells + * + * @param board nurikabe board + * @return the disjoint set containing the possible black regions + */ + public static DisjointSets getPossibleBlackRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets blackRegions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { - blackRegions.createSet(cell); - } - } + DisjointSets blackRegions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { + blackRegions.createSet(cell); + } + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.BLACK - || rightCell.getType() == NurikabeType.UNKNOWN)) { - blackRegions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.BLACK - || downCell.getType() == NurikabeType.UNKNOWN)) { - blackRegions.union(cell, downCell); - } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + if (cell.getType() == NurikabeType.BLACK + || cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.BLACK + || rightCell.getType() == NurikabeType.UNKNOWN)) { + blackRegions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.BLACK + || downCell.getType() == NurikabeType.UNKNOWN)) { + blackRegions.union(cell, downCell); + } + } + } } - } + return blackRegions; } - return blackRegions; - } - /** - * Gets the disjoint set containing the possible white regions be interpreting all unknown cells - * as white cells - * - * @param board nurikabe board - * @return the disjoint set containing the possible white regions - */ - public static DisjointSets getPossibleWhiteRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets the disjoint set containing the possible white regions be interpreting all unknown cells + * as white cells + * + * @param board nurikabe board + * @return the disjoint set containing the possible white regions + */ + public static DisjointSets getPossibleWhiteRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets whiteRegions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.WHITE - || cell.getType() == NurikabeType.NUMBER - || cell.getType() == NurikabeType.UNKNOWN) { - whiteRegions.createSet(cell); - } - } + DisjointSets whiteRegions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.WHITE + || cell.getType() == NurikabeType.NUMBER + || cell.getType() == NurikabeType.UNKNOWN) { + whiteRegions.createSet(cell); + } + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.WHITE - || cell.getType() == NurikabeType.NUMBER - || cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.WHITE - || rightCell.getType() == NurikabeType.NUMBER - || rightCell.getType() == NurikabeType.UNKNOWN)) { - whiteRegions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.WHITE - || downCell.getType() == NurikabeType.NUMBER - || downCell.getType() == NurikabeType.UNKNOWN)) { - whiteRegions.union(cell, downCell); - } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + if (cell.getType() == NurikabeType.WHITE + || cell.getType() == NurikabeType.NUMBER + || cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.WHITE + || rightCell.getType() == NurikabeType.NUMBER + || rightCell.getType() == NurikabeType.UNKNOWN)) { + whiteRegions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.WHITE + || downCell.getType() == NurikabeType.NUMBER + || downCell.getType() == NurikabeType.UNKNOWN)) { + whiteRegions.union(cell, downCell); + } + } + } } - } + return whiteRegions; } - return whiteRegions; - } - /** - * Makes a map where the keys are white/numbered cells and the values are the amount of cells that - * need to be added to the region - * - * @param board nurikabe board - * @return a map of cell keys to integer values - */ - public static HashMap getWhiteRegionMap(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Makes a map where the keys are white/numbered cells and the values are the amount of cells + * that need to be added to the region + * + * @param board nurikabe board + * @return a map of cell keys to integer values + */ + public static HashMap getWhiteRegionMap(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - Set numberedCells = getNurikabeNumberedCells(board); - // Final mapping of cell to size - HashMap whiteRegionMap = new HashMap<>(); - for (NurikabeCell center : numberedCells) { - // BFS for each center to find the size of the region - int size = 1; - // Mark all the vertices as not visited(By default - // set as false) - HashMap visited = new HashMap<>(); + Set numberedCells = getNurikabeNumberedCells(board); + // Final mapping of cell to size + HashMap whiteRegionMap = new HashMap<>(); + for (NurikabeCell center : numberedCells) { + // BFS for each center to find the size of the region + int size = 1; + // Mark all the vertices as not visited(By default + // set as false) + HashMap visited = new HashMap<>(); - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - // Mark the current node as visited and enqueue it - visited.put(center, true); - queue.add(center); + // Mark the current node as visited and enqueue it + visited.put(center, true); + queue.add(center); - // Set of cells in the current region - Set connected = new HashSet<>(); + // Set of cells in the current region + Set connected = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - // s is the source node in the graph - NurikabeCell s = queue.poll(); - System.out.print(s + " "); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + // s is the source node in the graph + NurikabeCell s = queue.poll(); + System.out.print(s + " "); - // Make a linked list of all adjacent squares - Set adj = new HashSet<>(); + // Make a linked list of all adjacent squares + Set adj = new HashSet<>(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(board.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(board.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(board.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(board.getCell(loc.x, loc.y + 1)); - } - // Get all adjacent vertices of the dequeued vertex s - // If a adjacent has not been visited, then mark it - // visited and enqueue it - for (NurikabeCell n : adj) { - if (!visited.getOrDefault(n, false) && n.getType() == NurikabeType.WHITE) { - connected.add(n); - visited.put(n, true); - queue.add(n); - ++size; - } + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(board.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(board.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(board.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(board.getCell(loc.x, loc.y + 1)); + } + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (NurikabeCell n : adj) { + if (!visited.getOrDefault(n, false) && n.getType() == NurikabeType.WHITE) { + connected.add(n); + visited.put(n, true); + queue.add(n); + ++size; + } + } + } + // Map the cells to the center-size (including the center) + whiteRegionMap.put(center, center.getData() - size); + for (NurikabeCell member : connected) { + whiteRegionMap.put(member, center.getData() - size); + } } - } - // Map the cells to the center-size (including the center) - whiteRegionMap.put(center, center.getData() - size); - for (NurikabeCell member : connected) { - whiteRegionMap.put(member, center.getData() - size); - } + return whiteRegionMap; } - return whiteRegionMap; - } - /** - * Gets all the non-black cells connected to the given cell - * - * @param board nurikabe board - * @param center nurikabe cell - * @return a set of all white/numbered cells in the region - */ - public static Set getSurroundedRegionOf(NurikabeBoard board, NurikabeCell center) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets all the non-black cells connected to the given cell + * + * @param board nurikabe board + * @param center nurikabe cell + * @return a set of all white/numbered cells in the region + */ + public static Set getSurroundedRegionOf( + NurikabeBoard board, NurikabeCell center) { + int width = board.getWidth(); + int height = board.getHeight(); - // Mark all the vertices as not visited(By default - // set as false) - Set visited = new HashSet<>(); + // Mark all the vertices as not visited(By default + // set as false) + Set visited = new HashSet<>(); - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - // Mark the current node as visited and enqueue it - visited.add(center); - queue.add(center); + // Mark the current node as visited and enqueue it + visited.add(center); + queue.add(center); - // Set of cells in the current region - Set connected = new HashSet<>(); + // Set of cells in the current region + Set connected = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - // s is the source node in the graph - NurikabeCell s = queue.poll(); - System.out.print(s + " "); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + // s is the source node in the graph + NurikabeCell s = queue.poll(); + System.out.print(s + " "); - // Make a set of all adjacent squares - Set adj = new HashSet<>(); + // Make a set of all adjacent squares + Set adj = new HashSet<>(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(board.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(board.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(board.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(board.getCell(loc.x, loc.y + 1)); - } - // Get all adjacent vertices of the dequeued vertex s - // If a adjacent has not been visited, then mark it - // visited and enqueue it - for (NurikabeCell n : adj) { - if (!visited.contains(n) && n.getType() != NurikabeType.BLACK) { - connected.add(n); - visited.add(n); - queue.add(n); + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(board.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(board.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(board.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(board.getCell(loc.x, loc.y + 1)); + } + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (NurikabeCell n : adj) { + if (!visited.contains(n) && n.getType() != NurikabeType.BLACK) { + connected.add(n); + visited.add(n); + queue.add(n); + } + } } - } - } - return connected; - } + return connected; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java index 04e1910e4..0bac7e3e5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java @@ -7,17 +7,18 @@ public class NurikabeView extends GridBoardView { - public NurikabeView(NurikabeBoard board) { - super(new BoardController(), new NurikabeController(), board.getDimension()); + public NurikabeView(NurikabeBoard board) { + super(new BoardController(), new NurikabeController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - Point loc = cell.getLocation(); - NurikabeElementView elementView = new NurikabeElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + Point loc = cell.getLocation(); + NurikabeElementView elementView = new NurikabeElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java index 25f817ff2..459a809e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BlackTile extends PlaceableElement { - public BlackTile() { - super( - "NURI-PLAC-0001", - "Black Tile", - "The black tile", - "edu/rpi/legup/images/nurikabe/tiles/BlackTile.png"); - } + public BlackTile() { + super( + "NURI-PLAC-0001", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/nurikabe/tiles/BlackTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java index 9c0f3ff94..475b278da 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java @@ -3,28 +3,28 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super( - "NURI-UNPL-0001", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/nurikabe/tiles/NumberTile.png"); - object_num = 0; - } + public NumberTile() { + super( + "NURI-UNPL-0001", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/nurikabe/tiles/NumberTile.png"); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java index 0b16d4a17..85d47e208 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "NURI-UNPL-0002", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/nurikabe/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "NURI-UNPL-0002", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/nurikabe/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java index c086ce55c..35eb63b81 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class WhiteTile extends PlaceableElement { - public WhiteTile() { - super( - "NURI-PLAC-0002", - "White Tile", - "The white tile", - "edu/rpi/legup/images/nurikabe/tiles/WhiteTile.png"); - } + public WhiteTile() { + super( + "NURI-PLAC-0002", + "White Tile", + "The white tile", + "edu/rpi/legup/images/nurikabe/tiles/WhiteTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java index f8fb66110..7428ac204 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java @@ -17,103 +17,106 @@ public class BlackBetweenRegionsDirectRule extends DirectRule { - public BlackBetweenRegionsDirectRule() { - super( - "NURI-BASC-0001", - "Black Between Regions", - "Any unknowns between two regions must be black.", - "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); - } + public BlackBetweenRegionsDirectRule() { + super( + "NURI-BASC-0001", + "Black Between Regions", + "Any unknowns between two regions must be black.", + "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new MultipleNumbersContradictionRule()); - contras.add(new TooManySpacesContradictionRule()); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new MultipleNumbersContradictionRule()); + contras.add(new TooManySpacesContradictionRule()); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + + ": Only black cells are allowed for this rule!"; + } - int x = cell.getLocation().x; - int y = cell.getLocation().y; + int x = cell.getLocation().x; + int y = cell.getLocation().y; - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adjacentWhiteRegions = new HashSet<>(); - NurikabeCell upCell = destBoardState.getCell(x, y - 1); - NurikabeCell rightCell = destBoardState.getCell(x + 1, y); - NurikabeCell downCell = destBoardState.getCell(x, y + 1); - NurikabeCell leftCell = destBoardState.getCell(x - 1, y); + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adjacentWhiteRegions = new HashSet<>(); + NurikabeCell upCell = destBoardState.getCell(x, y - 1); + NurikabeCell rightCell = destBoardState.getCell(x + 1, y); + NurikabeCell downCell = destBoardState.getCell(x, y + 1); + NurikabeCell leftCell = destBoardState.getCell(x - 1, y); - if (upCell != null - && (upCell.getType() == NurikabeType.WHITE || upCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(upCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (rightCell != null - && (rightCell.getType() == NurikabeType.WHITE - || rightCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(rightCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (downCell != null - && (downCell.getType() == NurikabeType.WHITE - || downCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(downCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (leftCell != null - && (leftCell.getType() == NurikabeType.WHITE - || leftCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(leftCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } + if (upCell != null + && (upCell.getType() == NurikabeType.WHITE + || upCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(upCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (rightCell != null + && (rightCell.getType() == NurikabeType.WHITE + || rightCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(rightCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (downCell != null + && (downCell.getType() == NurikabeType.WHITE + || downCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(downCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (leftCell != null + && (leftCell.getType() == NurikabeType.WHITE + || leftCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(leftCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } - if (adjacentWhiteRegions.size() < 2) { - return "The new black cell must separate two white regions for this rule!"; - } + if (adjacentWhiteRegions.size() < 2) { + return "The new black cell must separate two white regions for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); + NurikabeBoard modified = origBoardState.copy(); + modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); - for (ContradictionRule c : contras) { - if (c.checkContradiction(modified) == null) { - return null; - } + for (ContradictionRule c : contras) { + if (c.checkContradiction(modified) == null) { + return null; + } + } + return "Does not follow from the rule"; } - return "Does not follow from the rule"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java index 75035018b..a8a94178b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java @@ -12,54 +12,58 @@ public class BlackBottleNeckDirectRule extends DirectRule { - public BlackBottleNeckDirectRule() { - super( - "NURI-BASC-0002", - "Black Bottle Neck", - "If there is only one path for a black to escape, then those unknowns must be black.", - "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); - } + public BlackBottleNeckDirectRule() { + super( + "NURI-BASC-0002", + "Black Bottle Neck", + "If there is only one path for a black to escape, then those unknowns must be" + + " black.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new IsolateBlackContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new IsolateBlackContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + + ": Only black cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradiction(modified) == null) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This is not the only way for black to escape!"; + if (contraRule.checkContradiction(modified) == null) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This is not the only way for black to escape!"; + } } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java index 9c6bf1a63..fe1ffcf91 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java @@ -13,101 +13,102 @@ public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "NURI-CASE-0001", - "Black or White", - "Each blank cell is either black or white.", - "edu/rpi/legup/images/nurikabe/cases/BlackOrWhite.png"); - } - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + public BlackOrWhiteCaseRule() { + super( + "NURI-CASE-0001", + "Black or White", + "Each blank cell is either black or white.", + "edu/rpi/legup/images/nurikabe/cases/BlackOrWhite.png"); } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - NurikabeCell mod1 = (NurikabeCell) case1.getBoard().getModifiedData().iterator().next(); - NurikabeCell mod2 = (NurikabeCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - if (!((mod1.getType() == NurikabeType.WHITE && mod2.getType() == NurikabeType.BLACK) - || (mod2.getType() == NurikabeType.WHITE && mod1.getType() == NurikabeType.BLACK))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty white and black cell."; - } + NurikabeCell mod1 = (NurikabeCell) case1.getBoard().getModifiedData().iterator().next(); + NurikabeCell mod2 = (NurikabeCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } - return null; - } + if (!((mod1.getType() == NurikabeType.WHITE && mod2.getType() == NurikabeType.BLACK) + || (mod2.getType() == NurikabeType.WHITE + && mod1.getType() == NurikabeType.BLACK))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty white and black cell."; + } - @Override - public CaseBoard getCaseBoard(Board board) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(nurikabeBoard, this); - nurikabeBoard.setModifiable(false); - for (PuzzleElement element : nurikabeBoard.getPuzzleElements()) { - if (((NurikabeCell) element).getType() == NurikabeType.UNKNOWN) { - caseBoard.addPickableElement(element); - } + return null; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(NurikabeType.WHITE.toValue()); - case1.addModifiedData(data1); - cases.add(case1); + @Override + public CaseBoard getCaseBoard(Board board) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(nurikabeBoard, this); + nurikabeBoard.setModifiable(false); + for (PuzzleElement element : nurikabeBoard.getPuzzleElements()) { + if (((NurikabeCell) element).getType() == NurikabeType.UNKNOWN) { + caseBoard.addPickableElement(element); + } + } + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(NurikabeType.WHITE.toValue()); + case1.addModifiedData(data1); + cases.add(case1); - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(NurikabeType.BLACK.toValue()); - case2.addModifiedData(data2); - cases.add(case2); + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(NurikabeType.BLACK.toValue()); + case2.addModifiedData(data2); + cases.add(case2); - return cases; - } + return cases; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java index bdc72d921..751c88881 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java @@ -9,52 +9,52 @@ public class BlackSquareContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "No 2x2 square of black exists."; - private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - - public BlackSquareContradictionRule() { - super( - "NURI-CONT-0001", - "Black Square", - "There cannot be a 2x2 square of black.", - "edu/rpi/legup/images/nurikabe/contradictions/BlackSquare.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int height = nurikabeBoard.getHeight(); - int width = nurikabeBoard.getWidth(); - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + private final String NO_CONTRADICTION_MESSAGE = "No 2x2 square of black exists."; + private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; + + public BlackSquareContradictionRule() { + super( + "NURI-CONT-0001", + "Black Square", + "There cannot be a 2x2 square of black.", + "edu/rpi/legup/images/nurikabe/contradictions/BlackSquare.png"); } - for (int x = cell.getLocation().x - 1; - x >= 0 && x < cell.getLocation().x + 1 && x < width - 1; - x++) { - for (int y = cell.getLocation().y - 1; - y >= 0 && y < cell.getLocation().y + 1 && y < height - 1; - y++) { - if (nurikabeBoard.getCell(x, y).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x + 1, y).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x, y + 1).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x + 1, y + 1).getType() == NurikabeType.BLACK) { - return null; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } + + for (int x = cell.getLocation().x - 1; + x >= 0 && x < cell.getLocation().x + 1 && x < width - 1; + x++) { + for (int y = cell.getLocation().y - 1; + y >= 0 && y < cell.getLocation().y + 1 && y < height - 1; + y++) { + if (nurikabeBoard.getCell(x, y).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x + 1, y).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x, y + 1).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x + 1, y + 1).getType() == NurikabeType.BLACK) { + return null; + } + } } - } - } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java index 0b699b7bd..f3d3ee8f2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java @@ -11,52 +11,54 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; public class CannotReachCellDirectRule extends DirectRule { - public CannotReachCellDirectRule() { - super( - "NURI-BASC-0008", - "Can't Reach Cell", - "A cell must be black if it cannot be reached by any white region", - "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); - } + public CannotReachCellDirectRule() { + super( + "NURI-BASC-0008", + "Can't Reach Cell", + "A cell must be black if it cannot be reached by any white region", + "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + + ": Only black cells are allowed for this rule!"; + } - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeBoard modified = origBoardState.copy(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modifiedCell.setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { - return null; + NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modifiedCell.setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; } - return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java index bcb8edf0c..84ec45e99 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java @@ -15,113 +15,119 @@ public class CornerBlackDirectRule extends DirectRule { - public CornerBlackDirectRule() { - super( - "NURI-BASC-0003", - "Corners Black", - "If there is only one white square connected to unknowns and one more white is needed then the angles of that white square are black", - "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; + public CornerBlackDirectRule() { + super( + "NURI-BASC-0003", + "Corners Black", + "If there is only one white square connected to unknowns and one more white is" + + " needed then the angles of that white square are black", + "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); } - ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); - Point cellLocation = cell.getLocation(); - // 1. Find the coordinates of the white space (should be a corner of cell) - for (int i = -1; i < 2; i += 2) { - for (int j = -1; j < 2; j += 2) { - // If the corner does not exist, skip the corner - if (!(cellLocation.x + i >= 0 - && cellLocation.x + i < board.getWidth() - && cellLocation.y + j >= 0 - && cellLocation.y + j < board.getHeight())) { - continue; + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; } - NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); - NurikabeType cornerType = corner.getType(); - if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { - Point cornerLocation = corner.getLocation(); - // 2. Check if the intersecting adjacent spaces of the white space and the black corner - // are empty - if (board.getCell(cornerLocation.x, cellLocation.y).getType() == NurikabeType.UNKNOWN - && board.getCell(cellLocation.x, cornerLocation.y).getType() - == NurikabeType.UNKNOWN) { - // System.out.println("Went inside if statement"); - NurikabeBoard modified = board.copy(); - modified - .getCell(cornerLocation.x, cellLocation.y) - .setData(NurikabeType.BLACK.toValue()); - modified - .getCell(cellLocation.x, cornerLocation.y) - .setData(NurikabeType.BLACK.toValue()); - boolean containsContradiction = tooFewContra.checkContradiction(modified) == null; - if (containsContradiction) { - // 3. Check if the connected region is 1 under what is needed - Set region = - ConnectedRegions.getRegionAroundPoint( - cornerLocation, - NurikabeType.BLACK.toValue(), - modified.getIntArray(), - modified.getWidth(), - modified.getHeight()); - int regionNumber = 0; - // System.out.println("Region set size: " + region.size()); - for (Point p : region) { - NurikabeCell pCell = modified.getCell(p.x, p.y); - if (pCell.getType() == NurikabeType.NUMBER) { - if (regionNumber == 0) { - regionNumber = pCell.getData(); - } else { - return "There is a MultipleNumbers Contradiction on the board."; - } + ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); + Point cellLocation = cell.getLocation(); + // 1. Find the coordinates of the white space (should be a corner of cell) + for (int i = -1; i < 2; i += 2) { + for (int j = -1; j < 2; j += 2) { + // If the corner does not exist, skip the corner + if (!(cellLocation.x + i >= 0 + && cellLocation.x + i < board.getWidth() + && cellLocation.y + j >= 0 + && cellLocation.y + j < board.getHeight())) { + continue; + } + + NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); + NurikabeType cornerType = corner.getType(); + if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { + Point cornerLocation = corner.getLocation(); + // 2. Check if the intersecting adjacent spaces of the white space and the black + // corner + // are empty + if (board.getCell(cornerLocation.x, cellLocation.y).getType() + == NurikabeType.UNKNOWN + && board.getCell(cellLocation.x, cornerLocation.y).getType() + == NurikabeType.UNKNOWN) { + // System.out.println("Went inside if statement"); + NurikabeBoard modified = board.copy(); + modified.getCell(cornerLocation.x, cellLocation.y) + .setData(NurikabeType.BLACK.toValue()); + modified.getCell(cellLocation.x, cornerLocation.y) + .setData(NurikabeType.BLACK.toValue()); + boolean containsContradiction = + tooFewContra.checkContradiction(modified) == null; + if (containsContradiction) { + // 3. Check if the connected region is 1 under what is needed + Set region = + ConnectedRegions.getRegionAroundPoint( + cornerLocation, + NurikabeType.BLACK.toValue(), + modified.getIntArray(), + modified.getWidth(), + modified.getHeight()); + int regionNumber = 0; + // System.out.println("Region set size: " + region.size()); + for (Point p : region) { + NurikabeCell pCell = modified.getCell(p.x, p.y); + if (pCell.getType() == NurikabeType.NUMBER) { + if (regionNumber == 0) { + regionNumber = pCell.getData(); + } else { + return "There is a MultipleNumbers Contradiction on the" + + " board."; + } + } + } + // If the region size is 0, there is a possibility that there was only 1 + // cell in the + // white + // region, and that white cell was a NurikabeType.NUMBER cell + if (regionNumber == 0 + && corner.getType() == NurikabeType.NUMBER + && corner.getData() == 2) { + return null; + } + // If the region size is not 0, make sure the regionNumber and the + // region size match + // (need + // to add 1 to account for the cell that was surrounded + if (regionNumber != 0 && region.size() + 1 == regionNumber) { + return null; + } + } + } } - } - // If the region size is 0, there is a possibility that there was only 1 cell in the - // white - // region, and that white cell was a NurikabeType.NUMBER cell - if (regionNumber == 0 - && corner.getType() == NurikabeType.NUMBER - && corner.getData() == 2) { - return null; - } - // If the region size is not 0, make sure the regionNumber and the region size match - // (need - // to add 1 to account for the cell that was surrounded - if (regionNumber != 0 && region.size() + 1 == regionNumber) { - return null; - } } - } } - } + return "This is not a valid use of the corner black rule!"; } - return "This is not a valid use of the corner black rule!"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java index 3507d0a7f..7c4629f65 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java @@ -12,50 +12,51 @@ public class FillinBlackDirectRule extends DirectRule { - public FillinBlackDirectRule() { - super( - "NURI-BASC-0004", - "Fill In Black", - "If there an unknown region surrounded by black, it must be black.", - "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); - } + public FillinBlackDirectRule() { + super( + "NURI-BASC-0004", + "Fill In Black", + "If there an unknown region surrounded by black, it must be black.", + "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new NoNumberContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new NoNumberContradictionRule(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "Black cells must be placed in a region of black cells!"; + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "Black cells must be placed in a region of black cells!"; + } + return null; } - return null; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java index 30d5a3a51..05bb2f046 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java @@ -12,50 +12,51 @@ public class FillinWhiteDirectRule extends DirectRule { - public FillinWhiteDirectRule() { - super( - "NURI-BASC-0005", - "Fill In White", - "If there an unknown region surrounded by white, it must be white.", - "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); - } + public FillinWhiteDirectRule() { + super( + "NURI-BASC-0005", + "Fill In White", + "If there an unknown region surrounded by white, it must be white.", + "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new IsolateBlackContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new IsolateBlackContradictionRule(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "white cells must be placed in a region of white cells!"; + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "white cells must be placed in a region of white cells!"; + } + return null; } - return null; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java index 831dd134b..f26f0c3fe 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java @@ -12,50 +12,50 @@ public class IsolateBlackContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "Contradiction applied incorrectly. No isolated Blacks."; - private final String INVALID_USE_MESSAGE = "Contradiction must be a black cell"; + private final String NO_CONTRADICTION_MESSAGE = + "Contradiction applied incorrectly. No isolated Blacks."; + private final String INVALID_USE_MESSAGE = "Contradiction must be a black cell"; - public IsolateBlackContradictionRule() { - super( - "NURI-CONT-0003", - "Isolated Black", - "There must still be a possibility to connect every Black cell", - "edu/rpi/legup/images/nurikabe/contradictions/BlackArea.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule. - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified {@link - * PuzzleElement}, otherwise return a no contradiction message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + public IsolateBlackContradictionRule() { + super( + "NURI-CONT-0003", + "Isolated Black", + "There must still be a possibility to connect every Black cell", + "edu/rpi/legup/images/nurikabe/contradictions/BlackArea.png"); } - DisjointSets blackRegions = - NurikabeUtilities.getPossibleBlackRegions(nurikabeBoard); - boolean oneRegion = false; - for (Set region : blackRegions.getAllSets()) { - for (NurikabeCell c : region) { - if (c.getType() == NurikabeType.BLACK) { - if (oneRegion) { - return null; - } else { - oneRegion = true; - break; - } + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule. + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified {@link + * PuzzleElement}, otherwise return a no contradiction message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } + + DisjointSets blackRegions = + NurikabeUtilities.getPossibleBlackRegions(nurikabeBoard); + boolean oneRegion = false; + for (Set region : blackRegions.getAllSets()) { + for (NurikabeCell c : region) { + if (c.getType() == NurikabeType.BLACK) { + if (oneRegion) { + return null; + } else { + oneRegion = true; + break; + } + } + } } - } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java index d19cde25a..1925a68ec 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java @@ -12,41 +12,42 @@ public class MultipleNumbersContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a numbered cell"; + private final String NO_CONTRADICTION_MESSAGE = + "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a numbered cell"; - public MultipleNumbersContradictionRule() { - super( - "NURI-CONT-0004", - "Multiple Numbers", - "All white regions cannot have more than one number.", - "edu/rpi/legup/images/nurikabe/contradictions/MultipleNumbers.png"); - } + public MultipleNumbersContradictionRule() { + super( + "NURI-CONT-0004", + "Multiple Numbers", + "All white regions cannot have more than one number.", + "edu/rpi/legup/images/nurikabe/contradictions/MultipleNumbers.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + INVALID_USE_MESSAGE; - } - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); - Set numberedRegion = regions.getSet(cell); - for (NurikabeCell c : numberedRegion) { - if (c != cell && c.getType() == NurikabeType.NUMBER) { - return null; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + INVALID_USE_MESSAGE; + } + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); + Set numberedRegion = regions.getSet(cell); + for (NurikabeCell c : numberedRegion) { + if (c != cell && c.getType() == NurikabeType.NUMBER) { + return null; + } + } + return super.getNoContradictionMessage() + ": " + NO_CONTRADICTION_MESSAGE; } - return super.getNoContradictionMessage() + ": " + NO_CONTRADICTION_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java index 64d3383e1..6c69136b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java @@ -11,62 +11,63 @@ public class NoNumberContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white cell"; - private final String NOT_SURROUNDED_BY_BLACK_MESSAGE = "Must be surrounded by black cells"; + private final String NO_CONTRADICTION_MESSAGE = + "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white cell"; + private final String NOT_SURROUNDED_BY_BLACK_MESSAGE = "Must be surrounded by black cells"; - public NoNumberContradictionRule() { - super( - "NURI-CONT-0005", - "No Number", - "All enclosed white regions must have a number.", - "edu/rpi/legup/images/nurikabe/contradictions/NoNumber.png"); - } + public NoNumberContradictionRule() { + super( + "NURI-CONT-0005", + "No Number", + "All enclosed white regions must have a number.", + "edu/rpi/legup/images/nurikabe/contradictions/NoNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - Set region = NurikabeUtilities.getSurroundedRegionOf(nurikabeBoard, cell); + Set region = NurikabeUtilities.getSurroundedRegionOf(nurikabeBoard, cell); - boolean numberExists = false; - for (NurikabeCell c : region) { - if (c.getType() == NurikabeType.NUMBER) { - numberExists = true; - break; - } - } - if (!numberExists) { - return null; + boolean numberExists = false; + for (NurikabeCell c : region) { + if (c.getType() == NurikabeType.NUMBER) { + numberExists = true; + break; + } + } + if (!numberExists) { + return null; + } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - /** - * Checks whether a give NurikabeCell is empty. - * - * @param cell NurikabeCell to check if empty - * @return false if the NurikabeCell is not empty or null, true otherwise - */ - private boolean isEmptyCell(NurikabeCell cell) { - if (cell == null) { - return false; + /** + * Checks whether a give NurikabeCell is empty. + * + * @param cell NurikabeCell to check if empty + * @return false if the NurikabeCell is not empty or null, true otherwise + */ + private boolean isEmptyCell(NurikabeCell cell) { + if (cell == null) { + return false; + } + NurikabeType cellType = cell.getType(); + return cellType != NurikabeType.BLACK && cellType != NurikabeType.WHITE; } - NurikabeType cellType = cell.getType(); - return cellType != NurikabeType.BLACK && cellType != NurikabeType.WHITE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java index a9ae5441f..106c22f7a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java @@ -12,55 +12,56 @@ public class PreventBlackSquareDirectRule extends DirectRule { - public PreventBlackSquareDirectRule() { - super( - "NURI-BASC-0006", - "Prevent Black Square", - "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", - "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); - } + public PreventBlackSquareDirectRule() { + super( + "NURI-BASC-0006", + "Prevent Black Square", + "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", + "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new BlackSquareContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new BlackSquareContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradiction(modified) == null) { - return null; - } else { - return "Does not contain a contradiction at this index"; + if (contraRule.checkContradiction(modified) == null) { + return null; + } else { + return "Does not contain a contradiction at this index"; + } } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java index e471de3b1..8e260cf42 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java @@ -19,80 +19,85 @@ public class SurroundRegionDirectRule extends DirectRule { - public SurroundRegionDirectRule() { - super( - "NURI-BASC-0007", - "Surround Region", - "Surround Region", - "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); - } + public SurroundRegionDirectRule() { + super( + "NURI-BASC-0007", + "Surround Region", + "Surround Region", + "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); - if (cell.getType() == NurikabeType.BLACK) { - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adj = new HashSet<>(); // set to hold adjacent cells - Point loc = cell.getLocation(); // position of placed cell - List directions = - Arrays.asList(new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); - for (Point direction : directions) { - NurikabeCell curr = destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); - if (curr != null) { - if (curr.getType() == NurikabeType.WHITE || curr.getType() == NurikabeType.NUMBER) { - adj.add(curr); // adds cells to adj only if they are white or number blocks - } + if (cell.getType() == NurikabeType.BLACK) { + DisjointSets regions = + NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adj = new HashSet<>(); // set to hold adjacent cells + Point loc = cell.getLocation(); // position of placed cell + List directions = + Arrays.asList( + new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); + for (Point direction : directions) { + NurikabeCell curr = + destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); + if (curr != null) { + if (curr.getType() == NurikabeType.WHITE + || curr.getType() == NurikabeType.NUMBER) { + adj.add(curr); // adds cells to adj only if they are white or number blocks + } + } + } + List numberedCells = new ArrayList<>(); // number value of number cells + for (NurikabeCell c : adj) { // loops through adjacent cells + Set disRow = regions.getSet(c); // set of white spaces + for (NurikabeCell d : disRow) { // loops through white spaces + if (d.getType() == NurikabeType.NUMBER) { // if the white space is a number + numberedCells.add(d); // add that number to numberedCells + } + } + } + for (NurikabeCell number : numberedCells) { // loops through numberedCells + if (regions.getSet(number).size() + == number.getData()) { // if that cells white area is the exact + return null; // size of the number of one of the number cells within that set + } + } } - } - List numberedCells = new ArrayList<>(); // number value of number cells - for (NurikabeCell c : adj) { // loops through adjacent cells - Set disRow = regions.getSet(c); // set of white spaces - for (NurikabeCell d : disRow) { // loops through white spaces - if (d.getType() == NurikabeType.NUMBER) { // if the white space is a number - numberedCells.add(d); // add that number to numberedCells - } - } - } - for (NurikabeCell number : numberedCells) { // loops through numberedCells - if (regions.getSet(number).size() - == number.getData()) { // if that cells white area is the exact - return null; // size of the number of one of the number cells within that set - } - } + return "Does not follow from this rule at this index"; } - return "Does not follow from this rule at this index"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java index c9ae05064..e7995165b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java @@ -12,50 +12,53 @@ public class TooFewSpacesContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; - - public TooFewSpacesContradictionRule() { - super( - "NURI-CONT-0006", - "Too Few Spaces", - "A region cannot contain less spaces than its number.", - "edu/rpi/legup/images/nurikabe/contradictions/TooFewSpaces.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + private final String NO_CONTRADICTION_MESSAGE = + "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; - DisjointSets regions = NurikabeUtilities.getPossibleWhiteRegions(nurikabeBoard); - Set whiteRegion = regions.getSet(cell); - NurikabeCell numberedCell = null; - for (NurikabeCell c : whiteRegion) { - if (c.getType() == NurikabeType.NUMBER) { - numberedCell = c; - break; - } + public TooFewSpacesContradictionRule() { + super( + "NURI-CONT-0006", + "Too Few Spaces", + "A region cannot contain less spaces than its number.", + "edu/rpi/legup/images/nurikabe/contradictions/TooFewSpaces.png"); } - if (numberedCell != null && whiteRegion.size() < numberedCell.getData()) { - // System.err.println("Cell Value: " + numberedCell.getData() + ", Loc: " + cell.getLocation() - // + ", region: " + whiteRegion.size()); - return null; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } + + DisjointSets regions = + NurikabeUtilities.getPossibleWhiteRegions(nurikabeBoard); + Set whiteRegion = regions.getSet(cell); + NurikabeCell numberedCell = null; + for (NurikabeCell c : whiteRegion) { + if (c.getType() == NurikabeType.NUMBER) { + numberedCell = c; + break; + } + } + + if (numberedCell != null && whiteRegion.size() < numberedCell.getData()) { + // System.err.println("Cell Value: " + numberedCell.getData() + ", Loc: " + + // cell.getLocation() + // + ", region: " + whiteRegion.size()); + return null; + } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java index 550c07f57..7bd0883ef 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java @@ -13,49 +13,50 @@ public class TooManySpacesContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; - - public TooManySpacesContradictionRule() { - super( - "NURI-CONT-0007", - "Too Many Spaces", - "A region cannot contain more spaces than its number.", - "edu/rpi/legup/images/nurikabe/contradictions/TooManySpaces.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + private final String NO_CONTRADICTION_MESSAGE = + "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; + + public TooManySpacesContradictionRule() { + super( + "NURI-CONT-0007", + "Too Many Spaces", + "A region cannot contain more spaces than its number.", + "edu/rpi/legup/images/nurikabe/contradictions/TooManySpaces.png"); } - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); - Set whiteRegion = regions.getSet(cell); - ArrayList numberedCells = new ArrayList<>(); - for (NurikabeCell c : whiteRegion) { - if (c.getType() == NurikabeType.NUMBER) { - numberedCells.add(c); - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } + + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); + Set whiteRegion = regions.getSet(cell); + ArrayList numberedCells = new ArrayList<>(); + for (NurikabeCell c : whiteRegion) { + if (c.getType() == NurikabeType.NUMBER) { + numberedCells.add(c); + } + } + + for (NurikabeCell number : numberedCells) { + if (whiteRegion.size() > number.getData()) { + return null; + } + } + return super.getNoContradictionMessage() + ":" + this.NO_CONTRADICTION_MESSAGE; } - - for (NurikabeCell number : numberedCells) { - if (whiteRegion.size() > number.getData()) { - return null; - } - } - return super.getNoContradictionMessage() + ":" + this.NO_CONTRADICTION_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java index 92b6f8d3e..c578d317f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java @@ -12,94 +12,97 @@ public class UnreachableWhiteCellContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Cell at this index can be reached"; - private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; + private final String NO_CONTRADICTION_MESSAGE = "Cell at this index can be reached"; + private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - public UnreachableWhiteCellContradictionRule() { - super( - "NURI-CONT-0002", - "Unreachable White Cell", - "A white cell must be able to reach a white region", - "edu/rpi/legup/images/nurikabe/contradictions/CantReach.png"); - } + public UnreachableWhiteCellContradictionRule() { + super( + "NURI-CONT-0002", + "Unreachable White Cell", + "A white cell must be able to reach a white region", + "edu/rpi/legup/images/nurikabe/contradictions/CantReach.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - int height = nurikabeBoard.getHeight(); - int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); - // Get regions - HashMap whiteRegionMap = - NurikabeUtilities.getWhiteRegionMap(nurikabeBoard); - if (whiteRegionMap.containsKey(cell)) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - // BFS to a region + // Get regions + HashMap whiteRegionMap = + NurikabeUtilities.getWhiteRegionMap(nurikabeBoard); + if (whiteRegionMap.containsKey(cell)) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } + // BFS to a region - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - // Mark the current node as visited and enqueue it - HashMap visited = new HashMap<>(); - visited.put(cell, true); - queue.add(cell); - int pathLength = 1; - while (queue.size() != 0) { - // Set of adjacent squares - Set adj = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - NurikabeCell s = queue.poll(); + // Mark the current node as visited and enqueue it + HashMap visited = new HashMap<>(); + visited.put(cell, true); + queue.add(cell); + int pathLength = 1; + while (queue.size() != 0) { + // Set of adjacent squares + Set adj = new HashSet<>(); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + NurikabeCell s = queue.poll(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(nurikabeBoard.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(nurikabeBoard.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(nurikabeBoard.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(nurikabeBoard.getCell(loc.x, loc.y + 1)); - } + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(nurikabeBoard.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(nurikabeBoard.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(nurikabeBoard.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(nurikabeBoard.getCell(loc.x, loc.y + 1)); + } - for (NurikabeCell n : adj) { - int regionNeed = whiteRegionMap.getOrDefault(n, -1); - if (pathLength <= regionNeed) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - } - } + for (NurikabeCell n : adj) { + int regionNeed = whiteRegionMap.getOrDefault(n, -1); + if (pathLength <= regionNeed) { + return super.getNoContradictionMessage() + + ": " + + this.NO_CONTRADICTION_MESSAGE; + } + } + } - for (NurikabeCell n : adj) { - if (!visited.getOrDefault(n, false) - && (n.getType() == NurikabeType.UNKNOWN || n.getType() == NurikabeType.WHITE)) { - visited.put(n, true); - queue.add(n); + for (NurikabeCell n : adj) { + if (!visited.getOrDefault(n, false) + && (n.getType() == NurikabeType.UNKNOWN + || n.getType() == NurikabeType.WHITE)) { + visited.put(n, true); + queue.add(n); + } + } + ++pathLength; } - } - ++pathLength; - } - return null; - } + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java index ddc5e78b2..434e7ccde 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java @@ -14,57 +14,59 @@ public class WhiteBottleNeckDirectRule extends DirectRule { - public WhiteBottleNeckDirectRule() { - super( - "NURI-BASC-0009", - "White Bottle Neck", - "If a region needs more whites and there is only one path for the region to expand, then those unknowns must be white.", - "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); - } + public WhiteBottleNeckDirectRule() { + super( + "NURI-BASC-0009", + "White Bottle Neck", + "If a region needs more whites and there is only one path for the region to expand," + + " then those unknowns must be white.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new NoNumberContradictionRule()); + contras.add(new TooFewSpacesContradictionRule()); - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new NoNumberContradictionRule()); - contras.add(new TooFewSpacesContradictionRule()); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; + for (ContradictionRule contraRule : contras) { + if (contraRule.checkContradiction(modified) == null) { + return null; + } + } + return "This is not the only way for white to escape!"; } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); - for (ContradictionRule contraRule : contras) { - if (contraRule.checkContradiction(modified) == null) { + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { return null; - } } - return "This is not the only way for white to escape!"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java index 4e6f25cba..8b0b8e6d5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java @@ -7,104 +7,104 @@ public class ShortTruthTable extends Puzzle { - public ShortTruthTable() { - super(); - - this.name = "ShortTruthTable"; - - this.importer = new ShortTruthTableImporter(this); - this.exporter = new ShortTruthTableExporter(this); - - this.factory = new ShortTruthTableCellFactory(); - } - - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) currentBoard; - boardView = new ShortTruthTableView(sttBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } - - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } - - @Override - /** - * Determines if the given dimensions are valid for Short Truth Table - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Short Truth Table, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // Number of rows must be odd to allow for proper spacing between the statements - if (rows % 2 != 1) { - return false; + public ShortTruthTable() { + super(); + + this.name = "ShortTruthTable"; + + this.importer = new ShortTruthTableImporter(this); + this.exporter = new ShortTruthTableExporter(this); + + this.factory = new ShortTruthTableCellFactory(); + } + + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) currentBoard; + boardView = new ShortTruthTableView(sttBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); } - return true; - } - - /** - * Determines if the given statements are valid for Short Truth Table - * - * @param statements - * @return true if the statements are valid for Short Truth Table, false otherwise - */ - public boolean isValidTextInput(String[] statements) { - if (statements.length == 0) { - return false; + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; } - ShortTruthTableImporter importer = (ShortTruthTableImporter) this.getImporter(); - for (String s : statements) { - if (!importer.validGrammar(s)) { - return false; - } + @Override + /** + * Determines if the given dimensions are valid for Short Truth Table + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Short Truth Table, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // Number of rows must be odd to allow for proper spacing between the statements + if (rows % 2 != 1) { + return false; + } + + return true; } - return true; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - - ShortTruthTableBoard sttboard = (ShortTruthTableBoard) board; - - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(sttboard) == null) { - return false; - } + + /** + * Determines if the given statements are valid for Short Truth Table + * + * @param statements + * @return true if the statements are valid for Short Truth Table, false otherwise + */ + public boolean isValidTextInput(String[] statements) { + if (statements.length == 0) { + return false; + } + + ShortTruthTableImporter importer = (ShortTruthTableImporter) this.getImporter(); + for (String s : statements) { + if (!importer.validGrammar(s)) { + return false; + } + } + return true; } - for (PuzzleElement data : sttboard.getPuzzleElements()) { - ShortTruthTableCell cell = (ShortTruthTableCell) data; - if (cell.getType() == ShortTruthTableCellType.UNKNOWN) { - return false; - } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + + ShortTruthTableBoard sttboard = (ShortTruthTableBoard) board; + + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(sttboard) == null) { + return false; + } + } + for (PuzzleElement data : sttboard.getPuzzleElements()) { + ShortTruthTableCell cell = (ShortTruthTableCell) data; + if (cell.getType() == ShortTruthTableCellType.UNKNOWN) { + return false; + } + } + return true; } - return true; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java index 2876523f8..519a61974 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java @@ -10,115 +10,115 @@ public class ShortTruthTableBoard extends GridBoard { - private ShortTruthTableStatement[] statements; + private ShortTruthTableStatement[] statements; - public ShortTruthTableBoard(int width, int height, ShortTruthTableStatement[] statements) { + public ShortTruthTableBoard(int width, int height, ShortTruthTableStatement[] statements) { - super(width, height); + super(width, height); - this.statements = statements; - } + this.statements = statements; + } - public Set getCellsWithSymbol(char symbol) { - Set cells = new HashSet(); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - ShortTruthTableCell cell = (ShortTruthTableCell) getCell(x, y); - if (cell.getSymbol() == symbol) { - cells.add(cell); + public Set getCellsWithSymbol(char symbol) { + Set cells = new HashSet(); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + ShortTruthTableCell cell = (ShortTruthTableCell) getCell(x, y); + if (cell.getSymbol() == symbol) { + cells.add(cell); + } + } } - } + return cells; + } + + public ShortTruthTableCell getCellFromElement(PuzzleElement element) { + return (ShortTruthTableCell) getPuzzleElement(element); } - return cells; - } - - public ShortTruthTableCell getCellFromElement(PuzzleElement element) { - return (ShortTruthTableCell) getPuzzleElement(element); - } - - @Override - public ShortTruthTableCell getCell(int x, int y) { - return (ShortTruthTableCell) super.getCell(x, y); - } - - @Override - public ShortTruthTableBoard copy() { - - // Copy the statements - ShortTruthTableStatement[] statementsCopy = - new ShortTruthTableStatement[this.statements.length]; - for (int i = 0; i < statements.length; i++) { - statementsCopy[i] = this.statements[i].copy(); + + @Override + public ShortTruthTableCell getCell(int x, int y) { + return (ShortTruthTableCell) super.getCell(x, y); } - // copy the board and set the cells - ShortTruthTableBoard boardCopy = - new ShortTruthTableBoard(getWidth(), getHeight(), statementsCopy); - for (int r = 0; r < this.dimension.height; r++) { - for (int c = 0; c < this.dimension.width; c++) { - if (r % 2 == 0 && c < statementsCopy[r / 2].getLength()) { - boardCopy.setCell(c, r, statementsCopy[r / 2].getCell(c)); - } else { - boardCopy.setCell(c, r, getCell(c, r).copy()); + + @Override + public ShortTruthTableBoard copy() { + + // Copy the statements + ShortTruthTableStatement[] statementsCopy = + new ShortTruthTableStatement[this.statements.length]; + for (int i = 0; i < statements.length; i++) { + statementsCopy[i] = this.statements[i].copy(); + } + // copy the board and set the cells + ShortTruthTableBoard boardCopy = + new ShortTruthTableBoard(getWidth(), getHeight(), statementsCopy); + for (int r = 0; r < this.dimension.height; r++) { + for (int c = 0; c < this.dimension.width; c++) { + if (r % 2 == 0 && c < statementsCopy[r / 2].getLength()) { + boardCopy.setCell(c, r, statementsCopy[r / 2].getCell(c)); + } else { + boardCopy.setCell(c, r, getCell(c, r).copy()); + } + } + } + for (PuzzleElement e : modifiedData) { + boardCopy.getPuzzleElement(e).setModifiable(false); } - } + System.out.println("Board.copy()"); + System.out.println("original:\n" + this); + System.out.println("copy:\n" + boardCopy); + return boardCopy; } - for (PuzzleElement e : modifiedData) { - boardCopy.getPuzzleElement(e).setModifiable(false); + + public ShortTruthTableStatement[] getStatements() { + return statements; } - System.out.println("Board.copy()"); - System.out.println("original:\n" + this); - System.out.println("copy:\n" + boardCopy); - return boardCopy; - } - - public ShortTruthTableStatement[] getStatements() { - return statements; - } - - public static List copyStatementList( - List statements) { - List copy = new ArrayList(); - for (int i = 0; i < statements.size(); i++) { - copy.add(statements.get(i).copy()); + + public static List copyStatementList( + List statements) { + List copy = new ArrayList(); + for (int i = 0; i < statements.size(); i++) { + copy.add(statements.get(i).copy()); + } + return copy; } - return copy; - } - - // @Override - // public void setPuzzleElement(int index, PuzzleElement element){ - // ShortTruthTableCell cellElement = (ShortTruthTableCell) element; - // ShortTruthTableCell cell = getCell(cellElement.getX(), cellElement.getY()); - // cell.setType(cellElement.getType()); - // } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - int r = cell.getY(); - int c = cell.getX(); - if (r % 2 == 0 && c < statements[r / 2].getLength()) { - statements[r / 2] = statements[r / 2].replace(c, cell); - setCell(c, r, statements[r / 2].getCell(c)); + + // @Override + // public void setPuzzleElement(int index, PuzzleElement element){ + // ShortTruthTableCell cellElement = (ShortTruthTableCell) element; + // ShortTruthTableCell cell = getCell(cellElement.getX(), cellElement.getY()); + // cell.setType(cellElement.getType()); + // } + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + int r = cell.getY(); + int c = cell.getX(); + if (r % 2 == 0 && c < statements[r / 2].getLength()) { + statements[r / 2] = statements[r / 2].replace(c, cell); + setCell(c, r, statements[r / 2].getCell(c)); + } + super.notifyChange(cell); } - super.notifyChange(cell); - } - - @Override - public String toString() { - System.out.println("ShortTruthTableBoard toString() called"); - StringBuilder str = new StringBuilder(); - for (int i = 0; i < dimension.height; i += 2) { - for (int j = 0; j < dimension.width; j++) { - ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); - str.append(c.getSymbol()); - } - str.append(" "); - for (int j = 0; j < dimension.width; j++) { - ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); - str.append(ShortTruthTableCellType.toChar(c.getType())); - } - str.append('\n'); + + @Override + public String toString() { + System.out.println("ShortTruthTableBoard toString() called"); + StringBuilder str = new StringBuilder(); + for (int i = 0; i < dimension.height; i += 2) { + for (int j = 0; j < dimension.width; j++) { + ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); + str.append(c.getSymbol()); + } + str.append(" "); + for (int j = 0; j < dimension.width; j++) { + ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); + str.append(ShortTruthTableCellType.toChar(c.getType())); + } + str.append('\n'); + } + return str.toString(); } - return str.toString(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java index a432fe5e4..75bba369f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java @@ -7,210 +7,211 @@ public class ShortTruthTableCell extends GridCell { - // The symbol on the cell - private char symbol; - - // This is a reference to the statement that contains this cell - private ShortTruthTableStatement statement; - - // Constructors - - public ShortTruthTableCell(char symbol, ShortTruthTableCellType cellType, Point location) { - super(cellType, location); - this.symbol = symbol; - } - - /** - * Constructs a new NOT_IN_PLAY Cell - * - * @param location the location of this cell on the board - */ - public ShortTruthTableCell(Point location) { - this(' ', ShortTruthTableCellType.NOT_IN_PLAY, location); - } - - // Getters - - public ShortTruthTableStatement getStatementReference() { - return statement; - } - - public ShortTruthTableCellType getType() { - return data; - } - - public char getSymbol() { - return symbol; - } - - /** - * Returns true if this cell is a letter; false if it is an operation, paren, unused, etc - * - * @return true if cell is a variable; false otherwise - */ - public boolean isVariable() { - return Character.isLetter(symbol); - } - - public int getX() { - return (int) location.getX(); - } - - public int getY() { - return (int) location.getY(); - } - - public boolean isAssigned() { - return getType() == ShortTruthTableCellType.TRUE || getType() == ShortTruthTableCellType.FALSE; - } - - // Setters - - void setStatementReference(ShortTruthTableStatement statement) { - this.statement = statement; - } - - public void setType(ShortTruthTableCellType type) { - data = type; - } - - public void setGiven(ShortTruthTableCellType type) { - setType(type); - setModifiable(false); - setGiven(true); - } - - // Modifiers - - public void cycleTypeForward() { - switch (data) { - case UNKNOWN: - data = ShortTruthTableCellType.TRUE; - break; - case TRUE: - data = ShortTruthTableCellType.FALSE; - break; - case FALSE: - data = ShortTruthTableCellType.UNKNOWN; - break; - default: - break; - } - } - - public void cycleTypeBackward() { - cycleTypeForward(); - cycleTypeForward(); - } - - // TO STRING - - @Override - public String toString() { - return String.format("STTCell: %c %2d %-11s %s", symbol, index, data, location.toString()); - } - - // Copy function - - @Override - public ShortTruthTableCell copy() { - ShortTruthTableCell copy = new ShortTruthTableCell(symbol, data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } - - /** - * Sets the type of this ShortTruthTableCell - * - * @param e element to set the type of this Short Truth Table cell to - */ - @Override - public void setType(Element e, MouseEvent m) { - // Do not allow odd rows to be modified since they are spacer rows - if (this.getLocation().getY() % 2 == 1) { - return; - } - - // Red Element - if (e.getElementID().equals("STTT-PLAC-0002")) { - this.data = ShortTruthTableCellType.FALSE; - } - // Green Element - else { - if (e.getElementID().equals("STTT-PLAC-0001")) { - this.data = ShortTruthTableCellType.TRUE; - } - // Unknown Element - else { - if (e.getElementID().equals("STTT-PLAC-0003")) { - this.data = ShortTruthTableCellType.UNKNOWN; + // The symbol on the cell + private char symbol; + + // This is a reference to the statement that contains this cell + private ShortTruthTableStatement statement; + + // Constructors + + public ShortTruthTableCell(char symbol, ShortTruthTableCellType cellType, Point location) { + super(cellType, location); + this.symbol = symbol; + } + + /** + * Constructs a new NOT_IN_PLAY Cell + * + * @param location the location of this cell on the board + */ + public ShortTruthTableCell(Point location) { + this(' ', ShortTruthTableCellType.NOT_IN_PLAY, location); + } + + // Getters + + public ShortTruthTableStatement getStatementReference() { + return statement; + } + + public ShortTruthTableCellType getType() { + return data; + } + + public char getSymbol() { + return symbol; + } + + /** + * Returns true if this cell is a letter; false if it is an operation, paren, unused, etc + * + * @return true if cell is a variable; false otherwise + */ + public boolean isVariable() { + return Character.isLetter(symbol); + } + + public int getX() { + return (int) location.getX(); + } + + public int getY() { + return (int) location.getY(); + } + + public boolean isAssigned() { + return getType() == ShortTruthTableCellType.TRUE + || getType() == ShortTruthTableCellType.FALSE; + } + + // Setters + + void setStatementReference(ShortTruthTableStatement statement) { + this.statement = statement; + } + + public void setType(ShortTruthTableCellType type) { + data = type; + } + + public void setGiven(ShortTruthTableCellType type) { + setType(type); + setModifiable(false); + setGiven(true); + } + + // Modifiers + + public void cycleTypeForward() { + switch (data) { + case UNKNOWN: + data = ShortTruthTableCellType.TRUE; + break; + case TRUE: + data = ShortTruthTableCellType.FALSE; + break; + case FALSE: + data = ShortTruthTableCellType.UNKNOWN; + break; + default: + break; + } + } + + public void cycleTypeBackward() { + cycleTypeForward(); + cycleTypeForward(); + } + + // TO STRING + + @Override + public String toString() { + return String.format("STTCell: %c %2d %-11s %s", symbol, index, data, location.toString()); + } + + // Copy function + + @Override + public ShortTruthTableCell copy() { + ShortTruthTableCell copy = new ShortTruthTableCell(symbol, data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } + + /** + * Sets the type of this ShortTruthTableCell + * + * @param e element to set the type of this Short Truth Table cell to + */ + @Override + public void setType(Element e, MouseEvent m) { + // Do not allow odd rows to be modified since they are spacer rows + if (this.getLocation().getY() % 2 == 1) { + return; + } + + // Red Element + if (e.getElementID().equals("STTT-PLAC-0002")) { + this.data = ShortTruthTableCellType.FALSE; } - // Argument Element + // Green Element else { - if (e.getElementID().equals("STTT-UNPL-0001")) { - // Prevents non-argument symbols from being changed - if (!(this.symbol >= 'A' && this.symbol <= 'Z')) { - return; + if (e.getElementID().equals("STTT-PLAC-0001")) { + this.data = ShortTruthTableCellType.TRUE; } - - if (m.getButton() == MouseEvent.BUTTON1) { - this.symbol += 1; - if (this.symbol > 'Z') { - this.symbol = 'A'; - } - } else { - if (m.getButton() == MouseEvent.BUTTON3) { - this.symbol -= 1; - if (this.symbol < 'A') { - this.symbol = 'Z'; + // Unknown Element + else { + if (e.getElementID().equals("STTT-PLAC-0003")) { + this.data = ShortTruthTableCellType.UNKNOWN; } - } - } - } - // And/Or Element - else { - if (e.getElementID().equals("STTT-UNPL-0002")) { - if (m.getButton() == MouseEvent.BUTTON1) { - if (this.symbol == '^') { - this.symbol = '|'; - } else { - if (this.symbol == '|') { - this.symbol = '>'; - } else { - if (this.symbol == '>') { - this.symbol = '-'; - } else { - if (this.symbol == '-') { - this.symbol = '^'; - } + // Argument Element + else { + if (e.getElementID().equals("STTT-UNPL-0001")) { + // Prevents non-argument symbols from being changed + if (!(this.symbol >= 'A' && this.symbol <= 'Z')) { + return; + } + + if (m.getButton() == MouseEvent.BUTTON1) { + this.symbol += 1; + if (this.symbol > 'Z') { + this.symbol = 'A'; + } + } else { + if (m.getButton() == MouseEvent.BUTTON3) { + this.symbol -= 1; + if (this.symbol < 'A') { + this.symbol = 'Z'; + } + } + } } - } - } - } else { - if (m.getButton() == MouseEvent.BUTTON3) { - if (this.symbol == '^') { - this.symbol = '-'; - } else { - if (this.symbol == '|') { - this.symbol = '^'; - } else { - if (this.symbol == '>') { - this.symbol = '|'; - } else { - if (this.symbol == '-') { - this.symbol = '>'; + // And/Or Element + else { + if (e.getElementID().equals("STTT-UNPL-0002")) { + if (m.getButton() == MouseEvent.BUTTON1) { + if (this.symbol == '^') { + this.symbol = '|'; + } else { + if (this.symbol == '|') { + this.symbol = '>'; + } else { + if (this.symbol == '>') { + this.symbol = '-'; + } else { + if (this.symbol == '-') { + this.symbol = '^'; + } + } + } + } + } else { + if (m.getButton() == MouseEvent.BUTTON3) { + if (this.symbol == '^') { + this.symbol = '-'; + } else { + if (this.symbol == '|') { + this.symbol = '^'; + } else { + if (this.symbol == '>') { + this.symbol = '|'; + } else { + if (this.symbol == '-') { + this.symbol = '>'; + } + } + } + } + } + } } - } } - } } - } } - } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java index 288fd11f9..df74afdc9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java @@ -10,61 +10,64 @@ import org.w3c.dom.Node; public class ShortTruthTableCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public ShortTruthTableCell importCell(Node node, Board board) throws InvalidFileFormatException { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public ShortTruthTableCell importCell(Node node, Board board) + throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "ShortTruthTable Factory: unknown puzzleElement puzzleElement"); - } + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "ShortTruthTable Factory: unknown puzzleElement puzzleElement"); + } - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board; + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board; - // get the attributes for the cell - NamedNodeMap attributeList = node.getAttributes(); - int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); - int charIndex = Integer.valueOf(attributeList.getNamedItem("char_index").getNodeValue()); - String cellType = attributeList.getNamedItem("type").getNodeValue(); + // get the attributes for the cell + NamedNodeMap attributeList = node.getAttributes(); + int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); + int charIndex = + Integer.valueOf(attributeList.getNamedItem("char_index").getNodeValue()); + String cellType = attributeList.getNamedItem("type").getNodeValue(); - // modify the appropriate cell - ShortTruthTableCell cell = (ShortTruthTableCell) sttBoard.getCell(charIndex, rowIndex * 2); - cell.setData(ShortTruthTableCellType.valueOf(cellType)); + // modify the appropriate cell + ShortTruthTableCell cell = + (ShortTruthTableCell) sttBoard.getCell(charIndex, rowIndex * 2); + cell.setData(ShortTruthTableCellType.valueOf(cellType)); - return cell; + return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - org.w3c.dom.Element cellElement = document.createElement("cell"); - cellElement.setAttribute("row_index", String.valueOf(cell.getY() / 2)); - cellElement.setAttribute("char_index", String.valueOf(cell.getX())); - cellElement.setAttribute("type", String.valueOf(cell.getType())); + org.w3c.dom.Element cellElement = document.createElement("cell"); + cellElement.setAttribute("row_index", String.valueOf(cell.getY() / 2)); + cellElement.setAttribute("char_index", String.valueOf(cell.getX())); + cellElement.setAttribute("type", String.valueOf(cell.getType())); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java index fde55ee3c..d5a8292a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java @@ -4,64 +4,64 @@ import java.util.Map; public enum ShortTruthTableCellType { - FALSE(0), - TRUE(1), - UNKNOWN(-1), - NOT_IN_PLAY(-2), - PARENTHESIS(-3); + FALSE(0), + TRUE(1), + UNKNOWN(-1), + NOT_IN_PLAY(-2), + PARENTHESIS(-3); - public int value; - private static Map map = new HashMap<>(); + public int value; + private static Map map = new HashMap<>(); - ShortTruthTableCellType(int value) { - this.value = value; - } + ShortTruthTableCellType(int value) { + this.value = value; + } - static { - for (ShortTruthTableCellType cellType : ShortTruthTableCellType.values()) { - map.put(cellType.value, cellType); + static { + for (ShortTruthTableCellType cellType : ShortTruthTableCellType.values()) { + map.put(cellType.value, cellType); + } } - } - public static ShortTruthTableCellType valueOf(int cellType) { - return (ShortTruthTableCellType) map.get(cellType); - } + public static ShortTruthTableCellType valueOf(int cellType) { + return (ShortTruthTableCellType) map.get(cellType); + } - /** - * Gets the char value of a cell, Used for debugging - * - * @param type cell type input - * @return true if value is 1, false if value is 0, ? if value is -1, or blank otherwise - */ - public static char toChar(ShortTruthTableCellType type) { - if (type == TRUE) return 'T'; - if (type == FALSE) return 'F'; - if (type == UNKNOWN) return '?'; - return ' '; - } + /** + * Gets the char value of a cell, Used for debugging + * + * @param type cell type input + * @return true if value is 1, false if value is 0, ? if value is -1, or blank otherwise + */ + public static char toChar(ShortTruthTableCellType type) { + if (type == TRUE) return 'T'; + if (type == FALSE) return 'F'; + if (type == UNKNOWN) return '?'; + return ' '; + } - /** - * Returns true if this cell holds the value either TRUE or FALSE - * - * @return true if this cell holds the value either TRUE or FALSE - */ - public boolean isTrueOrFalse() { - return value == 0 || value == 1; - } + /** + * Returns true if this cell holds the value either TRUE or FALSE + * + * @return true if this cell holds the value either TRUE or FALSE + */ + public boolean isTrueOrFalse() { + return value == 0 || value == 1; + } - public ShortTruthTableCellType getNegation() { - switch (value) { - case 1: - return ShortTruthTableCellType.FALSE; - case 0: - return ShortTruthTableCellType.TRUE; - default: - throw new RuntimeException("Trying to negate a cell not assigned to true or false"); + public ShortTruthTableCellType getNegation() { + switch (value) { + case 1: + return ShortTruthTableCellType.FALSE; + case 0: + return ShortTruthTableCellType.TRUE; + default: + throw new RuntimeException("Trying to negate a cell not assigned to true or false"); + } } - } - public static ShortTruthTableCellType getDefaultType(char c) { - if (c == '(' || c == ')') return PARENTHESIS; - return UNKNOWN; - } + public static ShortTruthTableCellType getDefaultType(char c) { + if (c == '(' || c == ')') return PARENTHESIS; + return UNKNOWN; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java index e83c7b358..172867f5a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java @@ -6,29 +6,29 @@ public class ShortTruthTableController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { - System.out.println("STTController: Cell change"); + System.out.println("STTController: Cell change"); - // cast the data to a short truth table cell - ShortTruthTableCell cell = (ShortTruthTableCell) data; + // cast the data to a short truth table cell + ShortTruthTableCell cell = (ShortTruthTableCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - cell.cycleTypeForward(); - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - cell.cycleTypeBackward(); - } + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + cell.cycleTypeForward(); + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + cell.cycleTypeBackward(); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java index af6e412ba..43e1d2299 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java @@ -6,73 +6,74 @@ public class ShortTruthTableElementView extends GridElementView { - // Font - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; + // Font + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; - // Square Colors - private static final Color TRUE_COLOR = new Color(0, 130, 0); // green - private static final Color TRUE_COLOR_COLORBLIND = new Color(0, 0, 255); - private static final Color FALSE_COLOR = new Color(200, 0, 0); // red + // Square Colors + private static final Color TRUE_COLOR = new Color(0, 130, 0); // green + private static final Color TRUE_COLOR_COLORBLIND = new Color(0, 0, 255); + private static final Color FALSE_COLOR = new Color(200, 0, 0); // red - private static final Color FALSE_COLOR_COLORBLIND = new Color(255, 0, 0); - private static final Color UNKNOWN_COLOR = Color.WHITE; + private static final Color FALSE_COLOR_COLORBLIND = new Color(255, 0, 0); + private static final Color UNKNOWN_COLOR = Color.WHITE; - public ShortTruthTableElementView(ShortTruthTableCell cell) { - super(cell); - } + public ShortTruthTableElementView(ShortTruthTableCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public ShortTruthTableCell getPuzzleElement() { - return (ShortTruthTableCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public ShortTruthTableCell getPuzzleElement() { + return (ShortTruthTableCell) super.getPuzzleElement(); + } - @Override - public void drawElement(Graphics2D graphics2D) { + @Override + public void drawElement(Graphics2D graphics2D) { - // get information about the cell - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - ShortTruthTableCellType type = cell.getData(); + // get information about the cell + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + ShortTruthTableCellType type = cell.getData(); - // do not draw the cell if it is not in play - if (type == ShortTruthTableCellType.NOT_IN_PLAY) return; + // do not draw the cell if it is not in play + if (type == ShortTruthTableCellType.NOT_IN_PLAY) return; - // fill in background color of the cell - graphics2D.setStroke(new BasicStroke(1)); - LegupPreferences prefs = LegupPreferences.getInstance(); - switch (type) { - case TRUE: - if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - graphics2D.setColor(TRUE_COLOR_COLORBLIND); - break; - } - graphics2D.setColor(TRUE_COLOR); - break; - case FALSE: - if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - graphics2D.setColor(FALSE_COLOR_COLORBLIND); - break; + // fill in background color of the cell + graphics2D.setStroke(new BasicStroke(1)); + LegupPreferences prefs = LegupPreferences.getInstance(); + switch (type) { + case TRUE: + if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + graphics2D.setColor(TRUE_COLOR_COLORBLIND); + break; + } + graphics2D.setColor(TRUE_COLOR); + break; + case FALSE: + if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + graphics2D.setColor(FALSE_COLOR_COLORBLIND); + break; + } + graphics2D.setColor(FALSE_COLOR); + break; + default: + graphics2D.setColor(UNKNOWN_COLOR); + break; } - graphics2D.setColor(FALSE_COLOR); - break; - default: - graphics2D.setColor(UNKNOWN_COLOR); - break; - } - graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.fillRect(location.x, location.y, size.width, size.height); - // Draw the symbol on the cell - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getSymbol()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(ShortTruthTableOperation.getLogicSymbol(cell.getSymbol()), xText, yText); - } + // Draw the symbol on the cell + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getSymbol()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString( + ShortTruthTableOperation.getLogicSymbol(cell.getSymbol()), xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java index a3c2c6918..0914c159a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java @@ -6,40 +6,41 @@ public class ShortTruthTableExporter extends PuzzleExporter { - public ShortTruthTableExporter(ShortTruthTable stt) { - super(stt); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - ShortTruthTableBoard board; - if (puzzle.getTree() != null) { - board = (ShortTruthTableBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (ShortTruthTableBoard) puzzle.getBoardView().getBoard(); + public ShortTruthTableExporter(ShortTruthTable stt) { + super(stt); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - - org.w3c.dom.Element dataElement = newDocument.createElement("data"); - - ShortTruthTableStatement[] statements = board.getStatements(); - for (int i = 0; i < statements.length; i++) { - org.w3c.dom.Element statementElement = newDocument.createElement("statement"); - statementElement.setAttribute("representation", statements[i].getStringRep()); - statementElement.setAttribute("row_index", String.valueOf(i)); - dataElement.appendChild(statementElement); - } - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - ShortTruthTableCell cell = board.getCellFromElement(puzzleElement); - if (!cell.getType().isTrueOrFalse()) continue; - - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - dataElement.appendChild(cellElement); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + ShortTruthTableBoard board; + if (puzzle.getTree() != null) { + board = (ShortTruthTableBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (ShortTruthTableBoard) puzzle.getBoardView().getBoard(); + } + + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + + org.w3c.dom.Element dataElement = newDocument.createElement("data"); + + ShortTruthTableStatement[] statements = board.getStatements(); + for (int i = 0; i < statements.length; i++) { + org.w3c.dom.Element statementElement = newDocument.createElement("statement"); + statementElement.setAttribute("representation", statements[i].getStringRep()); + statementElement.setAttribute("row_index", String.valueOf(i)); + dataElement.appendChild(statementElement); + } + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + ShortTruthTableCell cell = board.getCellFromElement(puzzleElement); + if (!cell.getType().isTrueOrFalse()) continue; + + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + dataElement.appendChild(cellElement); + } + + boardElement.appendChild(dataElement); + return boardElement; } - - boardElement.appendChild(dataElement); - return boardElement; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java index c9cf388f1..396668380 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java @@ -14,334 +14,347 @@ class ShortTruthTableImporter extends PuzzleImporter { - public ShortTruthTableImporter(ShortTruthTable stt) { - super(stt); - } - - /** - * Parse a string into all the cells, the y position of the statement is passed so the y position - * can be set - * - * @param statement - * @param y - * @return - */ - private List getCells(String statement, int y) { - List cells = new ArrayList(); - // go through each char in the statement and make a cell for it - for (int i = 0; i < statement.length(); i++) { - char c = statement.charAt(i); - ShortTruthTableCell cell = - new ShortTruthTableCell(c, ShortTruthTableCellType.getDefaultType(c), new Point(i, y)); - // it is modifiable if the type is unknown - cell.setModifiable(cell.getType() == ShortTruthTableCellType.UNKNOWN); - cells.add(cell); - } - return cells; - } - - /** - * Parses the statementData into all the cells (with symbols) and statements for the puzzle. All - * cells are set to UNKNWON, it their value is given, it will be set later in the import process. - * - *

Both allCells and statements act as returns, They should be passed as empty arrays - * - * @param statementData The data to be imported - * @param allCells returns all the cells as a jagged 2d array - * @param statements returns all the statements - * @return the length, in chars, of the longest statement - */ - private int parseAllStatementsAndCells( - final NodeList statementData, - List> allCells, - List statements) - throws InvalidFileFormatException { - - int maxStatementLength = 0; - - // get a 2D arraylist of all the cells - for (int i = 0; i < statementData.getLength(); i++) { - - // Get the atributes from the statement i in the file - NamedNodeMap attributeList = statementData.item(i).getAttributes(); - - String statementRep = attributeList.getNamedItem("representation").getNodeValue(); - System.out.println("STATEMENT REP: " + statementRep); - System.out.println("ROW INDEX: " + attributeList.getNamedItem("row_index").getNodeValue()); - // parser time (on statementRep) - // if (!validGrammar(statementRep)) throw some error - if (!validGrammar(statementRep)) { - JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); - throw new InvalidFileFormatException("shorttruthtable importer: invalid sentence syntax"); - } - int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); - - // get the cells for the statement - List rowOfCells = getCells(statementRep, rowIndex * 2); - allCells.add(rowOfCells); - statements.add(new ShortTruthTableStatement(statementRep, rowOfCells)); - - // keep track of the length of the longest statement - maxStatementLength = Math.max(maxStatementLength, statementRep.length()); + public ShortTruthTableImporter(ShortTruthTable stt) { + super(stt); } - return maxStatementLength; - } - - private int parseAllStatementsAndCells( - String[] statementData, - List> allCells, - List statements) - throws IllegalArgumentException { - int maxStatementLength = 0; - - for (int i = 0; i < statementData.length; i++) { - if (!validGrammar(statementData[i])) { - JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); - throw new IllegalArgumentException("shorttruthtable importer: invalid sentence syntax"); - } - - // get the cells for the statement - List rowOfCells = getCells(statementData[i], i * 2); - allCells.add(rowOfCells); - statements.add(new ShortTruthTableStatement(statementData[i], rowOfCells)); - - // keep track of the length of the longest statement - maxStatementLength = Math.max(maxStatementLength, statementData[i].length()); + /** + * Parse a string into all the cells, the y position of the statement is passed so the y + * position can be set + * + * @param statement + * @param y + * @return + */ + private List getCells(String statement, int y) { + List cells = new ArrayList(); + // go through each char in the statement and make a cell for it + for (int i = 0; i < statement.length(); i++) { + char c = statement.charAt(i); + ShortTruthTableCell cell = + new ShortTruthTableCell( + c, ShortTruthTableCellType.getDefaultType(c), new Point(i, y)); + // it is modifiable if the type is unknown + cell.setModifiable(cell.getType() == ShortTruthTableCellType.UNKNOWN); + cells.add(cell); + } + return cells; } - return maxStatementLength; - } - - protected boolean validGrammar(String sentence) { - int open = 0; - int close = 0; - char[] valid_characters = new char[] {'^', 'v', '!', '>', '-', '&', '|', '~', '$', '%'}; - for (int i = 0; i < sentence.length(); i++) { - char s = sentence.charAt(i); - if (s == '(' || s == ')') { - switch (s) { - case ')': - close++; - break; - case '(': - open++; - break; - } - continue; - } - if (!Character.isLetter(s)) { - boolean valid = false; - for (char c : valid_characters) { - if (c == s) { - valid = true; - break; - } - } - if (!valid) { - System.out.println("Invalid character"); - System.out.println(s); - return false; + /** + * Parses the statementData into all the cells (with symbols) and statements for the puzzle. All + * cells are set to UNKNWON, it their value is given, it will be set later in the import + * process. + * + *

Both allCells and statements act as returns, They should be passed as empty arrays + * + * @param statementData The data to be imported + * @param allCells returns all the cells as a jagged 2d array + * @param statements returns all the statements + * @return the length, in chars, of the longest statement + */ + private int parseAllStatementsAndCells( + final NodeList statementData, + List> allCells, + List statements) + throws InvalidFileFormatException { + + int maxStatementLength = 0; + + // get a 2D arraylist of all the cells + for (int i = 0; i < statementData.getLength(); i++) { + + // Get the atributes from the statement i in the file + NamedNodeMap attributeList = statementData.item(i).getAttributes(); + + String statementRep = attributeList.getNamedItem("representation").getNodeValue(); + System.out.println("STATEMENT REP: " + statementRep); + System.out.println( + "ROW INDEX: " + attributeList.getNamedItem("row_index").getNodeValue()); + // parser time (on statementRep) + // if (!validGrammar(statementRep)) throw some error + if (!validGrammar(statementRep)) { + JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); + throw new InvalidFileFormatException( + "shorttruthtable importer: invalid sentence syntax"); + } + int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); + + // get the cells for the statement + List rowOfCells = getCells(statementRep, rowIndex * 2); + allCells.add(rowOfCells); + statements.add(new ShortTruthTableStatement(statementRep, rowOfCells)); + + // keep track of the length of the longest statement + maxStatementLength = Math.max(maxStatementLength, statementRep.length()); } - if (i != sentence.length() - 1) { - char next = sentence.charAt(i + 1); - if (next != '!' && next != '~') { - for (char c : valid_characters) { - if (c == next) { - System.out.println("Invalid next character"); - System.out.println(s); - System.out.println(next); - return false; - } + + return maxStatementLength; + } + + private int parseAllStatementsAndCells( + String[] statementData, + List> allCells, + List statements) + throws IllegalArgumentException { + int maxStatementLength = 0; + + for (int i = 0; i < statementData.length; i++) { + if (!validGrammar(statementData[i])) { + JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); + throw new IllegalArgumentException( + "shorttruthtable importer: invalid sentence syntax"); } - } + + // get the cells for the statement + List rowOfCells = getCells(statementData[i], i * 2); + allCells.add(rowOfCells); + statements.add(new ShortTruthTableStatement(statementData[i], rowOfCells)); + + // keep track of the length of the longest statement + maxStatementLength = Math.max(maxStatementLength, statementData[i].length()); } - } else { - if (i != sentence.length() - 1) { - if (Character.isLetter(sentence.charAt(i + 1))) { - System.out.println("Invalid next character"); - System.out.println(s); - System.out.println(sentence.charAt(i + 1)); - return false; - } + + return maxStatementLength; + } + + protected boolean validGrammar(String sentence) { + int open = 0; + int close = 0; + char[] valid_characters = new char[] {'^', 'v', '!', '>', '-', '&', '|', '~', '$', '%'}; + for (int i = 0; i < sentence.length(); i++) { + char s = sentence.charAt(i); + if (s == '(' || s == ')') { + switch (s) { + case ')': + close++; + break; + case '(': + open++; + break; + } + continue; + } + if (!Character.isLetter(s)) { + boolean valid = false; + for (char c : valid_characters) { + if (c == s) { + valid = true; + break; + } + } + if (!valid) { + System.out.println("Invalid character"); + System.out.println(s); + return false; + } + if (i != sentence.length() - 1) { + char next = sentence.charAt(i + 1); + if (next != '!' && next != '~') { + for (char c : valid_characters) { + if (c == next) { + System.out.println("Invalid next character"); + System.out.println(s); + System.out.println(next); + return false; + } + } + } + } + } else { + if (i != sentence.length() - 1) { + if (Character.isLetter(sentence.charAt(i + 1))) { + System.out.println("Invalid next character"); + System.out.println(s); + System.out.println(sentence.charAt(i + 1)); + return false; + } + } + } } - } + return open == close; } - return open == close; - } - - private ShortTruthTableBoard generateBoard( - List> allCells, - List statements, - int width) { - - // calculate the height for the board - int height = statements.size() * 2 - 1; - - // instantiate the board with the correct width and height - ShortTruthTableBoard sttBoard = - new ShortTruthTableBoard( - width, height, statements.toArray(new ShortTruthTableStatement[statements.size()])); - - // set the cells in the board. create not_in_play cells where needed - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - - // get the statement index for this row of the table - int statementIndex = y / 2; - - // get the cell at this location; or create a not_in_play one if necessary - ShortTruthTableCell cell = null; - - // for a cell to exist at (x, y), it must be a valid row and within the statement length - if (y % 2 == 0 && x < statements.get(statementIndex).getLength()) { - cell = allCells.get(statementIndex).get(x); - System.out.println("Importer: check cell statement ref: " + cell.getStatementReference()); - } else { - // if it is not a valid cell space, add a NOT_IN_PLAY cell - cell = new ShortTruthTableCell(' ', ShortTruthTableCellType.NOT_IN_PLAY, new Point(x, y)); - cell.setModifiable(false); + + private ShortTruthTableBoard generateBoard( + List> allCells, + List statements, + int width) { + + // calculate the height for the board + int height = statements.size() * 2 - 1; + + // instantiate the board with the correct width and height + ShortTruthTableBoard sttBoard = + new ShortTruthTableBoard( + width, + height, + statements.toArray(new ShortTruthTableStatement[statements.size()])); + + // set the cells in the board. create not_in_play cells where needed + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + + // get the statement index for this row of the table + int statementIndex = y / 2; + + // get the cell at this location; or create a not_in_play one if necessary + ShortTruthTableCell cell = null; + + // for a cell to exist at (x, y), it must be a valid row and within the statement + // length + if (y % 2 == 0 && x < statements.get(statementIndex).getLength()) { + cell = allCells.get(statementIndex).get(x); + System.out.println( + "Importer: check cell statement ref: " + cell.getStatementReference()); + } else { + // if it is not a valid cell space, add a NOT_IN_PLAY cell + cell = + new ShortTruthTableCell( + ' ', ShortTruthTableCellType.NOT_IN_PLAY, new Point(x, y)); + cell.setModifiable(false); + } + + // add the cell to the table + cell.setIndex(y * width + x); + sttBoard.setCell(x, y, cell); + } } - // add the cell to the table - cell.setIndex(y * width + x); - sttBoard.setCell(x, y, cell); - } + return sttBoard; } - return sttBoard; - } - - private void setGivenCells( - ShortTruthTableBoard sttBoard, - Element dataElement, - NodeList cellData, - List statements) - throws InvalidFileFormatException { - - // if it is normal, set all predicates to true and the conclusion to false - if (dataElement.getAttribute("normal").equalsIgnoreCase("true")) { - // set all predicates to true (all but the last one) - for (int i = 0; i < statements.size() - 1; i++) { - statements.get(i).getCell().setGiven(ShortTruthTableCellType.TRUE); - } - // set the conclusion to false (the last one) - statements.get(statements.size() - 1).getCell().setGiven(ShortTruthTableCellType.FALSE); - } + private void setGivenCells( + ShortTruthTableBoard sttBoard, + Element dataElement, + NodeList cellData, + List statements) + throws InvalidFileFormatException { + + // if it is normal, set all predicates to true and the conclusion to false + if (dataElement.getAttribute("normal").equalsIgnoreCase("true")) { + // set all predicates to true (all but the last one) + for (int i = 0; i < statements.size() - 1; i++) { + statements.get(i).getCell().setGiven(ShortTruthTableCellType.TRUE); + } + // set the conclusion to false (the last one) + statements.get(statements.size() - 1).getCell().setGiven(ShortTruthTableCellType.FALSE); + } - // set the given cell values - for (int i = 0; i < cellData.getLength(); i++) { - // set the value with the factory importer - ShortTruthTableCell cell = - (ShortTruthTableCell) puzzle.getFactory().importCell(cellData.item(i), sttBoard); - // set the modifiable and given flags - cell.setModifiable(false); - cell.setGiven(true); + // set the given cell values + for (int i = 0; i < cellData.getLength(); i++) { + // set the value with the factory importer + ShortTruthTableCell cell = + (ShortTruthTableCell) + puzzle.getFactory().importCell(cellData.item(i), sttBoard); + // set the modifiable and given flags + cell.setModifiable(false); + cell.setGiven(true); + } } - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return false; - } - - @Override - public boolean acceptsTextInput() { - return true; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException - */ - @Override - public void initializeBoard(int rows, int columns) {} - - // STATEMENT IMPORTER - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - - try { - - // Check File formatting - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "short truth table Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("data").getLength() == 0) { - throw new InvalidFileFormatException( - "short truth table Importer: no statements found for board"); - } - - // get all the cells in a 2D arraylist - List> allCells = new ArrayList>(); - // store the statement data structors - List statements = new ArrayList(); - - // get the elements from the file - Element dataElement = (Element) boardElement.getElementsByTagName("data").item(0); - NodeList statementData = dataElement.getElementsByTagName("statement"); - NodeList cellData = dataElement.getElementsByTagName("cell"); - - // Parse the data - int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); - - // generate the board - ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); - - // set the given cell values - setGivenCells(sttBoard, dataElement, cellData, statements); - - puzzle.setCurrentBoard(sttBoard); - - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "short truth table Importer: unknown value where integer expected"); + + @Override + public boolean acceptsRowsAndColumnsInput() { + return false; } - } - - /** - * Creates the board for building using statements - * - * @param statementInput - * @throws UnsupportedOperationException - * @throws IllegalArgumentException - */ - public void initializeBoard(String[] statementInput) - throws UnsupportedOperationException, IllegalArgumentException { - List statementsList = new LinkedList<>(); - for (String s : statementInput) { - if (s.strip().length() > 0) { - statementsList.add(s); - } + + @Override + public boolean acceptsTextInput() { + return true; } - String[] statementData = statementsList.toArray(new String[statementsList.size()]); - if (statementData.length == 0) { - throw new IllegalArgumentException( - "short truth table Importer: no statements found for board"); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException + */ + @Override + public void initializeBoard(int rows, int columns) {} + + // STATEMENT IMPORTER + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + + try { + + // Check File formatting + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "short truth table Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("data").getLength() == 0) { + throw new InvalidFileFormatException( + "short truth table Importer: no statements found for board"); + } + + // get all the cells in a 2D arraylist + List> allCells = new ArrayList>(); + // store the statement data structors + List statements = new ArrayList(); + + // get the elements from the file + Element dataElement = (Element) boardElement.getElementsByTagName("data").item(0); + NodeList statementData = dataElement.getElementsByTagName("statement"); + NodeList cellData = dataElement.getElementsByTagName("cell"); + + // Parse the data + int maxStatementLength = + parseAllStatementsAndCells(statementData, allCells, statements); + + // generate the board + ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); + + // set the given cell values + setGivenCells(sttBoard, dataElement, cellData, statements); + + puzzle.setCurrentBoard(sttBoard); + + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "short truth table Importer: unknown value where integer expected"); + } } - // Store all cells and statements - List> allCells = new ArrayList<>(); - List statements = new ArrayList<>(); + /** + * Creates the board for building using statements + * + * @param statementInput + * @throws UnsupportedOperationException + * @throws IllegalArgumentException + */ + public void initializeBoard(String[] statementInput) + throws UnsupportedOperationException, IllegalArgumentException { + List statementsList = new LinkedList<>(); + for (String s : statementInput) { + if (s.strip().length() > 0) { + statementsList.add(s); + } + } + String[] statementData = statementsList.toArray(new String[statementsList.size()]); + + if (statementData.length == 0) { + throw new IllegalArgumentException( + "short truth table Importer: no statements found for board"); + } - // Parse the data - int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); + // Store all cells and statements + List> allCells = new ArrayList<>(); + List statements = new ArrayList<>(); - // Generate and set the board - don't set given cell values since none are given - ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); - puzzle.setCurrentBoard(sttBoard); - } + // Parse the data + int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); + + // Generate and set the board - don't set given cell values since none are given + ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); + puzzle.setCurrentBoard(sttBoard); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java index 1a5fd3a12..8284474da 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java @@ -2,47 +2,47 @@ public class ShortTruthTableOperation { - public static final char AND = '^'; - public static final char OR = '|'; - public static final char NOT = '~'; - public static final char CONDITIONAL = '>'; - public static final char BICONDITIONAL = '-'; + public static final char AND = '^'; + public static final char OR = '|'; + public static final char NOT = '~'; + public static final char CONDITIONAL = '>'; + public static final char BICONDITIONAL = '-'; - private ShortTruthTableOperation() {} + private ShortTruthTableOperation() {} - public static String getLogicSymbol(char c) { - switch (c) { - case AND: - return "\u2227"; - case OR: - return "\u2228"; - case NOT: - return "\u00AC"; - case CONDITIONAL: - return "\u2192"; - case BICONDITIONAL: - return "\u2194"; + public static String getLogicSymbol(char c) { + switch (c) { + case AND: + return "\u2227"; + case OR: + return "\u2228"; + case NOT: + return "\u00AC"; + case CONDITIONAL: + return "\u2192"; + case BICONDITIONAL: + return "\u2194"; + } + return "" + c; } - return "" + c; - } - public static String getRuleName(char operation) { - switch (operation) { - case AND: - return "And"; - case OR: - return "Or"; - case NOT: - return "Not"; - case CONDITIONAL: - return "Conditional"; - case BICONDITIONAL: - return "Biconditional"; + public static String getRuleName(char operation) { + switch (operation) { + case AND: + return "And"; + case OR: + return "Or"; + case NOT: + return "Not"; + case CONDITIONAL: + return "Conditional"; + case BICONDITIONAL: + return "Biconditional"; + } + return null; } - return null; - } - public static boolean isOperation(char c) { - return c == AND || c == OR || c == NOT || c == CONDITIONAL || c == BICONDITIONAL; - } + public static boolean isOperation(char c) { + return c == AND || c == OR || c == NOT || c == CONDITIONAL || c == BICONDITIONAL; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java index 59073f8e3..2059e3ca5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java @@ -9,290 +9,292 @@ public class ShortTruthTableStatement extends PuzzleElement { - // the cell that this statement holds - private final ShortTruthTableCell cell; - - // child nodes of the tree - private final ShortTruthTableStatement parentStatement; - private final ShortTruthTableStatement leftStatement; - private final ShortTruthTableStatement rightStatement; - - // the representation string for this statement - private final String stringRep; - private final List cells; - - // constructor for root statement, sets parent to null - public ShortTruthTableStatement(String statement, List cells) { - this(statement, null, cells); - } - - // recursive constructor; constructs child statement nodes if necessary - private ShortTruthTableStatement( - String statement, ShortTruthTableStatement parent, List cells) { - - this.parentStatement = parent; - - // set the string rep to the statement (include parens in case this is a sub statement) - this.stringRep = statement; - this.cells = new ArrayList(cells); - - // remove the parens for parsing the statement - statement = removeParens(statement); - removeParens(cells); - - // get the index of the char that this statement represents - int index = parse(statement); - - // construct the cell for this node in the tree - cell = cells.get(index); - // give the cell a reference back to this statement - cell.setStatementReference(this); - - // get the strings on either side of this char in the string rep - String left = statement.substring(0, index); - String right = statement.substring(index + 1); - - List leftCells = - new ArrayList(cells.subList(0, index)); - List rightCells = - new ArrayList(cells.subList(index + 1, cells.size())); - - // construct sub-statements if necessary - if (left.length() > 0) { - leftStatement = new ShortTruthTableStatement(left, this, leftCells); - } else { - leftStatement = null; - } + // the cell that this statement holds + private final ShortTruthTableCell cell; - if (right.length() > 0) { - rightStatement = new ShortTruthTableStatement(right, this, rightCells); - } else { - rightStatement = null; - } - } + // child nodes of the tree + private final ShortTruthTableStatement parentStatement; + private final ShortTruthTableStatement leftStatement; + private final ShortTruthTableStatement rightStatement; - // parsing for the constructor - static String removeParens(String statement) { + // the representation string for this statement + private final String stringRep; + private final List cells; - if (statement.charAt(0) != '(') { - return statement; + // constructor for root statement, sets parent to null + public ShortTruthTableStatement(String statement, List cells) { + this(statement, null, cells); } - // if the statement does start with a paren, check that it matches with the last paren - int openParenCount = 1; - int i = 1; - while (i < statement.length() - 1) { - char c = statement.charAt(i); - if (c == '(') { - openParenCount++; - } else { - if (c == ')') openParenCount--; - } - - // if the first paren has been closed, and it is not the end of the string, - // then there is no whole statement parens to remove - if (openParenCount == 0 && i != statement.length() - 1) { - return statement; - } - - i++; - } - // if the while loop made it through the entire statement, there are parens around the whole - // thing - return statement.substring(1, statement.length() - 1); - } - - int parse(String statement) { - - // Split by and, or, CONDITIONAL, or biconditional - // keep track of the parens, it must be equal to zero to split - int openParenCount = 0; - // index for stepping through the string - int i = 0; - // step through each char in the statement - while (i < statement.length()) { - // get the char - char c = statement.charAt(i); - // keep track of the open parens - if (c == '(') { - openParenCount++; - } else { - if (c == ')') { - openParenCount--; + // recursive constructor; constructs child statement nodes if necessary + private ShortTruthTableStatement( + String statement, ShortTruthTableStatement parent, List cells) { + + this.parentStatement = parent; + + // set the string rep to the statement (include parens in case this is a sub statement) + this.stringRep = statement; + this.cells = new ArrayList(cells); + + // remove the parens for parsing the statement + statement = removeParens(statement); + removeParens(cells); + + // get the index of the char that this statement represents + int index = parse(statement); + + // construct the cell for this node in the tree + cell = cells.get(index); + // give the cell a reference back to this statement + cell.setStatementReference(this); + + // get the strings on either side of this char in the string rep + String left = statement.substring(0, index); + String right = statement.substring(index + 1); + + List leftCells = + new ArrayList(cells.subList(0, index)); + List rightCells = + new ArrayList(cells.subList(index + 1, cells.size())); + + // construct sub-statements if necessary + if (left.length() > 0) { + leftStatement = new ShortTruthTableStatement(left, this, leftCells); + } else { + leftStatement = null; } - // if the char is an operator, and there are no open parens, split the statement here - else { - if (openParenCount == 0 - && ShortTruthTableOperation.isOperation(c) - && c != ShortTruthTableOperation.NOT) { - return i; - } + + if (right.length() > 0) { + rightStatement = new ShortTruthTableStatement(right, this, rightCells); + } else { + rightStatement = null; } - } - // increment the index - i++; } - // if it made it through the while loop: - // this is an atomic statement or a negation - // either way, the important char is the first character in the string - return 0; - } + // parsing for the constructor + static String removeParens(String statement) { - static void removeParens(List cells) { + if (statement.charAt(0) != '(') { + return statement; + } - if (cells.get(0).getSymbol() != '(') { - return; + // if the statement does start with a paren, check that it matches with the last paren + int openParenCount = 1; + int i = 1; + while (i < statement.length() - 1) { + char c = statement.charAt(i); + if (c == '(') { + openParenCount++; + } else { + if (c == ')') openParenCount--; + } + + // if the first paren has been closed, and it is not the end of the string, + // then there is no whole statement parens to remove + if (openParenCount == 0 && i != statement.length() - 1) { + return statement; + } + + i++; + } + // if the while loop made it through the entire statement, there are parens around the whole + // thing + return statement.substring(1, statement.length() - 1); } - // if the statement does start with a paren, check that it matches with the last paren - int openParenCount = 1; - int i = 1; - while (i < cells.size() - 1) { - char c = cells.get(i).getSymbol(); - if (c == '(') { - openParenCount++; - } else { - if (c == ')') openParenCount--; - } - - // if the first paren has been closed, and it is not the end of the string, - // then there is no whole statement parens to remove - if (openParenCount == 0 && i != cells.size() - 1) { - return; - } - - i++; + int parse(String statement) { + + // Split by and, or, CONDITIONAL, or biconditional + // keep track of the parens, it must be equal to zero to split + int openParenCount = 0; + // index for stepping through the string + int i = 0; + // step through each char in the statement + while (i < statement.length()) { + // get the char + char c = statement.charAt(i); + // keep track of the open parens + if (c == '(') { + openParenCount++; + } else { + if (c == ')') { + openParenCount--; + } + // if the char is an operator, and there are no open parens, split the statement + // here + else { + if (openParenCount == 0 + && ShortTruthTableOperation.isOperation(c) + && c != ShortTruthTableOperation.NOT) { + return i; + } + } + } + // increment the index + i++; + } + + // if it made it through the while loop: + // this is an atomic statement or a negation + // either way, the important char is the first character in the string + return 0; + } + + static void removeParens(List cells) { + + if (cells.get(0).getSymbol() != '(') { + return; + } + + // if the statement does start with a paren, check that it matches with the last paren + int openParenCount = 1; + int i = 1; + while (i < cells.size() - 1) { + char c = cells.get(i).getSymbol(); + if (c == '(') { + openParenCount++; + } else { + if (c == ')') openParenCount--; + } + + // if the first paren has been closed, and it is not the end of the string, + // then there is no whole statement parens to remove + if (openParenCount == 0 && i != cells.size() - 1) { + return; + } + + i++; + } + + // if the while loop made it through the entire statement, there are parens around the whole + // thing + cells.remove(cells.size() - 1); + cells.remove(0); } - // if the while loop made it through the entire statement, there are parens around the whole - // thing - cells.remove(cells.size() - 1); - cells.remove(0); - } + // Getters - // Getters + public ShortTruthTableCell getCell() { + return cell; + } - public ShortTruthTableCell getCell() { - return cell; - } + public ShortTruthTableStatement getLeftStatement() { + return leftStatement; + } - public ShortTruthTableStatement getLeftStatement() { - return leftStatement; - } + public ShortTruthTableStatement getRightStatement() { + return rightStatement; + } - public ShortTruthTableStatement getRightStatement() { - return rightStatement; - } + public ShortTruthTableStatement getParentStatement() { + return parentStatement; + } - public ShortTruthTableStatement getParentStatement() { - return parentStatement; - } + @Override + public String toString() { + if (this.parentStatement == null) { + return "SST_Statement: " + stringRep + " parent: null"; + } + return "SST_Statement: " + stringRep + " parent: " + parentStatement.stringRep; + } - @Override - public String toString() { - if (this.parentStatement == null) { - return "SST_Statement: " + stringRep + " parent: null"; + public String getStringRep() { + return this.stringRep; } - return "SST_Statement: " + stringRep + " parent: " + parentStatement.stringRep; - } - - public String getStringRep() { - return this.stringRep; - } - - /** - * Returns the length of the statement in cells. This includes all cells used for parenthesis - * - * @return the number of cells contained in this statement - */ - public int getLength() { - return stringRep.length(); - } - - public ShortTruthTableCell getCell(int i) { - return cells.get(i); - } - - // Getters (recursive) - - // returns all cells in this statement with the symbol 'symbol'; runs recursively on both sides of - // the tree - public Set getCellsWithSymbol(char symbol) { - Set set = new HashSet(getLength()); - if (cell.getSymbol() == symbol) set.add(cell); - if (leftStatement != null) set.addAll(leftStatement.getCellsWithSymbol(symbol)); - if (rightStatement != null) set.addAll(rightStatement.getCellsWithSymbol(symbol)); - return set; - } - - /** - * Returns an array of three elements where [0] is the left statement type, [1] is this statement - * type, and [2] is the right statement type. null means either the statement doesn't exist or is - * an unknown value. - * - * @return the assigned values to this statement and its sub-statements - */ - public ShortTruthTableCellType[] getCellTypePattern() { - // get this type and the right type, they will always be used - ShortTruthTableCellType type = this.cell.getType(); - System.out.println("Right statement: " + rightStatement.getCell()); - ShortTruthTableCellType rightType = this.rightStatement.getCell().getType(); - System.out.println("Right type: " + rightType); - // if this is a not statement, there is no left side - if (cell.getSymbol() == ShortTruthTableOperation.NOT) { - return new ShortTruthTableCellType[] {null, type, rightType}; + + /** + * Returns the length of the statement in cells. This includes all cells used for parenthesis + * + * @return the number of cells contained in this statement + */ + public int getLength() { + return stringRep.length(); } - // if it is any other operation, get the left side too and return it - ShortTruthTableCellType leftType = this.leftStatement.getCell().getType(); - return new ShortTruthTableCellType[] {leftType, type, rightType}; - } - - // Setters - - private void setCellLocations(int rowIndex, int offset) { - // set the location of this cell - int xLoc = offset; - if (leftStatement != null) { - xLoc += leftStatement.getLength(); + + public ShortTruthTableCell getCell(int i) { + return cells.get(i); + } + + // Getters (recursive) + + // returns all cells in this statement with the symbol 'symbol'; runs recursively on both sides + // of + // the tree + public Set getCellsWithSymbol(char symbol) { + Set set = new HashSet(getLength()); + if (cell.getSymbol() == symbol) set.add(cell); + if (leftStatement != null) set.addAll(leftStatement.getCellsWithSymbol(symbol)); + if (rightStatement != null) set.addAll(rightStatement.getCellsWithSymbol(symbol)); + return set; } - cell.setLocation(new Point(xLoc, rowIndex)); - // recurse on both sides of the tree - if (leftStatement != null) { - leftStatement.setCellLocations(rowIndex, offset); + + /** + * Returns an array of three elements where [0] is the left statement type, [1] is this + * statement type, and [2] is the right statement type. null means either the statement doesn't + * exist or is an unknown value. + * + * @return the assigned values to this statement and its sub-statements + */ + public ShortTruthTableCellType[] getCellTypePattern() { + // get this type and the right type, they will always be used + ShortTruthTableCellType type = this.cell.getType(); + System.out.println("Right statement: " + rightStatement.getCell()); + ShortTruthTableCellType rightType = this.rightStatement.getCell().getType(); + System.out.println("Right type: " + rightType); + // if this is a not statement, there is no left side + if (cell.getSymbol() == ShortTruthTableOperation.NOT) { + return new ShortTruthTableCellType[] {null, type, rightType}; + } + // if it is any other operation, get the left side too and return it + ShortTruthTableCellType leftType = this.leftStatement.getCell().getType(); + return new ShortTruthTableCellType[] {leftType, type, rightType}; } - if (rightStatement != null) { - rightStatement.setCellLocations(rowIndex, xLoc + 1); + + // Setters + + private void setCellLocations(int rowIndex, int offset) { + // set the location of this cell + int xLoc = offset; + if (leftStatement != null) { + xLoc += leftStatement.getLength(); + } + cell.setLocation(new Point(xLoc, rowIndex)); + // recurse on both sides of the tree + if (leftStatement != null) { + leftStatement.setCellLocations(rowIndex, offset); + } + if (rightStatement != null) { + rightStatement.setCellLocations(rowIndex, xLoc + 1); + } } - } - public void setCellLocations(int rowIndex) { - setCellLocations(rowIndex, 0); - } + public void setCellLocations(int rowIndex) { + setCellLocations(rowIndex, 0); + } - public ShortTruthTableStatement copy() { - // copy all the cells - List cellsCopy = new ArrayList<>(); - for (ShortTruthTableCell c : cells) { - cellsCopy.add(c.copy()); + public ShortTruthTableStatement copy() { + // copy all the cells + List cellsCopy = new ArrayList<>(); + for (ShortTruthTableCell c : cells) { + cellsCopy.add(c.copy()); + } + // make a copy of the statement with all the copied cells + // return the new statement + return new ShortTruthTableStatement(stringRep, cellsCopy); } - // make a copy of the statement with all the copied cells - // return the new statement - return new ShortTruthTableStatement(stringRep, cellsCopy); - } - - public ShortTruthTableStatement replace(int column, ShortTruthTableCell cell) { - // copy all the cells (replacing one) - List cellsCopy = new ArrayList<>(); - for (ShortTruthTableCell c : cells) { - if (c.getX() == column) { - cellsCopy.add(cell); - } else { - cellsCopy.add(c); - } + + public ShortTruthTableStatement replace(int column, ShortTruthTableCell cell) { + // copy all the cells (replacing one) + List cellsCopy = new ArrayList<>(); + for (ShortTruthTableCell c : cells) { + if (c.getX() == column) { + cellsCopy.add(cell); + } else { + cellsCopy.add(c); + } + } + // make a copy of the statement with all the copied cells + // return the new statement + return new ShortTruthTableStatement(stringRep, cellsCopy); } - // make a copy of the statement with all the copied cells - // return the new statement - return new ShortTruthTableStatement(stringRep, cellsCopy); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java index e15f5b928..15becf443 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java @@ -7,18 +7,19 @@ public class ShortTruthTableView extends GridBoardView { - public ShortTruthTableView(ShortTruthTableBoard board) { - super(new BoardController(), new ShortTruthTableController(), board.getDimension()); + public ShortTruthTableView(ShortTruthTableBoard board) { + super(new BoardController(), new ShortTruthTableController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - // System.out.println("STTView :"+cell); - Point loc = cell.getLocation(); - ShortTruthTableElementView elementView = new ShortTruthTableElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + // System.out.println("STTView :"+cell); + Point loc = cell.getLocation(); + ShortTruthTableElementView elementView = new ShortTruthTableElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java index ed53dc3bf..9294fba4e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class ArgumentElement extends NonPlaceableElement { - public ArgumentElement() { - super( - "STTT-UNPL-0001", - "Argument Element", - "Argument of logic statement element", - "edu/rpi/legup/images/shorttruthtable/tiles/LetterTile.png"); - } + public ArgumentElement() { + super( + "STTT-UNPL-0001", + "Argument Element", + "Argument of logic statement element", + "edu/rpi/legup/images/shorttruthtable/tiles/LetterTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java index eb6b9996c..783186baa 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class GreenElement extends PlaceableElement { - public GreenElement() { - super( - "STTT-PLAC-0001", - "Green Element", - "A green tile to set certain tiles to true", - "edu/rpi/legup/images/shorttruthtable/tiles/GreenTile.png"); - } + public GreenElement() { + super( + "STTT-PLAC-0001", + "Green Element", + "A green tile to set certain tiles to true", + "edu/rpi/legup/images/shorttruthtable/tiles/GreenTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java index 8336e0a41..5fed4b1df 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class LogicSymbolElement extends NonPlaceableElement { - public LogicSymbolElement() { - super( - "STTT-UNPL-0002", - "Logic Symbol Element", - "Logic symbol element", - "edu/rpi/legup/images/shorttruthtable/tiles/ConditionalBiconditionalTile.png"); - } + public LogicSymbolElement() { + super( + "STTT-UNPL-0002", + "Logic Symbol Element", + "Logic symbol element", + "edu/rpi/legup/images/shorttruthtable/tiles/ConditionalBiconditionalTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java index c9e0472ae..e2a589b65 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class RedElement extends PlaceableElement { - public RedElement() { - super( - "STTT-PLAC-0002", - "Red Element", - "A red tile to set certain tiles to false", - "edu/rpi/legup/images/shorttruthtable/tiles/RedTile.png"); - } + public RedElement() { + super( + "STTT-PLAC-0002", + "Red Element", + "A red tile to set certain tiles to false", + "edu/rpi/legup/images/shorttruthtable/tiles/RedTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java index 87feed9ed..d475bc05d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class UnknownElement extends PlaceableElement { - public UnknownElement() { - super( - "STTT-PLAC-0003", - "Unknown Element", - "A blank tile", - "edu/rpi/legup/images/shorttruthtable/tiles/UnknownTile.png"); - } + public UnknownElement() { + super( + "STTT-PLAC-0003", + "Unknown Element", + "A blank tile", + "edu/rpi/legup/images/shorttruthtable/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java index f8421da08..38048b5b0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java @@ -4,13 +4,13 @@ public class DirectRuleAtomic extends DirectRule_Generic { - public DirectRuleAtomic() { - super( - "STTT-BASC-0001", - "Atomic Rule", - "All identical atoms have the same T/F value", - "Atomic", - new ContradictionRuleAtomic(), - false); - } + public DirectRuleAtomic() { + super( + "STTT-BASC-0001", + "Atomic Rule", + "All identical atoms have the same T/F value", + "Atomic", + new ContradictionRuleAtomic(), + false); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java index 106b34fd5..470ba7c29 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java @@ -11,78 +11,82 @@ public abstract class DirectRule_Generic extends DirectRule { - final ContradictionRule CORRESPONDING_CONTRADICTION_RULE; - final boolean ELIMINATION_RULE; + final ContradictionRule CORRESPONDING_CONTRADICTION_RULE; + final boolean ELIMINATION_RULE; - public DirectRule_Generic( - String ruleID, - String ruleName, - String description, - String imageName, - ContradictionRule contraRule, - boolean eliminationRule) { - super( - ruleID, - ruleName, - description, - "edu/rpi/legup/images/shorttruthtable/ruleimages/basic/" + imageName + ".png"); - this.CORRESPONDING_CONTRADICTION_RULE = contraRule; - this.ELIMINATION_RULE = eliminationRule; - } + public DirectRule_Generic( + String ruleID, + String ruleName, + String description, + String imageName, + ContradictionRule contraRule, + boolean eliminationRule) { + super( + ruleID, + ruleName, + description, + "edu/rpi/legup/images/shorttruthtable/ruleimages/basic/" + imageName + ".png"); + this.CORRESPONDING_CONTRADICTION_RULE = contraRule; + this.ELIMINATION_RULE = eliminationRule; + } - public String checkRuleRawAt(TreeTransition transition, PuzzleElement element) { - // Rule must have cell to evaluate on - if (element == null) return super.getInvalidUseOfRuleMessage() + ": Must have painted cell"; + public String checkRuleRawAt(TreeTransition transition, PuzzleElement element) { + // Rule must have cell to evaluate on + if (element == null) return super.getInvalidUseOfRuleMessage() + ": Must have painted cell"; - // Check that the puzzle element is not unknown - ShortTruthTableBoard parentBoard = - (ShortTruthTableBoard) transition.getParents().get(0).getBoard(); - ShortTruthTableBoard finalBoard = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell parentCell = (ShortTruthTableCell) parentBoard.getPuzzleElement(element); - ShortTruthTableCell finalCell = (ShortTruthTableCell) finalBoard.getPuzzleElement(element); + // Check that the puzzle element is not unknown + ShortTruthTableBoard parentBoard = + (ShortTruthTableBoard) transition.getParents().get(0).getBoard(); + ShortTruthTableBoard finalBoard = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell parentCell = + (ShortTruthTableCell) parentBoard.getPuzzleElement(element); + ShortTruthTableCell finalCell = (ShortTruthTableCell) finalBoard.getPuzzleElement(element); - if (!finalCell.isAssigned()) { - return super.getInvalidUseOfRuleMessage() - + ": Only assigned cells are allowed for basic rules"; - } + if (!finalCell.isAssigned()) { + return super.getInvalidUseOfRuleMessage() + + ": Only assigned cells are allowed for basic rules"; + } - // Strategy: Negate the modified cell and check if there is a contradiction. If there is one, - // then the - // original statement must be true. If there isn't one, then the original statement must be - // false. + // Strategy: Negate the modified cell and check if there is a contradiction. If there is + // one, + // then the + // original statement must be true. If there isn't one, then the original statement must be + // false. - ShortTruthTableBoard modifiedBoard = parentBoard.copy(); + ShortTruthTableBoard modifiedBoard = parentBoard.copy(); - PuzzleElement checkElement = - this.ELIMINATION_RULE - ? parentCell.getStatementReference().getParentStatement().getCell() - : element; + PuzzleElement checkElement = + this.ELIMINATION_RULE + ? parentCell.getStatementReference().getParentStatement().getCell() + : element; - ShortTruthTableCell checkCell = - this.ELIMINATION_RULE - ? (ShortTruthTableCell) modifiedBoard.getCell(parentCell.getX(), parentCell.getY()) - : (ShortTruthTableCell) modifiedBoard.getPuzzleElement(element); + ShortTruthTableCell checkCell = + this.ELIMINATION_RULE + ? (ShortTruthTableCell) + modifiedBoard.getCell(parentCell.getX(), parentCell.getY()) + : (ShortTruthTableCell) modifiedBoard.getPuzzleElement(element); - checkCell.setType(finalCell.getType().getNegation()); + checkCell.setType(finalCell.getType().getNegation()); - String contradictionMessage = - CORRESPONDING_CONTRADICTION_RULE.checkContradictionAt(modifiedBoard, checkElement); - if (contradictionMessage - == null) { // A contradiction exists in the modified statement; this is good! - return null; - } + String contradictionMessage = + CORRESPONDING_CONTRADICTION_RULE.checkContradictionAt(modifiedBoard, checkElement); + if (contradictionMessage + == null) { // A contradiction exists in the modified statement; this is good! + return null; + } - return super.getInvalidUseOfRuleMessage(); - } + return super.getInvalidUseOfRuleMessage(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node short truth table board used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node short truth table board used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java index b6e88fa65..6f48784a3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java @@ -4,7 +4,7 @@ public class DirectRuleAndElimination extends DirectRule_GenericElimination { - public DirectRuleAndElimination() { - super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); - } + public DirectRuleAndElimination() { + super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java index 8c12882a7..168877ca6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java @@ -4,7 +4,7 @@ public class DirectRuleBiconditionalElimination extends DirectRule_GenericElimination { - public DirectRuleBiconditionalElimination() { - super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); - } + public DirectRuleBiconditionalElimination() { + super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java index a316b4566..4a287b195 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java @@ -4,7 +4,7 @@ public class DirectRuleConditionalElimination extends DirectRule_GenericElimination { - public DirectRuleConditionalElimination() { - super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); - } + public DirectRuleConditionalElimination() { + super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java index f15a4d2b2..5acff5837 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java @@ -4,7 +4,7 @@ public class DirectRuleNotElimination extends DirectRule_GenericElimination { - public DirectRuleNotElimination() { - super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); - } + public DirectRuleNotElimination() { + super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java index 77d507764..fba43762a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java @@ -4,7 +4,7 @@ public class DirectRuleOrElimination extends DirectRule_GenericElimination { - public DirectRuleOrElimination() { - super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); - } + public DirectRuleOrElimination() { + super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java index b741f47b9..1f85e5b79 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java @@ -5,15 +5,15 @@ public abstract class DirectRule_GenericElimination extends DirectRule_Generic { - public DirectRule_GenericElimination( - String ruleID, String ruleName, ContradictionRule contradictionRule) { + public DirectRule_GenericElimination( + String ruleID, String ruleName, ContradictionRule contradictionRule) { - super( - ruleID, - ruleName + " Elimination", - ruleName + " statements must have a valid pattern", - "elimination/" + ruleName, - contradictionRule, - true); - } + super( + ruleID, + ruleName + " Elimination", + ruleName + " statements must have a valid pattern", + "elimination/" + ruleName, + contradictionRule, + true); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java index 838f28e4c..667b97a0f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleAndIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleAndIntroduction() { - super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); - } + public DirectRuleAndIntroduction() { + super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java index 5e332c355..c2dfeebba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleBiconditionalIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleBiconditionalIntroduction() { - super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); - } + public DirectRuleBiconditionalIntroduction() { + super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java index 7b3843fde..728d7f244 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleConditionalIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleConditionalIntroduction() { - super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); - } + public DirectRuleConditionalIntroduction() { + super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java index be6926915..80b963a56 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleNotIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleNotIntroduction() { - super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); - } + public DirectRuleNotIntroduction() { + super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java index 887b1bff0..66a569655 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleOrIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleOrIntroduction() { - super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); - } + public DirectRuleOrIntroduction() { + super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java index 5b6803dc2..8469ff0b9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java @@ -5,15 +5,15 @@ public abstract class DirectRule_GenericIntroduction extends DirectRule_Generic { - protected DirectRule_GenericIntroduction( - String ruleID, String ruleName, ContradictionRule contradictionRule) { + protected DirectRule_GenericIntroduction( + String ruleID, String ruleName, ContradictionRule contradictionRule) { - super( - ruleID, - ruleName + " Introduction", - ruleName + " statements must have a valid pattern", - "introduction/" + ruleName, - contradictionRule, - false); - } + super( + ruleID, + ruleName + " Introduction", + ruleName + " statements must have a valid pattern", + "introduction/" + ruleName, + contradictionRule, + false); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java index 60c9ab49e..9b589f14e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java @@ -5,13 +5,13 @@ public class CaseRuleAnd extends CaseRule_GenericStatement { - public CaseRuleAnd() { - super("STTT-CASE-0001", ShortTruthTableOperation.AND, "And", trueCases, falseCases); - } + public CaseRuleAnd() { + super("STTT-CASE-0001", ShortTruthTableOperation.AND, "And", trueCases, falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = {{T, T}}; - private static final ShortTruthTableCellType[][] falseCases = { - {F, U}, - {U, F} - }; + private static final ShortTruthTableCellType[][] trueCases = {{T, T}}; + private static final ShortTruthTableCellType[][] falseCases = { + {F, U}, + {U, F} + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java index 46975b7df..58d2068b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java @@ -11,57 +11,57 @@ public class CaseRuleAtomic extends CaseRule_Generic { - public CaseRuleAtomic() { - super( - "STTT-CASE-0002", - "Atomic", - "True or False", - "Each unknown cell must either be true or false"); - } + public CaseRuleAtomic() { + super( + "STTT-CASE-0002", + "Atomic", + "True or False", + "Each unknown cell must either be true or false"); + } - // Adds all elements that can be selected for this case rule - @Override - public CaseBoard getCaseBoard(Board board) { - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); - sttBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(sttBoard, this); - for (PuzzleElement element : sttBoard.getPuzzleElements()) { - if (((ShortTruthTableCell) element).getType() == ShortTruthTableCellType.UNKNOWN) { - caseBoard.addPickableElement(element); - } + // Adds all elements that can be selected for this case rule + @Override + public CaseBoard getCaseBoard(Board board) { + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); + sttBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(sttBoard, this); + for (PuzzleElement element : sttBoard.getPuzzleElements()) { + if (((ShortTruthTableCell) element).getType() == ShortTruthTableCellType.UNKNOWN) { + caseBoard.addPickableElement(element); + } + } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(ShortTruthTableCellType.TRUE); - case1.addModifiedData(data1); - cases.add(case1); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(ShortTruthTableCellType.TRUE); + case1.addModifiedData(data1); + cases.add(case1); - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(ShortTruthTableCellType.FALSE); - case2.addModifiedData(data2); - cases.add(case2); + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(ShortTruthTableCellType.FALSE); + case2.addModifiedData(data2); + cases.add(case2); - return cases; - } + return cases; + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java index 52058a6f5..1bb5f0332 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java @@ -5,21 +5,21 @@ public class CaseRuleBiconditional extends CaseRule_GenericStatement { - public CaseRuleBiconditional() { - super( - "STTT-CASE-0003", - ShortTruthTableOperation.BICONDITIONAL, - "Biconditional", - trueCases, - falseCases); - } + public CaseRuleBiconditional() { + super( + "STTT-CASE-0003", + ShortTruthTableOperation.BICONDITIONAL, + "Biconditional", + trueCases, + falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {T, T}, - {F, F} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - {F, T} - }; + private static final ShortTruthTableCellType[][] trueCases = { + {T, T}, + {F, F} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + {F, T} + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java index ea1f78408..397341f0e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java @@ -5,20 +5,20 @@ public class CaseRuleConditional extends CaseRule_GenericStatement { - public CaseRuleConditional() { - super( - "STTT-CASE-0004", - ShortTruthTableOperation.CONDITIONAL, - "Conditional", - trueCases, - falseCases); - } + public CaseRuleConditional() { + super( + "STTT-CASE-0004", + ShortTruthTableOperation.CONDITIONAL, + "Conditional", + trueCases, + falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {U, T}, - {F, U} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - }; + private static final ShortTruthTableCellType[][] trueCases = { + {U, T}, + {F, U} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java index a9b2abb65..36f4e6f87 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java @@ -5,15 +5,15 @@ public class CaseRuleOr extends CaseRule_GenericStatement { - public CaseRuleOr() { - super("STTT-CASE-0005", ShortTruthTableOperation.OR, "Or", trueCases, falseCases); - } + public CaseRuleOr() { + super("STTT-CASE-0005", ShortTruthTableOperation.OR, "Or", trueCases, falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {T, U}, - {U, T} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {F, F}, - }; + private static final ShortTruthTableCellType[][] trueCases = { + {T, U}, + {U, T} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {F, F}, + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java index b4a6afee6..5885f98f8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java @@ -7,56 +7,57 @@ public abstract class CaseRule_Generic extends CaseRule { - public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { - super( - ruleID, - title, - description, - "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - // Validate that two children are generated - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "ERROR: This case rule must spawn at least 1 child."; + public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { + super( + ruleID, + title, + description, + "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); } - // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE - // List cases = Arrays.asList(childTransitions.get(0), childTransitions.get(1)); - // for (TreeTransition c : cases) { - // ShortTruthTableCell mod1 = - // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // ShortTruthTableCell mod2 = - // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == - // ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && - // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == - // ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { - // return "ERROR: This case rule must be an unknown, true, or false cell."; - // } - // } - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + // Validate that two children are generated + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "ERROR: This case rule must spawn at least 1 child."; + } + + // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE + // List cases = Arrays.asList(childTransitions.get(0), + // childTransitions.get(1)); + // for (TreeTransition c : cases) { + // ShortTruthTableCell mod1 = + // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // ShortTruthTableCell mod2 = + // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == + // ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && + // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == + // ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { + // return "ERROR: This case rule must be an unknown, true, or false cell."; + // } + // } + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java index 68dd33b16..99f771246 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java @@ -13,133 +13,140 @@ public abstract class CaseRule_GenericStatement extends CaseRule_Generic { - public CaseRule_GenericStatement( - String ruleID, - char operation, - String title, - ShortTruthTableCellType[][] trueCases, - ShortTruthTableCellType[][] falseCases) { - super( - ruleID, - ShortTruthTableOperation.getRuleName(operation), - title + " case", - "A known " + title.toUpperCase() + " statement can have multiple forms"); - - this.operation = operation; - - this.trueCases = trueCases; - this.falseCases = falseCases; - } - - private final char operation; - - private final ShortTruthTableCellType[][] trueCases; - private final ShortTruthTableCellType[][] falseCases; - - protected static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; - protected static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; - protected static final ShortTruthTableCellType U = ShortTruthTableCellType.UNKNOWN; - - // Adds all elements that can be selected for this caserule - @Override - public CaseBoard getCaseBoard(Board board) { - // copy the board and add all elements that can be selected - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); - sttBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(sttBoard, this); - - // add all elements that can be selected for the case rule statement - for (PuzzleElement element : sttBoard.getPuzzleElements()) { - // get the cell object - ShortTruthTableCell cell = sttBoard.getCellFromElement(element); - // the cell must match the symbol - if (cell.getSymbol() != this.operation) continue; - // the statement must be assigned with unassigned sub-statements - if (!cell.getType().isTrueOrFalse()) continue; - if (cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) - continue; - if (this.operation != ShortTruthTableOperation.NOT - && cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) { - continue; - } - // if the element has passed all the checks, it can be selected - caseBoard.addPickableElement(element); + public CaseRule_GenericStatement( + String ruleID, + char operation, + String title, + ShortTruthTableCellType[][] trueCases, + ShortTruthTableCellType[][] falseCases) { + super( + ruleID, + ShortTruthTableOperation.getRuleName(operation), + title + " case", + "A known " + title.toUpperCase() + " statement can have multiple forms"); + + this.operation = operation; + + this.trueCases = trueCases; + this.falseCases = falseCases; } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ShortTruthTableBoard sttBoard = ((ShortTruthTableBoard) board); - ShortTruthTableCell cell = sttBoard.getCellFromElement(puzzleElement); - - // If the statement is set to true, collect true cases. Otherwise, collect the false cases - if (cell.getType() == ShortTruthTableCellType.TRUE) { - return getCasesFromCell(sttBoard, puzzleElement, trueCases); + + private final char operation; + + private final ShortTruthTableCellType[][] trueCases; + private final ShortTruthTableCellType[][] falseCases; + + protected static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; + protected static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; + protected static final ShortTruthTableCellType U = ShortTruthTableCellType.UNKNOWN; + + // Adds all elements that can be selected for this caserule + @Override + public CaseBoard getCaseBoard(Board board) { + // copy the board and add all elements that can be selected + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); + sttBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(sttBoard, this); + + // add all elements that can be selected for the case rule statement + for (PuzzleElement element : sttBoard.getPuzzleElements()) { + // get the cell object + ShortTruthTableCell cell = sttBoard.getCellFromElement(element); + // the cell must match the symbol + if (cell.getSymbol() != this.operation) continue; + // the statement must be assigned with unassigned sub-statements + if (!cell.getType().isTrueOrFalse()) continue; + if (cell.getStatementReference() + .getRightStatement() + .getCell() + .getType() + .isTrueOrFalse()) continue; + if (this.operation != ShortTruthTableOperation.NOT + && cell.getStatementReference() + .getRightStatement() + .getCell() + .getType() + .isTrueOrFalse()) { + continue; + } + // if the element has passed all the checks, it can be selected + caseBoard.addPickableElement(element); + } + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ShortTruthTableBoard sttBoard = ((ShortTruthTableBoard) board); + ShortTruthTableCell cell = sttBoard.getCellFromElement(puzzleElement); + + // If the statement is set to true, collect true cases. Otherwise, collect the false cases + if (cell.getType() == ShortTruthTableCellType.TRUE) { + return getCasesFromCell(sttBoard, puzzleElement, trueCases); + } + return getCasesFromCell(sttBoard, puzzleElement, falseCases); } - return getCasesFromCell(sttBoard, puzzleElement, falseCases); - } - - /** - * Collects a list of boards for each possible outcome of case-rule application - * - * @param board current board state - * @param puzzleElement case rule operator - * @param possibilities list of possibilities for operator state - * @return ArrayList of Boards - */ - private ArrayList getCasesFromCell( - ShortTruthTableBoard board, - PuzzleElement puzzleElement, - ShortTruthTableCellType[][] possibilities) { - // Create branch case for each possibility - ArrayList cases = new ArrayList<>(); - for (int i = 0; i < possibilities.length; i++) { - // Create a new board to modify and get statement of selected square - ShortTruthTableBoard b = board.copy(); - ShortTruthTableCell cell = b.getCellFromElement(puzzleElement); - ShortTruthTableStatement statement = cell.getStatementReference(); - - // Modify neighboring cells of case-rule application by the provided logical cases - if (possibilities[i][0] != ShortTruthTableCellType.UNKNOWN) { - ShortTruthTableCell leftCell = statement.getLeftStatement().getCell(); - leftCell.setData(possibilities[i][0]); - b.addModifiedData(leftCell); - } - if (possibilities[i][1] != ShortTruthTableCellType.UNKNOWN) { - ShortTruthTableCell rightCell = statement.getRightStatement().getCell(); - rightCell.setData(possibilities[i][1]); - b.addModifiedData(rightCell); - } - - cases.add(b); + + /** + * Collects a list of boards for each possible outcome of case-rule application + * + * @param board current board state + * @param puzzleElement case rule operator + * @param possibilities list of possibilities for operator state + * @return ArrayList of Boards + */ + private ArrayList getCasesFromCell( + ShortTruthTableBoard board, + PuzzleElement puzzleElement, + ShortTruthTableCellType[][] possibilities) { + // Create branch case for each possibility + ArrayList cases = new ArrayList<>(); + for (int i = 0; i < possibilities.length; i++) { + // Create a new board to modify and get statement of selected square + ShortTruthTableBoard b = board.copy(); + ShortTruthTableCell cell = b.getCellFromElement(puzzleElement); + ShortTruthTableStatement statement = cell.getStatementReference(); + + // Modify neighboring cells of case-rule application by the provided logical cases + if (possibilities[i][0] != ShortTruthTableCellType.UNKNOWN) { + ShortTruthTableCell leftCell = statement.getLeftStatement().getCell(); + leftCell.setData(possibilities[i][0]); + b.addModifiedData(leftCell); + } + if (possibilities[i][1] != ShortTruthTableCellType.UNKNOWN) { + ShortTruthTableCell rightCell = statement.getRightStatement().getCell(); + rightCell.setData(possibilities[i][1]); + b.addModifiedData(rightCell); + } + + cases.add(b); + } + return cases; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = super.dependentElements(board, puzzleElement); + + elements.add(board.getPuzzleElement(puzzleElement)); + + return elements; } - return cases; - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = super.dependentElements(board, puzzleElement); - - elements.add(board.getPuzzleElement(puzzleElement)); - - return elements; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java index 0549b5f99..595dd0cb2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java @@ -5,18 +5,18 @@ public class ContradictionRuleAnd extends ContradictionRule_GenericStatement { - public ContradictionRuleAnd() { - super( - "STTT-CONT-0001", - "Contradicting And", - "An AND statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/And.png", - ShortTruthTableOperation.AND, - new ShortTruthTableCellType[][] { - {n, T, F}, - {F, T, n}, - // {F, T, F}, - {T, F, T}, - }); - } + public ContradictionRuleAnd() { + super( + "STTT-CONT-0001", + "Contradicting And", + "An AND statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/And.png", + ShortTruthTableOperation.AND, + new ShortTruthTableCellType[][] { + {n, T, F}, + {F, T, n}, + // {F, T, F}, + {T, F, T}, + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java index 1c2342557..879b7c9a5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java @@ -11,48 +11,49 @@ public class ContradictionRuleAtomic extends ContradictionRule { - public ContradictionRuleAtomic() { - super( - "STTT-CONT-0002", - "Contradicting Variable", - "A single variable can not be both True and False", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Atomic.png"); - } - - @Override - public String checkContradictionAt(Board puzzleBoard, PuzzleElement puzzleElement) { - - // cast the board toa shortTruthTableBoard - ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - - // get the cell that contradicts another cell in the board - ShortTruthTableCell cell = (ShortTruthTableCell) board.getPuzzleElement(puzzleElement); - - if (!cell.isVariable()) { - System.out.println(" Not Var"); - return "Can not check for contradiction on a non-variable element"; + public ContradictionRuleAtomic() { + super( + "STTT-CONT-0002", + "Contradicting Variable", + "A single variable can not be both True and False", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Atomic.png"); } - ShortTruthTableCellType cellType = cell.getType(); - if (!cellType.isTrueOrFalse()) { - return "Can only check for a contradiction against a cell that is assigned a value of True or False"; + @Override + public String checkContradictionAt(Board puzzleBoard, PuzzleElement puzzleElement) { + + // cast the board toa shortTruthTableBoard + ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; + + // get the cell that contradicts another cell in the board + ShortTruthTableCell cell = (ShortTruthTableCell) board.getPuzzleElement(puzzleElement); + + if (!cell.isVariable()) { + System.out.println(" Not Var"); + return "Can not check for contradiction on a non-variable element"; + } + + ShortTruthTableCellType cellType = cell.getType(); + if (!cellType.isTrueOrFalse()) { + return "Can only check for a contradiction against a cell that is assigned a value of" + + " True or False"; + } + + // get all the cells with the same value + Set varCells = board.getCellsWithSymbol(cell.getSymbol()); + + // check if there are any contradictions + Iterator itr = varCells.iterator(); + while (itr.hasNext()) { + ShortTruthTableCell checkCell = itr.next(); + ShortTruthTableCellType checkCellType = checkCell.getType(); + // if there is an assigned contradiction, return null + if (checkCellType.isTrueOrFalse() && checkCellType != cellType) { + return null; + } + } + + // if it made it through the while loop, thene there is no contradiction + return "There is no contradiction for the variable " + cell.getSymbol(); } - - // get all the cells with the same value - Set varCells = board.getCellsWithSymbol(cell.getSymbol()); - - // check if there are any contradictions - Iterator itr = varCells.iterator(); - while (itr.hasNext()) { - ShortTruthTableCell checkCell = itr.next(); - ShortTruthTableCellType checkCellType = checkCell.getType(); - // if there is an assigned contradiction, return null - if (checkCellType.isTrueOrFalse() && checkCellType != cellType) { - return null; - } - } - - // if it made it through the while loop, thene there is no contradiction - return "There is no contradiction for the variable " + cell.getSymbol(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java index 2be92ffb1..bae07acce 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java @@ -5,18 +5,18 @@ public class ContradictionRuleBiconditional extends ContradictionRule_GenericStatement { - public ContradictionRuleBiconditional() { - super( - "STTT-CONT-0003", - "Contradicting Biconditional", - "A Biconditional statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Biconditional.png", - ShortTruthTableOperation.BICONDITIONAL, - new ShortTruthTableCellType[][] { - {T, T, F}, - {F, T, T}, - {T, F, T}, - {F, F, F} - }); - } + public ContradictionRuleBiconditional() { + super( + "STTT-CONT-0003", + "Contradicting Biconditional", + "A Biconditional statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Biconditional.png", + ShortTruthTableOperation.BICONDITIONAL, + new ShortTruthTableCellType[][] { + {T, T, F}, + {F, T, T}, + {T, F, T}, + {F, F, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java index b9ce9b74e..e3a51a00e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java @@ -5,17 +5,17 @@ public class ContradictionRuleConditional extends ContradictionRule_GenericStatement { - public ContradictionRuleConditional() { - super( - "STTT-CONT-0004", - "Contradicting Conditional", - "A Conditional statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Conditional.png", - ShortTruthTableOperation.CONDITIONAL, - new ShortTruthTableCellType[][] { - {n, F, T}, - {F, F, n}, - {T, T, F} - }); - } + public ContradictionRuleConditional() { + super( + "STTT-CONT-0004", + "Contradicting Conditional", + "A Conditional statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Conditional.png", + ShortTruthTableOperation.CONDITIONAL, + new ShortTruthTableCellType[][] { + {n, F, T}, + {F, F, n}, + {T, T, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java index 6c4bb40e0..4e20485bc 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java @@ -5,16 +5,16 @@ public class ContradictionRuleNot extends ContradictionRule_GenericStatement { - public ContradictionRuleNot() { - super( - "STTT-CONT-0005", - "Contradicting Negation", - "A negation and its following statement can not have the same truth value", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Not.png", - ShortTruthTableOperation.NOT, - new ShortTruthTableCellType[][] { - {n, T, T}, - {n, F, F} - }); - } + public ContradictionRuleNot() { + super( + "STTT-CONT-0005", + "Contradicting Negation", + "A negation and its following statement can not have the same truth value", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Not.png", + ShortTruthTableOperation.NOT, + new ShortTruthTableCellType[][] { + {n, T, T}, + {n, F, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java index 85f29ca3f..2ab197dad 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java @@ -5,17 +5,17 @@ public class ContradictionRuleOr extends ContradictionRule_GenericStatement { - public ContradictionRuleOr() { - super( - "STTT-CONT-0006", - "Contradicting Or", - "An OR statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Or.png", - ShortTruthTableOperation.OR, - new ShortTruthTableCellType[][] { - {n, F, T}, - {T, F, n}, - {F, T, F} - }); - } + public ContradictionRuleOr() { + super( + "STTT-CONT-0006", + "Contradicting Or", + "An OR statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Or.png", + ShortTruthTableOperation.OR, + new ShortTruthTableCellType[][] { + {n, F, T}, + {T, F, n}, + {F, T, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java index 95f0f495a..87b1ba628 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java @@ -10,76 +10,79 @@ public abstract class ContradictionRule_GenericStatement extends ContradictionRule { - private final char operationSymbol; - - private final ShortTruthTableCellType[][] contradictionPatterns; - - static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; - static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; - static final ShortTruthTableCellType n = null; - - private final String NOT_RIGHT_OPERATOR_ERROR_MESSAGE = - "This cell does not contain the correct operation"; - private final String NOT_TRUE_FALSE_ERROR_MESSAGE = - "Can only check for a contradiction on a cell that is assigned a value of True or False"; - - public ContradictionRule_GenericStatement( - String ruleID, - String ruleName, - String description, - String imageName, - char operationSymbol, - ShortTruthTableCellType[][] contradictionPatterns) { - super(ruleID, ruleName, description, imageName); - this.operationSymbol = operationSymbol; - this.contradictionPatterns = contradictionPatterns; - } - - @Override - public String checkContradictionAt(Board puzzleBoard, PuzzleElement operatorPuzzleElement) { - - // cast the board to a shortTruthTableBoard - ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - - // get the cell that contradicts another cell in the board - ShortTruthTableCell cell = board.getCellFromElement(operatorPuzzleElement); - ShortTruthTableStatement statement = cell.getStatementReference(); - - if (cell.getSymbol() != this.operationSymbol) { - return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_RIGHT_OPERATOR_ERROR_MESSAGE; + private final char operationSymbol; + + private final ShortTruthTableCellType[][] contradictionPatterns; + + static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; + static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; + static final ShortTruthTableCellType n = null; + + private final String NOT_RIGHT_OPERATOR_ERROR_MESSAGE = + "This cell does not contain the correct operation"; + private final String NOT_TRUE_FALSE_ERROR_MESSAGE = + "Can only check for a contradiction on a cell that is assigned a value of True or" + + " False"; + + public ContradictionRule_GenericStatement( + String ruleID, + String ruleName, + String description, + String imageName, + char operationSymbol, + ShortTruthTableCellType[][] contradictionPatterns) { + super(ruleID, ruleName, description, imageName); + this.operationSymbol = operationSymbol; + this.contradictionPatterns = contradictionPatterns; } - // check that the initial statement is assigned - ShortTruthTableCellType cellType = cell.getType(); + @Override + public String checkContradictionAt(Board puzzleBoard, PuzzleElement operatorPuzzleElement) { - if (!cellType.isTrueOrFalse()) { - return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_TRUE_FALSE_ERROR_MESSAGE; - } + // cast the board to a shortTruthTableBoard + ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - // get the pattern for this sub-statement - ShortTruthTableCellType[] testPattern = statement.getCellTypePattern(); + // get the cell that contradicts another cell in the board + ShortTruthTableCell cell = board.getCellFromElement(operatorPuzzleElement); + ShortTruthTableStatement statement = cell.getStatementReference(); - // if the board pattern matches any contradiction pattern, it is a valid contradiction - for (ShortTruthTableCellType[] pattern : contradictionPatterns) { - boolean matches = true; - for (int i = 0; i < 3; i++) { - // ull means that part does not affect the statement - if (pattern[i] == null) { - continue; + if (cell.getSymbol() != this.operationSymbol) { + return super.getInvalidUseOfRuleMessage() + + ": " + + this.NOT_RIGHT_OPERATOR_ERROR_MESSAGE; } - // if it is not null, it must match the test pattern - if (pattern[i] != testPattern[i]) { - matches = false; - break; + + // check that the initial statement is assigned + ShortTruthTableCellType cellType = cell.getType(); + + if (!cellType.isTrueOrFalse()) { + return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_TRUE_FALSE_ERROR_MESSAGE; } - } - // if testPattern matches one of the valid contradiction patterns, the contradiction is - // correct - if (matches) { - return null; - } - } - return super.getNoContradictionMessage(); - } + // get the pattern for this sub-statement + ShortTruthTableCellType[] testPattern = statement.getCellTypePattern(); + + // if the board pattern matches any contradiction pattern, it is a valid contradiction + for (ShortTruthTableCellType[] pattern : contradictionPatterns) { + boolean matches = true; + for (int i = 0; i < 3; i++) { + // ull means that part does not affect the statement + if (pattern[i] == null) { + continue; + } + // if it is not null, it must match the test pattern + if (pattern[i] != testPattern[i]) { + matches = false; + break; + } + } + // if testPattern matches one of the valid contradiction patterns, the contradiction is + // correct + if (matches) { + return null; + } + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java index 4dd2781e0..df5ba78a3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java @@ -7,78 +7,78 @@ public class Skyscrapers extends Puzzle { - public Skyscrapers() { - super(); + public Skyscrapers() { + super(); - this.name = "Skyscrapers"; + this.name = "Skyscrapers"; - this.importer = new SkyscrapersImporter(this); - this.exporter = new SkyscrapersExporter(this); + this.importer = new SkyscrapersImporter(this); + this.exporter = new SkyscrapersExporter(this); - this.factory = new SkyscrapersCellFactory(); - } + this.factory = new SkyscrapersCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new SkyscrapersView((SkyscrapersBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new SkyscrapersView((SkyscrapersBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Skyscrapers - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Skyscrapers, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows >= 4 && rows == columns; - } + @Override + /** + * Determines if the given dimensions are valid for Skyscrapers + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Skyscrapers, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows >= 4 && rows == columns; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - SkyscrapersBoard SkyscraperBoard = (SkyscrapersBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + SkyscrapersBoard SkyscraperBoard = (SkyscrapersBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(SkyscraperBoard) == null) { - System.out.println(rule.getRuleName()); - return false; - } - } - for (PuzzleElement data : SkyscraperBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) data; - if (cell.getType() == SkyscrapersType.UNKNOWN) { - return false; - } + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(SkyscraperBoard) == null) { + System.out.println(rule.getRuleName()); + return false; + } + } + for (PuzzleElement data : SkyscraperBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) data; + if (cell.getType() == SkyscrapersType.UNKNOWN) { + return false; + } + } + return true; } - return true; - } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java index 7bc754cb4..4cd09b254 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java @@ -10,264 +10,264 @@ public class SkyscrapersBoard extends GridBoard { - private ArrayList eastClues; - // EAST clues - private ArrayList southClues; - // SOUTH clues - private ArrayList westClues; - // WEST clues - private ArrayList northClues; - // NORTH clues + private ArrayList eastClues; + // EAST clues + private ArrayList southClues; + // SOUTH clues + private ArrayList westClues; + // WEST clues + private ArrayList northClues; + // NORTH clues - private boolean viewFlag = false; - private boolean dupeFlag = false; + private boolean viewFlag = false; + private boolean dupeFlag = false; - public SkyscrapersBoard(int size) { - super(size, size); + public SkyscrapersBoard(int size) { + super(size, size); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + this.northClues = new ArrayList<>(); - for (int i = 0; i < size; i++) { - eastClues.add(null); - southClues.add(null); - westClues.add(null); - northClues.add(null); + for (int i = 0; i < size; i++) { + eastClues.add(null); + southClues.add(null); + westClues.add(null); + northClues.add(null); + } } - } - - /** - * @return eastClues a list of the eastern clues ordered from loc.y = 0 to max - */ - public ArrayList getEastClues() { - return eastClues; - } - - /** - * @return southClues a list of the southern clues ordered from loc.x = 0 to max - */ - public ArrayList getSouthClues() { - return southClues; - } - - /** - * @return westClues a list of the western clues ordered from loc.y = 0 to max - */ - public ArrayList getWestClues() { - return westClues; - } - - /** - * @return northClues a list of the northern clues ordered from loc.x = 0 to max - */ - public ArrayList getNorthClues() { - return northClues; - } - public boolean getDupeFlag() { - return dupeFlag; - } - - public boolean getViewFlag() { - return viewFlag; - } - - public void setDupeFlag(boolean newFlag) { - dupeFlag = newFlag; - } + /** + * @return eastClues a list of the eastern clues ordered from loc.y = 0 to max + */ + public ArrayList getEastClues() { + return eastClues; + } - public void setViewFlag(boolean newFlag) { - viewFlag = newFlag; - } + /** + * @return southClues a list of the southern clues ordered from loc.x = 0 to max + */ + public ArrayList getSouthClues() { + return southClues; + } - @Override - public SkyscrapersCell getCell(int x, int y) { - return (SkyscrapersCell) super.getCell(x, y); - } + /** + * @return westClues a list of the western clues ordered from loc.y = 0 to max + */ + public ArrayList getWestClues() { + return westClues; + } - public int getSize() { - return this.getWidth(); - } + /** + * @return northClues a list of the northern clues ordered from loc.x = 0 to max + */ + public ArrayList getNorthClues() { + return northClues; + } - @Override - public PuzzleElement getPuzzleElement(PuzzleElement element) { - // If the element index is -2, it is a clue and should be returned separately - if (element.getIndex() == -2) { - return element; + public boolean getDupeFlag() { + return dupeFlag; } - return super.getPuzzleElement(element); - } - /** - * Gets the cells of a certain type directly adjacent to a given cell - * - * @param cell at the center, - * @param type of cell to collect - * @return list of cells of the given type - */ - public List getAdjacent(SkyscrapersCell cell, SkyscrapersType type) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - SkyscrapersCell up = getCell(loc.x, loc.y - 1); - SkyscrapersCell right = getCell(loc.x + 1, loc.y); - SkyscrapersCell down = getCell(loc.x, loc.y + 1); - SkyscrapersCell left = getCell(loc.x - 1, loc.y); - if (up != null && (up.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(up); + public boolean getViewFlag() { + return viewFlag; } - if (right != null && (right.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(right); + + public void setDupeFlag(boolean newFlag) { + dupeFlag = newFlag; } - if (down != null && (down.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(down); + + public void setViewFlag(boolean newFlag) { + viewFlag = newFlag; } - if (left != null && (left.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(left); + + @Override + public SkyscrapersCell getCell(int x, int y) { + return (SkyscrapersCell) super.getCell(x, y); } - return adj; - } - /** - * Gets the cells of a certain type directly diagonal to a given cell - * - * @param cell at the center, - * @param type of cell to collect - * @return list of cells of the given type - */ - public List getDiagonals(SkyscrapersCell cell, SkyscrapersType type) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - SkyscrapersCell upRight = getCell(loc.x + 1, loc.y - 1); - SkyscrapersCell downRight = getCell(loc.x + 1, loc.y + 1); - SkyscrapersCell downLeft = getCell(loc.x - 1, loc.y + 1); - SkyscrapersCell upLeft = getCell(loc.x - 1, loc.y - 1); - if (upRight != null && (upRight.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(upRight); + public int getSize() { + return this.getWidth(); } - if (downLeft != null && (downLeft.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(downLeft); + + @Override + public PuzzleElement getPuzzleElement(PuzzleElement element) { + // If the element index is -2, it is a clue and should be returned separately + if (element.getIndex() == -2) { + return element; + } + return super.getPuzzleElement(element); } - if (downRight != null && (downRight.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(downRight); + + /** + * Gets the cells of a certain type directly adjacent to a given cell + * + * @param cell at the center, + * @param type of cell to collect + * @return list of cells of the given type + */ + public List getAdjacent(SkyscrapersCell cell, SkyscrapersType type) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + SkyscrapersCell up = getCell(loc.x, loc.y - 1); + SkyscrapersCell right = getCell(loc.x + 1, loc.y); + SkyscrapersCell down = getCell(loc.x, loc.y + 1); + SkyscrapersCell left = getCell(loc.x - 1, loc.y); + if (up != null && (up.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(up); + } + if (right != null && (right.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(right); + } + if (down != null && (down.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(down); + } + if (left != null && (left.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(left); + } + return adj; } - if (upLeft != null && (upLeft.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(upLeft); + + /** + * Gets the cells of a certain type directly diagonal to a given cell + * + * @param cell at the center, + * @param type of cell to collect + * @return list of cells of the given type + */ + public List getDiagonals(SkyscrapersCell cell, SkyscrapersType type) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + SkyscrapersCell upRight = getCell(loc.x + 1, loc.y - 1); + SkyscrapersCell downRight = getCell(loc.x + 1, loc.y + 1); + SkyscrapersCell downLeft = getCell(loc.x - 1, loc.y + 1); + SkyscrapersCell upLeft = getCell(loc.x - 1, loc.y - 1); + if (upRight != null && (upRight.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(upRight); + } + if (downLeft != null && (downLeft.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(downLeft); + } + if (downRight != null && (downRight.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(downRight); + } + if (upLeft != null && (upLeft.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(upLeft); + } + return dia; } - return dia; - } - /** - * Gets the cells of a certain type in a given row/column - * - * @param index: y pos of row or x pos of col, - * @param type of cell to collect, - * @param isRow true if row, false if col - * @return list of cells of the given type, ordered west to east or north to south - */ - public List getRowCol(int index, SkyscrapersType type, boolean isRow) { - List list = new ArrayList<>(); - for (int i = 0; i < dimension.height; i++) { - SkyscrapersCell cell; - if (isRow) { - cell = getCell(i, index); - } else { - cell = getCell(index, i); - } + /** + * Gets the cells of a certain type in a given row/column + * + * @param index: y pos of row or x pos of col, + * @param type of cell to collect, + * @param isRow true if row, false if col + * @return list of cells of the given type, ordered west to east or north to south + */ + public List getRowCol(int index, SkyscrapersType type, boolean isRow) { + List list = new ArrayList<>(); + for (int i = 0; i < dimension.height; i++) { + SkyscrapersCell cell; + if (isRow) { + cell = getCell(i, index); + } else { + cell = getCell(index, i); + } - if (cell.getType() == type || type == SkyscrapersType.ANY) { - list.add(cell); - } + if (cell.getType() == type || type == SkyscrapersType.ANY) { + list.add(cell); + } + } + return list; } - return list; - } - /** Prints a semblance of the board to console (helps in debugging) */ - public void printBoard() { - for (int i = 0; i < this.dimension.height; i++) { - for (SkyscrapersCell cell : this.getRowCol(i, SkyscrapersType.ANY, true)) { - if (cell.getType() == SkyscrapersType.Number) { - System.out.print(cell.getData() + " "); - } else { - System.out.print(0 + " "); + /** Prints a semblance of the board to console (helps in debugging) */ + public void printBoard() { + for (int i = 0; i < this.dimension.height; i++) { + for (SkyscrapersCell cell : this.getRowCol(i, SkyscrapersType.ANY, true)) { + if (cell.getType() == SkyscrapersType.Number) { + System.out.print(cell.getData() + " "); + } else { + System.out.print(0 + " "); + } + } + System.out.println(); } - } - System.out.println(); } - } - /** - * @param x position of cell - * @param y position of cell - * @param e Element to be placed (null if nothing selected) - * @param m MouseEvent Increases clue values if in editor mode. Currently allows for presetting - * tile values, though they will not be saved. - */ - @Override - public void setCell(int x, int y, Element e, MouseEvent m) { - SkyscrapersClue clue = this.getClue(x, y); - if (e == null) return; - if (clue != null) { - if (!e.getElementID().equals("SKYS-UNPL-0003")) { - return; - } + /** + * @param x position of cell + * @param y position of cell + * @param e Element to be placed (null if nothing selected) + * @param m MouseEvent Increases clue values if in editor mode. Currently allows for presetting + * tile values, though they will not be saved. + */ + @Override + public void setCell(int x, int y, Element e, MouseEvent m) { + SkyscrapersClue clue = this.getClue(x, y); + if (e == null) return; + if (clue != null) { + if (!e.getElementID().equals("SKYS-UNPL-0003")) { + return; + } - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.height) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } - } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.height) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.height); + } + } } else { - clue.setData(dimension.height); + super.setCell(x - 1, y - 1, e, m); } - } - } else { - super.setCell(x - 1, y - 1, e, m); } - } - /** - * @param x position of element on boardView - * @param y position of element on boardView - * @return The clue at the given position - */ - public SkyscrapersClue getClue(int x, int y) { - int viewIndex = getSize() + 1; - if (x == 0 && y > 0 && y < viewIndex) { - return westClues.get(y - 1); - } else if (x == viewIndex && y > 0 && y < viewIndex) { - return eastClues.get(y - 1); - } else if (y == 0 && x > 0 && x < viewIndex) { - return northClues.get(x - 1); - } else if (y == viewIndex && x > 0 && x < viewIndex) { - return southClues.get(x - 1); + /** + * @param x position of element on boardView + * @param y position of element on boardView + * @return The clue at the given position + */ + public SkyscrapersClue getClue(int x, int y) { + int viewIndex = getSize() + 1; + if (x == 0 && y > 0 && y < viewIndex) { + return westClues.get(y - 1); + } else if (x == viewIndex && y > 0 && y < viewIndex) { + return eastClues.get(y - 1); + } else if (y == 0 && x > 0 && x < viewIndex) { + return northClues.get(x - 1); + } else if (y == viewIndex && x > 0 && x < viewIndex) { + return southClues.get(x - 1); + } + return null; } - return null; - } - @Override - public SkyscrapersBoard copy() { - SkyscrapersBoard copy = new SkyscrapersBoard(dimension.width); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.eastClues = eastClues; - copy.southClues = southClues; - copy.westClues = westClues; - copy.northClues = northClues; + @Override + public SkyscrapersBoard copy() { + SkyscrapersBoard copy = new SkyscrapersBoard(dimension.width); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.eastClues = eastClues; + copy.southClues = southClues; + copy.westClues = westClues; + copy.northClues = northClues; - copy.dupeFlag = dupeFlag; - copy.viewFlag = viewFlag; - return copy; - } + copy.dupeFlag = dupeFlag; + copy.viewFlag = viewFlag; + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java index a315ac788..1cf9a357b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java @@ -8,59 +8,59 @@ import java.awt.event.MouseEvent; public class SkyscrapersCell extends GridCell { - private int max; + private int max; - public SkyscrapersCell(Integer value, Point location, int size) { - super(value, location); - this.max = size; - } + public SkyscrapersCell(Integer value, Point location, int size) { + super(value, location); + this.max = size; + } - public SkyscrapersType getType() { - switch (convertToSkyType(data)) { - case UNKNOWN: - return SkyscrapersType.UNKNOWN; - default: - return SkyscrapersType.Number; + public SkyscrapersType getType() { + switch (convertToSkyType(data)) { + case UNKNOWN: + return SkyscrapersType.UNKNOWN; + default: + return SkyscrapersType.Number; + } } - } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "SKYS-UNPL-0001": - this.data = 0; - break; - case "SKYS-UNPL-0002": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data <= 0 || this.data >= this.max) { - this.data = 1; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 1) { - this.data = this.data - 1; - } else { - this.data = this.max; - } - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "SKYS-UNPL-0001": + this.data = 0; + break; + case "SKYS-UNPL-0002": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data <= 0 || this.data >= this.max) { + this.data = 1; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 1) { + this.data = this.data - 1; + } else { + this.data = this.max; + } + break; + } + break; } - break; } - } - public int getMax() { - return max; - } + public int getMax() { + return max; + } - @Override - public SkyscrapersCell copy() { - SkyscrapersCell copy = new SkyscrapersCell(data, (Point) location.clone(), max); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public SkyscrapersCell copy() { + SkyscrapersCell copy = new SkyscrapersCell(data, (Point) location.clone(), max); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java index 1f10b31d3..03572b816 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java @@ -10,65 +10,67 @@ import org.w3c.dom.Node; public class SkyscrapersCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if input is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Skyscrapers Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if input is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: unknown puzzleElement puzzleElement"); + } - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - int size = skyscrapersBoard.getSize(); - NamedNodeMap attributeList = node.getAttributes(); + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + int size = skyscrapersBoard.getSize(); + NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= size || y >= size) { - throw new InvalidFileFormatException("Skyscrapers Factory: cell location out of bounds"); - } - if (value < 0 || value > size) { - throw new InvalidFileFormatException("Skyscrapers Factory: cell unknown value"); - } + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= size || y >= size) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: cell location out of bounds"); + } + if (value < 0 || value > size) { + throw new InvalidFileFormatException("Skyscrapers Factory: cell unknown value"); + } - SkyscrapersCell cell = new SkyscrapersCell(value, new Point(x, y), size); - cell.setIndex(y * size + x); + SkyscrapersCell cell = new SkyscrapersCell(value, new Point(x, y), size); + cell.setIndex(y * size + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Skyscrapers Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Skyscrapers Factory: could not find attribute(s)"); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java index dd2bc5412..7b8bf635b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java @@ -3,53 +3,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class SkyscrapersClue extends PuzzleElement { - private SkyscrapersType type; - private int clueIndex; - - public SkyscrapersClue(int value, int clueIndex, SkyscrapersType type) { - super(value); - this.index = -2; - this.clueIndex = clueIndex; // index in list - this.type = type; - this.setModifiable(false); - } - - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; + private SkyscrapersType type; + private int clueIndex; + + public SkyscrapersClue(int value, int clueIndex, SkyscrapersType type) { + super(value); + this.index = -2; + this.clueIndex = clueIndex; // index in list + this.type = type; + this.setModifiable(false); } - return sb.reverse().toString(); - } - - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; + + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; + } + return sb.reverse().toString(); + } + + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; + } + return result; + } + + public int getClueIndex() { + return clueIndex; + } + + public SkyscrapersType getType() { + return type; + } + + public void setType(SkyscrapersType type) { + this.type = type; + } + + public SkyscrapersClue copy() { + SkyscrapersClue copy = new SkyscrapersClue(data, clueIndex, type); + copy.setIndex(index); + copy.setModifiable(isModifiable); + return copy; } - return result; - } - - public int getClueIndex() { - return clueIndex; - } - - public SkyscrapersType getType() { - return type; - } - - public void setType(SkyscrapersType type) { - this.type = type; - } - - public SkyscrapersClue copy() { - SkyscrapersClue copy = new SkyscrapersClue(data, clueIndex, type); - copy.setIndex(index); - copy.setModifiable(isModifiable); - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java index bd9abc162..5a49a1476 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java @@ -5,55 +5,55 @@ public class SkyscrapersClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public SkyscrapersClueView(SkyscrapersClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public SkyscrapersClue getPuzzleElement() { - return (SkyscrapersClue) super.getPuzzleElement(); - } - - @Override - public void draw(Graphics2D graphics2D) { - drawElement(graphics2D); - if (this.isShowCasePicker() && this.isCaseRulePickable()) { - drawCase(graphics2D); - if (this.isHover()) { - drawHover(graphics2D); - } + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public SkyscrapersClueView(SkyscrapersClue clue) { + super(clue); } - } - - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - SkyscrapersClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - case CLUE_EAST: - case CLUE_SOUTH: - case CLUE_WEST: - value = String.valueOf(clue.getData()); - break; - default: - value = ""; + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public SkyscrapersClue getPuzzleElement() { + return (SkyscrapersClue) super.getPuzzleElement(); } - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + @Override + public void draw(Graphics2D graphics2D) { + drawElement(graphics2D); + if (this.isShowCasePicker() && this.isCaseRulePickable()) { + drawCase(graphics2D); + if (this.isHover()) { + drawHover(graphics2D); + } + } + } + + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + SkyscrapersClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + case CLUE_EAST: + case CLUE_SOUTH: + case CLUE_WEST: + value = String.valueOf(clue.getData()); + break; + default: + value = ""; + } + + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java index e0503382e..f78774e35 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java @@ -6,29 +6,29 @@ public class SkyscrapersController extends ElementController { - public SkyscrapersController() { - super(); - } + public SkyscrapersController() { + super(); + } - @Override - public void changeCell(MouseEvent e, PuzzleElement element) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (e.getButton() == MouseEvent.BUTTON1) { - if (cell.getData() < cell.getMax()) { - int num = cell.getData() + 1; - cell.setData(num); - } else { - cell.setData(SkyscrapersType.UNKNOWN.toValue()); - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() > 0) { - int num = cell.getData() - 1; - cell.setData(num); + @Override + public void changeCell(MouseEvent e, PuzzleElement element) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (e.getButton() == MouseEvent.BUTTON1) { + if (cell.getData() < cell.getMax()) { + int num = cell.getData() + 1; + cell.setData(num); + } else { + cell.setData(SkyscrapersType.UNKNOWN.toValue()); + } } else { - cell.setData(cell.getMax()); + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() > 0) { + int num = cell.getData() - 1; + cell.setData(num); + } else { + cell.setData(cell.getMax()); + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java index 397ab5a93..2f33017c3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java @@ -4,33 +4,34 @@ import java.awt.*; public class SkyscrapersElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = new Color(0x212121); - private static final Color BORDER_COLOR = new Color(0x424242); - private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = new Color(0x212121); + private static final Color BORDER_COLOR = new Color(0x424242); + private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); - public SkyscrapersElementView(SkyscrapersCell cell) { - super(cell); - } + public SkyscrapersElementView(SkyscrapersCell cell) { + super(cell); + } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BACKGROUND_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BORDER_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BACKGROUND_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BORDER_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - int val = cell.getData(); - if (val != 0) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(val); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + int val = cell.getData(); + if (val != 0) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(val); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java index 5d85d950e..75d2bd04f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java @@ -6,58 +6,62 @@ public class SkyscrapersExporter extends PuzzleExporter { - public SkyscrapersExporter(Skyscrapers skyscrapers) { - super(skyscrapers); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - SkyscrapersBoard board; - if (puzzle.getTree() != null) { - board = (SkyscrapersBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (SkyscrapersBoard) puzzle.getBoardView().getBoard(); + public SkyscrapersExporter(Skyscrapers skyscrapers) { + super(skyscrapers); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("size", String.valueOf(board.getWidth())); - - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - if (cell.getData() != 0) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); - - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (int i = 0; i < board.getWidth(); i++) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(board.getEastClues().get(i).getData())); - clueElement.setAttribute("index", String.valueOf(board.getWestClues().get(i).getData())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); - - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (int i = 0; i < board.getWidth(); i++) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(board.getSouthClues().get(i).getData())); - clueElement.setAttribute("index", String.valueOf(board.getNorthClues().get(i).getData())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + SkyscrapersBoard board; + if (puzzle.getTree() != null) { + board = (SkyscrapersBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (SkyscrapersBoard) puzzle.getBoardView().getBoard(); + } + + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("size", String.valueOf(board.getWidth())); - org.w3c.dom.Element flagsElement = newDocument.createElement("flags"); - flagsElement.setAttribute("dupe", String.valueOf(board.getDupeFlag())); - flagsElement.setAttribute("view", String.valueOf(board.getViewFlag())); - boardElement.appendChild(flagsElement); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + if (cell.getData() != 0) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (int i = 0; i < board.getWidth(); i++) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute( + "value", String.valueOf(board.getEastClues().get(i).getData())); + clueElement.setAttribute( + "index", String.valueOf(board.getWestClues().get(i).getData())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); + + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (int i = 0; i < board.getWidth(); i++) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute( + "value", String.valueOf(board.getSouthClues().get(i).getData())); + clueElement.setAttribute( + "index", String.valueOf(board.getNorthClues().get(i).getData())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); + + org.w3c.dom.Element flagsElement = newDocument.createElement("flags"); + flagsElement.setAttribute("dupe", String.valueOf(board.getDupeFlag())); + flagsElement.setAttribute("view", String.valueOf(board.getViewFlag())); + boardElement.appendChild(flagsElement); + + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java index 5d88e6a69..0fc7e6c39 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java @@ -8,204 +8,217 @@ import org.w3c.dom.NodeList; public class SkyscrapersImporter extends PuzzleImporter { - public SkyscrapersImporter(Skyscrapers skyscrapers) { - super(skyscrapers); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } - - @Override - public boolean acceptsTextInput() { - return false; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - // assert(rows == columns); - int size = rows; - SkyscrapersBoard skyscrapersBoard = new SkyscrapersBoard(size); - - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - SkyscrapersCell cell = - new SkyscrapersCell(SkyscrapersType.UNKNOWN.toValue(), new Point(x, y), size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - skyscrapersBoard.setCell(x, y, cell); - } + public SkyscrapersImporter(Skyscrapers skyscrapers) { + super(skyscrapers); } - for (int i = 0; i < size; i++) { - skyscrapersBoard - .getWestClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_WEST)); - skyscrapersBoard - .getEastClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_EAST)); + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; } - for (int i = 0; i < size; i++) { - skyscrapersBoard - .getNorthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_NORTH)); - skyscrapersBoard - .getSouthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_SOUTH)); + @Override + public boolean acceptsTextInput() { + return false; } - puzzle.setCurrentBoard(skyscrapersBoard); - } - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "Skyscrapers Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - - SkyscrapersBoard skyscrapersBoard = null; - - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - skyscrapersBoard = new SkyscrapersBoard(size); - } - - if (skyscrapersBoard == null) { - throw new InvalidFileFormatException("Skyscraper Importer: invalid board dimensions"); - } - - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "Skyscrapers Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - int size = skyscrapersBoard.getSize(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - SkyscrapersCell cell = - (SkyscrapersCell) - puzzle.getFactory().importCell(elementDataList.item(i), skyscrapersBoard); - Point loc = cell.getLocation(); - if (cell.getData() != 0) { - cell.setModifiable(false); - cell.setGiven(true); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + // assert(rows == columns); + int size = rows; + SkyscrapersBoard skyscrapersBoard = new SkyscrapersBoard(size); + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + SkyscrapersCell cell = + new SkyscrapersCell( + SkyscrapersType.UNKNOWN.toValue(), new Point(x, y), size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + skyscrapersBoard.setCell(x, y, cell); + } } - skyscrapersBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - if (skyscrapersBoard.getCell(x, y) == null) { - SkyscrapersCell cell = - new SkyscrapersCell(SkyscrapersType.UNKNOWN.value, new Point(x, y), size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - skyscrapersBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("Skyscraper Importer: cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { - throw new InvalidFileFormatException( - "Skyscraper Importer: side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "Skyscraper Importer: axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != skyscrapersBoard.getHeight() - || southClues.getLength() != skyscrapersBoard.getWidth()) { - throw new InvalidFileFormatException( - "Skyscraper Importer: there must be same number of clues as the dimension of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - skyscrapersBoard - .getWestClues() - .set(/*index - 1*/ i, new SkyscrapersClue(index, i, SkyscrapersType.CLUE_WEST)); - skyscrapersBoard - .getEastClues() - .set(/*index - 1*/ i, new SkyscrapersClue(value, i, SkyscrapersType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - skyscrapersBoard - .getNorthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(index, i, SkyscrapersType.CLUE_NORTH)); - skyscrapersBoard - .getSouthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(value, i, SkyscrapersType.CLUE_SOUTH)); - } - - NodeList flagList = boardElement.getElementsByTagName("flags"); - if (flagList.getLength() == 1) { - Element flags = (Element) flagList.item(0); - if (flags.hasAttribute("dupe")) { - skyscrapersBoard.setDupeFlag(Boolean.parseBoolean(flags.getAttribute("dupe"))); + + for (int i = 0; i < size; i++) { + skyscrapersBoard + .getWestClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_WEST)); + skyscrapersBoard + .getEastClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_EAST)); } - if (flags.hasAttribute("view")) { - skyscrapersBoard.setViewFlag(Boolean.parseBoolean(flags.getAttribute("view"))); + + for (int i = 0; i < size; i++) { + skyscrapersBoard + .getNorthClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_NORTH)); + skyscrapersBoard + .getSouthClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_SOUTH)); } - } - puzzle.setCurrentBoard(skyscrapersBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Skyscraper Importer: unknown value where integer expected"); + puzzle.setCurrentBoard(skyscrapersBoard); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Skyscrapers cannot accept text input"); - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Skyscrapers Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + + SkyscrapersBoard skyscrapersBoard = null; + + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + skyscrapersBoard = new SkyscrapersBoard(size); + } + + if (skyscrapersBoard == null) { + throw new InvalidFileFormatException( + "Skyscraper Importer: invalid board dimensions"); + } + + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Skyscrapers Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + int size = skyscrapersBoard.getSize(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + SkyscrapersCell cell = + (SkyscrapersCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), skyscrapersBoard); + Point loc = cell.getLocation(); + if (cell.getData() != 0) { + cell.setModifiable(false); + cell.setGiven(true); + } + skyscrapersBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + if (skyscrapersBoard.getCell(x, y) == null) { + SkyscrapersCell cell = + new SkyscrapersCell( + SkyscrapersType.UNKNOWN.value, new Point(x, y), size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + skyscrapersBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("Skyscraper Importer: cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { + throw new InvalidFileFormatException( + "Skyscraper Importer: side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "Skyscraper Importer: axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != skyscrapersBoard.getHeight() + || southClues.getLength() != skyscrapersBoard.getWidth()) { + throw new InvalidFileFormatException( + "Skyscraper Importer: there must be same number of clues as the dimension" + + " of the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + skyscrapersBoard + .getWestClues() + .set( + /*index - 1*/ i, + new SkyscrapersClue(index, i, SkyscrapersType.CLUE_WEST)); + skyscrapersBoard + .getEastClues() + .set( + /*index - 1*/ i, + new SkyscrapersClue(value, i, SkyscrapersType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + skyscrapersBoard + .getNorthClues() + .set( + /*index - 1*/ i, + new SkyscrapersClue(index, i, SkyscrapersType.CLUE_NORTH)); + skyscrapersBoard + .getSouthClues() + .set( + /*index - 1*/ i, + new SkyscrapersClue(value, i, SkyscrapersType.CLUE_SOUTH)); + } + + NodeList flagList = boardElement.getElementsByTagName("flags"); + if (flagList.getLength() == 1) { + Element flags = (Element) flagList.item(0); + if (flags.hasAttribute("dupe")) { + skyscrapersBoard.setDupeFlag(Boolean.parseBoolean(flags.getAttribute("dupe"))); + } + if (flags.hasAttribute("view")) { + skyscrapersBoard.setViewFlag(Boolean.parseBoolean(flags.getAttribute("view"))); + } + } + + puzzle.setCurrentBoard(skyscrapersBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Skyscraper Importer: unknown value where integer expected"); + } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Skyscrapers cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java index e9feeed47..4c150e8ae 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java @@ -1,40 +1,40 @@ package edu.rpi.legup.puzzle.skyscrapers; public enum SkyscrapersType { - UNKNOWN(0), - Number(1), - CLUE_NORTH(-1), - CLUE_EAST(-2), - CLUE_SOUTH(-3), - CLUE_WEST(-4), - ANY(-5); + UNKNOWN(0), + Number(1), + CLUE_NORTH(-1), + CLUE_EAST(-2), + CLUE_SOUTH(-3), + CLUE_WEST(-4), + ANY(-5); - public int value; + public int value; - SkyscrapersType(int value) { - this.value = value; - } + SkyscrapersType(int value) { + this.value = value; + } - public int toValue() { - return value; - } + public int toValue() { + return value; + } - public static SkyscrapersType convertToSkyType(int num) { - switch (num) { - case 0: - return UNKNOWN; - case -1: - return CLUE_NORTH; - case -2: - return CLUE_EAST; - case -3: - return CLUE_SOUTH; - case -4: - return CLUE_WEST; - case -5: - return ANY; - default: - return Number; + public static SkyscrapersType convertToSkyType(int num) { + switch (num) { + case 0: + return UNKNOWN; + case -1: + return CLUE_NORTH; + case -2: + return CLUE_EAST; + case -3: + return CLUE_SOUTH; + case -4: + return CLUE_WEST; + case -5: + return ANY; + default: + return Number; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java index b922c808a..edd2cdbf5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java @@ -12,188 +12,195 @@ import org.apache.logging.log4j.Logger; public class SkyscrapersView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(SkyscrapersView.class.getName()); - - private ArrayList northClues; - private ArrayList eastClues; - private ArrayList southClues; - private ArrayList westClues; - - public SkyscrapersView(SkyscrapersBoard board) { - super(new BoardController(), new SkyscrapersController(), board.getDimension()); - - this.northClues = new ArrayList<>(); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); - SkyscrapersElementView elementView = new SkyscrapersElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); - elementViews.add(elementView); - } + private static final Logger LOGGER = LogManager.getLogger(SkyscrapersView.class.getName()); + + private ArrayList northClues; + private ArrayList eastClues; + private ArrayList southClues; + private ArrayList westClues; + + public SkyscrapersView(SkyscrapersBoard board) { + super(new BoardController(), new SkyscrapersController(), board.getDimension()); + + this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); + SkyscrapersElementView elementView = new SkyscrapersElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); + elementViews.add(elementView); + } - for (int i = 0; i < gridSize.height; i++) { - SkyscrapersClueView row = new SkyscrapersClueView(board.getWestClues().get(i)); - row.setLocation(new Point(0, (i + 1) * elementSize.height)); - row.setSize(elementSize); + for (int i = 0; i < gridSize.height; i++) { + SkyscrapersClueView row = new SkyscrapersClueView(board.getWestClues().get(i)); + row.setLocation(new Point(0, (i + 1) * elementSize.height)); + row.setSize(elementSize); - SkyscrapersClueView clue = new SkyscrapersClueView(board.getEastClues().get(i)); - clue.setLocation( - new Point((gridSize.height + 1) * elementSize.height, (i + 1) * elementSize.height)); - clue.setSize(elementSize); + SkyscrapersClueView clue = new SkyscrapersClueView(board.getEastClues().get(i)); + clue.setLocation( + new Point( + (gridSize.height + 1) * elementSize.height, + (i + 1) * elementSize.height)); + clue.setSize(elementSize); - westClues.add(row); - eastClues.add(clue); - } + westClues.add(row); + eastClues.add(clue); + } - for (int i = 0; i < gridSize.width; i++) { - SkyscrapersClueView col = new SkyscrapersClueView(board.getNorthClues().get(i)); - col.setLocation(new Point((i + 1) * elementSize.width, 0)); - col.setSize(elementSize); + for (int i = 0; i < gridSize.width; i++) { + SkyscrapersClueView col = new SkyscrapersClueView(board.getNorthClues().get(i)); + col.setLocation(new Point((i + 1) * elementSize.width, 0)); + col.setSize(elementSize); - SkyscrapersClueView clue = new SkyscrapersClueView(board.getSouthClues().get(i)); - clue.setLocation( - new Point((i + 1) * elementSize.width, (gridSize.width + 1) * elementSize.width)); - clue.setSize(elementSize); + SkyscrapersClueView clue = new SkyscrapersClueView(board.getSouthClues().get(i)); + clue.setLocation( + new Point( + (i + 1) * elementSize.width, (gridSize.width + 1) * elementSize.width)); + clue.setSize(elementSize); - northClues.add(col); - southClues.add(clue); - } - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - @Override - public ElementView getElement(Point point) { - Point scaledPoint = - new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - for (SkyscrapersClueView clueView : northClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : eastClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : southClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } + northClues.add(col); + southClues.add(clue); + } } - for (SkyscrapersClueView clueView : westClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + @Override + public ElementView getElement(Point point) { + Point scaledPoint = + new Point( + (int) Math.round(point.x / getScale()), + (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + for (SkyscrapersClueView clueView : northClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : eastClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : southClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : westClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + return null; + } + + public ArrayList getNorthClues() { + return northClues; + } + + public ArrayList getWestClues() { + return westClues; + } + + @Override + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = (gridSize.width + 2) * elementSize.width; + boardViewSize.height = (gridSize.height + 2) * elementSize.height; + return boardViewSize; + } + + /** + * Sets the board associated with this view + * + * @param board board + */ + @Override + public void setBoard(Board board) { + if (this.board != board) { + this.board = board; + + if (board instanceof CaseBoard) { + setCasePickable(); + } else { + for (ElementView elementView : elementViews) { + elementView.setPuzzleElement( + board.getPuzzleElement(elementView.getPuzzleElement())); + elementView.setShowCasePicker(false); + } + for (SkyscrapersClueView clueView : northClues) { + clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); + clueView.setShowCasePicker(false); + } + for (SkyscrapersClueView clueView : westClues) { + clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); + clueView.setShowCasePicker(false); + } + } + } } - return null; - } - - public ArrayList getNorthClues() { - return northClues; - } - - public ArrayList getWestClues() { - return westClues; - } - - @Override - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = (gridSize.width + 2) * elementSize.width; - boardViewSize.height = (gridSize.height + 2) * elementSize.height; - return boardViewSize; - } - - /** - * Sets the board associated with this view - * - * @param board board - */ - @Override - public void setBoard(Board board) { - if (this.board != board) { - this.board = board; - - if (board instanceof CaseBoard) { - setCasePickable(); - } else { + + @Override + protected void setCasePickable() { + CaseBoard caseBoard = (CaseBoard) board; + Board baseBoard = caseBoard.getBaseBoard(); + for (ElementView elementView : elementViews) { - elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); - elementView.setShowCasePicker(false); + PuzzleElement puzzleElement = + baseBoard.getPuzzleElement(elementView.getPuzzleElement()); + elementView.setPuzzleElement(puzzleElement); + elementView.setShowCasePicker(true); + elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); } for (SkyscrapersClueView clueView : northClues) { - clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); - clueView.setShowCasePicker(false); + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); + clueView.setPuzzleElement(puzzleElement); + clueView.setShowCasePicker(true); + clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); } for (SkyscrapersClueView clueView : westClues) { - clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); - clueView.setShowCasePicker(false); + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); + clueView.setPuzzleElement(puzzleElement); + clueView.setShowCasePicker(true); + clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); } - } } - } - - @Override - protected void setCasePickable() { - CaseBoard caseBoard = (CaseBoard) board; - Board baseBoard = caseBoard.getBaseBoard(); - - for (ElementView elementView : elementViews) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); - elementView.setPuzzleElement(puzzleElement); - elementView.setShowCasePicker(true); - elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - for (SkyscrapersClueView clueView : northClues) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); - clueView.setPuzzleElement(puzzleElement); - clueView.setShowCasePicker(true); - clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - for (SkyscrapersClueView clueView : westClues) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); - clueView.setPuzzleElement(puzzleElement); - clueView.setShowCasePicker(true); - clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); - for (SkyscrapersClueView clueView : northClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : northClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : eastClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : eastClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : southClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : southClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : westClues) { - clueView.draw(graphics2D); + for (SkyscrapersClueView clueView : westClues) { + clueView.draw(graphics2D); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java index e66e67f1c..64c9033e6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java @@ -4,11 +4,11 @@ public class ClueTile extends NonPlaceableElement { - public ClueTile() { - super( - "SKYS-UNPL-0003", - "Clue Tile", - "Clue Updater", - "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); - } + public ClueTile() { + super( + "SKYS-UNPL-0003", + "Clue Tile", + "Clue Updater", + "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java index 6df519c96..4d6b37c9a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - public NumberTile() { - super( - "SKYS-UNPL-0002", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); - } + public NumberTile() { + super( + "SKYS-UNPL-0002", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java index ee25f38c0..2fb21193a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "SKYS-UNPL-0001", - "Unknown", - "A blank tile", - "edu/rpi/legup/images/skyscrapers/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "SKYS-UNPL-0001", + "Unknown", + "A blank tile", + "edu/rpi/legup/images/skyscrapers/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java index 0889b0c25..45bdadea3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java @@ -12,184 +12,189 @@ import javax.swing.*; public class CellForNumberCaseRule extends CaseRule { - public CellForNumberCaseRule() { - super( - "SKYS-CASE-0002", - "Cell For Number", - "A number (1-n) must appear in any given row/column", - "edu/rpi/legup/images/skyscrapers/cases/CellForNumber.png"); - } - - private Integer selectedNumber; - - @Override - public CaseBoard getCaseBoard(Board board) { - SkyscrapersBoard currentBoard = (SkyscrapersBoard) board.copy(); - currentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(currentBoard, this); - for (SkyscrapersClue data : currentBoard.getWestClues()) { - // System.out.println(data.getType()); - caseBoard.addPickableElement(data); - } - for (SkyscrapersClue data : currentBoard.getNorthClues()) { - // System.out.println(data.getType()); - caseBoard.addPickableElement(data); + public CellForNumberCaseRule() { + super( + "SKYS-CASE-0002", + "Cell For Number", + "A number (1-n) must appear in any given row/column", + "edu/rpi/legup/images/skyscrapers/cases/CellForNumber.png"); } - // selects integer before checking Command.canExecute for use in Command.getErrorString - int size = ((SkyscrapersBoard) board).getWidth(); - Object[] possibleValues = new Object[size]; - for (int i = 0; i < size; i++) { - possibleValues[i] = i + 1; - } - Object selectedValue; - do { - selectedValue = - JOptionPane.showInputDialog( - null, - "Pick the number to be added", - "Cell For Number", - JOptionPane.INFORMATION_MESSAGE, - null, - possibleValues, - possibleValues[0]); - } while (selectedValue == null); - selectedNumber = (Integer) selectedValue; - - return caseBoard; - } - - public ArrayList getCasesFor(Board board, PuzzleElement puzzleElement, Integer number) { - ArrayList cases = new ArrayList<>(); - - SkyscrapersClue clue = (SkyscrapersClue) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - - List openCells = - skyscrapersboard.getRowCol( - clue.getClueIndex(), - SkyscrapersType.UNKNOWN, - clue.getType() == SkyscrapersType.CLUE_WEST); - for (SkyscrapersCell cell : openCells) { - SkyscrapersBoard newCase = skyscrapersboard.copy(); - PuzzleElement newCell = newCase.getPuzzleElement(cell); - newCell.setData(number); - newCase.addModifiedData(newCell); - - // if flags - boolean passed = true; - if (skyscrapersboard.getDupeFlag()) { - DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); - passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; - } - if (skyscrapersboard.getViewFlag()) { - PreemptiveVisibilityContradictionRule ViewRule = - new PreemptiveVisibilityContradictionRule(); - passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; - } - if (passed) { - cases.add(newCase); - } - } - return cases; - } - - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - return getCasesFor(board, puzzleElement, selectedNumber); - } - - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - SkyscrapersBoard oldBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - if (childTransitions.size() == 0) { - return "This case rule must have at least one child."; + private Integer selectedNumber; + + @Override + public CaseBoard getCaseBoard(Board board) { + SkyscrapersBoard currentBoard = (SkyscrapersBoard) board.copy(); + currentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(currentBoard, this); + for (SkyscrapersClue data : currentBoard.getWestClues()) { + // System.out.println(data.getType()); + caseBoard.addPickableElement(data); + } + for (SkyscrapersClue data : currentBoard.getNorthClues()) { + // System.out.println(data.getType()); + caseBoard.addPickableElement(data); + } + + // selects integer before checking Command.canExecute for use in Command.getErrorString + int size = ((SkyscrapersBoard) board).getWidth(); + Object[] possibleValues = new Object[size]; + for (int i = 0; i < size; i++) { + possibleValues[i] = i + 1; + } + Object selectedValue; + do { + selectedValue = + JOptionPane.showInputDialog( + null, + "Pick the number to be added", + "Cell For Number", + JOptionPane.INFORMATION_MESSAGE, + null, + possibleValues, + possibleValues[0]); + } while (selectedValue == null); + selectedNumber = (Integer) selectedValue; + + return caseBoard; } - if (childTransitions.size() - != getCasesFor( - oldBoard, - oldBoard.getPuzzleElement(transition.getSelection()), - (Integer) - childTransitions - .get(0) - .getBoard() - .getModifiedData() - .iterator() - .next() - .getData()) - .size()) { - // System.out.println("Wrong number of cases."); - return "Wrong number of cases."; + public ArrayList getCasesFor(Board board, PuzzleElement puzzleElement, Integer number) { + ArrayList cases = new ArrayList<>(); + + SkyscrapersClue clue = (SkyscrapersClue) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + + List openCells = + skyscrapersboard.getRowCol( + clue.getClueIndex(), + SkyscrapersType.UNKNOWN, + clue.getType() == SkyscrapersType.CLUE_WEST); + for (SkyscrapersCell cell : openCells) { + SkyscrapersBoard newCase = skyscrapersboard.copy(); + PuzzleElement newCell = newCase.getPuzzleElement(cell); + newCell.setData(number); + newCase.addModifiedData(newCell); + + // if flags + boolean passed = true; + if (skyscrapersboard.getDupeFlag()) { + DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); + passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; + } + if (skyscrapersboard.getViewFlag()) { + PreemptiveVisibilityContradictionRule ViewRule = + new PreemptiveVisibilityContradictionRule(); + passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; + } + if (passed) { + cases.add(newCase); + } + } + return cases; } - for (TreeTransition newTree : childTransitions) { - SkyscrapersBoard newBoard = (SkyscrapersBoard) newTree.getBoard(); - if (newBoard.getModifiedData().size() != 1) { - // System.out.println("Only one cell should be modified."); - return "Only one cell should be modified."; - } - SkyscrapersCell newCell = (SkyscrapersCell) newBoard.getModifiedData().iterator().next(); - if (newCell.getType() != SkyscrapersType.Number) { - // System.out.println("Changed value should be a number."); - return "Changed value should be a number."; - } + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + return getCasesFor(board, puzzleElement, selectedNumber); } - return null; - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; - SkyscrapersClue clue = (SkyscrapersClue) puzzleBoard.getPuzzleElement(puzzleElement); - - // check each point in modified row/col - List data = - puzzleBoard.getRowCol( - clue.getClueIndex(), SkyscrapersType.ANY, clue.getType() == SkyscrapersType.CLUE_WEST); - for (SkyscrapersCell point : data) { - List cells = new ArrayList<>(List.of(point)); - - // if dependent on row/col - if ((puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) - && point.getType() == SkyscrapersType.UNKNOWN) { - // get perpendicular row/col intersecting this point - int index; - if (clue.getType() == SkyscrapersType.CLUE_WEST) { - index = point.getLocation().x; - } else { - index = point.getLocation().y; + + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + SkyscrapersBoard oldBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + if (childTransitions.size() == 0) { + return "This case rule must have at least one child."; } - cells.addAll( - puzzleBoard.getRowCol( - index, SkyscrapersType.ANY, clue.getType() != SkyscrapersType.CLUE_WEST)); - } - - // add all to result - for (SkyscrapersCell cell : cells) { - if (!elements.contains(board.getPuzzleElement(cell))) { - elements.add(board.getPuzzleElement(cell)); + + if (childTransitions.size() + != getCasesFor( + oldBoard, + oldBoard.getPuzzleElement(transition.getSelection()), + (Integer) + childTransitions + .get(0) + .getBoard() + .getModifiedData() + .iterator() + .next() + .getData()) + .size()) { + // System.out.println("Wrong number of cases."); + return "Wrong number of cases."; } - } + + for (TreeTransition newTree : childTransitions) { + SkyscrapersBoard newBoard = (SkyscrapersBoard) newTree.getBoard(); + if (newBoard.getModifiedData().size() != 1) { + // System.out.println("Only one cell should be modified."); + return "Only one cell should be modified."; + } + SkyscrapersCell newCell = + (SkyscrapersCell) newBoard.getModifiedData().iterator().next(); + if (newCell.getType() != SkyscrapersType.Number) { + // System.out.println("Changed value should be a number."); + return "Changed value should be a number."; + } + } + return null; } - return elements; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; + SkyscrapersClue clue = (SkyscrapersClue) puzzleBoard.getPuzzleElement(puzzleElement); + + // check each point in modified row/col + List data = + puzzleBoard.getRowCol( + clue.getClueIndex(), + SkyscrapersType.ANY, + clue.getType() == SkyscrapersType.CLUE_WEST); + for (SkyscrapersCell point : data) { + List cells = new ArrayList<>(List.of(point)); + + // if dependent on row/col + if ((puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) + && point.getType() == SkyscrapersType.UNKNOWN) { + // get perpendicular row/col intersecting this point + int index; + if (clue.getType() == SkyscrapersType.CLUE_WEST) { + index = point.getLocation().x; + } else { + index = point.getLocation().y; + } + cells.addAll( + puzzleBoard.getRowCol( + index, + SkyscrapersType.ANY, + clue.getType() != SkyscrapersType.CLUE_WEST)); + } + + // add all to result + for (SkyscrapersCell cell : cells) { + if (!elements.contains(board.getPuzzleElement(cell))) { + elements.add(board.getPuzzleElement(cell)); + } + } + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java index 194bb905b..b13a62bc6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java @@ -12,57 +12,57 @@ public class DuplicateNumberContradictionRule extends ContradictionRule { - public DuplicateNumberContradictionRule() { - super( - "SKYS-CONT-0001", - "Duplicate Number", - "Skyscrapers of same height cannot be placed in the same row or column.", - "edu/rpi/legup/images/skyscrapers/contradictions/DuplicateNumber.png"); - } + public DuplicateNumberContradictionRule() { + super( + "SKYS-CONT-0001", + "Duplicate Number", + "Skyscrapers of same height cannot be placed in the same row or column.", + "edu/rpi/legup/images/skyscrapers/contradictions/DuplicateNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - Set candidates = new HashSet(); + Set candidates = new HashSet(); - // check row - for (int i = 0; i < skyscrapersboard.getWidth(); i++) { - SkyscrapersCell c = skyscrapersboard.getCell(i, loc.y); - if (i != loc.x - && cell.getType() == SkyscrapersType.Number - && c.getType() == SkyscrapersType.Number - && c.getData() == cell.getData()) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - return null; - } - } + // check row + for (int i = 0; i < skyscrapersboard.getWidth(); i++) { + SkyscrapersCell c = skyscrapersboard.getCell(i, loc.y); + if (i != loc.x + && cell.getType() == SkyscrapersType.Number + && c.getType() == SkyscrapersType.Number + && c.getData() == cell.getData()) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + return null; + } + } - // check column - for (int i = 0; i < skyscrapersboard.getHeight(); i++) { - SkyscrapersCell c = skyscrapersboard.getCell(loc.x, i); - if (i != loc.y - && cell.getType() == SkyscrapersType.Number - && c.getType() == SkyscrapersType.Number - && c.getData() == cell.getData()) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - return null; - } - } + // check column + for (int i = 0; i < skyscrapersboard.getHeight(); i++) { + SkyscrapersCell c = skyscrapersboard.getCell(loc.x, i); + if (i != loc.y + && cell.getType() == SkyscrapersType.Number + && c.getType() == SkyscrapersType.Number + && c.getData() == cell.getData()) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + return null; + } + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java index 08929e856..742bdb253 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java @@ -12,127 +12,128 @@ public class ExceedingVisibilityContradictionRule extends ContradictionRule { - public ExceedingVisibilityContradictionRule() { - super( - "SKYS-CONT-0002", - "Exceeding Visibility", - "More skyscrapers are visible than there should be.", - "edu/rpi/legup/images/skyscrapers/contradictions/ExceedingVisibility.png"); - } + public ExceedingVisibilityContradictionRule() { + super( + "SKYS-CONT-0002", + "Exceeding Visibility", + "More skyscrapers are visible than there should be.", + "edu/rpi/legup/images/skyscrapers/contradictions/ExceedingVisibility.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - // get borders - int west = skyscrapersboard.getWestClues().get(loc.y).getData(); - int east = skyscrapersboard.getEastClues().get(loc.y).getData(); - int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); - int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); + // get borders + int west = skyscrapersboard.getWestClues().get(loc.y).getData(); + int east = skyscrapersboard.getEastClues().get(loc.y).getData(); + int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); + int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); - // check row - int max = 0; - int count = 0; - List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); - if (row.size() == skyscrapersboard.getWidth()) { - // from west border - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > west) { - return null; - } + // check row + int max = 0; + int count = 0; + List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); + if (row.size() == skyscrapersboard.getWidth()) { + // from west border + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > west) { + return null; + } - max = 0; - count = 0; - // from east border - Collections.reverse(row); - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; + max = 0; + count = 0; + // from east border + Collections.reverse(row); + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > east) { + return null; + } } - } - if (count > east) { - return null; - } - } - // check column - List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); - if (col.size() == skyscrapersboard.getHeight()) { - // from north border - max = 0; - count = 0; - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // check column + List col = + skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); + if (col.size() == skyscrapersboard.getHeight()) { + // from north border + max = 0; + count = 0; + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > north) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > north) { + return null; + } - // from south border - max = 0; - count = 0; - Collections.reverse(col); - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // from south border + max = 0; + count = 0; + Collections.reverse(col); + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > south) { + return null; + } } - } - if (count > south) { - return null; - } - } - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); - } + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } - /** - * Checks whether the Skyscraper cell has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the Skyscraper cell contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } + /** + * Checks whether the Skyscraper cell has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the Skyscraper cell contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; } - return "No instance of the contradiction " + this.ruleName + " here"; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java index d969a3415..fa7c9074e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java @@ -12,128 +12,129 @@ public class InsufficientVisibilityContradictionRule extends ContradictionRule { - public InsufficientVisibilityContradictionRule() { - super( - "SKYS-CONT-0003", - "Insufficient Visibility", - "Less skyscrapers are visible than there should be.", - "edu/rpi/legup/images/skyscrapers/contradictions/InsufficientVisibility.png"); - } + public InsufficientVisibilityContradictionRule() { + super( + "SKYS-CONT-0003", + "Insufficient Visibility", + "Less skyscrapers are visible than there should be.", + "edu/rpi/legup/images/skyscrapers/contradictions/InsufficientVisibility.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - // get borders - int west = skyscrapersboard.getWestClues().get(loc.y).getData(); - int east = skyscrapersboard.getEastClues().get(loc.y).getData(); - int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); - int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); + // get borders + int west = skyscrapersboard.getWestClues().get(loc.y).getData(); + int east = skyscrapersboard.getEastClues().get(loc.y).getData(); + int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); + int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); - // check row - int max = 0; - int count = 0; - java.util.List row = - skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); - if (row.size() == skyscrapersboard.getWidth()) { - // from west border - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < west) { - return null; - } + // check row + int max = 0; + int count = 0; + java.util.List row = + skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); + if (row.size() == skyscrapersboard.getWidth()) { + // from west border + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < west) { + return null; + } - max = 0; - count = 0; - // from east border - Collections.reverse(row); - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; + max = 0; + count = 0; + // from east border + Collections.reverse(row); + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < east) { + return null; + } } - } - if (count < east) { - return null; - } - } - // check column - List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); - if (col.size() == skyscrapersboard.getHeight()) { - // from north border - max = 0; - count = 0; - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // check column + List col = + skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); + if (col.size() == skyscrapersboard.getHeight()) { + // from north border + max = 0; + count = 0; + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < north) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < north) { + return null; + } - // from south border - max = 0; - count = 0; - Collections.reverse(col); - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // from south border + max = 0; + count = 0; + Collections.reverse(col); + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < south) { + return null; + } } - } - if (count < south) { - return null; - } - } - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); - } + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } - /** - * Checks whether the Skyscraper cell has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the Skyscraper cell contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } + /** + * Checks whether the Skyscraper cell has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the Skyscraper cell contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; } - return "No instance of the contradiction " + this.ruleName + " here"; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java index 42f6aeeeb..391448781 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java @@ -12,114 +12,118 @@ public class LastSingularCellDirectRule extends DirectRule { - public LastSingularCellDirectRule() { - super( - "SKYS-BASC-0002", - "Last Cell for Number", - "There is only one cell on this row/col for this number that does not create a duplicate contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN - && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + public LastSingularCellDirectRule() { + super( + "SKYS-BASC-0002", + "Last Cell for Number", + "There is only one cell on this row/col for this number that does not create a" + + " duplicate contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getWestClues().get(finalCell.getLocation().y), - (Integer) finalCell.getData()); - ArrayList YCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getNorthClues().get(finalCell.getLocation().x), - (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN + && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } - // System.out.println(XCandidates.size()); - // System.out.println(YCandidates.size()); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getWestClues().get(finalCell.getLocation().y), + (Integer) finalCell.getData()); + ArrayList YCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getNorthClues().get(finalCell.getLocation().x), + (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - // return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; - } + // System.out.println(XCandidates.size()); + // System.out.println(YCandidates.size()); - // helper to check if candidate list is valid - private String candidateCheck( - ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() - == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; + // return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; } - return ": This cell is not forced."; - } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + // helper to check if candidate list is valid + private String candidateCheck( + ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() + == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() + == finalCell.getData()) { + return null; + } + return ": Wrong number in the cell."; + } + return ": No case for this cell."; + } + return ": This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java index bcb5a2608..fceee0cd1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java @@ -12,88 +12,92 @@ public class LastSingularNumberDirectRule extends DirectRule { - public LastSingularNumberDirectRule() { - super( - "SKYS-BASC-0003", - "Last Number for Cell", - "There is only one number for this cell that does not create a duplicate contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; + public LastSingularNumberDirectRule() { + super( + "SKYS-BASC-0003", + "Last Number for Cell", + "There is only one number for this cell that does not create a duplicate" + + " contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; - } + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + // check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() + == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; + } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java index b80143d7a..a853c657d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java @@ -12,117 +12,121 @@ public class LastVisibleCellDirectRule extends DirectRule { - public LastVisibleCellDirectRule() { - super( - "SKYS-BASC-0001", - "Last Visible Cell", - "There is only one cell on this row/col for this number that does not create a visibility contradiction", - "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - // last cell for number based on preemptive visibility rules - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; + public LastVisibleCellDirectRule() { + super( + "SKYS-BASC-0001", + "Last Visible Cell", + "There is only one cell on this row/col for this number that does not create a" + + " visibility contradiction", + "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getWestClues().get(finalCell.getLocation().y), - (Integer) finalCell.getData()); - ArrayList YCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getNorthClues().get(finalCell.getLocation().x), - (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + // last cell for number based on preemptive visibility rules + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // System.out.println(XCandidates.size()); - // System.out.println(YCandidates.size()); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getWestClues().get(finalCell.getLocation().y), + (Integer) finalCell.getData()); + ArrayList YCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getNorthClues().get(finalCell.getLocation().x), + (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - // return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; - } + // System.out.println(XCandidates.size()); + // System.out.println(YCandidates.size()); - // helper to check if candidate list is valid - private String candidateCheck( - ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() - == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; + // return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; } - return ": This cell is not forced."; - } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + // helper to check if candidate list is valid + private String candidateCheck( + ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() + == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() + == finalCell.getData()) { + return null; + } + return ": Wrong number in the cell."; + } + return ": No case for this cell."; + } + return ": This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(modBoard.getPuzzleElements().size()); - for (PuzzleElement element : modBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - modBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - // System.out.println(modBoard.getModifiedData().isEmpty()); - if (modBoard.getModifiedData().isEmpty()) { - return null; - } else { - return modBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(modBoard.getPuzzleElements().size()); + for (PuzzleElement element : modBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + modBoard.addModifiedData(cell); + } + } + // System.out.println(modBoard.getModifiedData().isEmpty()); + if (modBoard.getModifiedData().isEmpty()) { + return null; + } else { + return modBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java index b53afaba6..da1057b56 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java @@ -12,89 +12,93 @@ public class LastVisibleNumberDirectRule extends DirectRule { - public LastVisibleNumberDirectRule() { - super( - "SKYS-BASC-0005", - "Last Visible Number", - "There is only one number for this cell that does not create a visibility contradiction", - "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - // last number for cell based upon preemptive visibility rules - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; + public LastVisibleNumberDirectRule() { + super( + "SKYS-BASC-0005", + "Last Visible Number", + "There is only one number for this cell that does not create a visibility" + + " contradiction", + "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + // last number for cell based upon preemptive visibility rules + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; - } + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + // check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() + == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; + } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java index 79a478f9b..bbc202e72 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java @@ -12,92 +12,95 @@ public class NEdgeDirectRule extends DirectRule { - public NEdgeDirectRule() { - super( - "SKYS-BASC-0004", - "N Edge", - "If the maximum number appears on an edge, the row or column's numbers appear in ascending order, starting at that edge.", - "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN - && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + public NEdgeDirectRule() { + super( + "SKYS-BASC-0004", + "N Edge", + "If the maximum number appears on an edge, the row or column's numbers appear in" + + " ascending order, starting at that edge.", + "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); } - SkyscrapersBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); - Point loc = finalCell.getLocation(); - int max = initialBoard.getHeight(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN + && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } - if (initialBoard.getWestClues().get(loc.y).getData() == max - && finalCell.getData() == loc.x + 1) { - return null; - } - if (initialBoard.getEastClues().get(loc.y).getData() == max - && finalCell.getData() == max - loc.x) { - return null; - } - if (initialBoard.getNorthClues().get(loc.x).getData() == max - && finalCell.getData() == loc.y + 1) { - return null; - } - if (initialBoard.getSouthClues().get(loc.x).getData() == max - && finalCell.getData() == max - loc.y) { - return null; - } + SkyscrapersBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); + Point loc = finalCell.getLocation(); + int max = initialBoard.getHeight(); - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; - } + if (initialBoard.getWestClues().get(loc.y).getData() == max + && finalCell.getData() == loc.x + 1) { + return null; + } + if (initialBoard.getEastClues().get(loc.y).getData() == max + && finalCell.getData() == max - loc.x) { + return null; + } + if (initialBoard.getNorthClues().get(loc.x).getData() == max + && finalCell.getData() == loc.y + 1) { + return null; + } + if (initialBoard.getSouthClues().get(loc.x).getData() == max + && finalCell.getData() == max - loc.y) { + return null; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java index 9b6f67ca0..145dd6ee2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java @@ -16,158 +16,166 @@ public class NumberForCellCaseRule extends CaseRule { - public NumberForCellCaseRule() { - super( - "SKYS-CASE-0001", - "Number For Cell", - "A blank cell must have height of 1 to n.", - "edu/rpi/legup/images/skyscrapers/cases/NumberForCell.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) board.copy(); - lightUpBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((SkyscrapersCell) data).getType() == SkyscrapersType.UNKNOWN) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); - - Set candidates = new HashSet(); - for (int i = 1; i <= skyscrapersboard.getWidth(); i++) { - Board newCase = board.copy(); - PuzzleElement newCell = newCase.getPuzzleElement(puzzleElement); - newCell.setData(i); - newCase.addModifiedData(newCell); - - // if flags - boolean passed = true; - if (skyscrapersboard.getDupeFlag()) { - DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); - passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; - } - if (skyscrapersboard.getViewFlag()) { - PreemptiveVisibilityContradictionRule ViewRule = - new PreemptiveVisibilityContradictionRule(); - passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; - } - // how should unresolved be handled? should it be? - if (passed) { - cases.add(newCase); - } + public NumberForCellCaseRule() { + super( + "SKYS-CASE-0001", + "Number For Cell", + "A blank cell must have height of 1 to n.", + "edu/rpi/legup/images/skyscrapers/cases/NumberForCell.png"); } - return cases; - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "This case rule must have at least one child."; - } else { - if (childTransitions.size() - != getCases( - transition.getBoard(), - childTransitions.get(0).getBoard().getModifiedData().iterator().next()) - .size()) { - return "Wrong number of children."; - } + @Override + public CaseBoard getCaseBoard(Board board) { + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) board.copy(); + lightUpBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((SkyscrapersCell) data).getType() == SkyscrapersType.UNKNOWN) { + caseBoard.addPickableElement(data); + } + } + return caseBoard; } - // TreeTransition case1 = childTransitions.get(0); - // TreeTransition case2 = childTransitions.get(1); - TreeTransition case1 = childTransitions.get(0); - SkyscrapersCell mod1 = (SkyscrapersCell) case1.getBoard().getModifiedData().iterator().next(); - for (int i = 0; i < childTransitions.size(); i++) { - TreeTransition case2 = childTransitions.get(i); - if (case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } - SkyscrapersCell mod2 = (SkyscrapersCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } - if (!(mod2.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must assign a number."; - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); + + Set candidates = new HashSet(); + for (int i = 1; i <= skyscrapersboard.getWidth(); i++) { + Board newCase = board.copy(); + PuzzleElement newCell = newCase.getPuzzleElement(puzzleElement); + newCell.setData(i); + newCase.addModifiedData(newCell); + + // if flags + boolean passed = true; + if (skyscrapersboard.getDupeFlag()) { + DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); + passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; + } + if (skyscrapersboard.getViewFlag()) { + PreemptiveVisibilityContradictionRule ViewRule = + new PreemptiveVisibilityContradictionRule(); + passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; + } + // how should unresolved be handled? should it be? + if (passed) { + cases.add(newCase); + } + } + + return cases; } - // System.out.println("no contradiction"); - return null; - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; - SkyscrapersCell point = (SkyscrapersCell) puzzleBoard.getPuzzleElement(puzzleElement); - - List cells = new ArrayList<>(List.of(point)); - - // if dependent on row/col - if (puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) { - // add all cells in row/col intersecting given point - cells.addAll(puzzleBoard.getRowCol(point.getLocation().x, SkyscrapersType.ANY, false)); - cells.addAll(puzzleBoard.getRowCol(point.getLocation().y, SkyscrapersType.ANY, true)); + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "This case rule must have at least one child."; + } else { + if (childTransitions.size() + != getCases( + transition.getBoard(), + childTransitions + .get(0) + .getBoard() + .getModifiedData() + .iterator() + .next()) + .size()) { + return "Wrong number of children."; + } + } + + // TreeTransition case1 = childTransitions.get(0); + // TreeTransition case2 = childTransitions.get(1); + TreeTransition case1 = childTransitions.get(0); + SkyscrapersCell mod1 = + (SkyscrapersCell) case1.getBoard().getModifiedData().iterator().next(); + for (int i = 0; i < childTransitions.size(); i++) { + TreeTransition case2 = childTransitions.get(i); + if (case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } + SkyscrapersCell mod2 = + (SkyscrapersCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } + if (!(mod2.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must assign a number."; + } + } + // System.out.println("no contradiction"); + return null; } - for (SkyscrapersCell cell : cells) { - if (!elements.contains(board.getPuzzleElement(cell))) { - elements.add(board.getPuzzleElement(cell)); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); } - return elements; - } + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; + SkyscrapersCell point = (SkyscrapersCell) puzzleBoard.getPuzzleElement(puzzleElement); + + List cells = new ArrayList<>(List.of(point)); + + // if dependent on row/col + if (puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) { + // add all cells in row/col intersecting given point + cells.addAll(puzzleBoard.getRowCol(point.getLocation().x, SkyscrapersType.ANY, false)); + cells.addAll(puzzleBoard.getRowCol(point.getLocation().y, SkyscrapersType.ANY, true)); + } + + for (SkyscrapersCell cell : cells) { + if (!elements.contains(board.getPuzzleElement(cell))) { + elements.add(board.getPuzzleElement(cell)); + } + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java index 2d3095fdc..dc274eb15 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java @@ -13,184 +13,191 @@ public class PreemptiveVisibilityContradictionRule extends ContradictionRule { - public PreemptiveVisibilityContradictionRule() { - super( - "SKYS-CONT-0006", - "Preemptive Visibility", - "Visibility constraints are not met given an incomplete row/col", - "edu/rpi/legup/images/skyscrapers/contradictions/PreemptiveVisibility.png"); - } - - /** - * Checks whether there is an instance of a visibility contradiction in every possible row/col - * based on the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the all possible rows/cols contain a contradiction at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); - - // Initialize instances of necessary contradiction and case rules - InsufficientVisibilityContradictionRule tooFew = new InsufficientVisibilityContradictionRule(); - ExceedingVisibilityContradictionRule tooMany = new ExceedingVisibilityContradictionRule(); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - - // Initialize skyscraperBoard queues for rows and cols - Queue rowQ = new LinkedList<>(); - rowQ.add(skyscrapersBoard); - Queue colQ = new LinkedList<>(); - colQ.add(skyscrapersBoard); - - // find all cases for the corresponding row and column for each possible skyscraper height - - // Add every possible case for all heights for each corresponding row and column - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - int num = i + 1; - - // check row west clue - List rows; - - int size = rowQ.size(); - for (int j = 0; j < size; j++) { - SkyscrapersBoard temp = rowQ.poll(); // get row from the top of the stack - - // don't do anything if already in row - boolean exists = false; - for (SkyscrapersCell c : temp.getRowCol(loc.y, SkyscrapersType.Number, true)) { - if (c.getData() == num) { - exists = true; - break; - } - } + public PreemptiveVisibilityContradictionRule() { + super( + "SKYS-CONT-0006", + "Preemptive Visibility", + "Visibility constraints are not met given an incomplete row/col", + "edu/rpi/legup/images/skyscrapers/contradictions/PreemptiveVisibility.png"); + } - if (exists) { - rowQ.add(temp); - } else { - // set flags - boolean dupeTemp = temp.getDupeFlag(); - boolean viewTemp = temp.getViewFlag(); - temp.setDupeFlag(false); - temp.setViewFlag(false); - - // get all cases for corresponding row based on west clue - rows = caseRule.getCasesFor(temp, skyscrapersBoard.getWestClues().get(loc.y), num); - - // reset flags - temp.setDupeFlag(dupeTemp); - temp.setViewFlag(viewTemp); - - // add all row cases to row queue - for (Board k : rows) { - rowQ.add((SkyscrapersBoard) k); - } - } - } - - // check col north clue - List cols; - - size = colQ.size(); - for (int j = 0; j < size; j++) { - SkyscrapersBoard temp = colQ.poll(); // get row from the top of the stack - - // don't do anything if already in col - boolean exists = false; - for (SkyscrapersCell c : temp.getRowCol(loc.x, SkyscrapersType.Number, false)) { - if (c.getData() == num) { - exists = true; - break; - } + /** + * Checks whether there is an instance of a visibility contradiction in every possible row/col + * based on the specific puzzleElement index using this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the all possible rows/cols contain a contradiction at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); + + // Initialize instances of necessary contradiction and case rules + InsufficientVisibilityContradictionRule tooFew = + new InsufficientVisibilityContradictionRule(); + ExceedingVisibilityContradictionRule tooMany = new ExceedingVisibilityContradictionRule(); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + + // Initialize skyscraperBoard queues for rows and cols + Queue rowQ = new LinkedList<>(); + rowQ.add(skyscrapersBoard); + Queue colQ = new LinkedList<>(); + colQ.add(skyscrapersBoard); + + // find all cases for the corresponding row and column for each possible skyscraper height + + // Add every possible case for all heights for each corresponding row and column + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + int num = i + 1; + + // check row west clue + List rows; + + int size = rowQ.size(); + for (int j = 0; j < size; j++) { + SkyscrapersBoard temp = rowQ.poll(); // get row from the top of the stack + + // don't do anything if already in row + boolean exists = false; + for (SkyscrapersCell c : temp.getRowCol(loc.y, SkyscrapersType.Number, true)) { + if (c.getData() == num) { + exists = true; + break; + } + } + + if (exists) { + rowQ.add(temp); + } else { + // set flags + boolean dupeTemp = temp.getDupeFlag(); + boolean viewTemp = temp.getViewFlag(); + temp.setDupeFlag(false); + temp.setViewFlag(false); + + // get all cases for corresponding row based on west clue + rows = + caseRule.getCasesFor( + temp, skyscrapersBoard.getWestClues().get(loc.y), num); + + // reset flags + temp.setDupeFlag(dupeTemp); + temp.setViewFlag(viewTemp); + + // add all row cases to row queue + for (Board k : rows) { + rowQ.add((SkyscrapersBoard) k); + } + } + } + + // check col north clue + List cols; + + size = colQ.size(); + for (int j = 0; j < size; j++) { + SkyscrapersBoard temp = colQ.poll(); // get row from the top of the stack + + // don't do anything if already in col + boolean exists = false; + for (SkyscrapersCell c : temp.getRowCol(loc.x, SkyscrapersType.Number, false)) { + if (c.getData() == num) { + exists = true; + break; + } + } + + if (exists) { + colQ.add(temp); + } else { + // set flags + boolean dupeTemp = temp.getDupeFlag(); + boolean viewTemp = temp.getViewFlag(); + temp.setDupeFlag(false); + temp.setViewFlag(false); + + // get all cases for corresponding col based on north clue + cols = + caseRule.getCasesFor( + temp, skyscrapersBoard.getNorthClues().get(loc.x), num); + + // reset flags + temp.setDupeFlag(dupeTemp); + temp.setViewFlag(viewTemp); + + // add all row cases to row queue + for (Board k : cols) { + colQ.add((SkyscrapersBoard) k); + } + } + } } - if (exists) { - colQ.add(temp); - } else { - // set flags - boolean dupeTemp = temp.getDupeFlag(); - boolean viewTemp = temp.getViewFlag(); - temp.setDupeFlag(false); - temp.setViewFlag(false); - - // get all cases for corresponding col based on north clue - cols = caseRule.getCasesFor(temp, skyscrapersBoard.getNorthClues().get(loc.x), num); - - // reset flags - temp.setDupeFlag(dupeTemp); - temp.setViewFlag(viewTemp); - - // add all row cases to row queue - for (Board k : cols) { - colQ.add((SkyscrapersBoard) k); - } + String rowTooFew; + String rowTooMany; + boolean rowContradiction = true; + // check if each case board has a contradiction + while (rowQ.size() > 0) { + SkyscrapersBoard fullRow = rowQ.poll(); + + // checks if there is a contradiction given the row based on the west clue + rowTooFew = + tooFew.checkContradictionAt( + fullRow, cell); // is cell the correct puzzle element to check? + rowTooMany = tooMany.checkContradictionAt(fullRow, cell); + + // boolean that checks if there is a contradiction within all rows + rowContradiction = + rowContradiction + && (rowTooFew == null + || rowTooMany + == null); // !null means there isn't a contradiction, so + // there must be a valid + // permutation of the array } - } - } - String rowTooFew; - String rowTooMany; - boolean rowContradiction = true; - // check if each case board has a contradiction - while (rowQ.size() > 0) { - SkyscrapersBoard fullRow = rowQ.poll(); - - // checks if there is a contradiction given the row based on the west clue - rowTooFew = - tooFew.checkContradictionAt( - fullRow, cell); // is cell the correct puzzle element to check? - rowTooMany = tooMany.checkContradictionAt(fullRow, cell); - - // boolean that checks if there is a contradiction within all rows - rowContradiction = - rowContradiction - && (rowTooFew == null - || rowTooMany - == null); // !null means there isn't a contradiction, so there must be a valid - // permutation of the array - } + String colTooFew; + String colTooMany; + boolean colContradiction = true; + while (colQ.size() > 0) { + SkyscrapersBoard fullCol = colQ.poll(); - String colTooFew; - String colTooMany; - boolean colContradiction = true; - while (colQ.size() > 0) { - SkyscrapersBoard fullCol = colQ.poll(); + // checks if there is a contradiction given the col baesd on the north clue + colTooFew = tooFew.checkContradictionAt(fullCol, cell); + colTooMany = tooMany.checkContradictionAt(fullCol, cell); - // checks if there is a contradiction given the col baesd on the north clue - colTooFew = tooFew.checkContradictionAt(fullCol, cell); - colTooMany = tooMany.checkContradictionAt(fullCol, cell); + // boolean that checks if there is a contradiction within all the cols + colContradiction = colContradiction && (colTooFew == null || colTooMany == null); + } - // boolean that checks if there is a contradiction within all the cols - colContradiction = colContradiction && (colTooFew == null || colTooMany == null); + // if every possible permutation results in contradictions return null, else no + // contradiction + if (rowContradiction || colContradiction) { + return null; + } + return super.getNoContradictionMessage(); } - // if every possible permutation results in contradictions return null, else no contradiction - if (rowContradiction || colContradiction) { - return null; - } - return super.getNoContradictionMessage(); - } - - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; } - return "No instance of the contradiction " + this.ruleName + " here"; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java index a34fe0730..d4a3d0486 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java @@ -8,33 +8,33 @@ public class UnresolvedCellContradictionRule extends ContradictionRule { - public UnresolvedCellContradictionRule() { - super( - "SKYS-CONT-0004", - "Unresolved Cell", - "Elimination leaves no possible number for a cell.", - "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedCell.png"); - } + public UnresolvedCellContradictionRule() { + super( + "SKYS-CONT-0004", + "Unresolved Cell", + "Elimination leaves no possible number for a cell.", + "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedCell.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList cases = caseRule.getCases(board, puzzleElement); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList cases = caseRule.getCases(board, puzzleElement); - if (cases.size() == 0) { - return null; - } + if (cases.size() == 0) { + return null; + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java index b08fa67f3..fed429988 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java @@ -10,89 +10,92 @@ public class UnresolvedNumberContradictionRule extends ContradictionRule { - public UnresolvedNumberContradictionRule() { - super( - "SKYS-CONT-0005", - "Unresolved Number", - "No possible cell for a number without a duplicate contradiction.", - // specify a number? defaulting to every number for now. expand to more than duplicate? - "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedNumber.png"); - } + public UnresolvedNumberContradictionRule() { + super( + "SKYS-CONT-0005", + "Unresolved Number", + "No possible cell for a number without a duplicate contradiction.", + // specify a number? defaulting to every number for now. expand to more than + // duplicate? + "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - int num = i + 1; - // check row - // isn't already present - boolean exists = false; - for (SkyscrapersCell presentCell : - skyscrapersBoard.getRowCol(loc.y, SkyscrapersType.Number, true)) { - if (presentCell.getData() == num) { - exists = true; - break; - } - } - if (!exists) { - // and no possible cases - if (caseRule.getCasesFor(board, skyscrapersBoard.getWestClues().get(loc.y), num).size() - == 0) { - return null; - } - } + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + int num = i + 1; + // check row + // isn't already present + boolean exists = false; + for (SkyscrapersCell presentCell : + skyscrapersBoard.getRowCol(loc.y, SkyscrapersType.Number, true)) { + if (presentCell.getData() == num) { + exists = true; + break; + } + } + if (!exists) { + // and no possible cases + if (caseRule.getCasesFor(board, skyscrapersBoard.getWestClues().get(loc.y), num) + .size() + == 0) { + return null; + } + } - // check col - // same process as for row - exists = false; - for (SkyscrapersCell presentCell : - skyscrapersBoard.getRowCol(loc.x, SkyscrapersType.Number, false)) { - if (presentCell.getData() == num) { - exists = true; - break; - } - } - if (!exists) { - if (caseRule.getCasesFor(board, skyscrapersBoard.getNorthClues().get(loc.x), num).size() - == 0) { - return null; + // check col + // same process as for row + exists = false; + for (SkyscrapersCell presentCell : + skyscrapersBoard.getRowCol(loc.x, SkyscrapersType.Number, false)) { + if (presentCell.getData() == num) { + exists = true; + break; + } + } + if (!exists) { + if (caseRule.getCasesFor(board, skyscrapersBoard.getNorthClues().get(loc.x), num) + .size() + == 0) { + return null; + } + } } - } - } - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); - } + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return null; - } + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return null; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; } - return "No instance of the contradiction " + this.ruleName + " here"; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java index e0583a13b..a7cd9ac12 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.sudoku; public enum GroupType { - REGION, - ROW, - COLUMN + REGION, + ROW, + COLUMN } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java index e81bc909e..0b6971235 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java @@ -9,76 +9,76 @@ public class PossibleNumberCaseBoard extends CaseBoard { - private SudokuCell cell; - private Set pickableRegions; - private Set pickableRows; - private Set pickableCols; + private SudokuCell cell; + private Set pickableRegions; + private Set pickableRows; + private Set pickableCols; - public PossibleNumberCaseBoard( - SudokuBoard baseBoard, PossibleNumberCaseRule caseRule, SudokuCell cell) { - super(baseBoard, caseRule); - this.cell = cell; - this.pickableRegions = new HashSet<>(); - this.pickableRows = new HashSet<>(); - this.pickableCols = new HashSet<>(); - } - - @Override - public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { - if (e == null) { - return false; + public PossibleNumberCaseBoard( + SudokuBoard baseBoard, PossibleNumberCaseRule caseRule, SudokuCell cell) { + super(baseBoard, caseRule); + this.cell = cell; + this.pickableRegions = new HashSet<>(); + this.pickableRows = new HashSet<>(); + this.pickableCols = new HashSet<>(); } - SudokuCell sudokuCell = (SudokuCell) puzzleElement; - if (e.isShiftDown()) { - for (int r : pickableRows) { - if (r == sudokuCell.getLocation().y) { - return true; - } - } - } else { - if (e.isControlDown()) { - for (int c : pickableCols) { - if (c == sudokuCell.getLocation().x) { - return true; - } + @Override + public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { + if (e == null) { + return false; } - } else { - for (int r : pickableRegions) { - if (r == sudokuCell.getGroupIndex()) { - return true; - } + + SudokuCell sudokuCell = (SudokuCell) puzzleElement; + if (e.isShiftDown()) { + for (int r : pickableRows) { + if (r == sudokuCell.getLocation().y) { + return true; + } + } + } else { + if (e.isControlDown()) { + for (int c : pickableCols) { + if (c == sudokuCell.getLocation().x) { + return true; + } + } + } else { + for (int r : pickableRegions) { + if (r == sudokuCell.getGroupIndex()) { + return true; + } + } + } } - } + return false; } - return false; - } - public void addPickableRegion(int region) { - this.pickableRegions.add(region); - } + public void addPickableRegion(int region) { + this.pickableRegions.add(region); + } - public void addPickableRow(int row) { - this.pickableRows.add(row); - } + public void addPickableRow(int row) { + this.pickableRows.add(row); + } - public void addPickableCol(int col) { - this.pickableCols.add(col); - } + public void addPickableCol(int col) { + this.pickableCols.add(col); + } - public SudokuCell getCell() { - return cell; - } + public SudokuCell getCell() { + return cell; + } - public Set getPickableRegions() { - return pickableRegions; - } + public Set getPickableRegions() { + return pickableRegions; + } - public Set getPickableRows() { - return pickableRows; - } + public Set getPickableRows() { + return pickableRows; + } - public Set getPickableCols() { - return pickableCols; - } + public Set getPickableCols() { + return pickableCols; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java index 30aa78aac..877c92665 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java @@ -7,102 +7,102 @@ import edu.rpi.legup.ui.boardview.BoardView; public class Sudoku extends Puzzle { - private SudokuView boardView; - - /** Sudoku Constructor */ - public Sudoku() { - super(); - - this.name = "Sudoku"; - - this.importer = new SudokuImporter(this); - this.exporter = new SudokuExporter(this); - - this.factory = new SudokuCellFactory(); - } - - public BoardView getBoardView() { - return boardView; - } - - /** Initializes the game board */ - @Override - public void initializeView() { - boardView = new SudokuView((SudokuBoard) currentBoard); - } - - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } - - @Override - /** - * Determines if the given dimensions are valid for Sudoku - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Sudoku, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // The number of rows and columns must be greater than 1 - if (rows <= 1 || columns <= 1) { - return false; + private SudokuView boardView; + + /** Sudoku Constructor */ + public Sudoku() { + super(); + + this.name = "Sudoku"; + + this.importer = new SudokuImporter(this); + this.exporter = new SudokuExporter(this); + + this.factory = new SudokuCellFactory(); } - // The number of rows and columns must be equal - if (rows != columns) { - return false; + public BoardView getBoardView() { + return boardView; } - // For Sudoku, the number of rows and columns must be a perfect square - // Note: we don't need to check the columns since by this point, we have verified that the - // number of rows - // equals the number of columns - double sqrtRows = Math.sqrt(rows); - if (sqrtRows - Math.floor(sqrtRows) != 0) { - return false; + /** Initializes the game board */ + @Override + public void initializeView() { + boardView = new SudokuView((SudokuBoard) currentBoard); } - return true; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(sudokuBoard) == null) { - return false; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; } - for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { - SudokuCell cell = (SudokuCell) puzzleElement; - if (cell.getData() == 0) { - return false; - } + @Override + /** + * Determines if the given dimensions are valid for Sudoku + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Sudoku, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // The number of rows and columns must be greater than 1 + if (rows <= 1 || columns <= 1) { + return false; + } + + // The number of rows and columns must be equal + if (rows != columns) { + return false; + } + + // For Sudoku, the number of rows and columns must be a perfect square + // Note: we don't need to check the columns since by this point, we have verified that the + // number of rows + // equals the number of columns + double sqrtRows = Math.sqrt(rows); + if (sqrtRows - Math.floor(sqrtRows) != 0) { + return false; + } + + return true; } - return true; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(sudokuBoard) == null) { + return false; + } + } + + for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { + SudokuCell cell = (SudokuCell) puzzleElement; + if (cell.getData() == 0) { + return false; + } + } + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java index 095dbf64c..46e6020bb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java @@ -7,166 +7,166 @@ import java.util.Set; public class SudokuBoard extends GridBoard { - private int size; - private int groupSize; - - /** - * SudokuBoard Constructor - create a new Sudoku board - * - * @param size size of one side of the sudoku board, must be an integer square root - */ - public SudokuBoard(int size) { - super(size, size); - this.size = size; - this.groupSize = (int) Math.sqrt(dimension.width); - } - - /** - * Gets a SudokuCell from the board - * - * @param x x location of the cell - * @param y y location of the cell - * @return SudokuCell at location (x, y) - */ - @Override - public SudokuCell getCell(int x, int y) { - return (SudokuCell) super.getCell(x, y); - } - - /** - * Gets the SudokuCell in the specified group index at the x and y location given The group index - * must be by less than the width (or height) of the board and the x and y location is relative to - * the group. This means the x and y values must be less the square root of the width (or height) - * of the board. - * - * @param groupIndex group index of the cell - * @param x x location relative to the group - * @param y y location relative to the group - * @return cell in the specified group index at the given x and y location - */ - public SudokuCell getCell(int groupIndex, int x, int y) { - return getCell( - x + (groupIndex % groupSize) * groupSize, y + (groupIndex / groupSize) * groupSize); - } - - /** - * Gets the size of the sudoku board Standard board is 9x9 - * - * @return size of the board - */ - public int getSize() { - return size; - } - - /** - * Gets the minor group size of the sudoku board Standard board is 3x3x3x3 - * - * @return minor group size - */ - public int getGroupSize() { - return groupSize; - } - - /** - * Gets all the cells in the specified row - * - * @param rowNum row index - * @return list of all the cells in the row - */ - public Set getRow(int rowNum) { - Set row = new HashSet<>(); - for (int i = 0; i < size; i++) { - row.add(getCell(i, rowNum)); + private int size; + private int groupSize; + + /** + * SudokuBoard Constructor - create a new Sudoku board + * + * @param size size of one side of the sudoku board, must be an integer square root + */ + public SudokuBoard(int size) { + super(size, size); + this.size = size; + this.groupSize = (int) Math.sqrt(dimension.width); } - return row; - } - - /** - * Gets all the cells in the specified column - * - * @param colNum column index - * @return list of all the cells in the column - */ - public Set getCol(int colNum) { - Set col = new HashSet<>(); - for (int i = 0; i < size; i++) { - col.add(getCell(colNum, i)); + + /** + * Gets a SudokuCell from the board + * + * @param x x location of the cell + * @param y y location of the cell + * @return SudokuCell at location (x, y) + */ + @Override + public SudokuCell getCell(int x, int y) { + return (SudokuCell) super.getCell(x, y); } - return col; - } - - /** - * Gets all the cells in the specified region - * - * @param regionNum region index - * @return list of all the cells in the region - */ - public Set getRegion(int regionNum) { - Set region = new HashSet<>(); - for (int i = 0; i < size; i++) { - region.add(getCell(regionNum, i % groupSize, i / groupSize)); + + /** + * Gets the SudokuCell in the specified group index at the x and y location given The group + * index must be by less than the width (or height) of the board and the x and y location is + * relative to the group. This means the x and y values must be less the square root of the + * width (or height) of the board. + * + * @param groupIndex group index of the cell + * @param x x location relative to the group + * @param y y location relative to the group + * @return cell in the specified group index at the given x and y location + */ + public SudokuCell getCell(int groupIndex, int x, int y) { + return getCell( + x + (groupIndex % groupSize) * groupSize, y + (groupIndex / groupSize) * groupSize); } - return region; - } - - public Set getAffected(SudokuCell cell) { - Point loc = cell.getLocation(); - cell = getCell(loc.x, loc.y); - Set affected = new HashSet<>(); - affected.addAll(getRegion(cell.getGroupIndex())); - affected.addAll(getRow(loc.y)); - affected.addAll(getCol(loc.x)); - - return affected; - } - - public Set getPossibleValues(SudokuCell cell) { - Point loc = cell.getLocation(); - cell = getCell(loc.x, loc.y); - Set possible = getAffected(cell); - - Set possibleValues = new HashSet<>(); - for (int i = 0; i < size; i++) { - possibleValues.add(i); + + /** + * Gets the size of the sudoku board Standard board is 9x9 + * + * @return size of the board + */ + public int getSize() { + return size; } - for (SudokuCell c : possible) { - possibleValues.remove(c.getData()); + + /** + * Gets the minor group size of the sudoku board Standard board is 3x3x3x3 + * + * @return minor group size + */ + public int getGroupSize() { + return groupSize; } - return possibleValues; - } - - /** - * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent - * puzzle element with the new data. - * - * @param puzzleElement equivalent puzzle element with the new data. - */ - @Override - public void notifyChange(PuzzleElement puzzleElement) { - super.notifyChange(puzzleElement); - Set affected = getAffected((SudokuCell) puzzleElement); - for (SudokuCell c : affected) { - c.setAnnotations(getPossibleValues(c)); + /** + * Gets all the cells in the specified row + * + * @param rowNum row index + * @return list of all the cells in the row + */ + public Set getRow(int rowNum) { + Set row = new HashSet<>(); + for (int i = 0; i < size; i++) { + row.add(getCell(i, rowNum)); + } + return row; } - } - - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - @Override - public SudokuBoard copy() { - SudokuBoard copy = new SudokuBoard(size); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + + /** + * Gets all the cells in the specified column + * + * @param colNum column index + * @return list of all the cells in the column + */ + public Set getCol(int colNum) { + Set col = new HashSet<>(); + for (int i = 0; i < size; i++) { + col.add(getCell(colNum, i)); + } + return col; } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + /** + * Gets all the cells in the specified region + * + * @param regionNum region index + * @return list of all the cells in the region + */ + public Set getRegion(int regionNum) { + Set region = new HashSet<>(); + for (int i = 0; i < size; i++) { + region.add(getCell(regionNum, i % groupSize, i / groupSize)); + } + return region; + } + + public Set getAffected(SudokuCell cell) { + Point loc = cell.getLocation(); + cell = getCell(loc.x, loc.y); + Set affected = new HashSet<>(); + affected.addAll(getRegion(cell.getGroupIndex())); + affected.addAll(getRow(loc.y)); + affected.addAll(getCol(loc.x)); + + return affected; + } + + public Set getPossibleValues(SudokuCell cell) { + Point loc = cell.getLocation(); + cell = getCell(loc.x, loc.y); + Set possible = getAffected(cell); + + Set possibleValues = new HashSet<>(); + for (int i = 0; i < size; i++) { + possibleValues.add(i); + } + for (SudokuCell c : possible) { + possibleValues.remove(c.getData()); + } + + return possibleValues; + } + + /** + * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent + * puzzle element with the new data. + * + * @param puzzleElement equivalent puzzle element with the new data. + */ + @Override + public void notifyChange(PuzzleElement puzzleElement) { + super.notifyChange(puzzleElement); + Set affected = getAffected((SudokuCell) puzzleElement); + for (SudokuCell c : affected) { + c.setAnnotations(getPossibleValues(c)); + } + } + + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + @Override + public SudokuBoard copy() { + SudokuBoard copy = new SudokuBoard(size); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; } - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java index 4b9ea2b4c..006e6c0a5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java @@ -6,57 +6,57 @@ import java.util.Set; public class SudokuCell extends GridCell { - private int groupIndex; - private Set annotations; - private int max; - - /** - * SudokuCell Constructor - creates a new Sudoku cell to hold the puzzleElement - * - * @param value value of the sudoku cell - * @param location location of the cell on the board - * @param groupIndex index of the group the cell is in on the board - * @param size size of the sudoku cell - */ - public SudokuCell(int value, Point location, int groupIndex, int size) { - super(value, location); - this.groupIndex = groupIndex; - this.annotations = new HashSet<>(); - this.max = size; - } - - /** - * Gets the group index of the cell - * - * @return group index of the cell - */ - public int getGroupIndex() { - return groupIndex; - } - - public int getMax() { - return max; - } - - public Set getAnnotations() { - return annotations; - } - - public void setAnnotations(Set annotations) { - this.annotations = annotations; - } - - /** - * Performs a deep copy on the SudokuCell - * - * @return a new copy of the SudokuCell that is independent of this one - */ - @Override - public SudokuCell copy() { - SudokuCell copy = new SudokuCell(data, (Point) location.clone(), groupIndex, max); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + private int groupIndex; + private Set annotations; + private int max; + + /** + * SudokuCell Constructor - creates a new Sudoku cell to hold the puzzleElement + * + * @param value value of the sudoku cell + * @param location location of the cell on the board + * @param groupIndex index of the group the cell is in on the board + * @param size size of the sudoku cell + */ + public SudokuCell(int value, Point location, int groupIndex, int size) { + super(value, location); + this.groupIndex = groupIndex; + this.annotations = new HashSet<>(); + this.max = size; + } + + /** + * Gets the group index of the cell + * + * @return group index of the cell + */ + public int getGroupIndex() { + return groupIndex; + } + + public int getMax() { + return max; + } + + public Set getAnnotations() { + return annotations; + } + + public void setAnnotations(Set annotations) { + this.annotations = annotations; + } + + /** + * Performs a deep copy on the SudokuCell + * + * @return a new copy of the SudokuCell that is independent of this one + */ + @Override + public SudokuCell copy() { + SudokuCell copy = new SudokuCell(data, (Point) location.clone(), groupIndex, max); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java index edb095519..9b24f13da 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java @@ -5,33 +5,33 @@ import java.awt.event.MouseEvent; public class SudokuCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - SudokuCell cell = (SudokuCell) data; - System.out.print(111); - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() < cell.getMax()) { - data.setData(cell.getData() + 1); + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + SudokuCell cell = (SudokuCell) data; + System.out.print(111); + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() < cell.getMax()) { + data.setData(cell.getData() + 1); + } else { + data.setData(0); + } + } } else { - data.setData(0); + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() > 0) { + data.setData(cell.getData() - 1); + } else { + data.setData(cell.getMax()); + } + } } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() > 0) { - data.setData(cell.getData() - 1); - } else { - data.setData(cell.getMax()); - } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java index 7214193be..1ef24ea59 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java @@ -10,63 +10,65 @@ import org.w3c.dom.Node; public class SudokuCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public SudokuCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Sudoku Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public SudokuCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Sudoku Factory: unknown puzzleElement puzzleElement"); + } - SudokuBoard sudokuBoard = (SudokuBoard) board; - int size = sudokuBoard.getSize(); - int minorSize = (int) Math.sqrt(size); + SudokuBoard sudokuBoard = (SudokuBoard) board; + int size = sudokuBoard.getSize(); + int minorSize = (int) Math.sqrt(size); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= size || y >= size) { - throw new InvalidFileFormatException("Sudoku Factory: cell location out of bounds"); - } - if (value < 0 || value > 9) { - throw new InvalidFileFormatException("Sudoku Factory: cell unknown value"); - } - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(value, new Point(x, y), groupIndex, size); - cell.setIndex(y * size + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("Sudoku Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Sudoku Factory: could not find attribute(s)"); + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= size || y >= size) { + throw new InvalidFileFormatException("Sudoku Factory: cell location out of bounds"); + } + if (value < 0 || value > 9) { + throw new InvalidFileFormatException("Sudoku Factory: cell unknown value"); + } + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(value, new Point(x, y), groupIndex, size); + cell.setIndex(y * size + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Sudoku Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Sudoku Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - SudokuCell cell = (SudokuCell) puzzleElement; - Point loc = cell.getLocation(); + SudokuCell cell = (SudokuCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java index 142cf8f88..c3d236b53 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java @@ -6,65 +6,69 @@ import java.awt.*; public class SudokuElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Font ANNOTATE_FONT = new Font("TimesRoman", Font.BOLD, 8); - private static final Color FONT_COLOR = new Color(0x212121); - private static final Color BORDER_COLOR = new Color(0x424242); - private static final Color GIVEN_COLOR = new Color(0x75, 0x75, 0x75, 0x80); - private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Font ANNOTATE_FONT = new Font("TimesRoman", Font.BOLD, 8); + private static final Color FONT_COLOR = new Color(0x212121); + private static final Color BORDER_COLOR = new Color(0x424242); + private static final Color GIVEN_COLOR = new Color(0x75, 0x75, 0x75, 0x80); + private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); - public SudokuElementView(GridCell cell) { - super(cell); - } + public SudokuElementView(GridCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public SudokuCell getPuzzleElement() { - return (SudokuCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public SudokuCell getPuzzleElement() { + return (SudokuCell) super.getPuzzleElement(); + } - @Override - public void drawGiven(Graphics2D graphics2D) { - graphics2D.setColor(GIVEN_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } + @Override + public void drawGiven(Graphics2D graphics2D) { + graphics2D.setColor(GIVEN_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BACKGROUND_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BORDER_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BACKGROUND_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BORDER_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - SudokuCell cell = (SudokuCell) puzzleElement; - int val = cell.getData(); - if (val != 0) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(val); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } else { - boolean annotate = - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.SHOW_ANNOTATIONS) - .equalsIgnoreCase(Boolean.toString(true)); - if (annotate) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(ANNOTATE_FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getAnnotations()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + SudokuCell cell = (SudokuCell) puzzleElement; + int val = cell.getData(); + if (val != 0) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(val); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } else { + boolean annotate = + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.SHOW_ANNOTATIONS) + .equalsIgnoreCase(Boolean.toString(true)); + if (annotate) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(ANNOTATE_FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getAnnotations()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + + ((size.height - metrics.getHeight()) / 2) + + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java index 3bb78e9e9..f10aabae1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java @@ -6,33 +6,33 @@ public class SudokuExporter extends PuzzleExporter { - public SudokuExporter(Sudoku sudoku) { - super(sudoku); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - SudokuBoard board; - if (puzzle.getTree() != null) { - board = (SudokuBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (SudokuBoard) puzzle.getBoardView().getBoard(); + public SudokuExporter(Sudoku sudoku) { + super(sudoku); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("size", String.valueOf(board.getSize())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + SudokuBoard board; + if (puzzle.getTree() != null) { + board = (SudokuBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (SudokuBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SudokuCell cell = (SudokuCell) puzzleElement; - if (cell.getData() != 0) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("size", String.valueOf(board.getSize())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SudokuCell cell = (SudokuCell) puzzleElement; + if (cell.getData() != 0) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java index fd310a78e..68bf1e795 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java @@ -8,121 +8,128 @@ import org.w3c.dom.NodeList; public class SudokuImporter extends PuzzleImporter { - public SudokuImporter(Sudoku sudoku) { - super(sudoku); - } + public SudokuImporter(Sudoku sudoku) { + super(sudoku); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - SudokuBoard sudokuBoard; - int minorSize = (int) Math.sqrt(rows); - sudokuBoard = new SudokuBoard(rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + SudokuBoard sudokuBoard; + int minorSize = (int) Math.sqrt(rows); + sudokuBoard = new SudokuBoard(rows); - for (int y = 0; y < columns; y++) { - for (int x = 0; x < rows; x++) { - if (sudokuBoard.getCell(x, y) == null) { - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, rows); - cell.setIndex(y * rows + x); - cell.setModifiable(true); - sudokuBoard.setCell(x, y, cell); + for (int y = 0; y < columns; y++) { + for (int x = 0; x < rows; x++) { + if (sudokuBoard.getCell(x, y) == null) { + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, rows); + cell.setIndex(y * rows + x); + cell.setModifiable(true); + sudokuBoard.setCell(x, y, cell); + } + } } - } + + puzzle.setCurrentBoard(sudokuBoard); } - puzzle.setCurrentBoard(sudokuBoard); - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Sudoku Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Sudoku Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Sudoku Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Sudoku Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + SudokuBoard sudokuBoard; + int size; + int minorSize; + if (!boardElement.getAttribute("size").isEmpty()) { + size = Integer.valueOf(boardElement.getAttribute("size")); + minorSize = (int) Math.sqrt(size); + if (minorSize * minorSize != size) { + throw new InvalidFileFormatException( + "Sudoku Importer: invalid board dimensions"); + } + sudokuBoard = new SudokuBoard(size); + } else { + throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); + } - SudokuBoard sudokuBoard; - int size; - int minorSize; - if (!boardElement.getAttribute("size").isEmpty()) { - size = Integer.valueOf(boardElement.getAttribute("size")); - minorSize = (int) Math.sqrt(size); - if (minorSize * minorSize != size) { - throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); - } - sudokuBoard = new SudokuBoard(size); - } else { - throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + SudokuCell cell = + (SudokuCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), sudokuBoard); + Point loc = cell.getLocation(); + if (cell.getData() != 0) { + cell.setModifiable(false); + cell.setGiven(true); + } + sudokuBoard.setCell(loc.x, loc.y, cell); + } - for (int i = 0; i < elementDataList.getLength(); i++) { - SudokuCell cell = - (SudokuCell) puzzle.getFactory().importCell(elementDataList.item(i), sudokuBoard); - Point loc = cell.getLocation(); - if (cell.getData() != 0) { - cell.setModifiable(false); - cell.setGiven(true); - } - sudokuBoard.setCell(loc.x, loc.y, cell); - } + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + if (sudokuBoard.getCell(x, y) == null) { + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + sudokuBoard.setCell(x, y, cell); + } + } + } + // + // for(int y = 0; y < size; y++) + // { + // for(int x = 0; x < size; x++) + // { + // SudokuCell cell = sudokuBoard.getCell(x, y); + // System.err.println("(" + x + ", " + y + ") - " + + // cell.getGroupIndex()); + // } + // } - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - if (sudokuBoard.getCell(x, y) == null) { - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - sudokuBoard.setCell(x, y, cell); - } + puzzle.setCurrentBoard(sudokuBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Sudoku Importer: unknown value where integer expected"); } - } - // - // for(int y = 0; y < size; y++) - // { - // for(int x = 0; x < size; x++) - // { - // SudokuCell cell = sudokuBoard.getCell(x, y); - // System.err.println("(" + x + ", " + y + ") - " + cell.getGroupIndex()); - // } - // } - - puzzle.setCurrentBoard(sudokuBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("Sudoku Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Sudoku cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Sudoku cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java index 43939bbd4..aa58f9a23 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java @@ -10,160 +10,162 @@ import javax.swing.*; public class SudokuView extends GridBoardView { - private static final Color STROKE_COLOR = new Color(0, 0, 0); - private static final Stroke MINOR_STOKE = new BasicStroke(1); - private static final Stroke MAJOR_STOKE = new BasicStroke(4); - - public SudokuView(SudokuBoard board) { - super(new BoardController(), new SudokuCellController(), board.getDimension()); - - int minorSize = (int) Math.sqrt(gridSize.width); - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - Point location = - new Point( - k * elementSize.width + (k / minorSize) * 4 + 5, - i * elementSize.height + (i / minorSize) * 4 + 5); - SudokuElementView element = new SudokuElementView(board.getCell(k, i)); - element.setIndex(i * gridSize.width + k); - element.setSize(elementSize); - element.setLocation(location); - elementViews.add(element); - } + private static final Color STROKE_COLOR = new Color(0, 0, 0); + private static final Stroke MINOR_STOKE = new BasicStroke(1); + private static final Stroke MAJOR_STOKE = new BasicStroke(4); + + public SudokuView(SudokuBoard board) { + super(new BoardController(), new SudokuCellController(), board.getDimension()); + + int minorSize = (int) Math.sqrt(gridSize.width); + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + Point location = + new Point( + k * elementSize.width + (k / minorSize) * 4 + 5, + i * elementSize.height + (i / minorSize) * 4 + 5); + SudokuElementView element = new SudokuElementView(board.getCell(k, i)); + element.setIndex(i * gridSize.width + k); + element.setSize(elementSize); + element.setLocation(location); + elementViews.add(element); + } + } } - } - - /** - * Gets the SudokuElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return SudokuElementView at the specified index - */ - @Override - public SudokuElementView getElement(int index) { - return (SudokuElementView) super.getElement(index); - } - - public void drawGrid(Graphics2D graphics2D) { - int minorSize = (int) Math.sqrt(gridSize.width); - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MAJOR_STOKE); - graphics2D.drawRect( - 3, - 3, - gridSize.width * (elementSize.width + 1) + 3, - gridSize.height * (elementSize.height + 1) + 3); - - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MAJOR_STOKE); - for (int i = 1; i < minorSize; i++) { - int x = i * minorSize * elementSize.width + i * ((minorSize + 1)) + 3; - graphics2D.drawLine(x, 3, x, gridSize.height * (elementSize.height + 1) + 6); + + /** + * Gets the SudokuElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return SudokuElementView at the specified index + */ + @Override + public SudokuElementView getElement(int index) { + return (SudokuElementView) super.getElement(index); } - for (int i = 1; i < minorSize; i++) { - int y = i * minorSize * elementSize.height + i * ((minorSize + 1)) + 3; - graphics2D.drawLine(3, y, gridSize.width * (elementSize.width + 1) + 6, y); + + public void drawGrid(Graphics2D graphics2D) { + int minorSize = (int) Math.sqrt(gridSize.width); + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MAJOR_STOKE); + graphics2D.drawRect( + 3, + 3, + gridSize.width * (elementSize.width + 1) + 3, + gridSize.height * (elementSize.height + 1) + 3); + + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MAJOR_STOKE); + for (int i = 1; i < minorSize; i++) { + int x = i * minorSize * elementSize.width + i * ((minorSize + 1)) + 3; + graphics2D.drawLine(x, 3, x, gridSize.height * (elementSize.height + 1) + 6); + } + for (int i = 1; i < minorSize; i++) { + int y = i * minorSize * elementSize.height + i * ((minorSize + 1)) + 3; + graphics2D.drawLine(3, y, gridSize.width * (elementSize.width + 1) + 6, y); + } } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - drawGrid(graphics2D); + @Override + public void drawBoard(Graphics2D graphics2D) { + drawGrid(graphics2D); - if (board instanceof PossibleNumberCaseBoard) { - drawCaseBoard(graphics2D); - return; - } - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MINOR_STOKE); - ElementView hover = null; - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - ElementView element = elementViews.get(i * gridSize.height + k); - if (!element.isHover()) { - element.draw(graphics2D); - } else { - hover = element; + if (board instanceof PossibleNumberCaseBoard) { + drawCaseBoard(graphics2D); + return; + } + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MINOR_STOKE); + ElementView hover = null; + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + ElementView element = elementViews.get(i * gridSize.height + k); + if (!element.isHover()) { + element.draw(graphics2D); + } else { + hover = element; + } + } } - } - } - if (hover != null) { - hover.draw(graphics2D); + if (hover != null) { + hover.draw(graphics2D); + } } - } - - public void drawCaseBoard(Graphics2D graphics2D) { - drawGrid(graphics2D); - - PossibleNumberCaseBoard caseBoard = (PossibleNumberCaseBoard) board; - SudokuBoard sudokuBoard = (SudokuBoard) caseBoard.getBaseBoard(); - - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MINOR_STOKE); - ElementView hover = null; - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - ElementView element = elementViews.get(i * gridSize.height + k); - if (!element.isHover()) { - element.draw(graphics2D); - } else { - hover = element; + + public void drawCaseBoard(Graphics2D graphics2D) { + drawGrid(graphics2D); + + PossibleNumberCaseBoard caseBoard = (PossibleNumberCaseBoard) board; + SudokuBoard sudokuBoard = (SudokuBoard) caseBoard.getBaseBoard(); + + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MINOR_STOKE); + ElementView hover = null; + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + ElementView element = elementViews.get(i * gridSize.height + k); + if (!element.isHover()) { + element.draw(graphics2D); + } else { + hover = element; + } + } } - } + + graphics2D.setColor(new Color(0x1A, 0x23, 0x7E, 200)); + for (int r : caseBoard.getPickableRegions()) { + Set region = sudokuBoard.getRegion(r); + int x = Integer.MAX_VALUE, + y = Integer.MAX_VALUE, + w = Integer.MIN_VALUE, + h = Integer.MIN_VALUE; + for (SudokuCell c : region) { + x = Math.min(x, c.getLocation().x); + y = Math.min(y, c.getLocation().y); + w = Math.max(w, c.getLocation().x); + h = Math.max(h, c.getLocation().y); + } + + SudokuElementView firstElement = getElement(y * gridSize.width + x); + SudokuElementView lastElement = getElement(h * gridSize.width + w); + x = firstElement.getLocation().x; + y = firstElement.getLocation().y; + w = (lastElement.getLocation().x + elementSize.width) - x; + h = (lastElement.getLocation().y + elementSize.height) - y; + graphics2D.fillRect(x + 4, y + 4, w - 8, h - 8); + } + + // if(hover != null) + // hover.draw(graphics2D); } - graphics2D.setColor(new Color(0x1A, 0x23, 0x7E, 200)); - for (int r : caseBoard.getPickableRegions()) { - Set region = sudokuBoard.getRegion(r); - int x = Integer.MAX_VALUE, - y = Integer.MAX_VALUE, - w = Integer.MIN_VALUE, - h = Integer.MIN_VALUE; - for (SudokuCell c : region) { - x = Math.min(x, c.getLocation().x); - y = Math.min(y, c.getLocation().y); - w = Math.max(w, c.getLocation().x); - h = Math.max(h, c.getLocation().y); - } - - SudokuElementView firstElement = getElement(y * gridSize.width + x); - SudokuElementView lastElement = getElement(h * gridSize.width + w); - x = firstElement.getLocation().x; - y = firstElement.getLocation().y; - w = (lastElement.getLocation().x + elementSize.width) - x; - h = (lastElement.getLocation().y + elementSize.height) - y; - graphics2D.fillRect(x + 4, y + 4, w - 8, h - 8); + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = gridSize.width * (elementSize.width + 1) + 9; + boardViewSize.height = gridSize.height * (elementSize.height + 1) + 9; + return boardViewSize; } - // if(hover != null) - // hover.draw(graphics2D); - } - - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = gridSize.width * (elementSize.width + 1) + 9; - boardViewSize.height = gridSize.height * (elementSize.height + 1) + 9; - return boardViewSize; - } - - public DataSelectionView getSelectionPopupMenu() { - DataSelectionView selectionView = new DataSelectionView(elementController); - GridLayout layout = new GridLayout(3, 3); - selectionView.setLayout(layout); - for (int r = 1; r <= 3; r++) { - for (int c = 1; c <= 3; c++) { - SudokuElementView element = - new SudokuElementView(new SudokuCell((r - 1) * 3 + c, null, 0, gridSize.width)); - element.setSize(new Dimension(32, 32)); - element.setLocation(new Point(0, 0)); - SelectionItemView item = - new SelectionItemView(element.getPuzzleElement(), new ImageIcon(element.getImage())); - item.addActionListener(elementController); - item.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item); - } + public DataSelectionView getSelectionPopupMenu() { + DataSelectionView selectionView = new DataSelectionView(elementController); + GridLayout layout = new GridLayout(3, 3); + selectionView.setLayout(layout); + for (int r = 1; r <= 3; r++) { + for (int c = 1; c <= 3; c++) { + SudokuElementView element = + new SudokuElementView( + new SudokuCell((r - 1) * 3 + c, null, 0, gridSize.width)); + element.setSize(new Dimension(32, 32)); + element.setLocation(new Point(0, 0)); + SelectionItemView item = + new SelectionItemView( + element.getPuzzleElement(), new ImageIcon(element.getImage())); + item.addActionListener(elementController); + item.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item); + } + } + return selectionView; } - return selectionView; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java index 4a122dbcf..12183d70d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java @@ -3,24 +3,24 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class NumberTile extends PlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super("SUDO-PLAC-0001", "Number Tile", "A numbered tile", null); - object_num = 0; - } + public NumberTile() { + super("SUDO-PLAC-0001", "Number Tile", "A numbered tile", null); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java index 8db5163e0..190679b41 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java @@ -10,88 +10,90 @@ public class AdvancedDeductionDirectRule extends DirectRule { - public AdvancedDeductionDirectRule() { - super( - "SUDO-BASC-0001", - "Advanced Deduction", - "Use of group logic deduces more answers by means of forced by Location and forced by Deduction", - "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); - } + public AdvancedDeductionDirectRule() { + super( + "SUDO-BASC-0001", + "Advanced Deduction", + "Use of group logic deduces more answers by means of forced by Location and forced" + + " by Deduction", + "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - int index = cell.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int relX = rowIndex / groupDim; - int relY = colIndex % groupDim; - int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; - boolean[][] possible = new boolean[groupDim][groupDim]; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - SudokuCell c = initialBoard.getCell(groupNum, x, y); - if (c.getData() == cell.getData() && x != relX && y != relY) { - return super.getRuleName() + ": Duplicate value in sub-region"; + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + int index = cell.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int relX = rowIndex / groupDim; + int relY = colIndex % groupDim; + int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; + boolean[][] possible = new boolean[groupDim][groupDim]; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + SudokuCell c = initialBoard.getCell(groupNum, x, y); + if (c.getData() == cell.getData() && x != relX && y != relY) { + return super.getRuleName() + ": Duplicate value in sub-region"; + } + possible[y][x] = c.getData() == 0; + } } - possible[y][x] = c.getData() == 0; - } - } - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupSize; x++) { - SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); - SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); - if (r.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[y][i] = false; - } + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupSize; x++) { + SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); + SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); + if (r.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[y][i] = false; + } + } + if (c.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[i][y] = false; + } + } + } } - if (c.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[i][y] = false; - } + boolean isForced = false; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + if (possible[y][x] && !isForced) { + isForced = true; + } else { + if (possible[y][x]) { + return super.getInvalidUseOfRuleMessage() + ": Not forced"; + } + } + } } - } - } - boolean isForced = false; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - if (possible[y][x] && !isForced) { - isForced = true; - } else { - if (possible[y][x]) { + if (!isForced) { return super.getInvalidUseOfRuleMessage() + ": Not forced"; - } } - } + return null; } - if (!isForced) { - return super.getInvalidUseOfRuleMessage() + ": Not forced"; - } - return null; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java index fe32fc450..fd03ef36c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java @@ -10,85 +10,86 @@ import java.util.Set; public class LastCellForNumberDirectRule extends DirectRule { - public LastCellForNumberDirectRule() { - super( - "SUDO-BASC-0002", - "Last Cell for Number", - "This is the only cell open in its group for some number.", - "edu/rpi/legup/images/sudoku/forcedByElimination.png"); - } + public LastCellForNumberDirectRule() { + super( + "SUDO-BASC-0002", + "Last Cell for Number", + "This is the only cell open in its group for some number.", + "edu/rpi/legup/images/sudoku/forcedByElimination.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; - } + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } - int size = initialBoard.getSize(); + int size = initialBoard.getSize(); - Set region = initialBoard.getRegion(cell.getGroupIndex()); - Set row = initialBoard.getRow(cell.getLocation().y); - Set col = initialBoard.getCol(cell.getLocation().x); + Set region = initialBoard.getRegion(cell.getGroupIndex()); + Set row = initialBoard.getRow(cell.getLocation().y); + Set col = initialBoard.getCol(cell.getLocation().x); - boolean contains = false; - if (region.size() == size - 1) { - for (SudokuCell c : region) { - if (cell.getData() == c.getData()) { - contains = true; - break; + boolean contains = false; + if (region.size() == size - 1) { + for (SudokuCell c : region) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } } - } - if (!contains) { - return null; - } - } - if (row.size() == size - 1) { - contains = false; - for (SudokuCell c : row) { - if (cell.getData() == c.getData()) { - contains = true; - break; + if (row.size() == size - 1) { + contains = false; + for (SudokuCell c : row) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } } - } - if (!contains) { - return null; - } - } - if (col.size() == size - 1) { - contains = false; - for (SudokuCell c : col) { - if (cell.getData() == c.getData()) { - contains = true; - break; + if (col.size() == size - 1) { + contains = false; + for (SudokuCell c : col) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } } - } - if (!contains) { - return null; - } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java index 881df8455..ca0ac3023 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java @@ -11,69 +11,71 @@ public class LastNumberForCellDirectRule extends DirectRule { - public LastNumberForCellDirectRule() { - super( - "SUDO-BASC-0003", - "Last Number for Cell", - "This is the only number left that can fit in the cell of a group.", - "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); - } + public LastNumberForCellDirectRule() { + super( + "SUDO-BASC-0003", + "Last Number for Cell", + "This is the only number left that can fit in the cell of a group.", + "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - int index = puzzleElement.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; - HashSet numbers = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - numbers.add(i); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); - numbers.remove(cell.getData()); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(i, colIndex); - numbers.remove(cell.getData()); + int index = puzzleElement.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; + HashSet numbers = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + numbers.add(i); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); + numbers.remove(cell.getData()); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(i, colIndex); + numbers.remove(cell.getData()); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(rowIndex, i); + numbers.remove(cell.getData()); + } + if (numbers.size() > 1) { + return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; + } else { + if (numbers.size() == 1 + && numbers.iterator().next() + != finalBoard.getPuzzleElement(puzzleElement).getData()) { + return super.getInvalidUseOfRuleMessage() + + ": The number at the index is forced but not correct"; + } + } + return null; } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(rowIndex, i); - numbers.remove(cell.getData()); - } - if (numbers.size() > 1) { - return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; - } else { - if (numbers.size() == 1 - && numbers.iterator().next() != finalBoard.getPuzzleElement(puzzleElement).getData()) { - return super.getInvalidUseOfRuleMessage() - + ": The number at the index is forced but not correct"; - } - } - return null; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java index e87b77492..e44728d3e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java @@ -10,55 +10,55 @@ public class NoSolutionContradictionRule extends ContradictionRule { - public NoSolutionContradictionRule() { - super( - "SUDO-CONT-0001", - "No Solution for Cell", - "Process of elimination yields no valid numbers for an empty cell.", - "edu/rpi/legup/images/sudoku/NoSolution.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); - if (cell.getData() != 0) { - return super.getNoContradictionMessage(); + public NoSolutionContradictionRule() { + super( + "SUDO-CONT-0001", + "No Solution for Cell", + "Process of elimination yields no valid numbers for an empty cell.", + "edu/rpi/legup/images/sudoku/NoSolution.png"); } - int groupSize = sudokuBoard.getSize(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); + if (cell.getData() != 0) { + return super.getNoContradictionMessage(); + } - Set region = sudokuBoard.getRegion(cell.getGroupIndex()); - Set row = sudokuBoard.getRow(cell.getLocation().y); - Set col = sudokuBoard.getCol(cell.getLocation().x); - Set solution = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - solution.add(i); - } + int groupSize = sudokuBoard.getSize(); - for (SudokuCell c : region) { - solution.remove(c.getData()); - } - for (SudokuCell c : row) { - solution.remove(c.getData()); - } - for (SudokuCell c : col) { - solution.remove(c.getData()); - } + Set region = sudokuBoard.getRegion(cell.getGroupIndex()); + Set row = sudokuBoard.getRow(cell.getLocation().y); + Set col = sudokuBoard.getCol(cell.getLocation().x); + Set solution = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + solution.add(i); + } - if (solution.isEmpty()) { - return null; - } + for (SudokuCell c : region) { + solution.remove(c.getData()); + } + for (SudokuCell c : row) { + solution.remove(c.getData()); + } + for (SudokuCell c : col) { + solution.remove(c.getData()); + } - return super.getNoContradictionMessage(); - } + if (solution.isEmpty()) { + return null; + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java index be1875c90..fb6da62d4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java @@ -12,99 +12,99 @@ import java.util.Set; public class PossibleCellCaseRule extends CaseRule { - public PossibleCellCaseRule() { - super( - "SUDO-CASE-0001", - "Possible Cells for Number", - "A number has a limited set of cells in which it can be placed.", - "edu/rpi/legup/images/sudoku/possible_cells_number.png"); - } + public PossibleCellCaseRule() { + super( + "SUDO-CASE-0001", + "Possible Cells for Number", + "A number has a limited set of cells in which it can be placed.", + "edu/rpi/legup/images/sudoku/possible_cells_number.png"); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - @Override - public CaseBoard getCaseBoard(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(sudokuBoard, this); - for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { - if (((SudokuCell) puzzleElement).getData() == 0) { - caseBoard.addPickableElement(puzzleElement); - } + @Override + public CaseBoard getCaseBoard(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(sudokuBoard, this); + for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { + if (((SudokuCell) puzzleElement).getData() == 0) { + caseBoard.addPickableElement(puzzleElement); + } + } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) puzzleElement; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) puzzleElement; - Set possibleValue = new HashSet<>(); - for (int i = 1; i <= sudokuBoard.getSize(); i++) { - possibleValue.add(i); - } + Set possibleValue = new HashSet<>(); + for (int i = 1; i <= sudokuBoard.getSize(); i++) { + possibleValue.add(i); + } - int groupNum = cell.getGroupIndex(); - for (SudokuCell c : sudokuBoard.getRegion(groupNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int groupNum = cell.getGroupIndex(); + for (SudokuCell c : sudokuBoard.getRegion(groupNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - int rowNum = cell.getLocation().y; - for (SudokuCell c : sudokuBoard.getRegion(rowNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int rowNum = cell.getLocation().y; + for (SudokuCell c : sudokuBoard.getRegion(rowNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - int colNum = cell.getLocation().x; - for (SudokuCell c : sudokuBoard.getRegion(colNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int colNum = cell.getLocation().x; + for (SudokuCell c : sudokuBoard.getRegion(colNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - for (Integer i : possibleValue) { - SudokuBoard newCase = sudokuBoard.copy(); + for (Integer i : possibleValue) { + SudokuBoard newCase = sudokuBoard.copy(); - PuzzleElement newCasePuzzleElement = newCase.getPuzzleElement(puzzleElement); - newCasePuzzleElement.setData(i); - newCase.addModifiedData(newCasePuzzleElement); - cases.add(newCase); - } + PuzzleElement newCasePuzzleElement = newCase.getPuzzleElement(puzzleElement); + newCasePuzzleElement.setData(i); + newCase.addModifiedData(newCasePuzzleElement); + cases.add(newCase); + } - return cases; - } + return cases; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java index f638fbbb6..e6ab0e64c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java @@ -15,117 +15,117 @@ public class PossibleNumberCaseRule extends CaseRule { - public PossibleNumberCaseRule() { - super( - "SUDO-CASE-0002", - "Possible Numbers for Cell", - "An empty cell has a limited set of possible numbers that can fill it.", - "edu/rpi/legup/images/sudoku/PossibleValues.png"); - } + public PossibleNumberCaseRule() { + super( + "SUDO-CASE-0002", + "Possible Numbers for Cell", + "An empty cell has a limited set of possible numbers that can fill it.", + "edu/rpi/legup/images/sudoku/PossibleValues.png"); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - @Override - public CaseBoard getCaseBoard(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - PossibleNumberCaseBoard caseBoard = new PossibleNumberCaseBoard(sudokuBoard, this, null); - for (int i = 0; i < sudokuBoard.getSize(); i++) { - caseBoard.addPickableRegion(i); - caseBoard.addPickableRow(i); - caseBoard.addPickableCol(i); + @Override + public CaseBoard getCaseBoard(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + PossibleNumberCaseBoard caseBoard = new PossibleNumberCaseBoard(sudokuBoard, this, null); + for (int i = 0; i < sudokuBoard.getSize(); i++) { + caseBoard.addPickableRegion(i); + caseBoard.addPickableRow(i); + caseBoard.addPickableCol(i); + } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - return getCases(board, puzzleElement, 1, GroupType.REGION); - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + return getCases(board, puzzleElement, 1, GroupType.REGION); + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @param value value that the rule will be applied from - * @param groupType group type - * @return a list of elements the specified could be - */ - public ArrayList getCases( - Board board, PuzzleElement puzzleElement, int value, GroupType groupType) { - ArrayList cases = new ArrayList<>(); - SudokuBoard sudokuBoard = (SudokuBoard) board; - List caseCells = new ArrayList<>(); - SudokuCell cell = (SudokuCell) puzzleElement; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @param value value that the rule will be applied from + * @param groupType group type + * @return a list of elements the specified could be + */ + public ArrayList getCases( + Board board, PuzzleElement puzzleElement, int value, GroupType groupType) { + ArrayList cases = new ArrayList<>(); + SudokuBoard sudokuBoard = (SudokuBoard) board; + List caseCells = new ArrayList<>(); + SudokuCell cell = (SudokuCell) puzzleElement; - Set group; - if (groupType == GroupType.REGION) { - group = sudokuBoard.getRegion(cell.getGroupIndex()); - } else { - if (groupType == GroupType.ROW) { - group = sudokuBoard.getRow(cell.getLocation().y); - } else { - group = sudokuBoard.getCol(cell.getLocation().x); - } - } + Set group; + if (groupType == GroupType.REGION) { + group = sudokuBoard.getRegion(cell.getGroupIndex()); + } else { + if (groupType == GroupType.ROW) { + group = sudokuBoard.getRow(cell.getLocation().y); + } else { + group = sudokuBoard.getCol(cell.getLocation().x); + } + } - for (SudokuCell c : group) { - if (c.getData() == 0) { - Set blockableCells = sudokuBoard.getRegion(c.getGroupIndex()); - blockableCells.addAll(sudokuBoard.getRow(c.getLocation().y)); - blockableCells.addAll(sudokuBoard.getCol(c.getLocation().x)); + for (SudokuCell c : group) { + if (c.getData() == 0) { + Set blockableCells = sudokuBoard.getRegion(c.getGroupIndex()); + blockableCells.addAll(sudokuBoard.getRow(c.getLocation().y)); + blockableCells.addAll(sudokuBoard.getCol(c.getLocation().x)); - boolean repeat = false; - for (SudokuCell bc : blockableCells) { - if (bc.getData() == value) { - repeat = true; - break; - } + boolean repeat = false; + for (SudokuCell bc : blockableCells) { + if (bc.getData() == value) { + repeat = true; + break; + } + } + if (!repeat) { + caseCells.add(c); + } + } } - if (!repeat) { - caseCells.add(c); + + for (SudokuCell c : caseCells) { + Board newCase = sudokuBoard.copy(); + PuzzleElement element = newCase.getPuzzleElement(c); + element.setData(value); + newCase.addModifiedData(element); + cases.add(newCase); } - } - } - for (SudokuCell c : caseCells) { - Board newCase = sudokuBoard.copy(); - PuzzleElement element = newCase.getPuzzleElement(c); - element.setData(value); - newCase.addModifiedData(element); - cases.add(newCase); + return cases; } - - return cases; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java index cf0bfa600..955414e8e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java @@ -10,60 +10,60 @@ public class RepeatedNumberContradictionRule extends ContradictionRule { - public RepeatedNumberContradictionRule() { - super( - "SUDO-CONT-0002", - "Repeated Numbers", - "Two identical numbers are placed in the same group.", - "edu/rpi/legup/images/sudoku/RepeatedNumber.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getNoContradictionMessage(); + public RepeatedNumberContradictionRule() { + super( + "SUDO-CONT-0002", + "Repeated Numbers", + "Two identical numbers are placed in the same group.", + "edu/rpi/legup/images/sudoku/RepeatedNumber.png"); } - Set region = sudokuBoard.getRegion(cell.getGroupIndex()); - Set row = sudokuBoard.getRow(cell.getLocation().y); - Set col = sudokuBoard.getCol(cell.getLocation().x); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getNoContradictionMessage(); + } - Set regionDup = new HashSet<>(); - Set rowDup = new HashSet<>(); - Set colDup = new HashSet<>(); + Set region = sudokuBoard.getRegion(cell.getGroupIndex()); + Set row = sudokuBoard.getRow(cell.getLocation().y); + Set col = sudokuBoard.getCol(cell.getLocation().x); - for (SudokuCell c : region) { - if (regionDup.contains(c.getData())) { - return null; - } - regionDup.add(c.getData()); - } + Set regionDup = new HashSet<>(); + Set rowDup = new HashSet<>(); + Set colDup = new HashSet<>(); - for (SudokuCell c : row) { - if (rowDup.contains(c.getData())) { - return null; - } - rowDup.add(c.getData()); - } + for (SudokuCell c : region) { + if (regionDup.contains(c.getData())) { + return null; + } + regionDup.add(c.getData()); + } - for (SudokuCell c : col) { - if (colDup.contains(c.getData())) { - return null; - } - colDup.add(c.getData()); - } + for (SudokuCell c : row) { + if (rowDup.contains(c.getData())) { + return null; + } + rowDup.add(c.getData()); + } + + for (SudokuCell c : col) { + if (colDup.contains(c.getData())) { + return null; + } + colDup.add(c.getData()); + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java b/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java index fa66fcb1b..a11f5f05b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java @@ -15,169 +15,170 @@ import java.util.Map; public class ClueCommand extends PuzzleCommand { - private TreeViewSelection selection; - private TreeTentClueView clueView; - private Map addTran; - private List> emptyCells; - - public ClueCommand(TreeViewSelection selection, TreeTentClueView clueView) { - this.selection = selection; - this.clueView = clueView; - this.addTran = new HashMap<>(); - this.emptyCells = new ArrayList<>(); - } - - /** Executes a command */ - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - - final TreeViewSelection newSelection = new TreeViewSelection(); - for (int i = 0; i < selection.getSelectedViews().size(); i++) { - TreeElementView selectedView = selection.getSelectedViews().get(i); - TreeElement treeElement = selectedView.getTreeElement(); - - final TreeTransition finalTran; - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - List tempList = emptyCells.get(i); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - TreeTransition transition = addTran.get(treeNode); - if (transition == null) { - transition = tree.addNewTransition(treeNode); - addTran.put(treeNode, transition); - } else { - treeNode.addChild(transition); - } - - finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(finalTran)); - board = (TreeTentBoard) finalTran.getBoard(); - } else { - finalTran = (TreeTransition) treeElement; - newSelection.addToSelection(treeView.getElementView(treeElement)); - } - - for (TreeTentCell cell : tempList) { - cell = (TreeTentCell) board.getPuzzleElement(cell); - cell.setData(TreeTentType.GRASS); - board.addModifiedData(cell); - finalTran.propagateChange(cell); - - final TreeTentCell finalCell = cell; - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); - } - if (i == 0) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); - } - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - if (selection.getSelectedViews().isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + private TreeViewSelection selection; + private TreeTentClueView clueView; + private Map addTran; + private List> emptyCells; + + public ClueCommand(TreeViewSelection selection, TreeTentClueView clueView) { + this.selection = selection; + this.clueView = clueView; + this.addTran = new HashMap<>(); + this.emptyCells = new ArrayList<>(); } - emptyCells.clear(); - for (TreeElementView view : selection.getSelectedViews()) { - TreeElement treeElement = view.getTreeElement(); - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) treeElement; - if (!node.getChildren().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); + /** Executes a command */ + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + + final TreeViewSelection newSelection = new TreeViewSelection(); + for (int i = 0; i < selection.getSelectedViews().size(); i++) { + TreeElementView selectedView = selection.getSelectedViews().get(i); + TreeElement treeElement = selectedView.getTreeElement(); + + final TreeTransition finalTran; + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + List tempList = emptyCells.get(i); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + TreeTransition transition = addTran.get(treeNode); + if (transition == null) { + transition = tree.addNewTransition(treeNode); + addTran.put(treeNode, transition); + } else { + treeNode.addChild(transition); + } + + finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(finalTran)); + board = (TreeTentBoard) finalTran.getBoard(); + } else { + finalTran = (TreeTransition) treeElement; + newSelection.addToSelection(treeView.getElementView(treeElement)); + } + + for (TreeTentCell cell : tempList) { + cell = (TreeTentCell) board.getPuzzleElement(cell); + cell.setData(TreeTentType.GRASS); + board.addModifiedData(cell); + finalTran.propagateChange(cell); + + final TreeTentCell finalCell = cell; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); + } + if (i == 0) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); + } } - } else { - if (!board.isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - - List tempList = new ArrayList<>(); - TreeTentClue clue = clueView.getPuzzleElement(); - if (clue.getType() == TreeTentType.CLUE_NORTH || clue.getType() == TreeTentType.CLUE_SOUTH) { - int col = - clue.getType() == TreeTentType.CLUE_NORTH - ? clue.getClueIndex() - : clue.getClueIndex() - 1; - for (int i = 0; i < board.getWidth(); i++) { - TreeTentCell cell = board.getCell(col, i); - if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { - tempList.add(cell); - } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + if (selection.getSelectedViews().isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - } else { - int row = - clue.getType() == TreeTentType.CLUE_WEST - ? clue.getClueIndex() - : clue.getClueIndex() - 1; - for (int i = 0; i < board.getWidth(); i++) { - TreeTentCell cell = board.getCell(i, row); - if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { - tempList.add(cell); - } + + emptyCells.clear(); + for (TreeElementView view : selection.getSelectedViews()) { + TreeElement treeElement = view.getTreeElement(); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) treeElement; + if (!node.getChildren().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } else { + if (!board.isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } + + List tempList = new ArrayList<>(); + TreeTentClue clue = clueView.getPuzzleElement(); + if (clue.getType() == TreeTentType.CLUE_NORTH + || clue.getType() == TreeTentType.CLUE_SOUTH) { + int col = + clue.getType() == TreeTentType.CLUE_NORTH + ? clue.getClueIndex() + : clue.getClueIndex() - 1; + for (int i = 0; i < board.getWidth(); i++) { + TreeTentCell cell = board.getCell(col, i); + if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { + tempList.add(cell); + } + } + } else { + int row = + clue.getType() == TreeTentType.CLUE_WEST + ? clue.getClueIndex() + : clue.getClueIndex() - 1; + for (int i = 0; i < board.getWidth(); i++) { + TreeTentCell cell = board.getCell(i, row); + if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { + tempList.add(cell); + } + } + } + if (tempList.isEmpty()) { + return "There are no modifiable unknown cells in every selected tree element."; + } + emptyCells.add(tempList); } - } - if (tempList.isEmpty()) { - return "There are no modifiable unknown cells in every selected tree element."; - } - emptyCells.add(tempList); + return null; } - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - - for (int i = 0; i < selection.getSelectedViews().size(); i++) { - TreeElementView selectedView = selection.getSelectedViews().get(i); - TreeElement treeElement = selectedView.getTreeElement(); - - final TreeTransition finalTran; - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - List tempList = emptyCells.get(i); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - finalTran = treeNode.getChildren().get(0); - tree.removeTreeElement(finalTran); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); - - board = (TreeTentBoard) finalTran.getBoard(); - } else { - finalTran = (TreeTransition) treeElement; - } - - for (TreeTentCell cell : tempList) { - cell = (TreeTentCell) board.getPuzzleElement(cell); - cell.setData(TreeTentType.UNKNOWN); - board.removeModifiedData(cell); - - final TreeTentCell finalCell = cell; - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); - } - - if (i == 0) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); - } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + + for (int i = 0; i < selection.getSelectedViews().size(); i++) { + TreeElementView selectedView = selection.getSelectedViews().get(i); + TreeElement treeElement = selectedView.getTreeElement(); + + final TreeTransition finalTran; + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + List tempList = emptyCells.get(i); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + finalTran = treeNode.getChildren().get(0); + tree.removeTreeElement(finalTran); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); + + board = (TreeTentBoard) finalTran.getBoard(); + } else { + finalTran = (TreeTransition) treeElement; + } + + for (TreeTentCell cell : tempList) { + cell = (TreeTentCell) board.getPuzzleElement(cell); + cell.setData(TreeTentType.UNKNOWN); + board.removeModifiedData(cell); + + final TreeTentCell finalCell = cell; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); + } + + if (i == 0) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); + } + } + final TreeViewSelection newSelection = selection; + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - final TreeViewSelection newSelection = selection; - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java b/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java index 4420d791e..feece58a9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java @@ -14,212 +14,214 @@ import java.util.List; public class EditLineCommand extends PuzzleCommand { - private TreeTentElementView start; - private TreeTentElementView end; - - private TreeViewSelection selection; - - public EditLineCommand( - TreeViewSelection selection, TreeTentElementView start, ElementView endDrag) { - this.selection = selection; - this.start = start; - this.end = getViewInDirection(endDrag); - } - - /** Executes a command */ - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - TreeTentCell startCell; - TreeTentCell endCell; - - final TreeTransition transition; - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - transition = tree.addNewTransition(treeNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - - board = (TreeTentBoard) transition.getBoard(); - } else { - transition = (TreeTransition) treeElement; + private TreeTentElementView start; + private TreeTentElementView end; + + private TreeViewSelection selection; + + public EditLineCommand( + TreeViewSelection selection, TreeTentElementView start, ElementView endDrag) { + this.selection = selection; + this.start = start; + this.end = getViewInDirection(endDrag); } - startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); - endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + /** Executes a command */ + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); - TreeTentLine line = new TreeTentLine(startCell, endCell); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + TreeTentCell startCell; + TreeTentCell endCell; - TreeTentLine dupLine = null; - for (TreeTentLine l : board.getLines()) { - if (line.compare(l)) { - dupLine = l; - break; - } - } + final TreeTransition transition; + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; - final TreeTentLine notifyLine; - if (dupLine == null) { - board.addModifiedData(line); - board.getLines().add(line); - notifyLine = line; - transition.propagateAddition(notifyLine); - } else { - board.removeModifiedData(dupLine); - board.getLines().remove(dupLine); - notifyLine = dupLine; - transition.propagateDeletion(notifyLine); - } + transition = tree.addNewTransition(treeNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); - - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(transition)); - - final TreeViewSelection newSelection = - new TreeViewSelection(treeView.getElementView(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); - } + board = (TreeTentBoard) transition.getBoard(); + } else { + transition = (TreeTransition) treeElement; + } - if (start == null || end == null) { - return "The line must connect a tree to a tent."; - } + startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); + endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); - TreeElementView view = selection.getFirstSelection(); - TreeElement treeElement = view.getTreeElement(); - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) treeElement; - if (!node.getChildren().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } else { - if (!board.isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - TreeTentLine line = - new TreeTentLine( - (TreeTentCell) start.getPuzzleElement(), (TreeTentCell) end.getPuzzleElement()); - for (TreeTentLine l : board.getLines()) { - if (line.compare(l) && !l.isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); - } - } + TreeTentLine line = new TreeTentLine(startCell, endCell); - TreeTentCell startCell = (TreeTentCell) start.getPuzzleElement(); - TreeTentCell endCell = (TreeTentCell) end.getPuzzleElement(); - if (!((startCell.getType() == TreeTentType.TENT && endCell.getType() == TreeTentType.TREE) - || (endCell.getType() == TreeTentType.TENT && startCell.getType() == TreeTentType.TREE))) { - return "The line must connect a tree to a tent."; - } + TreeTentLine dupLine = null; + for (TreeTentLine l : board.getLines()) { + if (line.compare(l)) { + dupLine = l; + break; + } + } + + final TreeTentLine notifyLine; + if (dupLine == null) { + board.addModifiedData(line); + board.getLines().add(line); + notifyLine = line; + transition.propagateAddition(notifyLine); + } else { + board.removeModifiedData(dupLine); + board.getLines().remove(dupLine); + notifyLine = dupLine; + transition.propagateDeletion(notifyLine); + } - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - TreeTentCell startCell; - TreeTentCell endCell; - TreeTransition transition; - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - transition = treeNode.getChildren().get(0); - - tree.removeTreeElement(transition); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - - board = (TreeTentBoard) transition.getBoard(); - } else { - transition = (TreeTransition) treeElement; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(transition)); + + final TreeViewSelection newSelection = + new TreeViewSelection(treeView.getElementView(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); - endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); + } - TreeTentLine line = new TreeTentLine(startCell, endCell); + if (start == null || end == null) { + return "The line must connect a tree to a tent."; + } - TreeTentLine dupLine = null; - for (TreeTentLine l : board.getLines()) { - if (line.compare(l)) { - dupLine = l; - break; - } + TreeElementView view = selection.getFirstSelection(); + TreeElement treeElement = view.getTreeElement(); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) treeElement; + if (!node.getChildren().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } else { + if (!board.isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } + TreeTentLine line = + new TreeTentLine( + (TreeTentCell) start.getPuzzleElement(), + (TreeTentCell) end.getPuzzleElement()); + for (TreeTentLine l : board.getLines()) { + if (line.compare(l) && !l.isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); + } + } + + TreeTentCell startCell = (TreeTentCell) start.getPuzzleElement(); + TreeTentCell endCell = (TreeTentCell) end.getPuzzleElement(); + if (!((startCell.getType() == TreeTentType.TENT && endCell.getType() == TreeTentType.TREE) + || (endCell.getType() == TreeTentType.TENT + && startCell.getType() == TreeTentType.TREE))) { + return "The line must connect a tree to a tent."; + } + + return null; } - final TreeTentLine notifyLine; - if (dupLine == null) { - board.addModifiedData(line); - board.getLines().add(line); - notifyLine = line; - } else { - board.removeModifiedData(dupLine); - board.getLines().remove(dupLine); - notifyLine = dupLine; + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + TreeTentCell startCell; + TreeTentCell endCell; + TreeTransition transition; + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + transition = treeNode.getChildren().get(0); + + tree.removeTreeElement(transition); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + + board = (TreeTentBoard) transition.getBoard(); + } else { + transition = (TreeTransition) treeElement; + } + + startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); + endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + + TreeTentLine line = new TreeTentLine(startCell, endCell); + + TreeTentLine dupLine = null; + for (TreeTentLine l : board.getLines()) { + if (line.compare(l)) { + dupLine = l; + break; + } + } + + final TreeTentLine notifyLine; + if (dupLine == null) { + board.addModifiedData(line); + board.getLines().add(line); + notifyLine = line; + } else { + board.removeModifiedData(dupLine); + board.getLines().remove(dupLine); + notifyLine = dupLine; + } + transition.propagateChange(notifyLine); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } - transition.propagateChange(notifyLine); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } - - private TreeTentElementView getViewInDirection(ElementView endDrag) { - TreeTentView boardView = (TreeTentView) getInstance().getLegupUI().getBoardView(); - Dimension size = boardView.getElementSize(); - int xIndex, yIndex; - - Point startLoc = start.getLocation(); - Point endLoc = endDrag.getLocation(); - double radians = Math.atan2(startLoc.y - endLoc.y, endLoc.x - startLoc.x); - if (radians >= Math.PI / 4 && radians < 3 * Math.PI / 4) { - // up - xIndex = startLoc.x / size.width; - yIndex = (startLoc.y / size.height) - 1; - } else { - if (radians >= -Math.PI / 4 && radians < Math.PI / 4) { - // right - xIndex = (startLoc.x / size.width) + 1; - yIndex = startLoc.y / size.height; - } else { - if (radians >= -3 * Math.PI / 4 && radians < -Math.PI / 4) { - // down - xIndex = startLoc.x / size.width; - yIndex = (startLoc.y / size.height) + 1; + + private TreeTentElementView getViewInDirection(ElementView endDrag) { + TreeTentView boardView = (TreeTentView) getInstance().getLegupUI().getBoardView(); + Dimension size = boardView.getElementSize(); + int xIndex, yIndex; + + Point startLoc = start.getLocation(); + Point endLoc = endDrag.getLocation(); + double radians = Math.atan2(startLoc.y - endLoc.y, endLoc.x - startLoc.x); + if (radians >= Math.PI / 4 && radians < 3 * Math.PI / 4) { + // up + xIndex = startLoc.x / size.width; + yIndex = (startLoc.y / size.height) - 1; } else { - // left - xIndex = (startLoc.x / size.width) - 1; - yIndex = startLoc.y / size.height; + if (radians >= -Math.PI / 4 && radians < Math.PI / 4) { + // right + xIndex = (startLoc.x / size.width) + 1; + yIndex = startLoc.y / size.height; + } else { + if (radians >= -3 * Math.PI / 4 && radians < -Math.PI / 4) { + // down + xIndex = startLoc.x / size.width; + yIndex = (startLoc.y / size.height) + 1; + } else { + // left + xIndex = (startLoc.x / size.width) - 1; + yIndex = startLoc.y / size.height; + } + } } - } + return (TreeTentElementView) boardView.getElement(xIndex - 1, yIndex - 1); } - return (TreeTentElementView) boardView.getElement(xIndex - 1, yIndex - 1); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java index 94381b031..68c97865d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java @@ -7,82 +7,82 @@ public class TreeTent extends Puzzle { - public TreeTent() { - super(); + public TreeTent() { + super(); - this.name = "TreeTent"; + this.name = "TreeTent"; - this.importer = new TreeTentImporter(this); - this.exporter = new TreeTentExporter(this); + this.importer = new TreeTentImporter(this); + this.exporter = new TreeTentExporter(this); - this.factory = new TreeTentCellFactory(); - } + this.factory = new TreeTentCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - TreeTentBoard board = (TreeTentBoard) currentBoard; - boardView = new TreeTentView((TreeTentBoard) currentBoard); - boardView.setBoard(board); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + TreeTentBoard board = (TreeTentBoard) currentBoard; + boardView = new TreeTentView((TreeTentBoard) currentBoard); + boardView.setBoard(board); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Tree Tent - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Tree Tent, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - return rows > 0 && columns > 0; - } + @Override + /** + * Determines if the given dimensions are valid for Tree Tent + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Tree Tent, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + return rows > 0 && columns > 0; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} - /** - * @return if it is valid TreeTent puzzle must have same number of clues as the dimension size - */ - @Override - public boolean checkValidity() { - TreeTentBoard b = (TreeTentBoard) this.getBoardView().getBoard(); - List elements = b.getPuzzleElements(); - int treeCount = 0; - for (PuzzleElement element : elements) { - TreeTentCell c = (TreeTentCell) element; - if (c.getType() == TreeTentType.TREE) { - treeCount++; - } + /** + * @return if it is valid TreeTent puzzle must have same number of clues as the dimension size + */ + @Override + public boolean checkValidity() { + TreeTentBoard b = (TreeTentBoard) this.getBoardView().getBoard(); + List elements = b.getPuzzleElements(); + int treeCount = 0; + for (PuzzleElement element : elements) { + TreeTentCell c = (TreeTentCell) element; + if (c.getType() == TreeTentType.TREE) { + treeCount++; + } + } + return treeCount != 0; } - return treeCount != 0; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java index ac1dcca38..09706f92a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java @@ -9,234 +9,234 @@ public class TreeTentBoard extends GridBoard { - private ArrayList lines; + private ArrayList lines; - private ArrayList rowClues; - private ArrayList colClues; + private ArrayList rowClues; + private ArrayList colClues; - public TreeTentBoard(int width, int height) { - super(width, height); + public TreeTentBoard(int width, int height) { + super(width, height); - this.lines = new ArrayList<>(); + this.lines = new ArrayList<>(); - this.rowClues = new ArrayList<>(); - this.colClues = new ArrayList<>(); + this.rowClues = new ArrayList<>(); + this.colClues = new ArrayList<>(); - for (int i = 0; i < height; i++) { - rowClues.add(null); - } - for (int i = 0; i < width; i++) { - colClues.add(null); - } - } - - public TreeTentBoard(int size) { - this(size, size); - } - - public ArrayList getLines() { - return lines; - } - - public ArrayList getRowClues() { - return rowClues; - } - - public ArrayList getColClues() { - return colClues; - } - - @Override - public TreeTentCell getCell(int x, int y) { - return (TreeTentCell) super.getCell(x, y); - } - - @Override - public PuzzleElement getPuzzleElement(PuzzleElement element) { - switch (element.getIndex()) { - case -2: - return element; - case -1: - TreeTentLine line = (TreeTentLine) element; - TreeTentLine thisLine = null; - for (TreeTentLine l : lines) { - if (line.compare(l)) { - thisLine = l; - break; - } - } - return thisLine; - default: - return super.getPuzzleElement(element); - } - } - - public TreeTentClue getClue(int x, int y) { - if (x == getWidth() && 0 <= y && y < getHeight()) { - return rowClues.get(y); - } else { - if (y == getHeight() && 0 <= x && x < getWidth()) { - return colClues.get(x); - } - } - return null; - } - - /** - * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element - * with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - @Override - public void notifyAddition(PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - lines.add((TreeTentLine) puzzleElement); - } - } - - /** - * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle - * element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - @Override - public void notifyDeletion(PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - for (TreeTentLine line : lines) { - if (line.compare((TreeTentLine) puzzleElement)) { - lines.remove(line); - break; - } - } - } - } - - /** - * Get a list of all orthogonally adjacent cells. - * - * @param cell The cell to get adjacent cells from. - * @param type The cell types to get. - * @return List of adjacent cells in the form { up, right, down, left }. If an adjacent cell is - * null, it will not be added to the list. - */ - public List getAdjacent(TreeTentCell cell, TreeTentType type) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - for (int i = -2; i < 2; i++) { - TreeTentCell adjCell = getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); - if (adjCell != null && adjCell.getType() == type) { - adj.add(adjCell); - } + for (int i = 0; i < height; i++) { + rowClues.add(null); + } + for (int i = 0; i < width; i++) { + colClues.add(null); + } } - return adj; - } - - /** - * Gets all cells of a specified type that are diagonals of a specified cell - * - * @param cell the base cell - * @param type the type to look for - * @return a list of TreeTentCells that are diagonals of the given TreeTentCell and are of the - * given TreeTentType - */ - public List getDiagonals(TreeTentCell cell, TreeTentType type) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - TreeTentCell upRight = getCell(loc.x + 1, loc.y - 1); - TreeTentCell downRight = getCell(loc.x + 1, loc.y + 1); - TreeTentCell downLeft = getCell(loc.x - 1, loc.y + 1); - TreeTentCell upLeft = getCell(loc.x - 1, loc.y - 1); - if (upRight != null && upRight.getType() == type) { - dia.add(upRight); + + public TreeTentBoard(int size) { + this(size, size); } - if (downLeft != null && downLeft.getType() == type) { - dia.add(downLeft); + + public ArrayList getLines() { + return lines; } - if (downRight != null && downRight.getType() == type) { - dia.add(downRight); + + public ArrayList getRowClues() { + return rowClues; } - if (upLeft != null && upLeft.getType() == type) { - dia.add(upLeft); + + public ArrayList getColClues() { + return colClues; } - return dia; - } - - /** - * Creates and returns a list of TreeTentCells that match the given TreeTentType - * - * @param index the row or column number - * @param type type of TreeTent element - * @param isRow boolean value beased on whether a row of column is being checked - * @return List of TreeTentCells that match the given TreeTentType - */ - public List getRowCol(int index, TreeTentType type, boolean isRow) { - List list = new ArrayList<>(); - if (isRow) { - for (int i = 0; i < dimension.height; i++) { - TreeTentCell cell = getCell(i, index); - if (cell.getType() == type) { - list.add(cell); - } - } - } else { - for (int i = 0; i < dimension.width; i++) { - TreeTentCell cell = getCell(index, i); - if (cell.getType() == type) { - list.add(cell); - } - } + + @Override + public TreeTentCell getCell(int x, int y) { + return (TreeTentCell) super.getCell(x, y); } - return list; - } - - /** - * Determines if this board contains the equivalent puzzle elements as the one specified - * - * @param board board to check equivalence - * @return true if the boards are equivalent, false otherwise - */ - @Override - public boolean equalsBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - for (TreeTentLine l1 : lines) { - boolean hasLine = false; - for (TreeTentLine l2 : treeTentBoard.lines) { - if (l1.compare(l2)) { - hasLine = true; - } - } - if (!hasLine) { - return false; - } + + @Override + public PuzzleElement getPuzzleElement(PuzzleElement element) { + switch (element.getIndex()) { + case -2: + return element; + case -1: + TreeTentLine line = (TreeTentLine) element; + TreeTentLine thisLine = null; + for (TreeTentLine l : lines) { + if (line.compare(l)) { + thisLine = l; + break; + } + } + return thisLine; + default: + return super.getPuzzleElement(element); + } } - return super.equalsBoard(treeTentBoard); - } - - /** - * Performs a deep copy of the TreeTentBoard - * - * @return a TreeTentBoard object that is a deep copy of the current TreeTentBoard - */ - @Override - public TreeTentBoard copy() { - TreeTentBoard copy = new TreeTentBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + + public TreeTentClue getClue(int x, int y) { + if (x == getWidth() && 0 <= y && y < getHeight()) { + return rowClues.get(y); + } else { + if (y == getHeight() && 0 <= x && x < getWidth()) { + return colClues.get(x); + } + } + return null; + } + + /** + * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + @Override + public void notifyAddition(PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + lines.add((TreeTentLine) puzzleElement); + } } - for (TreeTentLine line : lines) { - TreeTentLine lineCpy = line.copy(); - lineCpy.setModifiable(false); - copy.getLines().add(lineCpy); + + /** + * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + @Override + public void notifyDeletion(PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + for (TreeTentLine line : lines) { + if (line.compare((TreeTentLine) puzzleElement)) { + lines.remove(line); + break; + } + } + } } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + /** + * Get a list of all orthogonally adjacent cells. + * + * @param cell The cell to get adjacent cells from. + * @param type The cell types to get. + * @return List of adjacent cells in the form { up, right, down, left }. If an adjacent cell is + * null, it will not be added to the list. + */ + public List getAdjacent(TreeTentCell cell, TreeTentType type) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + for (int i = -2; i < 2; i++) { + TreeTentCell adjCell = getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); + if (adjCell != null && adjCell.getType() == type) { + adj.add(adjCell); + } + } + return adj; + } + + /** + * Gets all cells of a specified type that are diagonals of a specified cell + * + * @param cell the base cell + * @param type the type to look for + * @return a list of TreeTentCells that are diagonals of the given TreeTentCell and are of the + * given TreeTentType + */ + public List getDiagonals(TreeTentCell cell, TreeTentType type) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + TreeTentCell upRight = getCell(loc.x + 1, loc.y - 1); + TreeTentCell downRight = getCell(loc.x + 1, loc.y + 1); + TreeTentCell downLeft = getCell(loc.x - 1, loc.y + 1); + TreeTentCell upLeft = getCell(loc.x - 1, loc.y - 1); + if (upRight != null && upRight.getType() == type) { + dia.add(upRight); + } + if (downLeft != null && downLeft.getType() == type) { + dia.add(downLeft); + } + if (downRight != null && downRight.getType() == type) { + dia.add(downRight); + } + if (upLeft != null && upLeft.getType() == type) { + dia.add(upLeft); + } + return dia; + } + + /** + * Creates and returns a list of TreeTentCells that match the given TreeTentType + * + * @param index the row or column number + * @param type type of TreeTent element + * @param isRow boolean value beased on whether a row of column is being checked + * @return List of TreeTentCells that match the given TreeTentType + */ + public List getRowCol(int index, TreeTentType type, boolean isRow) { + List list = new ArrayList<>(); + if (isRow) { + for (int i = 0; i < dimension.height; i++) { + TreeTentCell cell = getCell(i, index); + if (cell.getType() == type) { + list.add(cell); + } + } + } else { + for (int i = 0; i < dimension.width; i++) { + TreeTentCell cell = getCell(index, i); + if (cell.getType() == type) { + list.add(cell); + } + } + } + return list; + } + + /** + * Determines if this board contains the equivalent puzzle elements as the one specified + * + * @param board board to check equivalence + * @return true if the boards are equivalent, false otherwise + */ + @Override + public boolean equalsBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + for (TreeTentLine l1 : lines) { + boolean hasLine = false; + for (TreeTentLine l2 : treeTentBoard.lines) { + if (l1.compare(l2)) { + hasLine = true; + } + } + if (!hasLine) { + return false; + } + } + return super.equalsBoard(treeTentBoard); + } + + /** + * Performs a deep copy of the TreeTentBoard + * + * @return a TreeTentBoard object that is a deep copy of the current TreeTentBoard + */ + @Override + public TreeTentBoard copy() { + TreeTentBoard copy = new TreeTentBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (TreeTentLine line : lines) { + TreeTentLine lineCpy = line.copy(); + lineCpy.setModifiable(false); + copy.getLines().add(lineCpy); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.rowClues = rowClues; + copy.colClues = colClues; + return copy; } - copy.rowClues = rowClues; - copy.colClues = colClues; - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java index e19c8b3a2..c7c9f0d21 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java @@ -7,50 +7,50 @@ public class TreeTentCell extends GridCell { - public TreeTentCell(TreeTentType value, Point location) { - super(value, location); - } + public TreeTentCell(TreeTentType value, Point location) { + super(value, location); + } - public TreeTentType getType() { - return data; - } + public TreeTentType getType() { + return data; + } - public int getValue() { - switch (data) { - case TREE: - return 1; - case GRASS: - return 2; - case TENT: - return 3; - default: - return 0; + public int getValue() { + switch (data) { + case TREE: + return 1; + case GRASS: + return 2; + case TENT: + return 3; + default: + return 0; + } } - } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementName()) { - case "Unknown Tile": - this.data = TreeTentType.UNKNOWN; - break; - case "Tree Tile": - this.data = TreeTentType.TREE; - break; - case "Grass Tile": - this.data = TreeTentType.GRASS; - break; - case "Tent Tile": - this.data = TreeTentType.TENT; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementName()) { + case "Unknown Tile": + this.data = TreeTentType.UNKNOWN; + break; + case "Tree Tile": + this.data = TreeTentType.TREE; + break; + case "Grass Tile": + this.data = TreeTentType.GRASS; + break; + case "Tent Tile": + this.data = TreeTentType.TENT; + } } - } - @Override - public TreeTentCell copy() { - TreeTentCell copy = new TreeTentCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public TreeTentCell copy() { + TreeTentCell copy = new TreeTentCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java index 10bcf77c7..1697b8bd5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java @@ -10,92 +10,94 @@ import org.w3c.dom.Node; public class TreeTentCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - int width = treeTentBoard.getWidth(); - int height = treeTentBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - if (node.getNodeName().equalsIgnoreCase("cell")) { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { + try { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + int width = treeTentBoard.getWidth(); + int height = treeTentBoard.getHeight(); + NamedNodeMap attributeList = node.getAttributes(); + if (node.getNodeName().equalsIgnoreCase("cell")) { - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("TreeTent Factory: cell location out of bounds"); - } - if (value < 0 || value > 3) { - throw new InvalidFileFormatException("TreeTent Factory: cell unknown value"); - } + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "TreeTent Factory: cell location out of bounds"); + } + if (value < 0 || value > 3) { + throw new InvalidFileFormatException("TreeTent Factory: cell unknown value"); + } - TreeTentCell cell = new TreeTentCell(TreeTentType.valueOf(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } else { - if (node.getNodeName().equalsIgnoreCase("line")) { - int x1 = Integer.valueOf(attributeList.getNamedItem("x1").getNodeValue()); - int y1 = Integer.valueOf(attributeList.getNamedItem("y1").getNodeValue()); - int x2 = Integer.valueOf(attributeList.getNamedItem("x2").getNodeValue()); - int y2 = Integer.valueOf(attributeList.getNamedItem("y2").getNodeValue()); - if (x1 >= width || y1 >= height || x2 >= width || y2 >= height) { - throw new InvalidFileFormatException("TreeTent Factory: line location out of bounds"); - } + TreeTentCell cell = new TreeTentCell(TreeTentType.valueOf(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } else { + if (node.getNodeName().equalsIgnoreCase("line")) { + int x1 = Integer.valueOf(attributeList.getNamedItem("x1").getNodeValue()); + int y1 = Integer.valueOf(attributeList.getNamedItem("y1").getNodeValue()); + int x2 = Integer.valueOf(attributeList.getNamedItem("x2").getNodeValue()); + int y2 = Integer.valueOf(attributeList.getNamedItem("y2").getNodeValue()); + if (x1 >= width || y1 >= height || x2 >= width || y2 >= height) { + throw new InvalidFileFormatException( + "TreeTent Factory: line location out of bounds"); + } - TreeTentCell c1 = treeTentBoard.getCell(x1, y1); - TreeTentCell c2 = treeTentBoard.getCell(x2, y2); - return new TreeTentLine(c1, c2); - } else { - throw new InvalidFileFormatException( - "TreeTent Factory: unknown puzzleElement puzzleElement"); + TreeTentCell c1 = treeTentBoard.getCell(x1, y1); + TreeTentCell c2 = treeTentBoard.getCell(x2, y2); + return new TreeTentLine(c1, c2); + } else { + throw new InvalidFileFormatException( + "TreeTent Factory: unknown puzzleElement puzzleElement"); + } + } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "TreeTent Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("TreeTent Factory: could not find attribute(s)"); } - } - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "TreeTent Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("TreeTent Factory: could not find attribute(s)"); } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentCell) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentCell) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); + TreeTentCell cell = (TreeTentCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getValue())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getValue())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } else { - org.w3c.dom.Element lineElement = document.createElement("line"); + return cellElement; + } else { + org.w3c.dom.Element lineElement = document.createElement("line"); - TreeTentLine line = (TreeTentLine) puzzleElement; + TreeTentLine line = (TreeTentLine) puzzleElement; - lineElement.setAttribute("x1", String.valueOf(line.getC1().getLocation().x)); - lineElement.setAttribute("y1", String.valueOf(line.getC1().getLocation().y)); - lineElement.setAttribute("x2", String.valueOf(line.getC2().getLocation().x)); - lineElement.setAttribute("y2", String.valueOf(line.getC2().getLocation().y)); + lineElement.setAttribute("x1", String.valueOf(line.getC1().getLocation().x)); + lineElement.setAttribute("y1", String.valueOf(line.getC1().getLocation().y)); + lineElement.setAttribute("x2", String.valueOf(line.getC2().getLocation().x)); + lineElement.setAttribute("y2", String.valueOf(line.getC2().getLocation().y)); - return lineElement; + return lineElement; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java index df9e7eed2..bcba7dc94 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java @@ -3,53 +3,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class TreeTentClue extends PuzzleElement { - private TreeTentType type; - private int clueIndex; - - public TreeTentClue(int value, int clueIndex, TreeTentType type) { - super(value); - this.index = -2; - this.clueIndex = clueIndex; - this.type = type; - } - - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; - } - return sb.reverse().toString(); - } - - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; - } - return result; - } - - public int getClueIndex() { - return clueIndex; - } - - public void setClueIndex(int clueIndex) { - this.clueIndex = clueIndex; - } - - public TreeTentType getType() { - return type; - } - - public void setType(TreeTentType type) { - this.type = type; - } - - public TreeTentClue copy() { - return null; - } + private TreeTentType type; + private int clueIndex; + + public TreeTentClue(int value, int clueIndex, TreeTentType type) { + super(value); + this.index = -2; + this.clueIndex = clueIndex; + this.type = type; + } + + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; + } + return sb.reverse().toString(); + } + + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; + } + return result; + } + + public int getClueIndex() { + return clueIndex; + } + + public void setClueIndex(int clueIndex) { + this.clueIndex = clueIndex; + } + + public TreeTentType getType() { + return type; + } + + public void setType(TreeTentType type) { + this.type = type; + } + + public TreeTentClue copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java index e59c86f62..d1b230d20 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java @@ -5,50 +5,50 @@ public class TreeTentClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public TreeTentClueView(TreeTentClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public TreeTentClue getPuzzleElement() { - return (TreeTentClue) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - TreeTentClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - value = String.valueOf(clue.getData() + 1); - break; - case CLUE_EAST: - value = String.valueOf(clue.getData()); - break; - case CLUE_SOUTH: - value = String.valueOf(clue.getData()); - break; - case CLUE_WEST: - value = TreeTentClue.colNumToString(clue.getData() + 1); - break; - default: - value = ""; + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public TreeTentClueView(TreeTentClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public TreeTentClue getPuzzleElement() { + return (TreeTentClue) super.getPuzzleElement(); } - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + TreeTentClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + value = String.valueOf(clue.getData() + 1); + break; + case CLUE_EAST: + value = String.valueOf(clue.getData()); + break; + case CLUE_SOUTH: + value = String.valueOf(clue.getData()); + break; + case CLUE_WEST: + value = TreeTentClue.colNumToString(clue.getData() + 1); + break; + default: + value = ""; + } + + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java index d3a4b3d26..79e074657 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java @@ -19,115 +19,120 @@ public class TreeTentController extends ElementController { - private ElementView lastCellPressed; - private ElementView dragStart; + private ElementView lastCellPressed; + private ElementView dragStart; - public TreeTentController() { - super(); - this.dragStart = null; - this.lastCellPressed = null; - } + public TreeTentController() { + super(); + this.dragStart = null; + this.lastCellPressed = null; + } - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() != MouseEvent.BUTTON2) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - dragStart = boardView.getElement(e.getPoint()); - lastCellPressed = boardView.getElement(e.getPoint()); + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() != MouseEvent.BUTTON2) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + dragStart = boardView.getElement(e.getPoint()); + lastCellPressed = boardView.getElement(e.getPoint()); + } } - } - @Override - public void mouseReleased(MouseEvent e) { - if (GameBoardFacade.getInstance().getLegupUI().getTreePanel() != null - && e.getButton() != MouseEvent.BUTTON2) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - lastCellPressed = boardView.getElement(e.getPoint()); - Board board = boardView.getBoard(); - TreeViewSelection selection = treeView.getSelection(); + @Override + public void mouseReleased(MouseEvent e) { + if (GameBoardFacade.getInstance().getLegupUI().getTreePanel() != null + && e.getButton() != MouseEvent.BUTTON2) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = + GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + lastCellPressed = boardView.getElement(e.getPoint()); + Board board = boardView.getBoard(); + TreeViewSelection selection = treeView.getSelection(); - if (dragStart != null) { - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - AutoCaseRuleCommand autoCaseRuleCommand = - new AutoCaseRuleCommand(dragStart, selection, caseBoard.getCaseRule(), caseBoard, e); - if (autoCaseRuleCommand.canExecute()) { - autoCaseRuleCommand.execute(); - getInstance().getHistory().pushChange(autoCaseRuleCommand); - treePanel.updateError(""); - } else { - treePanel.updateError(autoCaseRuleCommand.getError()); - } - } else { - if (dragStart == lastCellPressed) { - if (dragStart.getPuzzleElement().getIndex() >= 0) { - ICommand edit = new EditDataCommand(lastCellPressed, selection, e); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - treePanel.updateError(""); - } else { - treePanel.updateError(edit.getError()); - } - } else { - ClueCommand edit = new ClueCommand(selection, (TreeTentClueView) dragStart); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - treePanel.updateError(""); - } else { - treePanel.updateError(edit.getError()); - } - } - } else { - if (lastCellPressed != null) { - if (dragStart instanceof TreeTentElementView) { - ICommand editLine = - new EditLineCommand( - selection, (TreeTentElementView) dragStart, lastCellPressed); - if (editLine.canExecute()) { - editLine.execute(); - getInstance().getHistory().pushChange(editLine); + if (dragStart != null) { + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + AutoCaseRuleCommand autoCaseRuleCommand = + new AutoCaseRuleCommand( + dragStart, selection, caseBoard.getCaseRule(), caseBoard, e); + if (autoCaseRuleCommand.canExecute()) { + autoCaseRuleCommand.execute(); + getInstance().getHistory().pushChange(autoCaseRuleCommand); + treePanel.updateError(""); + } else { + treePanel.updateError(autoCaseRuleCommand.getError()); + } } else { - treePanel.updateError(editLine.getError()); + if (dragStart == lastCellPressed) { + if (dragStart.getPuzzleElement().getIndex() >= 0) { + ICommand edit = new EditDataCommand(lastCellPressed, selection, e); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + treePanel.updateError(""); + } else { + treePanel.updateError(edit.getError()); + } + } else { + ClueCommand edit = + new ClueCommand(selection, (TreeTentClueView) dragStart); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + treePanel.updateError(""); + } else { + treePanel.updateError(edit.getError()); + } + } + } else { + if (lastCellPressed != null) { + if (dragStart instanceof TreeTentElementView) { + ICommand editLine = + new EditLineCommand( + selection, + (TreeTentElementView) dragStart, + lastCellPressed); + if (editLine.canExecute()) { + editLine.execute(); + getInstance().getHistory().pushChange(editLine); + } else { + treePanel.updateError(editLine.getError()); + } + } + } + } } - } } - } + dragStart = null; + lastCellPressed = null; } - } - dragStart = null; - lastCellPressed = null; } - } - @Override - public void changeCell(MouseEvent e, PuzzleElement element) { - TreeTentCell cell = (TreeTentCell) element; - if (e.getButton() == MouseEvent.BUTTON1) { - if (cell.getData() == TreeTentType.UNKNOWN) { - element.setData(TreeTentType.GRASS); - } else { - if (cell.getData() == TreeTentType.GRASS) { - element.setData(TreeTentType.TENT); - } else { - element.setData(TreeTentType.UNKNOWN); - } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == TreeTentType.UNKNOWN) { - element.setData(TreeTentType.TENT); + @Override + public void changeCell(MouseEvent e, PuzzleElement element) { + TreeTentCell cell = (TreeTentCell) element; + if (e.getButton() == MouseEvent.BUTTON1) { + if (cell.getData() == TreeTentType.UNKNOWN) { + element.setData(TreeTentType.GRASS); + } else { + if (cell.getData() == TreeTentType.GRASS) { + element.setData(TreeTentType.TENT); + } else { + element.setData(TreeTentType.UNKNOWN); + } + } } else { - if (cell.getData() == TreeTentType.GRASS) { - element.setData(TreeTentType.UNKNOWN); - } else { - element.setData(TreeTentType.GRASS); - } + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == TreeTentType.UNKNOWN) { + element.setData(TreeTentType.TENT); + } else { + if (cell.getData() == TreeTentType.GRASS) { + element.setData(TreeTentType.UNKNOWN); + } else { + element.setData(TreeTentType.GRASS); + } + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java index 740ea5ea8..1196ab075 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java @@ -5,51 +5,69 @@ import java.awt.geom.Rectangle2D; public class TreeTentElementView extends GridElementView { - public TreeTentElementView(TreeTentCell cell) { - super(cell); - } + public TreeTentElementView(TreeTentCell cell) { + super(cell); + } - /** - * Draws on the given frame based on the type of the cell of the current puzzleElement - * - * @param graphics2D the frame to be drawn on - */ - @Override - public void drawElement(Graphics2D graphics2D) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - TreeTentType type = cell.getType(); - graphics2D.setStroke(new BasicStroke(0)); - if (type == TreeTentType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fill( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); - graphics2D.setColor(Color.BLACK); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); - } else { - if (type == TreeTentType.TREE) { - graphics2D.drawImage( - TreeTentView.TREE, location.x, location.y, size.width, size.height, null, null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == TreeTentType.GRASS) { - graphics2D.drawImage( - TreeTentView.GRASS, location.x, location.y, size.width, size.height, null, null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == TreeTentType.TENT) { - graphics2D.drawImage( - TreeTentView.TENT, location.x, location.y, size.width, size.height, null, null); + /** + * Draws on the given frame based on the type of the cell of the current puzzleElement + * + * @param graphics2D the frame to be drawn on + */ + @Override + public void drawElement(Graphics2D graphics2D) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + TreeTentType type = cell.getType(); + graphics2D.setStroke(new BasicStroke(0)); + if (type == TreeTentType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fill( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } + graphics2D.draw( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); + } else { + if (type == TreeTentType.TREE) { + graphics2D.drawImage( + TreeTentView.TREE, + location.x, + location.y, + size.width, + size.height, + null, + null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == TreeTentType.GRASS) { + graphics2D.drawImage( + TreeTentView.GRASS, + location.x, + location.y, + size.width, + size.height, + null, + null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == TreeTentType.TENT) { + graphics2D.drawImage( + TreeTentView.TENT, + location.x, + location.y, + size.width, + size.height, + null, + null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java index 621ea0a38..475aaab1e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java @@ -6,68 +6,68 @@ public class TreeTentExporter extends PuzzleExporter { - public TreeTentExporter(TreeTent treeTent) { - super(treeTent); - } - - /** - * Creates and returns a new board element in the XML document specified - * - * @param newDocument the XML document to append to - * @return the new board element - */ - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - TreeTentBoard board; - if (puzzle.getTree() != null) { - board = (TreeTentBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (TreeTentBoard) puzzle.getBoardView().getBoard(); + public TreeTentExporter(TreeTent treeTent) { + super(treeTent); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + /** + * Creates and returns a new board element in the XML document specified + * + * @param newDocument the XML document to append to + * @return the new board element + */ + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + TreeTentBoard board; + if (puzzle.getTree() != null) { + board = (TreeTentBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (TreeTentBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getData() != TreeTentType.UNKNOWN) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (TreeTentClue clue : board.getRowClues()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", TreeTentClue.colNumToString(clue.getClueIndex())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getData() != TreeTentType.UNKNOWN) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (TreeTentClue clue : board.getRowClues()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", String.valueOf(clue.getClueIndex())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (TreeTentClue clue : board.getRowClues()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", TreeTentClue.colNumToString(clue.getClueIndex())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); + + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (TreeTentClue clue : board.getRowClues()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", String.valueOf(clue.getClueIndex())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); - if (!board.getLines().isEmpty()) { - org.w3c.dom.Element linesElement = newDocument.createElement("lines"); - for (PuzzleElement data : board.getLines()) { - org.w3c.dom.Element lineElement = puzzle.getFactory().exportCell(newDocument, data); - linesElement.appendChild(lineElement); - } - boardElement.appendChild(linesElement); + if (!board.getLines().isEmpty()) { + org.w3c.dom.Element linesElement = newDocument.createElement("lines"); + for (PuzzleElement data : board.getLines()) { + org.w3c.dom.Element lineElement = puzzle.getFactory().exportCell(newDocument, data); + linesElement.appendChild(lineElement); + } + boardElement.appendChild(linesElement); + } + return boardElement; } - return boardElement; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java index a446d96cd..0117f41ce 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java @@ -8,202 +8,212 @@ import org.w3c.dom.NodeList; public class TreeTentImporter extends PuzzleImporter { - public TreeTentImporter(TreeTent treeTent) { - super(treeTent); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } - - @Override - public boolean acceptsTextInput() { - return false; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - TreeTentBoard treeTentBoard = new TreeTentBoard(columns, rows); - - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - if (treeTentBoard.getCell(x, y) == null) { - TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - treeTentBoard.setCell(x, y, cell); - } - } + public TreeTentImporter(TreeTent treeTent) { + super(treeTent); } - for (int i = 0; i < rows; i++) { - treeTentBoard.getRowClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_EAST)); + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; } - for (int i = 0; i < columns; i++) { - treeTentBoard.getColClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_SOUTH)); + @Override + public boolean acceptsTextInput() { + return false; } - puzzle.setCurrentBoard(treeTentBoard); - } - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("TreeTent Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("TreeTent Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - TreeTentBoard treeTentBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - treeTentBoard = new TreeTentBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - treeTentBoard = new TreeTentBoard(width, height); - } - } - - if (treeTentBoard == null) { - throw new InvalidFileFormatException("TreeTent Importer: invalid board dimensions"); - } - - int width = treeTentBoard.getWidth(); - int height = treeTentBoard.getHeight(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - TreeTentCell cell = - (TreeTentCell) puzzle.getFactory().importCell(elementDataList.item(i), treeTentBoard); - Point loc = cell.getLocation(); - if (cell.getData() != TreeTentType.UNKNOWN) { - cell.setModifiable(false); - cell.setGiven(true); - } - treeTentBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (treeTentBoard.getCell(x, y) == null) { - TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - treeTentBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("TreeTent Importer: cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { - throw new InvalidFileFormatException( - "TreeTent Importer: side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "TreeTent Importer: axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != treeTentBoard.getHeight() - || southClues.getLength() != treeTentBoard.getWidth()) { - throw new InvalidFileFormatException( - "TreeTent Importer: there must be same number of clues as the dimension of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = TreeTentClue.colStringToColNum(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > treeTentBoard.getHeight()) { - throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + TreeTentBoard treeTentBoard = new TreeTentBoard(columns, rows); + + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + if (treeTentBoard.getCell(x, y) == null) { + TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + treeTentBoard.setCell(x, y, cell); + } + } } - if (treeTentBoard.getRowClues().get(index - 1) != null) { - throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); - } - treeTentBoard - .getRowClues() - .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > treeTentBoard.getWidth()) { - throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); + for (int i = 0; i < rows; i++) { + treeTentBoard.getRowClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_EAST)); } - if (treeTentBoard.getColClues().get(index - 1) != null) { - throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); + for (int i = 0; i < columns; i++) { + treeTentBoard.getColClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_SOUTH)); } - treeTentBoard - .getColClues() - .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_SOUTH)); - } - - if (boardElement.getElementsByTagName("lines").getLength() == 1) { - Element linesElement = (Element) boardElement.getElementsByTagName("lines").item(0); - NodeList linesList = linesElement.getElementsByTagName("line"); - for (int i = 0; i < linesList.getLength(); i++) { - treeTentBoard - .getLines() - .add((TreeTentLine) puzzle.getFactory().importCell(linesList.item(i), treeTentBoard)); - } - } - puzzle.setCurrentBoard(treeTentBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "TreeTent Importer: unknown value where integer expected"); + puzzle.setCurrentBoard(treeTentBoard); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Tree Tent cannot accept text input"); - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "TreeTent Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "TreeTent Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + TreeTentBoard treeTentBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + treeTentBoard = new TreeTentBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + treeTentBoard = new TreeTentBoard(width, height); + } + } + + if (treeTentBoard == null) { + throw new InvalidFileFormatException("TreeTent Importer: invalid board dimensions"); + } + + int width = treeTentBoard.getWidth(); + int height = treeTentBoard.getHeight(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + TreeTentCell cell = + (TreeTentCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), treeTentBoard); + Point loc = cell.getLocation(); + if (cell.getData() != TreeTentType.UNKNOWN) { + cell.setModifiable(false); + cell.setGiven(true); + } + treeTentBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (treeTentBoard.getCell(x, y) == null) { + TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + treeTentBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("TreeTent Importer: cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { + throw new InvalidFileFormatException( + "TreeTent Importer: side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "TreeTent Importer: axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != treeTentBoard.getHeight() + || southClues.getLength() != treeTentBoard.getWidth()) { + throw new InvalidFileFormatException( + "TreeTent Importer: there must be same number of clues as the dimension of" + + " the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = TreeTentClue.colStringToColNum(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > treeTentBoard.getHeight()) { + throw new InvalidFileFormatException( + "TreeTent Importer: clue index out of bounds"); + } + + if (treeTentBoard.getRowClues().get(index - 1) != null) { + throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); + } + treeTentBoard + .getRowClues() + .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > treeTentBoard.getWidth()) { + throw new InvalidFileFormatException( + "TreeTent Importer: clue index out of bounds"); + } + + if (treeTentBoard.getColClues().get(index - 1) != null) { + throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); + } + treeTentBoard + .getColClues() + .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_SOUTH)); + } + + if (boardElement.getElementsByTagName("lines").getLength() == 1) { + Element linesElement = (Element) boardElement.getElementsByTagName("lines").item(0); + NodeList linesList = linesElement.getElementsByTagName("line"); + for (int i = 0; i < linesList.getLength(); i++) { + treeTentBoard + .getLines() + .add( + (TreeTentLine) + puzzle.getFactory() + .importCell(linesList.item(i), treeTentBoard)); + } + } + + puzzle.setCurrentBoard(treeTentBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "TreeTent Importer: unknown value where integer expected"); + } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Tree Tent cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java index bc252b0ba..dae10a1ae 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java @@ -5,40 +5,40 @@ public class TreeTentLine extends PuzzleElement> { - public TreeTentLine(TreeTentCell c1, TreeTentCell c2) { - this.data = new Entry<>(c1, c2); - } - - public TreeTentCell getC1() { - return data.getKey(); - } - - public void setC1(TreeTentCell c1) { - this.data.setKey(c1); - } - - public TreeTentCell getC2() { - return data.getValue(); - } - - public void setC2(TreeTentCell c2) { - this.data.setValue(c2); - } - - public boolean compare(TreeTentLine line) { - return ((line.getC1().getLocation().equals(data.getKey().getLocation()) - && line.getC2().getLocation().equals(data.getValue().getLocation())) - || (line.getC1().getLocation().equals(data.getValue().getLocation()) - && line.getC2().getLocation().equals(data.getKey().getLocation()))); - } - - /** - * Copies this elements puzzleElement to a new PuzzleElement object - * - * @return copied PuzzleElement object - */ - @Override - public TreeTentLine copy() { - return new TreeTentLine(data.getKey().copy(), data.getValue().copy()); - } + public TreeTentLine(TreeTentCell c1, TreeTentCell c2) { + this.data = new Entry<>(c1, c2); + } + + public TreeTentCell getC1() { + return data.getKey(); + } + + public void setC1(TreeTentCell c1) { + this.data.setKey(c1); + } + + public TreeTentCell getC2() { + return data.getValue(); + } + + public void setC2(TreeTentCell c2) { + this.data.setValue(c2); + } + + public boolean compare(TreeTentLine line) { + return ((line.getC1().getLocation().equals(data.getKey().getLocation()) + && line.getC2().getLocation().equals(data.getValue().getLocation())) + || (line.getC1().getLocation().equals(data.getValue().getLocation()) + && line.getC2().getLocation().equals(data.getKey().getLocation()))); + } + + /** + * Copies this elements puzzleElement to a new PuzzleElement object + * + * @return copied PuzzleElement object + */ + @Override + public TreeTentLine copy() { + return new TreeTentLine(data.getKey().copy(), data.getValue().copy()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java index b2e6ed7b5..6d478cff8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java @@ -4,28 +4,28 @@ import java.awt.*; public class TreeTentLineView extends ElementView { - private final Color LINE_COLOR = Color.GREEN; + private final Color LINE_COLOR = Color.GREEN; - private final Stroke LINE_STROKE = new BasicStroke(2); + private final Stroke LINE_STROKE = new BasicStroke(2); - public TreeTentLineView(TreeTentLine line) { - super(line); - } + public TreeTentLineView(TreeTentLine line) { + super(line); + } - @Override - public void draw(Graphics2D graphics2D) { + @Override + public void draw(Graphics2D graphics2D) { - TreeTentLine line = (TreeTentLine) puzzleElement; - Point p1 = line.getC1().getLocation(); - Point p2 = line.getC2().getLocation(); - int x1 = (p1.x + 1) * size.width + size.width / 2; - int y1 = (p1.y + 1) * size.height + size.height / 2; + TreeTentLine line = (TreeTentLine) puzzleElement; + Point p1 = line.getC1().getLocation(); + Point p2 = line.getC2().getLocation(); + int x1 = (p1.x + 1) * size.width + size.width / 2; + int y1 = (p1.y + 1) * size.height + size.height / 2; - int x2 = (p2.x + 1) * size.width + size.width / 2; - int y2 = (p2.y + 1) * size.height + size.height / 2; - // graphics2D.setColor(LINE_COLOR); - graphics2D.setColor(line.isModified() ? Color.GREEN : Color.WHITE); - graphics2D.setStroke(LINE_STROKE); - graphics2D.drawLine(x1, y1, x2, y2); - } + int x2 = (p2.x + 1) * size.width + size.width / 2; + int y2 = (p2.y + 1) * size.height + size.height / 2; + // graphics2D.setColor(LINE_COLOR); + graphics2D.setColor(line.isModified() ? Color.GREEN : Color.WHITE); + graphics2D.setStroke(LINE_STROKE); + graphics2D.drawLine(x1, y1, x2, y2); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java index b1e480335..230283418 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java @@ -1,25 +1,25 @@ package edu.rpi.legup.puzzle.treetent; public enum TreeTentType { - UNKNOWN, - TREE, - GRASS, - TENT, - CLUE_NORTH, - CLUE_EAST, - CLUE_SOUTH, - CLUE_WEST; + UNKNOWN, + TREE, + GRASS, + TENT, + CLUE_NORTH, + CLUE_EAST, + CLUE_SOUTH, + CLUE_WEST; - public static TreeTentType valueOf(int num) { - switch (num) { - case 1: - return TREE; - case 2: - return GRASS; - case 3: - return TENT; - default: - return UNKNOWN; + public static TreeTentType valueOf(int num) { + switch (num) { + case 1: + return TREE; + case 2: + return GRASS; + case 3: + return TENT; + default: + return UNKNOWN; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java index 0973f9452..3b8cadad6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java @@ -14,201 +14,212 @@ import org.apache.logging.log4j.Logger; public class TreeTentView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(TreeTentView.class.getName()); - - static Image TREE, GRASS, TENT; - - static { - try { - TREE = - ImageIO.read( - ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tree.png")); - GRASS = - ImageIO.read( - ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/grass.png")); - TENT = - ImageIO.read( - ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tent.png")); - } catch (IOException e) { - LOGGER.error("Failed to open TreeTent images"); + private static final Logger LOGGER = LogManager.getLogger(TreeTentView.class.getName()); + + static Image TREE, GRASS, TENT; + + static { + try { + TREE = + ImageIO.read( + ClassLoader.getSystemResourceAsStream( + "edu/rpi/legup/images/treetent/tree.png")); + GRASS = + ImageIO.read( + ClassLoader.getSystemResourceAsStream( + "edu/rpi/legup/images/treetent/grass.png")); + TENT = + ImageIO.read( + ClassLoader.getSystemResourceAsStream( + "edu/rpi/legup/images/treetent/tent.png")); + } catch (IOException e) { + LOGGER.error("Failed to open TreeTent images"); + } + } + + private ArrayList lineViews; + + private ArrayList northClues; + private ArrayList eastClues; + private ArrayList southClues; + private ArrayList westClues; + + public TreeTentView(TreeTentBoard board) { + super(new BoardController(), new TreeTentController(), board.getDimension()); + + this.lineViews = new ArrayList<>(); + + this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + Point loc = cell.getLocation(); + TreeTentElementView elementView = new TreeTentElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); + elementViews.add(elementView); + } + + for (TreeTentLine line : board.getLines()) { + TreeTentLineView lineView = new TreeTentLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + + for (int i = 0; i < gridSize.height; i++) { + TreeTentClueView row = + new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_WEST)); + row.setLocation(new Point(0, (i + 1) * elementSize.height)); + row.setSize(elementSize); + + TreeTentClueView clue = new TreeTentClueView(board.getRowClues().get(i)); + clue.setLocation( + new Point( + (gridSize.width + 1) * elementSize.width, + (i + 1) * elementSize.height)); + clue.setSize(elementSize); + + westClues.add(row); + eastClues.add(clue); + } + + for (int i = 0; i < gridSize.width; i++) { + TreeTentClueView col = + new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_NORTH)); + col.setLocation(new Point((i + 1) * elementSize.width, 0)); + col.setSize(elementSize); + + TreeTentClueView clue = new TreeTentClueView(board.getColClues().get(i)); + clue.setLocation( + new Point( + (i + 1) * elementSize.width, + (gridSize.height + 1) * elementSize.height)); + clue.setSize(elementSize); + + northClues.add(col); + southClues.add(clue); + } + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + @Override + public ElementView getElement(Point point) { + Point scaledPoint = + new Point( + (int) Math.round(point.x / getScale()), + (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + for (TreeTentClueView clueView : northClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : eastClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : southClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : westClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + return null; + } + + public ArrayList getLineViews() { + return lineViews; + } + + public ArrayList getNorthClues() { + return northClues; + } + + public ArrayList getEastClues() { + return eastClues; + } + + public ArrayList getSouthClues() { + return southClues; + } + + public ArrayList getWestClues() { + return westClues; + } + + @Override + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = (gridSize.width + 2) * elementSize.width; + boardViewSize.height = (gridSize.height + 2) * elementSize.height; + return boardViewSize; + } + + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + super.onTreeElementChanged(treeElement); + TreeTentBoard treeTentBoard; + if (board instanceof CaseBoard) { + treeTentBoard = (TreeTentBoard) ((CaseBoard) board).getBaseBoard(); + } else { + treeTentBoard = (TreeTentBoard) board; + } + + lineViews.clear(); + for (TreeTentLine line : treeTentBoard.getLines()) { + TreeTentLineView lineView = new TreeTentLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + } + + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); + + for (TreeTentLineView view : lineViews) { + view.draw(graphics2D); + } + + for (TreeTentClueView clueView : northClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : eastClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : southClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : westClues) { + clueView.draw(graphics2D); + } } - } - - private ArrayList lineViews; - - private ArrayList northClues; - private ArrayList eastClues; - private ArrayList southClues; - private ArrayList westClues; - - public TreeTentView(TreeTentBoard board) { - super(new BoardController(), new TreeTentController(), board.getDimension()); - - this.lineViews = new ArrayList<>(); - - this.northClues = new ArrayList<>(); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - TreeTentElementView elementView = new TreeTentElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); - elementViews.add(elementView); - } - - for (TreeTentLine line : board.getLines()) { - TreeTentLineView lineView = new TreeTentLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - - for (int i = 0; i < gridSize.height; i++) { - TreeTentClueView row = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_WEST)); - row.setLocation(new Point(0, (i + 1) * elementSize.height)); - row.setSize(elementSize); - - TreeTentClueView clue = new TreeTentClueView(board.getRowClues().get(i)); - clue.setLocation( - new Point((gridSize.width + 1) * elementSize.width, (i + 1) * elementSize.height)); - clue.setSize(elementSize); - - westClues.add(row); - eastClues.add(clue); - } - - for (int i = 0; i < gridSize.width; i++) { - TreeTentClueView col = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_NORTH)); - col.setLocation(new Point((i + 1) * elementSize.width, 0)); - col.setSize(elementSize); - - TreeTentClueView clue = new TreeTentClueView(board.getColClues().get(i)); - clue.setLocation( - new Point((i + 1) * elementSize.width, (gridSize.height + 1) * elementSize.height)); - clue.setSize(elementSize); - - northClues.add(col); - southClues.add(clue); - } - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - @Override - public ElementView getElement(Point point) { - Point scaledPoint = - new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - for (TreeTentClueView clueView : northClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : eastClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : southClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : westClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - return null; - } - - public ArrayList getLineViews() { - return lineViews; - } - - public ArrayList getNorthClues() { - return northClues; - } - - public ArrayList getEastClues() { - return eastClues; - } - - public ArrayList getSouthClues() { - return southClues; - } - - public ArrayList getWestClues() { - return westClues; - } - - @Override - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = (gridSize.width + 2) * elementSize.width; - boardViewSize.height = (gridSize.height + 2) * elementSize.height; - return boardViewSize; - } - - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - super.onTreeElementChanged(treeElement); - TreeTentBoard treeTentBoard; - if (board instanceof CaseBoard) { - treeTentBoard = (TreeTentBoard) ((CaseBoard) board).getBaseBoard(); - } else { - treeTentBoard = (TreeTentBoard) board; - } - - lineViews.clear(); - for (TreeTentLine line : treeTentBoard.getLines()) { - TreeTentLineView lineView = new TreeTentLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - } - - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); - - for (TreeTentLineView view : lineViews) { - view.draw(graphics2D); - } - - for (TreeTentClueView clueView : northClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : eastClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : southClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : westClues) { - clueView.draw(graphics2D); - } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java index 4d452f48d..5356120a8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java @@ -4,11 +4,11 @@ public class GrassTile extends PlaceableElement { - public GrassTile() { - super( - "TREE-PlAC-0002", - "Grass Tile", - "The grass crest tile", - "edu/rpi/legup/images/treetent/grass.png"); - } + public GrassTile() { + super( + "TREE-PlAC-0002", + "Grass Tile", + "The grass crest tile", + "edu/rpi/legup/images/treetent/grass.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java index 249b22b04..950aebfa7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java @@ -4,7 +4,11 @@ public class TentTile extends PlaceableElement { - public TentTile() { - super("TREE-PLAC-0001", "Tent Tile", "The tent tile", "edu/rpi/legup/images/treetent/tent.png"); - } + public TentTile() { + super( + "TREE-PLAC-0001", + "Tent Tile", + "The tent tile", + "edu/rpi/legup/images/treetent/tent.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java index eab34e0b2..d04886ed5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java @@ -4,7 +4,11 @@ public class TreeTile extends NonPlaceableElement { - public TreeTile() { - super("TREE-UNPL-0001", "Tree Tile", "The tree tile", "edu/rpi/legup/images/treetent/tree.png"); - } + public TreeTile() { + super( + "TREE-UNPL-0001", + "Tree Tile", + "The tree tile", + "edu/rpi/legup/images/treetent/tree.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java index 589053d5a..a54240efd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "TREE-UNPL-0002", - "Unknown Tile", - "The blank tile", - "edu/rpi/legup/images/treetent/UnknownTile.png"); - } + public UnknownTile() { + super( + "TREE-UNPL-0002", + "Unknown Tile", + "The blank tile", + "edu/rpi/legup/images/treetent/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java index 2e7b7a031..c91a60b1a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java @@ -12,77 +12,78 @@ import java.util.List; public class EmptyFieldDirectRule extends DirectRule { - public EmptyFieldDirectRule() { - super( - "TREE-BASC-0001", - "Empty Field", - "Blank cells not adjacent to an unlinked tree are grass.", - "edu/rpi/legup/images/treetent/noTreesAround.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS - && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; + public EmptyFieldDirectRule() { + super( + "TREE-BASC-0001", + "Empty Field", + "Blank cells not adjacent to an unlinked tree are grass.", + "edu/rpi/legup/images/treetent/noTreesAround.png"); } - if (isForced(finalBoard, finalCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS + && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; + } - /** - * Returns a boolean value based on whether the specified cell has adjacent cells (true - no - * adjacent, false - has adjacent) - * - * @param board the TreeTent board - * @param cell the specified TreeTent cell - * @return true - no adjacent, false - has adjacent - */ - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjCells = board.getAdjacent(cell, TreeTentType.TREE); - return adjCells.isEmpty(); - } + if (isForced(finalBoard, finalCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; + } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } + /** + * Returns a boolean value based on whether the specified cell has adjacent cells (true - no + * adjacent, false - has adjacent) + * + * @param board the TreeTent board + * @param cell the specified TreeTent cell + * @return true - no adjacent, false - has adjacent + */ + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjCells = board.getAdjacent(cell, TreeTentType.TREE); + return adjCells.isEmpty(); } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java index 16db6e662..0116c0dcd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java @@ -15,190 +15,198 @@ public class FillinRowCaseRule extends CaseRule { - public FillinRowCaseRule() { - super( - "TREE-CASE-0001", - "Fill In row", - "A row must have the number of tents of its clue.", - "edu/rpi/legup/images/treetent/case_rowcount.png"); - } - - /** - * Gets the case board that indicates where this case rule can be applied on the given Board. - * - * @param board the given board - * @return the case board object - */ - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - ArrayList clues = treeTentBoard.getRowClues(); - clues.addAll(treeTentBoard.getColClues()); - for (PuzzleElement element : clues) { - // if ((((TreeTentCell) element).getType() == TreeTentType.CLUE_SOUTH && - // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().y, TreeTentType.UNKNOWN, - // true).size() != 0) || - // (((TreeTentCell) element).getType() == TreeTentType.CLUE_EAST && - // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().x, TreeTentType.UNKNOWN, - // false).size() != 0)) { - // caseBoard.addPickableElement(element); - // } - caseBoard.addPickableElement(element); - } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - List group; - int tentsLeft; - TreeTentClue clue = ((TreeTentClue) puzzleElement); - int clueIndex = clue.getClueIndex() - 1; - TreeTentBoard tBoard = (TreeTentBoard) board; - if (clue.getType() == TreeTentType.CLUE_SOUTH) { - group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, false); - tentsLeft = - tBoard.getRowClues().get(clueIndex).getData() - - tBoard.getRowCol(clueIndex, TreeTentType.TENT, false).size(); - cases = genCombinations(tBoard, group, tentsLeft, clueIndex, false); - } else { - group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, true); - tentsLeft = - tBoard.getRowClues().get(clueIndex).getData() - - tBoard.getRowCol(clueIndex, TreeTentType.TENT, true).size(); - cases = genCombinations(tBoard, group, tentsLeft, clueIndex, true); + public FillinRowCaseRule() { + super( + "TREE-CASE-0001", + "Fill In row", + "A row must have the number of tents of its clue.", + "edu/rpi/legup/images/treetent/case_rowcount.png"); } - // generate every combination (nCr) - // call goodBoard for each generated combination - // alternitive would be to implement collision avoidance while generating instead of after - if (cases.size() > 0) { - return cases; + /** + * Gets the case board that indicates where this case rule can be applied on the given Board. + * + * @param board the given board + * @return the case board object + */ + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + ArrayList clues = treeTentBoard.getRowClues(); + clues.addAll(treeTentBoard.getColClues()); + for (PuzzleElement element : clues) { + // if ((((TreeTentCell) element).getType() == TreeTentType.CLUE_SOUTH && + // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().y, + // TreeTentType.UNKNOWN, + // true).size() != 0) || + // (((TreeTentCell) element).getType() == TreeTentType.CLUE_EAST && + // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().x, + // TreeTentType.UNKNOWN, + // false).size() != 0)) { + // caseBoard.addPickableElement(element); + // } + caseBoard.addPickableElement(element); + } + return caseBoard; } - return null; - } - - private ArrayList genCombinations( - TreeTentBoard iBoard, List tiles, int target, Integer index, boolean isRow) { - return genCombRecursive( - iBoard, tiles, tiles, target, 0, new ArrayList(), index, isRow); - } - - private ArrayList genCombRecursive( - TreeTentBoard iBoard, - List original, - List tiles, - int target, - int current, - List selected, - Integer index, - boolean isRow) { - ArrayList b = new ArrayList<>(); - if (target == current) { - TreeTentBoard temp = iBoard.copy(); - for (TreeTentCell c : original) { - if (selected.contains(c)) { - PuzzleElement change = temp.getPuzzleElement(c); - change.setData(TreeTentType.TENT); - temp.addModifiedData(change); + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + List group; + int tentsLeft; + TreeTentClue clue = ((TreeTentClue) puzzleElement); + int clueIndex = clue.getClueIndex() - 1; + TreeTentBoard tBoard = (TreeTentBoard) board; + if (clue.getType() == TreeTentType.CLUE_SOUTH) { + group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, false); + tentsLeft = + tBoard.getRowClues().get(clueIndex).getData() + - tBoard.getRowCol(clueIndex, TreeTentType.TENT, false).size(); + cases = genCombinations(tBoard, group, tentsLeft, clueIndex, false); } else { - PuzzleElement change = temp.getPuzzleElement(c); - change.setData(TreeTentType.GRASS); - temp.addModifiedData(change); + group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, true); + tentsLeft = + tBoard.getRowClues().get(clueIndex).getData() + - tBoard.getRowCol(clueIndex, TreeTentType.TENT, true).size(); + cases = genCombinations(tBoard, group, tentsLeft, clueIndex, true); + } + + // generate every combination (nCr) + // call goodBoard for each generated combination + // alternitive would be to implement collision avoidance while generating instead of after + if (cases.size() > 0) { + return cases; } - } - if (goodBoard(temp, index, isRow)) { - b.add(temp); - } - return b; + return null; } - for (int i = 0; i < tiles.size(); ++i) { - List sub = tiles.subList(i + 1, tiles.size()); - List next = new ArrayList(selected); - next.add(tiles.get(i)); - b.addAll(genCombRecursive(iBoard, original, sub, target, current + 1, next, index, isRow)); + + private ArrayList genCombinations( + TreeTentBoard iBoard, + List tiles, + int target, + Integer index, + boolean isRow) { + return genCombRecursive( + iBoard, tiles, tiles, target, 0, new ArrayList(), index, isRow); } - return b; - } - - // Effectively runs TouchingTents check on all the added tents to make sure that the proposed - // board is valid. - // Could check more or less in the future depending on how "smart" this case rule should be. - private boolean goodBoard(TreeTentBoard board, Integer index, boolean isRow) { - List tents; - if (isRow) { - tents = board.getRowCol(index, TreeTentType.TENT, true); - } else { - tents = board.getRowCol(index, TreeTentType.TENT, false); + + private ArrayList genCombRecursive( + TreeTentBoard iBoard, + List original, + List tiles, + int target, + int current, + List selected, + Integer index, + boolean isRow) { + ArrayList b = new ArrayList<>(); + if (target == current) { + TreeTentBoard temp = iBoard.copy(); + for (TreeTentCell c : original) { + if (selected.contains(c)) { + PuzzleElement change = temp.getPuzzleElement(c); + change.setData(TreeTentType.TENT); + temp.addModifiedData(change); + } else { + PuzzleElement change = temp.getPuzzleElement(c); + change.setData(TreeTentType.GRASS); + temp.addModifiedData(change); + } + } + if (goodBoard(temp, index, isRow)) { + b.add(temp); + } + return b; + } + for (int i = 0; i < tiles.size(); ++i) { + List sub = tiles.subList(i + 1, tiles.size()); + List next = new ArrayList(selected); + next.add(tiles.get(i)); + b.addAll( + genCombRecursive( + iBoard, original, sub, target, current + 1, next, index, isRow)); + } + return b; } - for (TreeTentCell t : tents) { - List adj = board.getAdjacent(t, TreeTentType.TENT); - List diag = board.getDiagonals(t, TreeTentType.TENT); - if (adj.size() > 0 || diag.size() > 0) { - return false; - } + // Effectively runs TouchingTents check on all the added tents to make sure that the proposed + // board is valid. + // Could check more or less in the future depending on how "smart" this case rule should be. + private boolean goodBoard(TreeTentBoard board, Integer index, boolean isRow) { + List tents; + if (isRow) { + tents = board.getRowCol(index, TreeTentType.TENT, true); + } else { + tents = board.getRowCol(index, TreeTentType.TENT, false); + } + + for (TreeTentCell t : tents) { + List adj = board.getAdjacent(t, TreeTentType.TENT); + List diag = board.getDiagonals(t, TreeTentType.TENT); + if (adj.size() > 0 || diag.size() > 0) { + return false; + } + } + return true; } - return true; - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentClue clue = (TreeTentClue) puzzleElement; - - // add all elements of filled row - for (int i = 0; i < treeTentBoard.getWidth(); i++) { - TreeTentCell cell = treeTentBoard.getCell(i, clue.getClueIndex() - 1); - elements.add(board.getPuzzleElement((cell))); + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; } - return elements; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentClue clue = (TreeTentClue) puzzleElement; + + // add all elements of filled row + for (int i = 0; i < treeTentBoard.getWidth(); i++) { + TreeTentCell cell = treeTentBoard.getCell(i, clue.getClueIndex() - 1); + elements.add(board.getPuzzleElement((cell))); + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java index bb371c52b..838a3ca24 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java @@ -14,73 +14,74 @@ public class FinishWithGrassDirectRule extends DirectRule { - public FinishWithGrassDirectRule() { - super( - "TREE-BASC-0002", - "Finish with Grass", - "Grass can be added to finish a row or column that has reached its tent limit.", - "edu/rpi/legup/images/treetent/finishGrass.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS - && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; + public FinishWithGrassDirectRule() { + super( + "TREE-BASC-0002", + "Finish with Grass", + "Grass can be added to finish a row or column that has reached its tent limit.", + "edu/rpi/legup/images/treetent/finishGrass.png"); } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS + && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; + } + } - return tentsRow.size() >= board.getRowClues().get(loc.y).getData() - || tentsCol.size() >= board.getColClues().get(loc.x).getData(); - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } + return tentsRow.size() >= board.getRowClues().get(loc.y).getData() + || tentsCol.size() >= board.getColClues().get(loc.x).getData(); } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java index cae95b4ff..ae1a72e9d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java @@ -14,74 +14,77 @@ public class FinishWithTentsDirectRule extends DirectRule { - public FinishWithTentsDirectRule() { - super( - "TREE-BASC-0003", - "Finish with Tents", - "Tents can be added to finish a row or column that has one open spot per required tent.", - "edu/rpi/legup/images/treetent/finishTent.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + public FinishWithTentsDirectRule() { + super( + "TREE-BASC-0003", + "Finish with Tents", + "Tents can be added to finish a row or column that has one open spot per required" + + " tent.", + "edu/rpi/legup/images/treetent/finishTent.png"); } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN + && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; + } + } - return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() - || unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } + return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() + || unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java index bfa432cfa..53f7b9831 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java @@ -13,88 +13,92 @@ public class LastCampingSpotDirectRule extends DirectRule { - public LastCampingSpotDirectRule() { - super( - "TREE-BASC-0004", - "Last Camping Spot", - "If an unlinked tree is adjacent to only one blank cell and not adjacent to any unlinked tents, the blank cell must be a tent.", - "edu/rpi/legup/images/treetent/oneTentPosition.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + public LastCampingSpotDirectRule() { + super( + "TREE-BASC-0004", + "Last Camping Spot", + "If an unlinked tree is adjacent to only one blank cell and not adjacent to any" + + " unlinked tents, the blank cell must be a tent.", + "edu/rpi/legup/images/treetent/oneTentPosition.png"); } - if (isForced(finalBoard, finalCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN + && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); - for (TreeTentCell c : adjTrees) { - List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); - List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); - if (unkAroundTree.size() == 0) { - if (tntAroundTree.size() == 1) { - return true; + if (isForced(finalBoard, finalCell)) { + return null; } else { - for (TreeTentCell t : tntAroundTree) { - if (t == cell) { - continue; - } - List treesAroundTents = board.getAdjacent(t, TreeTentType.TREE); - if (treesAroundTents.size() == 1) { - return false; - } - } - return true; + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; } - } } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); + for (TreeTentCell c : adjTrees) { + List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); + List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); + if (unkAroundTree.size() == 0) { + if (tntAroundTree.size() == 1) { + return true; + } else { + for (TreeTentCell t : tntAroundTree) { + if (t == cell) { + continue; + } + List treesAroundTents = + board.getAdjacent(t, TreeTentType.TREE); + if (treesAroundTents.size() == 1) { + return false; + } + } + return true; + } + } + } + return false; } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java index fec820260..bd303174a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java @@ -15,163 +15,165 @@ public class LinkTentCaseRule extends CaseRule { - public LinkTentCaseRule() { - super( - "TREE-CASE-0002", - "Links from tent", - "A tent must link to exactly one adjacent tree.", - "edu/rpi/legup/images/treetent/caseLinkTent.png"); - } + public LinkTentCaseRule() { + super( + "TREE-CASE-0002", + "Links from tent", + "A tent must link to exactly one adjacent tree.", + "edu/rpi/legup/images/treetent/caseLinkTent.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.TENT - && !getCases(board, element).isEmpty()) { - Boolean canAdd = true; - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) - || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { - canAdd = false; - break; - } - } - if (canAdd) { - caseBoard.addPickableElement(element); + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.TENT + && !getCases(board, element).isEmpty()) { + Boolean canAdd = true; + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) + || l.getC2() + .getLocation() + .equals(((TreeTentCell) element).getLocation())) { + canAdd = false; + break; + } + } + if (canAdd) { + caseBoard.addPickableElement(element); + } + } } - } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - TreeTentCell cell = (TreeTentCell) puzzleElement; - List adj = ((TreeTentBoard) board).getAdjacent(cell, TreeTentType.TREE); - List lines = ((TreeTentBoard) board).getLines(); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + TreeTentCell cell = (TreeTentCell) puzzleElement; + List adj = ((TreeTentBoard) board).getAdjacent(cell, TreeTentType.TREE); + List lines = ((TreeTentBoard) board).getLines(); - for (TreeTentCell tree : adj) { - Boolean makeline = true; - for (TreeTentLine l : ((TreeTentBoard) board).getLines()) { - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - makeline = false; + for (TreeTentCell tree : adj) { + Boolean makeline = true; + for (TreeTentLine l : ((TreeTentBoard) board).getLines()) { + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + makeline = false; + } + } + if (makeline) { + TreeTentBoard temp = ((TreeTentBoard) board).copy(); + TreeTentLine l = + new TreeTentLine( + (TreeTentCell) temp.getPuzzleElement(cell), + (TreeTentCell) temp.getPuzzleElement(tree)); + temp.getLines().add(l); + temp.addModifiedData(l); + cases.add(temp); + } } - } - if (makeline) { - TreeTentBoard temp = ((TreeTentBoard) board).copy(); - TreeTentLine l = - new TreeTentLine( - (TreeTentCell) temp.getPuzzleElement(cell), - (TreeTentCell) temp.getPuzzleElement(tree)); - temp.getLines().add(l); - temp.addModifiedData(l); - cases.add(temp); - } + return cases; } - return cases; - } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } - PuzzleElement mod = modCells.iterator().next(); - TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; - if (line == null) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; - } - TreeTentCell tent = null; - if (line.getC1().getType() == TreeTentType.TENT) { - tent = line.getC1(); - } - if (line.getC2().getType() == TreeTentType.TENT) { - tent = line.getC2(); - } - if (tent == null) { - return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; - } - - TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - ArrayList cases = getCases(parentBoard, tent); - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != cases.size()) { - return super.getInvalidUseOfRuleMessage(); - } - for (Board caseBoard : cases) { - TreeTentBoard cBoard = (TreeTentBoard) caseBoard; - TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); - boolean hasLine = false; - for (TreeTransition tran : childTransitions) { - TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); - if (tBoard.getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage(); + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; } - PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); - if (!(tElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; + PuzzleElement mod = modCells.iterator().next(); + TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; + if (line == null) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; } - if (cLine.compare((TreeTentLine) tElement)) { - hasLine = true; - break; + TreeTentCell tent = null; + if (line.getC1().getType() == TreeTentType.TENT) { + tent = line.getC1(); + } + if (line.getC2().getType() == TreeTentType.TENT) { + tent = line.getC2(); + } + if (tent == null) { + return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; } - } - if (!hasLine) { - return super.getInvalidUseOfRuleMessage(); - } - } - return null; - } + TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + ArrayList cases = getCases(parentBoard, tent); + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != cases.size()) { + return super.getInvalidUseOfRuleMessage(); + } + for (Board caseBoard : cases) { + TreeTentBoard cBoard = (TreeTentBoard) caseBoard; + TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); + boolean hasLine = false; + for (TreeTransition tran : childTransitions) { + TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); + if (tBoard.getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage(); + } + PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); + if (!(tElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; + } + if (cLine.compare((TreeTentLine) tElement)) { + hasLine = true; + break; + } + } + if (!hasLine) { + return super.getInvalidUseOfRuleMessage(); + } + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - return List.of(board.getPuzzleElement(puzzleElement)); - } + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + return List.of(board.getPuzzleElement(puzzleElement)); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java index 65bc52723..03d039898 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java @@ -16,174 +16,177 @@ public class LinkTreeCaseRule extends CaseRule { - public LinkTreeCaseRule() { - super( - "TREE-CASE-0003", - "Links from tree", - "A tree must link to exactly one adjacent tent.", - "edu/rpi/legup/images/treetent/caseLinkTree.png"); - } + public LinkTreeCaseRule() { + super( + "TREE-CASE-0003", + "Links from tree", + "A tree must link to exactly one adjacent tent.", + "edu/rpi/legup/images/treetent/caseLinkTree.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.TREE - && !getCases(treeTentBoard, element).isEmpty()) { + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.TREE + && !getCases(treeTentBoard, element).isEmpty()) { - Boolean canAdd = true; - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) - || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { - canAdd = false; - break; - } - } - if (canAdd) { - caseBoard.addPickableElement(element); + Boolean canAdd = true; + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) + || l.getC2() + .getLocation() + .equals(((TreeTentCell) element).getLocation())) { + canAdd = false; + break; + } + } + if (canAdd) { + caseBoard.addPickableElement(element); + } + } } - } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - List adjCells = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); - for (TreeTentCell c : adjCells) { - Boolean makeline = true; - for (TreeTentLine l : treeTentBoard.getLines()) { - if (l.getC1().getLocation().equals(c.getLocation()) - || l.getC2().getLocation().equals(c.getLocation())) { - makeline = false; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + List adjCells = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); + for (TreeTentCell c : adjCells) { + Boolean makeline = true; + for (TreeTentLine l : treeTentBoard.getLines()) { + if (l.getC1().getLocation().equals(c.getLocation()) + || l.getC2().getLocation().equals(c.getLocation())) { + makeline = false; + } + } + if (makeline) { + TreeTentBoard caseBoard = (TreeTentBoard) board.copy(); + TreeTentLine line = new TreeTentLine(cell, c); + caseBoard.getLines().add(line); + caseBoard.addModifiedData(line); + cases.add(caseBoard); + } } - } - if (makeline) { - TreeTentBoard caseBoard = (TreeTentBoard) board.copy(); - TreeTentLine line = new TreeTentLine(cell, c); - caseBoard.getLines().add(line); - caseBoard.addModifiedData(line); - cases.add(caseBoard); - } + return cases; } - return cases; - } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } - PuzzleElement mod = modCells.iterator().next(); - TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; - if (line == null) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; - } - TreeTentCell tree = null; - if (line.getC1().getType() == TreeTentType.TREE) { - tree = line.getC1(); - } - if (line.getC2().getType() == TreeTentType.TREE) { - tree = line.getC2(); - } - if (tree == null) { - return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; - } - - TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - ArrayList cases = getCases(parentBoard, tree); - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != cases.size()) { - return super.getInvalidUseOfRuleMessage(); - } - for (Board caseBoard : cases) { - TreeTentBoard cBoard = (TreeTentBoard) caseBoard; - TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); - boolean hasLine = false; - for (TreeTransition tran : childTransitions) { - TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); - if (tBoard.getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage(); + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; } - PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); - if (!(tElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; + PuzzleElement mod = modCells.iterator().next(); + TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; + if (line == null) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; } - if (cLine.compare((TreeTentLine) tElement)) { - hasLine = true; - break; + TreeTentCell tree = null; + if (line.getC1().getType() == TreeTentType.TREE) { + tree = line.getC1(); } - } - if (!hasLine) { - return super.getInvalidUseOfRuleMessage(); - } + if (line.getC2().getType() == TreeTentType.TREE) { + tree = line.getC2(); + } + if (tree == null) { + return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; + } + + TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + ArrayList cases = getCases(parentBoard, tree); + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != cases.size()) { + return super.getInvalidUseOfRuleMessage(); + } + for (Board caseBoard : cases) { + TreeTentBoard cBoard = (TreeTentBoard) caseBoard; + TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); + boolean hasLine = false; + for (TreeTransition tran : childTransitions) { + TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); + if (tBoard.getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage(); + } + PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); + if (!(tElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; + } + if (cLine.compare((TreeTentLine) tElement)) { + hasLine = true; + break; + } + } + if (!hasLine) { + return super.getInvalidUseOfRuleMessage(); + } + } + + return null; } - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = + new ArrayList<>(List.of(board.getPuzzleElement(puzzleElement))); - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(List.of(board.getPuzzleElement(puzzleElement))); + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell point = (TreeTentCell) puzzleElement; - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell point = (TreeTentCell) puzzleElement; + // get all adjacent cells + Point loc = point.getLocation(); + for (int i = -2; i < 2; i++) { + TreeTentCell cell = treeTentBoard.getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); + if (cell != null) { + elements.add(board.getPuzzleElement(cell)); + } + } - // get all adjacent cells - Point loc = point.getLocation(); - for (int i = -2; i < 2; i++) { - TreeTentCell cell = treeTentBoard.getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); - if (cell != null) { - elements.add(board.getPuzzleElement(cell)); - } + return elements; } - - return elements; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java index 900c37d92..912fa6d20 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java @@ -12,57 +12,57 @@ public class NoTentForTreeContradictionRule extends ContradictionRule { - public NoTentForTreeContradictionRule() { - super( - "TREE-CONT-0001", - "No Tent For Tree", - "Each tree must link to a tent.", - "edu/rpi/legup/images/treetent/contra_NoTentForTree.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TREE) { - return super.getNoContradictionMessage(); + public NoTentForTreeContradictionRule() { + super( + "TREE-CONT-0001", + "No Tent For Tree", + "Each tree must link to a tent.", + "edu/rpi/legup/images/treetent/contra_NoTentForTree.png"); } - int adjTent = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); - int adjUnknown = treeTentBoard.getAdjacent(cell, TreeTentType.UNKNOWN).size(); - if (adjTent == 0 && adjUnknown == 0) { - return null; - } else { - if (adjTent != 0) { - List lines = treeTentBoard.getLines(); - List adjTents = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); - for (TreeTentLine l : lines) { - Iterator i = adjTents.iterator(); - while (i.hasNext()) { - TreeTentCell t = i.next(); - if (t.getLocation().equals(l.getC1().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - if (t.getLocation().equals(l.getC2().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TREE) { + return super.getNoContradictionMessage(); } - if (adjTents.size() == 0 && adjUnknown == 0) { - return null; + int adjTent = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); + int adjUnknown = treeTentBoard.getAdjacent(cell, TreeTentType.UNKNOWN).size(); + if (adjTent == 0 && adjUnknown == 0) { + return null; + } else { + if (adjTent != 0) { + List lines = treeTentBoard.getLines(); + List adjTents = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); + for (TreeTentLine l : lines) { + Iterator i = adjTents.iterator(); + while (i.hasNext()) { + TreeTentCell t = i.next(); + if (t.getLocation().equals(l.getC1().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + if (t.getLocation().equals(l.getC2().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + } + } + if (adjTents.size() == 0 && adjUnknown == 0) { + return null; + } + } + return super.getNoContradictionMessage(); } - } - return super.getNoContradictionMessage(); } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java index c6cf2fc35..9bc3fddea 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java @@ -12,51 +12,51 @@ public class NoTreeForTentContradictionRule extends ContradictionRule { - public NoTreeForTentContradictionRule() { - super( - "TREE-CONT-0002", - "No Tree For Tent", - "Each tent must link to a tree.", - "edu/rpi/legup/images/treetent/contra_NoTreeForTent.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TENT) { - return super.getNoContradictionMessage(); + public NoTreeForTentContradictionRule() { + super( + "TREE-CONT-0002", + "No Tree For Tent", + "Each tent must link to a tree.", + "edu/rpi/legup/images/treetent/contra_NoTreeForTent.png"); } - List adjTrees = treeTentBoard.getAdjacent(cell, TreeTentType.TREE); - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - Iterator i = adjTrees.iterator(); - while (i.hasNext()) { - TreeTentCell t = i.next(); - if (t.getLocation().equals(l.getC1().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TENT) { + return super.getNoContradictionMessage(); } - if (t.getLocation().equals(l.getC2().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); + List adjTrees = treeTentBoard.getAdjacent(cell, TreeTentType.TREE); + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + Iterator i = adjTrees.iterator(); + while (i.hasNext()) { + TreeTentCell t = i.next(); + if (t.getLocation().equals(l.getC1().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + if (t.getLocation().equals(l.getC2().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + } + } + int adjTree = adjTrees.size(); + if (adjTree == 0) { + return null; + } else { + return super.getNoContradictionMessage(); } - } - } - int adjTree = adjTrees.size(); - if (adjTree == 0) { - return null; - } else { - return super.getNoContradictionMessage(); } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java index 447bbcde0..e800dc416 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java @@ -13,73 +13,74 @@ public class SurroundTentWithGrassDirectRule extends DirectRule { - public SurroundTentWithGrassDirectRule() { - super( - "TREE-BASC-0005", - "Surround Tent with Grass", - "Blank cells adjacent or diagonal to a tent are grass.", - "edu/rpi/legup/images/treetent/aroundTent.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement == null) { - return null; - } - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN - && finalCell.getType() == TreeTentType.GRASS)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + public SurroundTentWithGrassDirectRule() { + super( + "TREE-BASC-0005", + "Surround Tent with Grass", + "Blank cells adjacent or diagonal to a tent are grass.", + "edu/rpi/legup/images/treetent/aroundTent.png"); } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement == null) { + return null; + } + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN + && finalCell.getType() == TreeTentType.GRASS)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List tents = board.getAdjacent(cell, TreeTentType.TENT); - tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); - return !tents.isEmpty(); - } + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; + } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List tents = board.getAdjacent(cell, TreeTentType.TENT); + tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); + return !tents.isEmpty(); } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java index 5091068a8..8044faa0e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java @@ -14,109 +14,112 @@ public class TentForTreeDirectRule extends DirectRule { - public TentForTreeDirectRule() { - super( - "TREE-BASC-0006", - "Tent for Tree", - "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the unlinked tree must link to the unlinked tent.", - "edu/rpi/legup/images/treetent/NewTreeLink.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE - && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } else { - if (line.getC2().getType() == TreeTentType.TREE - && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } else { - return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; - } + public TentForTreeDirectRule() { + super( + "TREE-BASC-0006", + "Tent for Tree", + "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the" + + " unlinked tree must link to the unlinked tent.", + "edu/rpi/legup/images/treetent/NewTreeLink.png"); } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; - } else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; - } else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE + && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); } else { - return super.getInvalidUseOfRuleMessage() - + ": This tree and tent don't need to be linked."; + if (line.getC2().getType() == TreeTentType.TREE + && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } else { + return super.getInvalidUseOfRuleMessage() + + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This tree and tent don't need to be linked."; + } + } } - } } - } - private Integer isForced( - TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTents = board.getAdjacent(tree, TreeTentType.TENT); - adjTents.remove(tent); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTents) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tree.getLocation())) { - return -1; - } - toRemove.add(c); + private Integer isForced( + TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTents = board.getAdjacent(tree, TreeTentType.TENT); + adjTents.remove(tent); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTents) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); - } else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tree.getLocation())) { - return -1; + } else { + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); + } + } } - toRemove.add(c); - } + for (TreeTentCell c : toRemove) { + adjTents.remove(c); + } + toRemove.clear(); + } + if (adjTents.size() == 0) { + return 1; + } else { + return 0; } - } - for (TreeTentCell c : toRemove) { - adjTents.remove(c); - } - toRemove.clear(); - } - if (adjTents.size() == 0) { - return 1; - } else { - return 0; } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java index 2b6afd5d0..63478f83e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java @@ -13,101 +13,101 @@ public class TentOrGrassCaseRule extends CaseRule { - public TentOrGrassCaseRule() { - super( - "TREE-CASE-0004", - "Tent or Grass", - "Each blank cell is either a tent or grass.", - "edu/rpi/legup/images/treetent/caseTentOrGrass.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.UNKNOWN) { - caseBoard.addPickableElement(element); - } + public TentOrGrassCaseRule() { + super( + "TREE-CASE-0004", + "Tent or Grass", + "Each blank cell is either a tent or grass.", + "edu/rpi/legup/images/treetent/caseTentOrGrass.png"); } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(TreeTentType.TENT); - case1.addModifiedData(data1); - cases.add(case1); + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.UNKNOWN) { + caseBoard.addPickableElement(element); + } + } + return caseBoard; + } - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(TreeTentType.GRASS); - case2.addModifiedData(data2); - cases.add(case2); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(TreeTentType.TENT); + case1.addModifiedData(data1); + cases.add(case1); - return cases; - } + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(TreeTentType.GRASS); + case2.addModifiedData(data2); + cases.add(case2); - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + return cases; } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - TreeTentCell mod1 = (TreeTentCell) case1.getBoard().getModifiedData().iterator().next(); - TreeTentCell mod2 = (TreeTentCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - if (!((mod1.getType() == TreeTentType.TENT && mod2.getType() == TreeTentType.GRASS) - || (mod2.getType() == TreeTentType.TENT && mod1.getType() == TreeTentType.GRASS))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have a tent and a grass cell."; - } + TreeTentCell mod1 = (TreeTentCell) case1.getBoard().getModifiedData().iterator().next(); + TreeTentCell mod2 = (TreeTentCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } + + if (!((mod1.getType() == TreeTentType.TENT && mod2.getType() == TreeTentType.GRASS) + || (mod2.getType() == TreeTentType.TENT && mod1.getType() == TreeTentType.GRASS))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have a tent and a grass cell."; + } - return null; - } + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java index 220a9aeb0..7b3f43dbe 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java @@ -10,39 +10,39 @@ public class TooFewTentsContradictionRule extends ContradictionRule { - public TooFewTentsContradictionRule() { - super( - "TREE-CONT-0003", - "Too Few Tents", - "Rows and columns cannot have fewer tents than their clue.", - "edu/rpi/legup/images/treetent/too_few_tents.png"); - } + public TooFewTentsContradictionRule() { + super( + "TREE-CONT-0003", + "Too Few Tents", + "Rows and columns cannot have fewer tents than their clue.", + "edu/rpi/legup/images/treetent/too_few_tents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); - int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); - int rowUnknowns = treeTentBoard.getRowCol(loc.y, TreeTentType.UNKNOWN, true).size(); - int colUnknowns = treeTentBoard.getRowCol(loc.x, TreeTentType.UNKNOWN, false).size(); + Point loc = cell.getLocation(); + int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); + int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); + int rowUnknowns = treeTentBoard.getRowCol(loc.y, TreeTentType.UNKNOWN, true).size(); + int colUnknowns = treeTentBoard.getRowCol(loc.x, TreeTentType.UNKNOWN, false).size(); - if (rowTents + rowUnknowns < treeTentBoard.getRowClues().get(loc.y).getData() - || colTents + colUnknowns < treeTentBoard.getColClues().get(loc.x).getData()) { - return null; - } else { - return super.getNoContradictionMessage(); + if (rowTents + rowUnknowns < treeTentBoard.getRowClues().get(loc.y).getData() + || colTents + colUnknowns < treeTentBoard.getColClues().get(loc.x).getData()) { + return null; + } else { + return super.getNoContradictionMessage(); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java index da2a3964d..dcc65feb6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java @@ -10,37 +10,37 @@ public class TooManyTentsContradictionRule extends ContradictionRule { - public TooManyTentsContradictionRule() { - super( - "TREE-CONT-0004", - "Too Many Tents", - "Rows and columns cannot have more tents than their clue.", - "edu/rpi/legup/images/treetent/too_many_tents.png"); - } + public TooManyTentsContradictionRule() { + super( + "TREE-CONT-0004", + "Too Many Tents", + "Rows and columns cannot have more tents than their clue.", + "edu/rpi/legup/images/treetent/too_many_tents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); - int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); + Point loc = cell.getLocation(); + int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); + int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); - if (rowTents > treeTentBoard.getRowClues().get(loc.y).getData() - || colTents > treeTentBoard.getColClues().get(loc.x).getData()) { - return null; - } else { - return super.getNoContradictionMessage(); + if (rowTents > treeTentBoard.getRowClues().get(loc.y).getData() + || colTents > treeTentBoard.getColClues().get(loc.x).getData()) { + return null; + } else { + return super.getNoContradictionMessage(); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java index 075003130..d9dd36e12 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java @@ -9,36 +9,36 @@ public class TouchingTentsContradictionRule extends ContradictionRule { - public TouchingTentsContradictionRule() { - super( - "TREE-CONT-0005", - "Touching Tents", - "Tents cannot touch other tents.", - "edu/rpi/legup/images/treetent/contra_adjacentTents.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent {@link PuzzleElement} - * @return null if the transition contains a contradiction at the specified - * puzzleElement, otherwise error message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TENT) { - return super.getNoContradictionMessage(); + public TouchingTentsContradictionRule() { + super( + "TREE-CONT-0005", + "Touching Tents", + "Tents cannot touch other tents.", + "edu/rpi/legup/images/treetent/contra_adjacentTents.png"); } - int adjTree = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); - int diagTree = treeTentBoard.getDiagonals(cell, TreeTentType.TENT).size(); - if (adjTree > 0 || diagTree > 0) { - return null; - } else { - return super.getNoContradictionMessage(); + + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent {@link PuzzleElement} + * @return null if the transition contains a contradiction at the specified + * puzzleElement, otherwise error message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TENT) { + return super.getNoContradictionMessage(); + } + int adjTree = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); + int diagTree = treeTentBoard.getDiagonals(cell, TreeTentType.TENT).size(); + if (adjTree > 0 || diagTree > 0) { + return null; + } else { + return super.getNoContradictionMessage(); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java index a6c213c28..d4360c7f6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java @@ -13,109 +13,112 @@ import java.util.List; public class TreeForTentDirectRule extends DirectRule { - public TreeForTentDirectRule() { - super( - "TREE-BASC-0007", - "Tree for Tent", - "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must link to the unlinked tree.", - "edu/rpi/legup/images/treetent/NewTentLink.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE - && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } else { - if (line.getC2().getType() == TreeTentType.TREE - && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } else { - return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; - } + public TreeForTentDirectRule() { + super( + "TREE-BASC-0007", + "Tree for Tent", + "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must" + + " link to the unlinked tree.", + "edu/rpi/legup/images/treetent/NewTentLink.png"); } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; - } else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; - } else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE + && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); } else { - return super.getInvalidUseOfRuleMessage() - + ": This tree and tent don't need to be linked."; + if (line.getC2().getType() == TreeTentType.TREE + && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } else { + return super.getInvalidUseOfRuleMessage() + + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This tree and tent don't need to be linked."; + } + } } - } } - } - private Integer isForced( - TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); - adjTrees.remove(tree); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTrees) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tent.getLocation())) { - return -1; - } - toRemove.add(c); + private Integer isForced( + TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); + adjTrees.remove(tree); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTrees) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); - } else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tent.getLocation())) { - return -1; + } else { + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); + } + } } - toRemove.add(c); - } + for (TreeTentCell c : toRemove) { + adjTrees.remove(c); + } + toRemove.clear(); + } + if (adjTrees.size() == 0) { + return 1; + } else { + return 0; } - } - for (TreeTentCell c : toRemove) { - adjTrees.remove(c); - } - toRemove.clear(); - } - if (adjTrees.size() == 0) { - return 1; - } else { - return 0; } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/save/ExportFileException.java b/src/main/java/edu/rpi/legup/save/ExportFileException.java index 70eec7868..9def1f392 100644 --- a/src/main/java/edu/rpi/legup/save/ExportFileException.java +++ b/src/main/java/edu/rpi/legup/save/ExportFileException.java @@ -2,7 +2,7 @@ public class ExportFileException extends Exception { - public ExportFileException(String message) { - super("Export File Exception: " + message); - } + public ExportFileException(String message) { + super("Export File Exception: " + message); + } } diff --git a/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java b/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java index 9207aeaa6..1e24c5762 100644 --- a/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java +++ b/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java @@ -2,7 +2,7 @@ public class InvalidFileFormatException extends Exception { - public InvalidFileFormatException(String message) { - super("InvalidFileFormatException: " + message); - } + public InvalidFileFormatException(String message) { + super("InvalidFileFormatException: " + message); + } } diff --git a/src/main/java/edu/rpi/legup/save/SavableBoard.java b/src/main/java/edu/rpi/legup/save/SavableBoard.java index a0d141dea..bd246303b 100644 --- a/src/main/java/edu/rpi/legup/save/SavableBoard.java +++ b/src/main/java/edu/rpi/legup/save/SavableBoard.java @@ -4,13 +4,13 @@ import java.io.InputStream; public class SavableBoard { - private static final String LEGUP_HEADER = "edu.rpi.legup.Legup"; + private static final String LEGUP_HEADER = "edu.rpi.legup.Legup"; - private String filePath; - private InputStream inputStream; + private String filePath; + private InputStream inputStream; - public SavableBoard(String filePath) throws Exception { - this.filePath = filePath; - this.inputStream = new FileInputStream(filePath); - } + public SavableBoard(String filePath) throws Exception { + this.filePath = filePath; + this.inputStream = new FileInputStream(filePath); + } } diff --git a/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java b/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java index 65af81f7f..70fbea033 100644 --- a/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java +++ b/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java @@ -11,205 +11,216 @@ import javax.swing.*; public class CreatePuzzleDialog extends JDialog { - private HomePanel homePanel; - - private String[] games; - private JComboBox gameBox; - private ActionListener gameBoxListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JComboBox comboBox = (JComboBox) e.getSource(); - String puzzleName = (String) comboBox.getSelectedItem(); - if (puzzleName.equals("ShortTruthTable")) { + private HomePanel homePanel; + + private String[] games; + private JComboBox gameBox; + private ActionListener gameBoxListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JComboBox comboBox = (JComboBox) e.getSource(); + String puzzleName = (String) comboBox.getSelectedItem(); + if (puzzleName.equals("ShortTruthTable")) { + textInputScrollPane.setVisible(true); + rowsLabel.setVisible(false); + rows.setVisible(false); + columnsLabel.setVisible(false); + columns.setVisible(false); + } else { + textInputScrollPane.setVisible(false); + rowsLabel.setVisible(true); + rows.setVisible(true); + columnsLabel.setVisible(true); + columns.setVisible(true); + } + } + }; + + private JLabel puzzleLabel; + private JLabel rowsLabel; + private JTextField rows; + private JLabel columnsLabel; + private JTextField columns; + + private JTextArea textArea; + private JScrollPane textInputScrollPane; + + private JButton ok = new JButton("Ok"); + private ActionListener okButtonListener = + new ActionListener() { + /** + * Attempts to open the puzzle editor interface for the given game with the given + * dimensions + * + * @param ae the event to be processed + */ + @Override + public void actionPerformed(ActionEvent ae) { + String game = + Config.convertDisplayNameToClassName( + (String) gameBox.getSelectedItem()); + + // Check if all 3 TextFields are filled + if (game.equals("ShortTruthTable") && textArea.getText().isEmpty()) { + System.out.println("Unfilled fields"); + return; + } + if (!game.equals("ShortTruthTable") + && (game.isEmpty() + || rows.getText().isEmpty() + || columns.getText().isEmpty())) { + System.out.println("Unfilled fields"); + return; + } + + try { + if (game.equals("ShortTruthTable")) { + homePanel.openEditorWithNewPuzzle( + "ShortTruthTable", textArea.getText().split("\n")); + } else { + homePanel.openEditorWithNewPuzzle( + game, + Integer.valueOf(rows.getText()), + Integer.valueOf(columns.getText())); + } + setVisible(false); + } catch (IllegalArgumentException e) { + System.out.println("Failed to open editor with new puzzle"); + e.printStackTrace(System.out); + } + } + }; + + private JButton cancel = new JButton("Cancel"); + private ActionListener cancelButtonListener = + new ActionListener() { + /** + * Dispose the puzzle creation dialog + * + * @param e the event to be processed + */ + @Override + public void actionPerformed(ActionEvent e) { + dispose(); + } + }; + + public CreatePuzzleDialog(JFrame parent, HomePanel homePanel) { + super(parent, true); + + this.homePanel = homePanel; + + initPuzzles(); + + Rectangle b = parent.getBounds(); + + setSize(350, 200); + setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); + + Container c = getContentPane(); + c.setLayout(null); + + puzzleLabel = new JLabel("Puzzle:"); + puzzleLabel.setBounds(10, 30, 70, 25); + gameBox.setBounds(80, 30, 190, 25); + + ok.setBounds(20, 130, 60, 25); + cancel.setBounds(170, 130, 90, 25); + + c.add(puzzleLabel); + c.add(gameBox); + + rows = new JTextField(); + columns = new JTextField(); + + rowsLabel = new JLabel("Rows:"); + columnsLabel = new JLabel("Columns:"); + + rowsLabel.setBounds(30, 70, 60, 25); + columnsLabel.setBounds(30, 95, 60, 25); + + rows.setBounds(100, 70, 60, 25); + columns.setBounds(100, 95, 60, 25); + + c.add(rowsLabel); + c.add(columnsLabel); + + c.add(rows); + c.add(columns); + + textArea = new JTextArea(); + textInputScrollPane = + new JScrollPane( + textArea, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + textInputScrollPane.setBounds(10, 70, this.getWidth() - 30, 50); + c.add(textInputScrollPane); + + c.add(ok); + c.add(cancel); + + if (Objects.equals(this.gameBox.getSelectedItem(), "ShortTruthTable")) { textInputScrollPane.setVisible(true); rowsLabel.setVisible(false); rows.setVisible(false); columnsLabel.setVisible(false); columns.setVisible(false); - } else { + } else { textInputScrollPane.setVisible(false); rowsLabel.setVisible(true); rows.setVisible(true); columnsLabel.setVisible(true); columns.setVisible(true); - } - } - }; - - private JLabel puzzleLabel; - private JLabel rowsLabel; - private JTextField rows; - private JLabel columnsLabel; - private JTextField columns; - - private JTextArea textArea; - private JScrollPane textInputScrollPane; - - private JButton ok = new JButton("Ok"); - private ActionListener okButtonListener = - new ActionListener() { - /** - * Attempts to open the puzzle editor interface for the given game with the given dimensions - * - * @param ae the event to be processed - */ - @Override - public void actionPerformed(ActionEvent ae) { - String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); - - // Check if all 3 TextFields are filled - if (game.equals("ShortTruthTable") && textArea.getText().isEmpty()) { - System.out.println("Unfilled fields"); - return; - } - if (!game.equals("ShortTruthTable") - && (game.isEmpty() || rows.getText().isEmpty() || columns.getText().isEmpty())) { - System.out.println("Unfilled fields"); - return; - } - - try { - if (game.equals("ShortTruthTable")) { - homePanel.openEditorWithNewPuzzle("ShortTruthTable", textArea.getText().split("\n")); - } else { - homePanel.openEditorWithNewPuzzle( - game, Integer.valueOf(rows.getText()), Integer.valueOf(columns.getText())); - } - setVisible(false); - } catch (IllegalArgumentException e) { - System.out.println("Failed to open editor with new puzzle"); - e.printStackTrace(System.out); - } } - }; - - private JButton cancel = new JButton("Cancel"); - private ActionListener cancelButtonListener = - new ActionListener() { - /** - * Dispose the puzzle creation dialog - * - * @param e the event to be processed - */ - @Override - public void actionPerformed(ActionEvent e) { - dispose(); - } - }; - - public CreatePuzzleDialog(JFrame parent, HomePanel homePanel) { - super(parent, true); - - this.homePanel = homePanel; - - initPuzzles(); - - Rectangle b = parent.getBounds(); - - setSize(350, 200); - setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); - - Container c = getContentPane(); - c.setLayout(null); - - puzzleLabel = new JLabel("Puzzle:"); - puzzleLabel.setBounds(10, 30, 70, 25); - gameBox.setBounds(80, 30, 190, 25); - - ok.setBounds(20, 130, 60, 25); - cancel.setBounds(170, 130, 90, 25); - c.add(puzzleLabel); - c.add(gameBox); - - rows = new JTextField(); - columns = new JTextField(); - - rowsLabel = new JLabel("Rows:"); - columnsLabel = new JLabel("Columns:"); - - rowsLabel.setBounds(30, 70, 60, 25); - columnsLabel.setBounds(30, 95, 60, 25); - - rows.setBounds(100, 70, 60, 25); - columns.setBounds(100, 95, 60, 25); - - c.add(rowsLabel); - c.add(columnsLabel); - - c.add(rows); - c.add(columns); - - textArea = new JTextArea(); - textInputScrollPane = - new JScrollPane( - textArea, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - textInputScrollPane.setBounds(10, 70, this.getWidth() - 30, 50); - c.add(textInputScrollPane); - - c.add(ok); - c.add(cancel); + ActionListener cursorSelectedGame = CursorController.createListener(this, gameBoxListener); + gameBox.addActionListener(cursorSelectedGame); + ActionListener cursorPressedOk = CursorController.createListener(this, okButtonListener); + ok.addActionListener(cursorPressedOk); + ActionListener cursorPressedCancel = + CursorController.createListener(this, cancelButtonListener); + cancel.addActionListener(cursorPressedCancel); + } - if (Objects.equals(this.gameBox.getSelectedItem(), "ShortTruthTable")) { - textInputScrollPane.setVisible(true); - rowsLabel.setVisible(false); - rows.setVisible(false); - columnsLabel.setVisible(false); - columns.setVisible(false); - } else { - textInputScrollPane.setVisible(false); - rowsLabel.setVisible(true); - rows.setVisible(true); - columnsLabel.setVisible(true); - columns.setVisible(true); + public void initPuzzles() { + this.games = + GameBoardFacade.getInstance() + .getConfig() + .getFileCreationEnabledPuzzles() + .toArray(new String[0]); + Arrays.sort(this.games); + gameBox = new JComboBox(this.games); } - ActionListener cursorSelectedGame = CursorController.createListener(this, gameBoxListener); - gameBox.addActionListener(cursorSelectedGame); - ActionListener cursorPressedOk = CursorController.createListener(this, okButtonListener); - ok.addActionListener(cursorPressedOk); - ActionListener cursorPressedCancel = - CursorController.createListener(this, cancelButtonListener); - cancel.addActionListener(cursorPressedCancel); - } - - public void initPuzzles() { - this.games = - GameBoardFacade.getInstance() - .getConfig() - .getFileCreationEnabledPuzzles() - .toArray(new String[0]); - Arrays.sort(this.games); - gameBox = new JComboBox(this.games); - } - - // ^This method seems useless and never got covered - public void actionPerformed(ActionEvent e) { - if (e.getSource() == ok) { - String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); - - try { - if (game.equals("ShortTruthTable")) { - this.homePanel.openEditorWithNewPuzzle( - "ShortTruthTable", this.textArea.getText().split("\n")); + // ^This method seems useless and never got covered + public void actionPerformed(ActionEvent e) { + if (e.getSource() == ok) { + String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); + + try { + if (game.equals("ShortTruthTable")) { + this.homePanel.openEditorWithNewPuzzle( + "ShortTruthTable", this.textArea.getText().split("\n")); + } else { + this.homePanel.openEditorWithNewPuzzle( + game, + Integer.valueOf(this.rows.getText()), + Integer.valueOf(this.columns.getText())); + } + this.setVisible(false); + } catch (IllegalArgumentException exception) { + // Don't do anything. This is here to prevent the dialog from closing if the + // dimensions are + // invalid. + } } else { - this.homePanel.openEditorWithNewPuzzle( - game, Integer.valueOf(this.rows.getText()), Integer.valueOf(this.columns.getText())); + if (e.getSource() == cancel) { + this.setVisible(false); + } else { + // Unknown Action Event + } } - this.setVisible(false); - } catch (IllegalArgumentException exception) { - // Don't do anything. This is here to prevent the dialog from closing if the dimensions are - // invalid. - } - } else { - if (e.getSource() == cancel) { - this.setVisible(false); - } else { - // Unknown Action Event - } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/DynamicView.java b/src/main/java/edu/rpi/legup/ui/DynamicView.java index 1dea7a905..8d3024c86 100644 --- a/src/main/java/edu/rpi/legup/ui/DynamicView.java +++ b/src/main/java/edu/rpi/legup/ui/DynamicView.java @@ -18,203 +18,210 @@ public class DynamicView extends JPanel { - private ScrollView scrollView; - private JPanel zoomWrapper; - private JPanel zoomer; - private JLabel status; - - private static final Font ERROR_FONT = MaterialFonts.ITALIC; - private static final Color ERROR_COLOR = MaterialColors.RED_700; - - private static final Font INFO_FONT = MaterialFonts.REGULAR; - private static final Color INFO_COLOR = MaterialColors.GRAY_900; - - public DynamicView(ScrollView scrollView, DynamicViewType type) { - this.scrollView = scrollView; - - setLayout(new BorderLayout()); - - add(scrollView, CENTER); - add(setUpZoomer(type), SOUTH); - } - - /** - * Sets up the zoomer for the given DynamicViewType - * - * @param type The DynamicView that we are setting up the zoomer for (so the zoomer for the board - * view or the zoomer for the proof tree view) - * @return A JPanel containing the zoomer - */ - private JPanel setUpZoomer(DynamicViewType type) { - if (type == DynamicViewType.BOARD) { - return setUpBoardZoomer(); - } else { - if (type == DynamicViewType.PROOF_TREE) { - return setUpProofTreeZoomer(); - } + private ScrollView scrollView; + private JPanel zoomWrapper; + private JPanel zoomer; + private JLabel status; + + private static final Font ERROR_FONT = MaterialFonts.ITALIC; + private static final Color ERROR_COLOR = MaterialColors.RED_700; + + private static final Font INFO_FONT = MaterialFonts.REGULAR; + private static final Color INFO_COLOR = MaterialColors.GRAY_900; + + public DynamicView(ScrollView scrollView, DynamicViewType type) { + this.scrollView = scrollView; + + setLayout(new BorderLayout()); + + add(scrollView, CENTER); + add(setUpZoomer(type), SOUTH); } - // Should never reach here; if you reach here, that's a problem! - return null; - } - - /** - * Sets up the zoomer for the board view - * - * @return A JPanel containing the zoomer - */ - private JPanel setUpBoardZoomer() { - final String label = "Resize Board"; - ActionListener listener = (ActionListener) -> this.fitBoardViewToScreen(); - return this.setUpZoomerHelper(label, listener); - } - - /** - * Sets up the zoomer for the proof tree view - * - * @return A JPanel containing the zoomer - */ - private JPanel setUpProofTreeZoomer() { - final String label = "Resize Proof"; - ActionListener listener = - (ActionListener) -> - GameBoardFacade.getInstance().getLegupUI().getProofEditor().fitTreeViewToScreen(); - return this.setUpZoomerHelper(label, listener); - } - - /** - * Creates the zoomer - * - * @param label A string containing the label to be displayed on the fit to screen button - * @param listener A listener that determines what the resize button will do - * @return A JPanel containing the zoomer - */ - private JPanel setUpZoomerHelper(final String label, ActionListener listener) { - zoomWrapper = new JPanel(); - try { - zoomer = new JPanel(); - - // Create and add the resize button to the zoomer - JButton resizeButton = new JButton(label); - resizeButton.setFocusPainted(false); - resizeButton.setFocusPainted(false); - resizeButton.setEnabled(true); - resizeButton.setSize(100, 50); - resizeButton.addActionListener(listener); - zoomer.add(resizeButton); - - JLabel zoomLabel = new JLabel("100%"); - zoomLabel.setFont(MaterialFonts.getRegularFont(16f)); - - JSlider zoomSlider = new JSlider(25, 400, 100); - - JButton plus = - new JButton( - new ImageIcon( - ImageIO.read( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/imgs/add.png"))))); - plus.setFocusPainted(false); - plus.setFont(MaterialFonts.getRegularFont(10f)); - plus.setPreferredSize(new Dimension(20, 20)); - plus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() + 25)); - - JButton minus = - new JButton( - new ImageIcon( - ImageIO.read( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/imgs/remove.png"))))); - minus.setFocusPainted(false); - minus.setPreferredSize(new Dimension(20, 20)); - minus.setFont(MaterialFonts.getRegularFont(10f)); - minus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() - 25)); - this.scrollView.setWheelScrollingEnabled(true); - - zoomSlider.setPreferredSize(new Dimension(160, 30)); - - scrollView.addComponentListener( - new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - zoomSlider.setValue(scrollView.getZoom()); - zoomLabel.setText(zoomSlider.getValue() + "%"); + /** + * Sets up the zoomer for the given DynamicViewType + * + * @param type The DynamicView that we are setting up the zoomer for (so the zoomer for the + * board view or the zoomer for the proof tree view) + * @return A JPanel containing the zoomer + */ + private JPanel setUpZoomer(DynamicViewType type) { + if (type == DynamicViewType.BOARD) { + return setUpBoardZoomer(); + } else { + if (type == DynamicViewType.PROOF_TREE) { + return setUpProofTreeZoomer(); } - }); - - zoomSlider.addChangeListener( - (ChangeEvent e) -> { - scrollView.zoomTo(zoomSlider.getValue() / 100.0); - zoomLabel.setText(zoomSlider.getValue() + "%"); - }); - - zoomSlider.setMajorTickSpacing(100); - zoomSlider.setMinorTickSpacing(25); - zoomSlider.setPaintTicks(true); - - Hashtable labelTable = new Hashtable<>(); - labelTable.put(0, new JLabel("25%")); - labelTable.put(100, new JLabel("100%")); - labelTable.put(400, new JLabel("400%")); - zoomSlider.setLabelTable(labelTable); - - zoomer.setLayout(new FlowLayout()); - - zoomer.add(minus); - zoomer.add(zoomSlider); - zoomer.add(plus); - zoomer.add(zoomLabel); - - status = new JLabel(); - - zoomWrapper.setLayout(new BorderLayout()); - zoomWrapper.add(status, WEST); - zoomWrapper.add(zoomer, EAST); - } catch (IOException e) { - e.printStackTrace(); + } + + // Should never reach here; if you reach here, that's a problem! + return null; + } + + /** + * Sets up the zoomer for the board view + * + * @return A JPanel containing the zoomer + */ + private JPanel setUpBoardZoomer() { + final String label = "Resize Board"; + ActionListener listener = (ActionListener) -> this.fitBoardViewToScreen(); + return this.setUpZoomerHelper(label, listener); + } + + /** + * Sets up the zoomer for the proof tree view + * + * @return A JPanel containing the zoomer + */ + private JPanel setUpProofTreeZoomer() { + final String label = "Resize Proof"; + ActionListener listener = + (ActionListener) -> + GameBoardFacade.getInstance() + .getLegupUI() + .getProofEditor() + .fitTreeViewToScreen(); + return this.setUpZoomerHelper(label, listener); + } + + /** + * Creates the zoomer + * + * @param label A string containing the label to be displayed on the fit to screen button + * @param listener A listener that determines what the resize button will do + * @return A JPanel containing the zoomer + */ + private JPanel setUpZoomerHelper(final String label, ActionListener listener) { + zoomWrapper = new JPanel(); + try { + zoomer = new JPanel(); + + // Create and add the resize button to the zoomer + JButton resizeButton = new JButton(label); + resizeButton.setFocusPainted(false); + resizeButton.setFocusPainted(false); + resizeButton.setEnabled(true); + resizeButton.setSize(100, 50); + resizeButton.addActionListener(listener); + zoomer.add(resizeButton); + + JLabel zoomLabel = new JLabel("100%"); + zoomLabel.setFont(MaterialFonts.getRegularFont(16f)); + + JSlider zoomSlider = new JSlider(25, 400, 100); + + JButton plus = + new JButton( + new ImageIcon( + ImageIO.read( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource( + "edu/rpi/legup/imgs/add.png"))))); + plus.setFocusPainted(false); + plus.setFont(MaterialFonts.getRegularFont(10f)); + plus.setPreferredSize(new Dimension(20, 20)); + plus.addActionListener( + (ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() + 25)); + + JButton minus = + new JButton( + new ImageIcon( + ImageIO.read( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource( + "edu/rpi/legup/imgs/remove.png"))))); + minus.setFocusPainted(false); + minus.setPreferredSize(new Dimension(20, 20)); + minus.setFont(MaterialFonts.getRegularFont(10f)); + minus.addActionListener( + (ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() - 25)); + this.scrollView.setWheelScrollingEnabled(true); + + zoomSlider.setPreferredSize(new Dimension(160, 30)); + + scrollView.addComponentListener( + new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + zoomSlider.setValue(scrollView.getZoom()); + zoomLabel.setText(zoomSlider.getValue() + "%"); + } + }); + + zoomSlider.addChangeListener( + (ChangeEvent e) -> { + scrollView.zoomTo(zoomSlider.getValue() / 100.0); + zoomLabel.setText(zoomSlider.getValue() + "%"); + }); + + zoomSlider.setMajorTickSpacing(100); + zoomSlider.setMinorTickSpacing(25); + zoomSlider.setPaintTicks(true); + + Hashtable labelTable = new Hashtable<>(); + labelTable.put(0, new JLabel("25%")); + labelTable.put(100, new JLabel("100%")); + labelTable.put(400, new JLabel("400%")); + zoomSlider.setLabelTable(labelTable); + + zoomer.setLayout(new FlowLayout()); + + zoomer.add(minus); + zoomer.add(zoomSlider); + zoomer.add(plus); + zoomer.add(zoomLabel); + + status = new JLabel(); + + zoomWrapper.setLayout(new BorderLayout()); + zoomWrapper.add(status, WEST); + zoomWrapper.add(zoomer, EAST); + } catch (IOException e) { + e.printStackTrace(); + } + return zoomWrapper; + } + + public ScrollView getScrollView() { + return this.scrollView; + } + + public JPanel getZoomWrapper() { + return this.zoomWrapper; + } + + public JPanel getZoomer() { + return this.zoomer; + } + + public void updateInfo(String message) { + status.setFont(INFO_FONT); + status.setForeground(INFO_COLOR); + status.setText(message); + } + + public void updateError(String message) { + status.setFont(ERROR_FONT); + status.setForeground(ERROR_COLOR); + status.setText(message); + } + + public void resetStatus() { + status.setText(""); + } + + public void reset() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + Board board1 = GameBoardFacade.getInstance().getBoard(); + board1.setModifiable(true); + Dimension bi = new Dimension(1200, 900); + this.getScrollView().zoomFit(); + } + + protected void fitBoardViewToScreen() { + scrollView.zoomFit(); } - return zoomWrapper; - } - - public ScrollView getScrollView() { - return this.scrollView; - } - - public JPanel getZoomWrapper() { - return this.zoomWrapper; - } - - public JPanel getZoomer() { - return this.zoomer; - } - - public void updateInfo(String message) { - status.setFont(INFO_FONT); - status.setForeground(INFO_COLOR); - status.setText(message); - } - - public void updateError(String message) { - status.setFont(ERROR_FONT); - status.setForeground(ERROR_COLOR); - status.setText(message); - } - - public void resetStatus() { - status.setText(""); - } - - public void reset() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - Board board1 = GameBoardFacade.getInstance().getBoard(); - board1.setModifiable(true); - Dimension bi = new Dimension(1200, 900); - this.getScrollView().zoomFit(); - } - - protected void fitBoardViewToScreen() { - scrollView.zoomFit(); - } } diff --git a/src/main/java/edu/rpi/legup/ui/DynamicViewType.java b/src/main/java/edu/rpi/legup/ui/DynamicViewType.java index cf345c4e1..8c2f285cd 100644 --- a/src/main/java/edu/rpi/legup/ui/DynamicViewType.java +++ b/src/main/java/edu/rpi/legup/ui/DynamicViewType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.ui; public enum DynamicViewType { - BOARD, - PROOF_TREE + BOARD, + PROOF_TREE } diff --git a/src/main/java/edu/rpi/legup/ui/HomePanel.java b/src/main/java/edu/rpi/legup/ui/HomePanel.java index 9097b648c..11f51eb0e 100644 --- a/src/main/java/edu/rpi/legup/ui/HomePanel.java +++ b/src/main/java/edu/rpi/legup/ui/HomePanel.java @@ -26,637 +26,648 @@ import org.xml.sax.helpers.DefaultHandler; public class HomePanel extends LegupPanel { - private static final Logger LOGGER = LogManager.getLogger(HomePanel.class.getName()); - private LegupUI legupUI; - private JFrame frame; - private JButton[] buttons; - private JLabel[] text; - private JMenuBar menuBar; - private JFileChooser folderBrowser; - - private final int buttonSize = 100; - - private ActionListener openProofListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Object[] items = legupUI.getProofEditor().promptPuzzle(); - if (items == null) { - // The attempt to prompt a puzzle ended gracefully (cancel) - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - legupUI.getProofEditor().loadPuzzle(fileName, puzzleFile); - } - }; - - private ActionListener openPuzzleListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Object[] items = legupUI.getPuzzleEditor().promptPuzzle(); - if (items == null) { - // The attempt to prompt a puzzle ended gracefully (cancel) - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - legupUI.getPuzzleEditor().loadPuzzle(fileName, puzzleFile); - } - }; - - public HomePanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.legupUI = legupUI; - this.frame = frame; - setLayout(new GridLayout(1, 2)); - initText(); - initButtons(); - } - - public JMenuBar getMenuBar() { - this.menuBar = new JMenuBar(); - JMenu settings = new JMenu("Settings"); - menuBar.add(settings); - JMenuItem preferences = new JMenuItem("Preferences"); - preferences.addActionListener( - a -> { - PreferencesDialog preferencesDialog = new PreferencesDialog(this.frame); - System.out.println("Preferences clicked"); - }); - settings.addSeparator(); - settings.add(preferences); - - JMenuItem contribute = new JMenuItem("Contribute to Legup"); - contribute.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop().browse(URI.create("https://github.com/Bram-Hub/Legup")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - settings.add(contribute); - - return this.menuBar; - } - - @Override - public void makeVisible() { - render(); - frame.setJMenuBar(this.getMenuBar()); - } - - private static ImageIcon resizeButtonIcon(ImageIcon icon, int width, int height) { - Image image = icon.getImage(); - Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); - return new ImageIcon(resizedImage); - } - - private void initButtons() { - this.buttons = new JButton[4]; - - this.buttons[0] = - new JButton("Solve Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } - }; - - URL button0IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/proof_file.png"); - ImageIcon button0Icon = new ImageIcon(button0IconLocation); - this.buttons[0].setFocusPainted(false); - this.buttons[0].setIcon(resizeButtonIcon(button0Icon, this.buttonSize, this.buttonSize)); - this.buttons[0].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[0].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[0].addActionListener(CursorController.createListener(this, openProofListener)); - - this.buttons[1] = - new JButton("Create Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } - }; - URL button1IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/new_puzzle_file.png"); - ImageIcon button1Icon = new ImageIcon(button1IconLocation); - this.buttons[1].setFocusPainted(false); - this.buttons[1].setIcon(resizeButtonIcon(button1Icon, this.buttonSize, this.buttonSize)); - this.buttons[1].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[1].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[1].addActionListener(l -> this.openNewPuzzleDialog()); - - this.buttons[2] = - new JButton("Edit Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } - }; - URL button2IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/puzzle_file.png"); - ImageIcon button2Icon = new ImageIcon(button2IconLocation); - this.buttons[2].setFocusPainted(false); - this.buttons[2].setIcon(resizeButtonIcon(button2Icon, this.buttonSize, this.buttonSize)); - this.buttons[2].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[2].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[2].addActionListener( - CursorController.createListener(this, openPuzzleListener)); // PLACEHOLDER - - for (int i = 0; i < this.buttons.length - 1; i++) { // -1 to avoid the batch grader button - this.buttons[i].setBounds(200, 200, 700, 700); - } - this.buttons[3] = new JButton("Batch Grader"); - this.buttons[3].setFocusPainted(false); - this.buttons[3].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[3].setVerticalTextPosition(AbstractButton.BOTTOM); - - this.buttons[3].addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - try { - use_xml_to_check(); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - System.out.println("finished checking the folder"); - } - }); - } - - public void checkFolder() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ + private static final Logger LOGGER = LogManager.getLogger(HomePanel.class.getName()); + private LegupUI legupUI; + private JFrame frame; + private JButton[] buttons; + private JLabel[] text; + private JMenuBar menuBar; + private JFileChooser folderBrowser; + + private final int buttonSize = 100; + + private ActionListener openProofListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Object[] items = legupUI.getProofEditor().promptPuzzle(); + if (items == null) { + // The attempt to prompt a puzzle ended gracefully (cancel) + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + legupUI.getProofEditor().loadPuzzle(fileName, puzzleFile); + } + }; - JFileChooser folderBrowser = new JFileChooser(); - - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - File folder = folderBrowser.getSelectedFile(); - - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name"); - writer.append(","); - writer.append("File Name"); - writer.append(","); - writer.append("Solved?"); - writer.append("\n"); - - for (final File folderEntry : folder.listFiles(File::isDirectory)) { - writer.append(folderEntry.getName()); - writer.append(","); - int count1 = 0; - for (final File fileEntry : folderEntry.listFiles()) { - if (fileEntry.getName().charAt(0) == '.') { - continue; - } - count1++; - if (count1 > 1) { - writer.append(folderEntry.getName()); - writer.append(","); - } - writer.append(fileEntry.getName()); - writer.append(","); - String fileName = folderEntry.getAbsolutePath() + File.separator + fileEntry.getName(); - System.out.println("This is path " + fileName); - File puzzleFile = new File(fileName); - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(1); - legupUI.getProofEditor(); - GameBoardFacade.getInstance().loadPuzzle(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - legupUI.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - if (puzzle.isPuzzleComplete()) { - writer.append("Solved"); - System.out.println(fileEntry.getName() + " solved"); - } else { - writer.append("Not Solved"); - System.out.println(fileEntry.getName() + " not solved"); - } - writer.append("\n"); - } catch (InvalidFileFormatException e) { - LOGGER.error(e.getMessage()); - } - } - } - if (count1 == 0) { - writer.append("No file"); - writer.append("\n"); - } - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); - this.buttons[3].addActionListener((ActionEvent e) -> use_xml_to_check()); - } - } - - /** - * @effect batch grade using .xml parser - go through a collection of files and report their - * "solved?" status - */ - private void use_xml_to_check() { - /* Select a folder, go through each .xml file in the subfolders, look for "isSolved" flag */ - JFileChooser folderBrowser = new JFileChooser(); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - folderBrowser.setSelectedFile(null); - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - File folder = folderBrowser.getSelectedFile(); - - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Solved?,Last Saved\n"); - // Go through student folders, recurse for inner folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - String path = folderEntry.getName(); - // use this helper function to write to the .csv file - recursive_parser(folderEntry, writer, path, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); + private ActionListener openPuzzleListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Object[] items = legupUI.getPuzzleEditor().promptPuzzle(); + if (items == null) { + // The attempt to prompt a puzzle ended gracefully (cancel) + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + legupUI.getPuzzleEditor().loadPuzzle(fileName, puzzleFile); + } + }; + + public HomePanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.legupUI = legupUI; + this.frame = frame; + setLayout(new GridLayout(1, 2)); + initText(); + initButtons(); } - if (resultFile.exists()) { - try { - Desktop desktop = Desktop.getDesktop(); - desktop.open(resultFile); - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); - } + + public JMenuBar getMenuBar() { + this.menuBar = new JMenuBar(); + JMenu settings = new JMenu("Settings"); + menuBar.add(settings); + JMenuItem preferences = new JMenuItem("Preferences"); + preferences.addActionListener( + a -> { + PreferencesDialog preferencesDialog = new PreferencesDialog(this.frame); + System.out.println("Preferences clicked"); + }); + settings.addSeparator(); + settings.add(preferences); + + JMenuItem contribute = new JMenuItem("Contribute to Legup"); + contribute.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/Legup")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + settings.add(contribute); + + return this.menuBar; } - JOptionPane.showMessageDialog(null, "Batch grading complete."); - } - - /** - * @param file - the input file - * @return true if it is a .xml file, else return false - */ - public boolean isxmlfile(File file) { - boolean flag = true; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - builder.parse(file); - flag = true; - } catch (Exception e) { - flag = false; + + @Override + public void makeVisible() { + render(); + frame.setJMenuBar(this.getMenuBar()); } - return flag; - } - - /** - * @param folder - the input folder - * @param writer - write to .csv - * @param path - the current path - * @param name - student's name (the first subfolders of the main folder) - * @throws IOException - */ - private void recursive_parser(File folder, BufferedWriter writer, String path, String name) - throws IOException { - // Empty folder - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,Ungradeable\n"); - return; + + private static ImageIcon resizeButtonIcon(ImageIcon icon, int width, int height) { + Image image = icon.getImage(); + Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); + return new ImageIcon(resizedImage); } - // Go through every other file in the folder - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxParser = spf.newSAXParser(); - for (final File fileEntry : Objects.requireNonNull(folder.listFiles())) { - if (fileEntry.getName().equals("result.csv")) { - continue; - } - // Recurse if it is a subfolder - if (fileEntry.isDirectory()) { - recursive_parser(fileEntry, writer, path + "/" + fileEntry.getName(), name); - continue; - } - // Set path name - String fName = fileEntry.getName(); - String fPath = fileEntry.getAbsolutePath(); - if (fileEntry.getName().charAt(0) == '.') { - continue; - } - // write data - writer.write(name); - writer.write(","); - writer.write(fName); - writer.write(","); - path = folder.getAbsolutePath() + File.separator + fileEntry.getName(); - System.out.println(path); - if (isxmlfile(fileEntry)) { - saxParser.parse( - path, - new DefaultHandler() { - @Override - public void startDocument() throws SAXException {} - boolean solvedFlagExists = false; - boolean puzzleTypeExists = false; + private void initButtons() { + this.buttons = new JButton[4]; - @Override - public void startElement( - String uri, String localName, String qName, Attributes attributes) - throws SAXException { - // append file type to the writer - if (qName.equals("puzzle") - && attributes.getQName(0) == "name" - && !puzzleTypeExists) { - try { - writer.write(attributes.getValue(0)); - writer.write(","); - puzzleTypeExists = true; - } catch (IOException e) { - throw new RuntimeException(e); + this.buttons[0] = + new JButton("Solve Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); } - } - // append the "solved?" status of the proof to the writer - else if (qName.equals("solved") && !solvedFlagExists) { - String isSolved = attributes.getValue(0); - String lastSaved = attributes.getValue(1); - if (isSolved != null) { - if (isSolved.equals("true")) { - try { - writer.write("Solved"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } else if (isSolved.equals("false")) { + }; + + URL button0IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/proof_file.png"); + ImageIcon button0Icon = new ImageIcon(button0IconLocation); + this.buttons[0].setFocusPainted(false); + this.buttons[0].setIcon(resizeButtonIcon(button0Icon, this.buttonSize, this.buttonSize)); + this.buttons[0].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[0].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[0].addActionListener(CursorController.createListener(this, openProofListener)); + + this.buttons[1] = + new JButton("Create Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } + }; + URL button1IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/new_puzzle_file.png"); + ImageIcon button1Icon = new ImageIcon(button1IconLocation); + this.buttons[1].setFocusPainted(false); + this.buttons[1].setIcon(resizeButtonIcon(button1Icon, this.buttonSize, this.buttonSize)); + this.buttons[1].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[1].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[1].addActionListener(l -> this.openNewPuzzleDialog()); + + this.buttons[2] = + new JButton("Edit Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } + }; + URL button2IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/puzzle_file.png"); + ImageIcon button2Icon = new ImageIcon(button2IconLocation); + this.buttons[2].setFocusPainted(false); + this.buttons[2].setIcon(resizeButtonIcon(button2Icon, this.buttonSize, this.buttonSize)); + this.buttons[2].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[2].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[2].addActionListener( + CursorController.createListener(this, openPuzzleListener)); // PLACEHOLDER + + for (int i = 0; i < this.buttons.length - 1; i++) { // -1 to avoid the batch grader button + this.buttons[i].setBounds(200, 200, 700, 700); + } + this.buttons[3] = new JButton("Batch Grader"); + this.buttons[3].setFocusPainted(false); + this.buttons[3].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[3].setVerticalTextPosition(AbstractButton.BOTTOM); + + this.buttons[3].addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { try { - writer.write("Not Solved"); - } catch (IOException e) { - throw new RuntimeException(e); + use_xml_to_check(); + } catch (Exception ex) { + throw new RuntimeException(ex); } - } else { + System.out.println("finished checking the folder"); + } + }); + } + + public void checkFolder() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ + + JFileChooser folderBrowser = new JFileChooser(); + + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + File folder = folderBrowser.getSelectedFile(); + + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name"); + writer.append(","); + writer.append("File Name"); + writer.append(","); + writer.append("Solved?"); + writer.append("\n"); + + for (final File folderEntry : folder.listFiles(File::isDirectory)) { + writer.append(folderEntry.getName()); + writer.append(","); + int count1 = 0; + for (final File fileEntry : folderEntry.listFiles()) { + if (fileEntry.getName().charAt(0) == '.') { + continue; + } + count1++; + if (count1 > 1) { + writer.append(folderEntry.getName()); + writer.append(","); + } + writer.append(fileEntry.getName()); + writer.append(","); + String fileName = + folderEntry.getAbsolutePath() + File.separator + fileEntry.getName(); + System.out.println("This is path " + fileName); + File puzzleFile = new File(fileName); + if (puzzleFile != null && puzzleFile.exists()) { try { - writer.write("Error"); - } catch (IOException e) { - throw new RuntimeException(e); + legupUI.displayPanel(1); + legupUI.getProofEditor(); + GameBoardFacade.getInstance().loadPuzzle(fileName); + String puzzleName = + GameBoardFacade.getInstance().getPuzzleModule().getName(); + legupUI.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + if (puzzle.isPuzzleComplete()) { + writer.append("Solved"); + System.out.println(fileEntry.getName() + " solved"); + } else { + writer.append("Not Solved"); + System.out.println(fileEntry.getName() + " not solved"); + } + writer.append("\n"); + } catch (InvalidFileFormatException e) { + LOGGER.error(e.getMessage()); } - } } - // append when is this proof last saved - if (lastSaved != null) { - try { - writer.write(","); - writer.write(lastSaved); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - solvedFlagExists = true; - } } + if (count1 == 0) { + writer.append("No file"); + writer.append("\n"); + } + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + this.buttons[3].addActionListener((ActionEvent e) -> use_xml_to_check()); + } + } - @Override - public void characters(char[] ch, int start, int length) throws SAXException {} + /** + * @effect batch grade using .xml parser - go through a collection of files and report their + * "solved?" status + */ + private void use_xml_to_check() { + /* Select a folder, go through each .xml file in the subfolders, look for "isSolved" flag */ + JFileChooser folderBrowser = new JFileChooser(); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + folderBrowser.setSelectedFile(null); + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + File folder = folderBrowser.getSelectedFile(); + + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Solved?,Last Saved\n"); + // Go through student folders, recurse for inner folders + for (final File folderEntry : + Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + String path = folderEntry.getName(); + // use this helper function to write to the .csv file + recursive_parser(folderEntry, writer, path, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + } + if (resultFile.exists()) { + try { + Desktop desktop = Desktop.getDesktop(); + desktop.open(resultFile); + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + } + } + JOptionPane.showMessageDialog(null, "Batch grading complete."); + } - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException {} + /** + * @param file - the input file + * @return true if it is a .xml file, else return false + */ + public boolean isxmlfile(File file) { + boolean flag = true; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + builder.parse(file); + flag = true; + } catch (Exception e) { + flag = false; + } + return flag; + } - @Override - public void endDocument() throws SAXException { - if (!puzzleTypeExists) { - try { - writer.write("not a LEGUP puzzle!"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } else if (!solvedFlagExists) { - try { - writer.write("missing flag!"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - }); + /** + * @param folder - the input folder + * @param writer - write to .csv + * @param path - the current path + * @param name - student's name (the first subfolders of the main folder) + * @throws IOException + */ + private void recursive_parser(File folder, BufferedWriter writer, String path, String name) + throws IOException { + // Empty folder + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,Ungradeable\n"); + return; } - // If wrong file type, ungradeable - else { - writer.write("not a \".xml\" file!"); + // Go through every other file in the folder + try { + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser saxParser = spf.newSAXParser(); + for (final File fileEntry : Objects.requireNonNull(folder.listFiles())) { + if (fileEntry.getName().equals("result.csv")) { + continue; + } + // Recurse if it is a subfolder + if (fileEntry.isDirectory()) { + recursive_parser(fileEntry, writer, path + "/" + fileEntry.getName(), name); + continue; + } + // Set path name + String fName = fileEntry.getName(); + String fPath = fileEntry.getAbsolutePath(); + if (fileEntry.getName().charAt(0) == '.') { + continue; + } + // write data + writer.write(name); + writer.write(","); + writer.write(fName); + writer.write(","); + path = folder.getAbsolutePath() + File.separator + fileEntry.getName(); + System.out.println(path); + if (isxmlfile(fileEntry)) { + saxParser.parse( + path, + new DefaultHandler() { + @Override + public void startDocument() throws SAXException {} + + boolean solvedFlagExists = false; + boolean puzzleTypeExists = false; + + @Override + public void startElement( + String uri, + String localName, + String qName, + Attributes attributes) + throws SAXException { + // append file type to the writer + if (qName.equals("puzzle") + && attributes.getQName(0) == "name" + && !puzzleTypeExists) { + try { + writer.write(attributes.getValue(0)); + writer.write(","); + puzzleTypeExists = true; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + // append the "solved?" status of the proof to the writer + else if (qName.equals("solved") && !solvedFlagExists) { + String isSolved = attributes.getValue(0); + String lastSaved = attributes.getValue(1); + if (isSolved != null) { + if (isSolved.equals("true")) { + try { + writer.write("Solved"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else if (isSolved.equals("false")) { + try { + writer.write("Not Solved"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else { + try { + writer.write("Error"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + // append when is this proof last saved + if (lastSaved != null) { + try { + writer.write(","); + writer.write(lastSaved); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + solvedFlagExists = true; + } + } + + @Override + public void characters(char[] ch, int start, int length) + throws SAXException {} + + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException {} + + @Override + public void endDocument() throws SAXException { + if (!puzzleTypeExists) { + try { + writer.write("not a LEGUP puzzle!"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else if (!solvedFlagExists) { + try { + writer.write("missing flag!"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + }); + } + // If wrong file type, ungradeable + else { + writer.write("not a \".xml\" file!"); + } + writer.write("\n"); + } + } catch (ParserConfigurationException | SAXException | IOException e) { + LOGGER.error(e.getMessage()); } - writer.write("\n"); - } - } catch (ParserConfigurationException | SAXException | IOException e) { - LOGGER.error(e.getMessage()); } - } - - private void initText() { - // TODO: add version text after auto-changing version label is implemented. (text[2] = version) - this.text = new JLabel[2]; - - JLabel welcome = new JLabel("Welcome to LEGUP"); - welcome.setFont(new Font("Roboto", Font.BOLD, 23)); - welcome.setAlignmentX(Component.CENTER_ALIGNMENT); - - JLabel credits = new JLabel("A project by Dr. Bram van Heuveln"); - credits.setFont(new Font("Roboto", Font.PLAIN, 12)); - credits.setAlignmentX(Component.CENTER_ALIGNMENT); - - JLabel version = new JLabel("Version 5.1.0"); // This should be autochanged in the future - version.setFont(new Font("Roboto", Font.ITALIC, 10)); - version.setAlignmentX(Component.CENTER_ALIGNMENT); - - this.text[0] = welcome; - this.text[1] = credits; - } - - private void render() { - this.removeAll(); - - this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); - this.legupUI.setTitle("LEGUP: A Better Way to Learn Formal Logic"); - - JPanel buttons = new JPanel(); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[0]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[1]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[2]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - - JPanel batchGraderButton = new JPanel(); - batchGraderButton.add(this.buttons[3]); - batchGraderButton.setAlignmentX(Component.CENTER_ALIGNMENT); - - this.add(Box.createRigidArea(new Dimension(0, 5))); - for (int i = 0; i < this.text.length; i++) { - this.add(this.text[i]); + + private void initText() { + // TODO: add version text after auto-changing version label is implemented. (text[2] = + // version) + this.text = new JLabel[2]; + + JLabel welcome = new JLabel("Welcome to LEGUP"); + welcome.setFont(new Font("Roboto", Font.BOLD, 23)); + welcome.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel credits = new JLabel("A project by Dr. Bram van Heuveln"); + credits.setFont(new Font("Roboto", Font.PLAIN, 12)); + credits.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel version = new JLabel("Version 5.1.0"); // This should be autochanged in the future + version.setFont(new Font("Roboto", Font.ITALIC, 10)); + version.setAlignmentX(Component.CENTER_ALIGNMENT); + + this.text[0] = welcome; + this.text[1] = credits; } - this.add(buttons); - this.add(batchGraderButton); - this.add(Box.createRigidArea(new Dimension(0, 5))); - } - - private void openNewPuzzleDialog() { - CreatePuzzleDialog cpd = new CreatePuzzleDialog(this.frame, this); - cpd.setVisible(true); - } - - private void checkProofAll() { - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - LegupPreferences preferences = LegupPreferences.getInstance(); - File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); - folderBrowser = new JFileChooser(preferredDirectory); - - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - - File folder = folderBrowser.getSelectedFile(); - - // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); - - // Go through student folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - // Write path - String path = folderEntry.getName(); - traverseDir(folderEntry, writer, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); + private void render() { + this.removeAll(); + + this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + this.legupUI.setTitle("LEGUP: A Better Way to Learn Formal Logic"); + + JPanel buttons = new JPanel(); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[0]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[1]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[2]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + + JPanel batchGraderButton = new JPanel(); + batchGraderButton.add(this.buttons[3]); + batchGraderButton.setAlignmentX(Component.CENTER_ALIGNMENT); + + this.add(Box.createRigidArea(new Dimension(0, 5))); + for (int i = 0; i < this.text.length; i++) { + this.add(this.text[i]); + } + this.add(buttons); + this.add(batchGraderButton); + this.add(Box.createRigidArea(new Dimension(0, 5))); } - JOptionPane.showMessageDialog(null, "Batch grading complete."); - } - - private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { - // Recursively traverse directory - GameBoardFacade facade = GameBoardFacade.getInstance(); - // Folder is empty - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,Ungradeable\n"); - return; + + private void openNewPuzzleDialog() { + CreatePuzzleDialog cpd = new CreatePuzzleDialog(this.frame, this); + cpd.setVisible(true); } - // Travese directory, recurse if sub-directory found - // If ungradeable, do not leave a score (0, 1) - for (final File f : Objects.requireNonNull(folder.listFiles())) { - // Recurse - if (f.isDirectory()) { - traverseDir(f, writer, path + "/" + f.getName()); - continue; - } - - // Set path name - writer.append(path).append(","); - - // Load puzzle, run checker - // If wrong file type, ungradeable - String fName = f.getName(); - String fPath = f.getAbsolutePath(); - File puzzleFile = new File(fPath); - if (puzzleFile.exists()) { - // Try to load file. If invalid, note in csv - try { - // Load puzzle, run checker - GameBoardFacade.getInstance().loadPuzzle(fPath); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - - // Write data - writer.append(fName).append(","); - writer.append(puzzle.getName()).append(","); - if (puzzle.isPuzzleComplete()) { - writer.append("Solved\n"); - } else { - writer.append("Unsolved\n"); - } - } catch (InvalidFileFormatException e) { - writer.append(fName).append("InvalidFile,Ungradeable\n"); + + private void checkProofAll() { + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ + + LegupPreferences preferences = LegupPreferences.getInstance(); + File preferredDirectory = + new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); + folderBrowser = new JFileChooser(preferredDirectory); + + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + + File folder = folderBrowser.getSelectedFile(); + + // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); + + // Go through student folders + for (final File folderEntry : + Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + // Write path + String path = folderEntry.getName(); + traverseDir(folderEntry, writer, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } - } else { - LOGGER.debug("Failed to run sim"); - } + JOptionPane.showMessageDialog(null, "Batch grading complete."); } - } - - public void openEditorWithNewPuzzle(String game, int rows, int columns) - throws IllegalArgumentException { - // Validate the dimensions - GameBoardFacade facade = GameBoardFacade.getInstance(); - boolean isValidDimensions = facade.validateDimensions(game, rows, columns); - if (!isValidDimensions) { - JOptionPane.showMessageDialog( - null, - "The dimensions you entered are invalid. Please double check \n" - + "the number of rows and columns and try again.", - "ERROR: Invalid Dimensions", - JOptionPane.ERROR_MESSAGE); - throw new IllegalArgumentException("ERROR: Invalid dimensions given"); + + private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { + // Recursively traverse directory + GameBoardFacade facade = GameBoardFacade.getInstance(); + // Folder is empty + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,Ungradeable\n"); + return; + } + // Travese directory, recurse if sub-directory found + // If ungradeable, do not leave a score (0, 1) + for (final File f : Objects.requireNonNull(folder.listFiles())) { + // Recurse + if (f.isDirectory()) { + traverseDir(f, writer, path + "/" + f.getName()); + continue; + } + + // Set path name + writer.append(path).append(","); + + // Load puzzle, run checker + // If wrong file type, ungradeable + String fName = f.getName(); + String fPath = f.getAbsolutePath(); + File puzzleFile = new File(fPath); + if (puzzleFile.exists()) { + // Try to load file. If invalid, note in csv + try { + // Load puzzle, run checker + GameBoardFacade.getInstance().loadPuzzle(fPath); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + + // Write data + writer.append(fName).append(","); + writer.append(puzzle.getName()).append(","); + if (puzzle.isPuzzleComplete()) { + writer.append("Solved\n"); + } else { + writer.append("Unsolved\n"); + } + } catch (InvalidFileFormatException e) { + writer.append(fName).append("InvalidFile,Ungradeable\n"); + } + } else { + LOGGER.debug("Failed to run sim"); + } + } } - // Set game type on the puzzle editor - this.legupUI.displayPanel(2); - this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, rows, columns); - } - - /** - * Opens the puzzle editor for the specified game with the given statements - * - * @param game a String containing the name of the game - * @param statements an array of statements - */ - public void openEditorWithNewPuzzle(String game, String[] statements) { - // Validate the text input - GameBoardFacade facade = GameBoardFacade.getInstance(); - boolean isValidTextInput = facade.validateTextInput(game, statements); - if (!isValidTextInput) { - JOptionPane.showMessageDialog( - null, - "The input you entered is invalid. Please double check \n" - + "your statements and try again.", - "ERROR: Invalid Text Input", - JOptionPane.ERROR_MESSAGE); - throw new IllegalArgumentException("ERROR: Invalid dimensions given"); + public void openEditorWithNewPuzzle(String game, int rows, int columns) + throws IllegalArgumentException { + // Validate the dimensions + GameBoardFacade facade = GameBoardFacade.getInstance(); + boolean isValidDimensions = facade.validateDimensions(game, rows, columns); + if (!isValidDimensions) { + JOptionPane.showMessageDialog( + null, + "The dimensions you entered are invalid. Please double check \n" + + "the number of rows and columns and try again.", + "ERROR: Invalid Dimensions", + JOptionPane.ERROR_MESSAGE); + throw new IllegalArgumentException("ERROR: Invalid dimensions given"); + } + + // Set game type on the puzzle editor + this.legupUI.displayPanel(2); + this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, rows, columns); } - // Set game type on the puzzle editor - this.legupUI.displayPanel(2); - this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, statements); - } + /** + * Opens the puzzle editor for the specified game with the given statements + * + * @param game a String containing the name of the game + * @param statements an array of statements + */ + public void openEditorWithNewPuzzle(String game, String[] statements) { + // Validate the text input + GameBoardFacade facade = GameBoardFacade.getInstance(); + boolean isValidTextInput = facade.validateTextInput(game, statements); + if (!isValidTextInput) { + JOptionPane.showMessageDialog( + null, + "The input you entered is invalid. Please double check \n" + + "your statements and try again.", + "ERROR: Invalid Text Input", + JOptionPane.ERROR_MESSAGE); + throw new IllegalArgumentException("ERROR: Invalid dimensions given"); + } + + // Set game type on the puzzle editor + this.legupUI.displayPanel(2); + this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, statements); + } } diff --git a/src/main/java/edu/rpi/legup/ui/LegupPanel.java b/src/main/java/edu/rpi/legup/ui/LegupPanel.java index d671e1c4d..d16167b3d 100644 --- a/src/main/java/edu/rpi/legup/ui/LegupPanel.java +++ b/src/main/java/edu/rpi/legup/ui/LegupPanel.java @@ -3,8 +3,8 @@ import javax.swing.*; public abstract class LegupPanel extends JPanel { - /** Alerts panel that it will be going visible now */ - protected final int TOOLBAR_ICON_SCALE = 40; + /** Alerts panel that it will be going visible now */ + protected final int TOOLBAR_ICON_SCALE = 40; - public abstract void makeVisible(); + public abstract void makeVisible(); } diff --git a/src/main/java/edu/rpi/legup/ui/LegupUI.java b/src/main/java/edu/rpi/legup/ui/LegupUI.java index 562d73ffd..33ae11d0c 100644 --- a/src/main/java/edu/rpi/legup/ui/LegupUI.java +++ b/src/main/java/edu/rpi/legup/ui/LegupUI.java @@ -15,187 +15,191 @@ import org.apache.logging.log4j.Logger; public class LegupUI extends JFrame implements WindowListener { - private static final Logger LOGGER = LogManager.getLogger(LegupUI.class.getName()); - - protected FileDialog fileDialog; - protected JPanel window; - protected LegupPanel[] panels; - - /** - * Identifies operating system - * - * @return operating system, either mac or win - */ - public static String getOS() { - String os = System.getProperty("os.name").toLowerCase(); - if (os.contains("mac")) { - os = "mac"; - } else { - os = "win"; - } - return os; - } - - /** LegupUI Constructor - creates a new LegupUI to setup the menu and toolbar */ - public LegupUI() { - setTitle("LEGUP"); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - LegupPreferences prefs = LegupPreferences.getInstance(); - - try { - if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { - UIManager.setLookAndFeel(new FlatDarkLaf()); - } else { - UIManager.setLookAndFeel(new FlatLightLaf()); - } - } catch (UnsupportedLookAndFeelException e) { - System.err.println("Not supported ui look and feel"); - } - - fileDialog = new FileDialog(this); - - initPanels(); - displayPanel(0); - - setIconImage( - new ImageIcon( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif"))) - .getImage()); - - if (LegupPreferences.getInstance() - .getUserPref(LegupPreferences.START_FULL_SCREEN) - .equals(Boolean.toString(true))) { - setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); - } - - this.addWindowListener(this); - addKeyListener( - new KeyAdapter() { - /** - * Invoked when a key has been typed. This event occurs when a key press is followed by a - * key release. - * - * @param e - */ - @Override - public void keyTyped(KeyEvent e) { - System.err.println(e.getKeyChar()); - super.keyTyped(e); - } - }); - setMinimumSize(getPreferredSize()); - setVisible(true); - } - - private void initPanels() { - window = new JPanel(); - window.setLayout(new BorderLayout()); - add(window); - panels = new LegupPanel[3]; - - panels[0] = new HomePanel(this.fileDialog, this, this); - panels[1] = new ProofEditorPanel(this.fileDialog, this, this); - panels[2] = new PuzzleEditorPanel(this.fileDialog, this, this); - } - - protected void displayPanel(int option) { - if (option > panels.length || option < 0) { - throw new InvalidParameterException("Invalid option"); - } - this.window.removeAll(); - panels[option].makeVisible(); - this.window.add(panels[option]); - pack(); - setLocationRelativeTo(null); - revalidate(); - repaint(); - } - - public ProofEditorPanel getProofEditor() { - return (ProofEditorPanel) panels[1]; - } - - public PuzzleEditorPanel getPuzzleEditor() { - return (PuzzleEditorPanel) panels[2]; - } - - public void repaintTree() { - getProofEditor().repaintTree(); - } - - private void directions() { - JOptionPane.showMessageDialog( - null, - "For every move you make, you must provide a rules for it (located in the Rules panel).\n" - + "While working on the edu.rpi.legup.puzzle, you may click on the \"Check\" button to test your proof for correctness.", - "Directions", - JOptionPane.PLAIN_MESSAGE); - } - - public void showStatus(String status, boolean error) { - showStatus(status, error, 1); - } - - public void errorEncountered(String error) { - JOptionPane.showMessageDialog(null, error); - } - - public void showStatus(String status, boolean error, int timer) { - // TODO: implement - } - - // ask to edu.rpi.legup.save current proof - public boolean noquit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - @Override - public void windowOpened(WindowEvent e) {} - - public void windowClosing(WindowEvent e) { - if (GameBoardFacade.getInstance().getHistory().getIndex() > -1) { - if (noquit("Exiting LEGUP?")) { - this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - } else { - this.setDefaultCloseOperation(EXIT_ON_CLOSE); - } - } else { - this.setDefaultCloseOperation(EXIT_ON_CLOSE); - } - } - - public void windowClosed(WindowEvent e) { - System.exit(0); - } - - public void windowIconified(WindowEvent e) {} - - public void windowDeiconified(WindowEvent e) {} - - public void windowActivated(WindowEvent e) {} - - public void windowDeactivated(WindowEvent e) {} - - public BoardView getBoardView() { - return getProofEditor().getBoardView(); - } - - public BoardView getEditorBoardView() { - return getPuzzleEditor().getBoardView(); - } - - public DynamicView getDynamicBoardView() { - return getProofEditor().getDynamicBoardView(); - } - - public DynamicView getEditorDynamicBoardView() { - return getPuzzleEditor().getDynamicBoardView(); - } - - public TreePanel getTreePanel() { - return getProofEditor().getTreePanel(); - } + private static final Logger LOGGER = LogManager.getLogger(LegupUI.class.getName()); + + protected FileDialog fileDialog; + protected JPanel window; + protected LegupPanel[] panels; + + /** + * Identifies operating system + * + * @return operating system, either mac or win + */ + public static String getOS() { + String os = System.getProperty("os.name").toLowerCase(); + if (os.contains("mac")) { + os = "mac"; + } else { + os = "win"; + } + return os; + } + + /** LegupUI Constructor - creates a new LegupUI to setup the menu and toolbar */ + public LegupUI() { + setTitle("LEGUP"); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + LegupPreferences prefs = LegupPreferences.getInstance(); + + try { + if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { + UIManager.setLookAndFeel(new FlatDarkLaf()); + } else { + UIManager.setLookAndFeel(new FlatLightLaf()); + } + } catch (UnsupportedLookAndFeelException e) { + System.err.println("Not supported ui look and feel"); + } + + fileDialog = new FileDialog(this); + + initPanels(); + displayPanel(0); + + setIconImage( + new ImageIcon( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource( + "edu/rpi/legup/images/Legup/Direct" + + " Rules.gif"))) + .getImage()); + + if (LegupPreferences.getInstance() + .getUserPref(LegupPreferences.START_FULL_SCREEN) + .equals(Boolean.toString(true))) { + setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); + } + + this.addWindowListener(this); + addKeyListener( + new KeyAdapter() { + /** + * Invoked when a key has been typed. This event occurs when a key press is + * followed by a key release. + * + * @param e + */ + @Override + public void keyTyped(KeyEvent e) { + System.err.println(e.getKeyChar()); + super.keyTyped(e); + } + }); + setMinimumSize(getPreferredSize()); + setVisible(true); + } + + private void initPanels() { + window = new JPanel(); + window.setLayout(new BorderLayout()); + add(window); + panels = new LegupPanel[3]; + + panels[0] = new HomePanel(this.fileDialog, this, this); + panels[1] = new ProofEditorPanel(this.fileDialog, this, this); + panels[2] = new PuzzleEditorPanel(this.fileDialog, this, this); + } + + protected void displayPanel(int option) { + if (option > panels.length || option < 0) { + throw new InvalidParameterException("Invalid option"); + } + this.window.removeAll(); + panels[option].makeVisible(); + this.window.add(panels[option]); + pack(); + setLocationRelativeTo(null); + revalidate(); + repaint(); + } + + public ProofEditorPanel getProofEditor() { + return (ProofEditorPanel) panels[1]; + } + + public PuzzleEditorPanel getPuzzleEditor() { + return (PuzzleEditorPanel) panels[2]; + } + + public void repaintTree() { + getProofEditor().repaintTree(); + } + + private void directions() { + JOptionPane.showMessageDialog( + null, + "For every move you make, you must provide a rules for it (located in the Rules" + + " panel).\n" + + "While working on the edu.rpi.legup.puzzle, you may click on the \"Check\"" + + " button to test your proof for correctness.", + "Directions", + JOptionPane.PLAIN_MESSAGE); + } + + public void showStatus(String status, boolean error) { + showStatus(status, error, 1); + } + + public void errorEncountered(String error) { + JOptionPane.showMessageDialog(null, error); + } + + public void showStatus(String status, boolean error, int timer) { + // TODO: implement + } + + // ask to edu.rpi.legup.save current proof + public boolean noquit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + @Override + public void windowOpened(WindowEvent e) {} + + public void windowClosing(WindowEvent e) { + if (GameBoardFacade.getInstance().getHistory().getIndex() > -1) { + if (noquit("Exiting LEGUP?")) { + this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } else { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + } else { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + } + + public void windowClosed(WindowEvent e) { + System.exit(0); + } + + public void windowIconified(WindowEvent e) {} + + public void windowDeiconified(WindowEvent e) {} + + public void windowActivated(WindowEvent e) {} + + public void windowDeactivated(WindowEvent e) {} + + public BoardView getBoardView() { + return getProofEditor().getBoardView(); + } + + public BoardView getEditorBoardView() { + return getPuzzleEditor().getBoardView(); + } + + public DynamicView getDynamicBoardView() { + return getProofEditor().getDynamicBoardView(); + } + + public DynamicView getEditorDynamicBoardView() { + return getPuzzleEditor().getDynamicBoardView(); + } + + public TreePanel getTreePanel() { + return getProofEditor().getTreePanel(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java b/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java index 43cb35584..01d696f19 100644 --- a/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java +++ b/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java @@ -5,5 +5,5 @@ public class ManualPuzzleCreatorDialog extends JDialog { - public ManualPuzzleCreatorDialog() {} + public ManualPuzzleCreatorDialog() {} } diff --git a/src/main/java/edu/rpi/legup/ui/PickGameDialog.java b/src/main/java/edu/rpi/legup/ui/PickGameDialog.java index acdc99bee..f703ffcbc 100644 --- a/src/main/java/edu/rpi/legup/ui/PickGameDialog.java +++ b/src/main/java/edu/rpi/legup/ui/PickGameDialog.java @@ -16,156 +16,156 @@ import javax.swing.JTextField; public class PickGameDialog extends JDialog implements ActionListener { - JLabel gameLabel = new JLabel("Game:"); - String[] games; - JComboBox gameBox; - - JLabel puzzleLabel = new JLabel("Puzzle:"); - String[][] puzzles; - String puzzle; - - JTextField puzzleBox; - - JButton puzzleButton = new JButton("..."); - JFileChooser puzzleChooser = new JFileChooser(); - - JButton ok = new JButton("Ok"); - JButton cancel = new JButton("Cancel"); - - JCheckBox autotreeCheckBox = new JCheckBox("Auto-tree"); - JCheckBox showtreeCheckBox = new JCheckBox("Show tree"); - JCheckBox autojustifyCheckBox = new JCheckBox("Auto-justify"); - - public boolean okPressed = false; - private boolean pickBoth; - - /** - * Initialize the dialog - * - * @param parent the parent JFrame - * @param pickBothAtOnce if true they can pick a game type and a specific edu.rpi.legup.puzzle, if - * false they can only pick a game type - */ - public PickGameDialog(JFrame parent, boolean pickBothAtOnce) { - super(parent, true); - - pickBoth = pickBothAtOnce; - initPuzzles(); - - Rectangle b = parent.getBounds(); - - setSize(350, 200); - setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); - setTitle("Select Puzzle"); - - // listeners - gameBox.addActionListener(this); - ok.addActionListener(this); - cancel.addActionListener(this); - - // add components - Container c = getContentPane(); - c.setLayout(null); - - if (pickBoth) { - gameLabel.setBounds(10, 10, 70, 25); - gameBox.setBounds(80, 10, 190, 25); - } else { - gameLabel.setBounds(10, 30, 70, 25); - gameBox.setBounds(80, 30, 190, 25); - } + JLabel gameLabel = new JLabel("Game:"); + String[] games; + JComboBox gameBox; - puzzleLabel.setBounds(10, 40, 70, 25); + JLabel puzzleLabel = new JLabel("Puzzle:"); + String[][] puzzles; + String puzzle; - puzzleBox.setBounds(80, 40, 190, 25); - puzzleButton.setBounds(270, 40, 25, 25); + JTextField puzzleBox; - ok.setBounds(20, 130, 60, 25); - cancel.setBounds(170, 130, 90, 25); + JButton puzzleButton = new JButton("..."); + JFileChooser puzzleChooser = new JFileChooser(); - c.add(gameLabel); - c.add(gameBox); + JButton ok = new JButton("Ok"); + JButton cancel = new JButton("Cancel"); - if (pickBoth) { - c.add(puzzleLabel); - c.add(puzzleBox); - } + JCheckBox autotreeCheckBox = new JCheckBox("Auto-tree"); + JCheckBox showtreeCheckBox = new JCheckBox("Show tree"); + JCheckBox autojustifyCheckBox = new JCheckBox("Auto-justify"); + + public boolean okPressed = false; + private boolean pickBoth; + + /** + * Initialize the dialog + * + * @param parent the parent JFrame + * @param pickBothAtOnce if true they can pick a game type and a specific edu.rpi.legup.puzzle, + * if false they can only pick a game type + */ + public PickGameDialog(JFrame parent, boolean pickBothAtOnce) { + super(parent, true); + + pickBoth = pickBothAtOnce; + initPuzzles(); + + Rectangle b = parent.getBounds(); + + setSize(350, 200); + setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); + setTitle("Select Puzzle"); - c.add(puzzleButton); - puzzleButton.addActionListener(this); + // listeners + gameBox.addActionListener(this); + ok.addActionListener(this); + cancel.addActionListener(this); - c.add(ok); - c.add(cancel); + // add components + Container c = getContentPane(); + c.setLayout(null); - autotreeCheckBox.setBounds(20, 70, 100, 25); - showtreeCheckBox.setBounds(20, 90, 100, 25); - autojustifyCheckBox.setBounds(20, 110, 100, 25); + if (pickBoth) { + gameLabel.setBounds(10, 10, 70, 25); + gameBox.setBounds(80, 10, 190, 25); + } else { + gameLabel.setBounds(10, 30, 70, 25); + gameBox.setBounds(80, 30, 190, 25); + } + + puzzleLabel.setBounds(10, 40, 70, 25); + + puzzleBox.setBounds(80, 40, 190, 25); + puzzleButton.setBounds(270, 40, 25, 25); - c.add(autotreeCheckBox); - c.add(showtreeCheckBox); - c.add(autojustifyCheckBox); - } + ok.setBounds(20, 130, 60, 25); + cancel.setBounds(170, 130, 90, 25); + + c.add(gameLabel); + c.add(gameBox); + + if (pickBoth) { + c.add(puzzleLabel); + c.add(puzzleBox); + } - public void initPuzzles() { - Object[] o = GameBoardFacade.getInstance().getConfig().getPuzzleClassNames().toArray(); + c.add(puzzleButton); + puzzleButton.addActionListener(this); - games = new String[o.length]; + c.add(ok); + c.add(cancel); - for (int x = 0; x < o.length; ++x) { - games[x] = (String) o[x]; + autotreeCheckBox.setBounds(20, 70, 100, 25); + showtreeCheckBox.setBounds(20, 90, 100, 25); + autojustifyCheckBox.setBounds(20, 110, 100, 25); + + c.add(autotreeCheckBox); + c.add(showtreeCheckBox); + c.add(autojustifyCheckBox); } - puzzles = new String[games.length][]; - puzzleBox = new JTextField(); - for (int x = 0; x < games.length; ++x) { - puzzles[x] = new String[o.length]; + public void initPuzzles() { + Object[] o = GameBoardFacade.getInstance().getConfig().getPuzzleClassNames().toArray(); + + games = new String[o.length]; + + for (int x = 0; x < o.length; ++x) { + games[x] = (String) o[x]; + } - for (int y = 0; y < o.length; ++y) { - puzzles[x][y] = (String) o[y]; - } + puzzles = new String[games.length][]; + puzzleBox = new JTextField(); + for (int x = 0; x < games.length; ++x) { + puzzles[x] = new String[o.length]; + + for (int y = 0; y < o.length; ++y) { + puzzles[x][y] = (String) o[y]; + } + } + + gameBox = new JComboBox(games); + } + + public String getPuzzle() { + return puzzleBox.getText(); } - gameBox = new JComboBox(games); - } - - public String getPuzzle() { - return puzzleBox.getText(); - } - - public String getGame() { - return (String) gameBox.getSelectedItem(); - } - - public void actionPerformed(ActionEvent e) { - if (e.getSource() == gameBox) { - int index = gameBox.getSelectedIndex(); - } else { - if (e.getSource() == ok) { - okPressed = true; - setVisible(false); - } else { - if (e.getSource() == cancel) { - okPressed = false; - setVisible(false); + public String getGame() { + return (String) gameBox.getSelectedItem(); + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == gameBox) { + int index = gameBox.getSelectedIndex(); } else { - if (e.getSource() == puzzleButton) { - File f = - new File( - "puzzlefiles" - + File.separator - + gameBox.getSelectedItem().toString().toLowerCase() - + File.separator); - if (f.exists() && f.isDirectory()) { - puzzleChooser = new JFileChooser(f); + if (e.getSource() == ok) { + okPressed = true; + setVisible(false); } else { - puzzleChooser = new JFileChooser(); - } - if (puzzleChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - puzzleBox.setText(puzzleChooser.getSelectedFile().getAbsolutePath()); + if (e.getSource() == cancel) { + okPressed = false; + setVisible(false); + } else { + if (e.getSource() == puzzleButton) { + File f = + new File( + "puzzlefiles" + + File.separator + + gameBox.getSelectedItem().toString().toLowerCase() + + File.separator); + if (f.exists() && f.isDirectory()) { + puzzleChooser = new JFileChooser(f); + } else { + puzzleChooser = new JFileChooser(); + } + if (puzzleChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + puzzleBox.setText(puzzleChooser.getSelectedFile().getAbsolutePath()); + } + } + } } - } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java b/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java index 68adb2bae..475f4bb68 100644 --- a/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java +++ b/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java @@ -19,412 +19,419 @@ public class PreferencesDialog extends JDialog { - private RuleFrame rulesFrame; - - private static final Logger LOGGER = Logger.getLogger(PreferencesDialog.class.getName()); - - private JCheckBox fullScreen, - autoUpdate, - darkMode, - showMistakes, - showAnnotations, - allowDefault, - generateCases, - immFeedback, - colorBlind; - - private JTextField workDirectory; - - private static Image folderIcon; - - static { - try { - folderIcon = - ImageIO.read(PreferencesDialog.class.getResource("/edu/rpi/legup/imgs/folder.png")); - } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Unable to locate icons"); - } - } - - public static PreferencesDialog CreateDialogForProofEditor(Frame frame, RuleFrame rules) { - PreferencesDialog p = new PreferencesDialog(frame); - p.rulesFrame = rules; - return p; - } - - public PreferencesDialog(Frame frame) { - super(frame); - - setTitle("Preferences"); - - JPanel mainPanel = new JPanel(); - mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - mainPanel.setLayout(new BorderLayout()); - - mainPanel.add(createGeneralTab()); - - JPanel bottomPanel = new JPanel(); - bottomPanel.setBorder(null); - bottomPanel.setLayout(new BorderLayout()); - - JToolBar toolbar = new JToolBar(); - toolbar.setBorder(null); - JButton okButton = new JButton("Ok"); - okButton.addActionListener( - l -> { - applyPreferences(); - this.setVisible(false); - this.dispose(); - }); - toolbar.add(okButton); - JButton cancelButton = new JButton("Cancel"); - cancelButton.addActionListener( - l -> { - this.setVisible(false); - this.dispose(); - }); - toolbar.add(cancelButton); - JButton applyButton = new JButton("Apply"); - applyButton.addActionListener( - l -> { - applyPreferences(); - }); - toolbar.add(applyButton); - bottomPanel.add(toolbar, BorderLayout.EAST); - - mainPanel.add(bottomPanel, BorderLayout.SOUTH); - - setContentPane(mainPanel); - - setSize(600, 400); - setLocationRelativeTo(frame); - setVisible(true); - } - - private void toggleDarkMode(LegupPreferences prefs) { - try { - if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { - UIManager.setLookAndFeel(new FlatDarkLaf()); - } else { - UIManager.setLookAndFeel(new FlatLightLaf()); - } - com.formdev.flatlaf.FlatLaf.updateUI(); - } catch (UnsupportedLookAndFeelException e) { - System.err.println("Not supported ui look and feel"); - } - } - - private JScrollPane createGeneralTab() { - LegupPreferences prefs = LegupPreferences.getInstance(); - JScrollPane scrollPane = new JScrollPane(); - JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); - - contentPane.add(createLeftLabel("General Preferences")); - contentPane.add(createLineSeparator()); - - JPanel workRow = new JPanel(); - workRow.setLayout(new BorderLayout()); - JLabel workDirLabel = new JLabel("Work Directory"); - workDirLabel.setToolTipText("This is where the open and save dialogs will open to."); - workRow.add(workDirLabel, BorderLayout.WEST); - workDirectory = new JTextField(prefs.getUserPref(LegupPreferences.WORK_DIRECTORY)); - workRow.add(workDirectory, BorderLayout.CENTER); - JButton openDir = new JButton(new ImageIcon(folderIcon)); - openDir.addActionListener( - a -> { - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(workDirectory.getText())); - chooser.setDialogTitle("Choose work directory"); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setAcceptAllFileFilterUsed(false); - chooser.setVisible(true); - - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - File newFile = chooser.getSelectedFile(); - workDirectory.setText(newFile.toString()); - } - }); - workRow.add(openDir, BorderLayout.EAST); - workRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, workRow.getPreferredSize().height)); - contentPane.add(workRow); - - fullScreen = - new JCheckBox( - "Full Screen", Boolean.valueOf(prefs.getUserPref(LegupPreferences.START_FULL_SCREEN))); - fullScreen.setToolTipText("If checked this starts Legup in full screen."); - JPanel fullScreenRow = new JPanel(); - fullScreenRow.setLayout(new BorderLayout()); - fullScreenRow.add(fullScreen, BorderLayout.WEST); - fullScreenRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, fullScreenRow.getPreferredSize().height)); - contentPane.add(fullScreenRow); - - autoUpdate = - new JCheckBox( - "Automatically Check for Updates", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_UPDATE))); - autoUpdate.setToolTipText( - "If checked this automatically checks for updates on startup of Legup"); - JPanel autoUpdateRow = new JPanel(); - autoUpdateRow.setLayout(new BorderLayout()); - autoUpdateRow.add(autoUpdate, BorderLayout.WEST); - autoUpdateRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, autoUpdateRow.getPreferredSize().height)); - contentPane.add(autoUpdateRow); - // contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - darkMode = - new JCheckBox("Dark Mode", Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))); - darkMode.setToolTipText("This turns dark mode on and off"); - JPanel darkModeRow = new JPanel(); - darkModeRow.setLayout(new BorderLayout()); - darkModeRow.add(darkMode, BorderLayout.WEST); - darkModeRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, darkModeRow.getPreferredSize().height)); - contentPane.add(darkModeRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - contentPane.add(createLeftLabel("Board View Preferences")); - contentPane.add(createLineSeparator()); - showMistakes = - new JCheckBox( - "Show Mistakes", Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_MISTAKES))); - showMistakes.setToolTipText( - "If checked this show incorrectly applied rule applications in red on the board"); - JPanel showMistakesRow = new JPanel(); - showMistakesRow.setLayout(new BorderLayout()); - showMistakesRow.add(showMistakes, BorderLayout.WEST); - showMistakesRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); - contentPane.add(showMistakesRow); - - showAnnotations = - new JCheckBox( - "Show Annotations", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_ANNOTATIONS))); - showAnnotations.setToolTipText( - "If checked this show incorrectly applied rule applications in red on the board"); - JPanel showAnnotationsRow = new JPanel(); - showAnnotationsRow.setLayout(new BorderLayout()); - showAnnotationsRow.add(showAnnotations, BorderLayout.WEST); - showAnnotationsRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showAnnotationsRow.getPreferredSize().height)); - contentPane.add(showAnnotationsRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - contentPane.add(createLeftLabel("Tree View Preferences")); - contentPane.add(createLineSeparator()); - - allowDefault = - new JCheckBox( - "Allow Default Rule Applications", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES))); - allowDefault.setEnabled(false); - allowDefault.setToolTipText( - "If checked this automatically applies a rule where it can on the board"); - - JPanel allowDefaultRow = new JPanel(); - allowDefaultRow.setLayout(new BorderLayout()); - allowDefaultRow.add(allowDefault, BorderLayout.WEST); - allowDefaultRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, allowDefaultRow.getPreferredSize().height)); - contentPane.add(allowDefaultRow); - - generateCases = - new JCheckBox( - "Automatically Generate Cases", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_GENERATE_CASES))); - generateCases.setToolTipText( - "If checked this automatically generates all cases for a case rule"); - JPanel generateCasesRow = new JPanel(); - generateCasesRow.setLayout(new BorderLayout()); - generateCasesRow.add(generateCases, BorderLayout.WEST); - generateCasesRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, generateCasesRow.getPreferredSize().height)); - contentPane.add(generateCasesRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - immFeedback = - new JCheckBox( - "Provide Immediate Feedback", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); - immFeedback.setToolTipText( - "If checked this will update the colors of the tree view elements immediately"); - JPanel immFeedbackRow = new JPanel(); - immFeedbackRow.setLayout(new BorderLayout()); - immFeedbackRow.add(immFeedback, BorderLayout.WEST); - immFeedbackRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); - contentPane.add(immFeedbackRow); - - contentPane.add(createLeftLabel("Instructor Preferences")); - contentPane.add(createLineSeparator()); - immFeedback = - new JCheckBox( - "Instructor Mode", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); - immFeedback.setToolTipText("Currently unimplemented, this does nothing right now"); - immFeedbackRow.setLayout(new BorderLayout()); - immFeedbackRow.add(immFeedback, BorderLayout.WEST); - immFeedbackRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); - contentPane.add(immFeedbackRow); - - contentPane.add(createLeftLabel("Color Preferences")); - contentPane.add(createLineSeparator()); - colorBlind = - new JCheckBox( - "Deuteranomaly(red/green colorblindness)", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.COLOR_BLIND))); - - JPanel colorBlindRow = new JPanel(); - colorBlindRow.setLayout(new BorderLayout()); - colorBlindRow.add(colorBlind, BorderLayout.WEST); - colorBlindRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); - contentPane.add(colorBlindRow); - - scrollPane.setViewportView(contentPane); - return scrollPane; - } - - private JScrollPane createPuzzleTab(Puzzle puzzle) { - JScrollPane scrollPane = new JScrollPane(); - scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - - JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); - - contentPane.add(createLeftLabel("Rules")); - contentPane.add(createLineSeparator()); - - contentPane.add(createLeftLabel("Direct Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getDirectRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + private RuleFrame rulesFrame; + + private static final Logger LOGGER = Logger.getLogger(PreferencesDialog.class.getName()); + + private JCheckBox fullScreen, + autoUpdate, + darkMode, + showMistakes, + showAnnotations, + allowDefault, + generateCases, + immFeedback, + colorBlind; + + private JTextField workDirectory; + + private static Image folderIcon; + + static { + try { + folderIcon = + ImageIO.read( + PreferencesDialog.class.getResource("/edu/rpi/legup/imgs/folder.png")); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Unable to locate icons"); + } } - contentPane.add(createLeftLabel("Case Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getCaseRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + public static PreferencesDialog CreateDialogForProofEditor(Frame frame, RuleFrame rules) { + PreferencesDialog p = new PreferencesDialog(frame); + p.rulesFrame = rules; + return p; } - contentPane.add(createLeftLabel("Contradiction Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getContradictionRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + public PreferencesDialog(Frame frame) { + super(frame); + + setTitle("Preferences"); + + JPanel mainPanel = new JPanel(); + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + mainPanel.setLayout(new BorderLayout()); + + mainPanel.add(createGeneralTab()); + + JPanel bottomPanel = new JPanel(); + bottomPanel.setBorder(null); + bottomPanel.setLayout(new BorderLayout()); + + JToolBar toolbar = new JToolBar(); + toolbar.setBorder(null); + JButton okButton = new JButton("Ok"); + okButton.addActionListener( + l -> { + applyPreferences(); + this.setVisible(false); + this.dispose(); + }); + toolbar.add(okButton); + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener( + l -> { + this.setVisible(false); + this.dispose(); + }); + toolbar.add(cancelButton); + JButton applyButton = new JButton("Apply"); + applyButton.addActionListener( + l -> { + applyPreferences(); + }); + toolbar.add(applyButton); + bottomPanel.add(toolbar, BorderLayout.EAST); + + mainPanel.add(bottomPanel, BorderLayout.SOUTH); + + setContentPane(mainPanel); + + setSize(600, 400); + setLocationRelativeTo(frame); + setVisible(true); } - scrollPane.setViewportView(contentPane); - return scrollPane; - } - - private JPanel createRuleRow(Rule rule) { - JPanel ruleRow = new JPanel(); - ruleRow.setLayout(new BorderLayout()); - - JLabel ruleLabel = new JLabel(rule.getRuleName()); - ruleRow.add(ruleLabel, BorderLayout.WEST); - - JLabel ruleAcc = new JLabel(); - ruleAcc.setHorizontalAlignment(JLabel.CENTER); - ruleAcc.setBorder(MaterialBorders.LIGHT_LINE_BORDER); - ruleAcc.setPreferredSize(new Dimension(60, 20)); - ruleAcc.addMouseListener( - new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent e) { - ruleAcc.requestFocusInWindow(); - } - }); - - ruleAcc.addKeyListener( - new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - int keyCode = e.getKeyCode(); - String combo = ""; - if (e.isControlDown()) { - combo += "Ctrl + "; + private void toggleDarkMode(LegupPreferences prefs) { + try { + if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { + UIManager.setLookAndFeel(new FlatDarkLaf()); } else { - if (e.isShiftDown()) { - combo += "Shift + "; - } else { - if (e.isAltDown()) { - combo += "Alt + "; - } - } + UIManager.setLookAndFeel(new FlatLightLaf()); } - if (keyCode == KeyEvent.VK_CONTROL - || keyCode == KeyEvent.VK_SHIFT - || keyCode == KeyEvent.VK_ALT) { - return; - } - combo += KeyEvent.getKeyText(keyCode); - ruleAcc.setText(combo); - } - }); - - ruleRow.add(ruleAcc, BorderLayout.EAST); - - ruleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, ruleRow.getPreferredSize().height)); - return ruleRow; - } - - private JPanel createLeftLabel(String text) { - JPanel labelRow = new JPanel(); - labelRow.setLayout(new BorderLayout()); - JLabel label = new JLabel(text); - label.setFont(MaterialFonts.BOLD); - label.setHorizontalAlignment(JLabel.LEFT); - labelRow.add(label, BorderLayout.WEST); - - labelRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, labelRow.getPreferredSize().height)); - return labelRow; - } - - private JSeparator createLineSeparator() { - JSeparator separator = new JSeparator(); - separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5)); - return separator; - } - - public void applyPreferences() { - LegupPreferences prefs = LegupPreferences.getInstance(); - prefs.setUserPref(LegupPreferences.WORK_DIRECTORY, workDirectory.getText()); - prefs.setUserPref( - LegupPreferences.START_FULL_SCREEN, Boolean.toString(fullScreen.isSelected())); - prefs.setUserPref(LegupPreferences.AUTO_UPDATE, Boolean.toString(autoUpdate.isSelected())); - prefs.setUserPref(LegupPreferences.DARK_MODE, Boolean.toString(darkMode.isSelected())); - prefs.setUserPref(LegupPreferences.SHOW_MISTAKES, Boolean.toString(showMistakes.isSelected())); - prefs.setUserPref( - LegupPreferences.SHOW_ANNOTATIONS, Boolean.toString(showAnnotations.isSelected())); - prefs.setUserPref( - LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); - prefs.setUserPref( - LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(generateCases.isSelected())); - prefs.setUserPref( - LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(immFeedback.isSelected())); - prefs.setUserPref(LegupPreferences.COLOR_BLIND, Boolean.toString(colorBlind.isSelected())); - - if (rulesFrame != null) { - rulesFrame.getCasePanel().updateRules(); - rulesFrame.getDirectRulePanel().updateRules(); - rulesFrame.getContradictionPanel().updateRules(); + com.formdev.flatlaf.FlatLaf.updateUI(); + } catch (UnsupportedLookAndFeelException e) { + System.err.println("Not supported ui look and feel"); + } + } + + private JScrollPane createGeneralTab() { + LegupPreferences prefs = LegupPreferences.getInstance(); + JScrollPane scrollPane = new JScrollPane(); + JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); + + contentPane.add(createLeftLabel("General Preferences")); + contentPane.add(createLineSeparator()); + + JPanel workRow = new JPanel(); + workRow.setLayout(new BorderLayout()); + JLabel workDirLabel = new JLabel("Work Directory"); + workDirLabel.setToolTipText("This is where the open and save dialogs will open to."); + workRow.add(workDirLabel, BorderLayout.WEST); + workDirectory = new JTextField(prefs.getUserPref(LegupPreferences.WORK_DIRECTORY)); + workRow.add(workDirectory, BorderLayout.CENTER); + JButton openDir = new JButton(new ImageIcon(folderIcon)); + openDir.addActionListener( + a -> { + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(workDirectory.getText())); + chooser.setDialogTitle("Choose work directory"); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setAcceptAllFileFilterUsed(false); + chooser.setVisible(true); + + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + File newFile = chooser.getSelectedFile(); + workDirectory.setText(newFile.toString()); + } + }); + workRow.add(openDir, BorderLayout.EAST); + workRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, workRow.getPreferredSize().height)); + contentPane.add(workRow); + + fullScreen = + new JCheckBox( + "Full Screen", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.START_FULL_SCREEN))); + fullScreen.setToolTipText("If checked this starts Legup in full screen."); + JPanel fullScreenRow = new JPanel(); + fullScreenRow.setLayout(new BorderLayout()); + fullScreenRow.add(fullScreen, BorderLayout.WEST); + fullScreenRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, fullScreenRow.getPreferredSize().height)); + contentPane.add(fullScreenRow); + + autoUpdate = + new JCheckBox( + "Automatically Check for Updates", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_UPDATE))); + autoUpdate.setToolTipText( + "If checked this automatically checks for updates on startup of Legup"); + JPanel autoUpdateRow = new JPanel(); + autoUpdateRow.setLayout(new BorderLayout()); + autoUpdateRow.add(autoUpdate, BorderLayout.WEST); + autoUpdateRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, autoUpdateRow.getPreferredSize().height)); + contentPane.add(autoUpdateRow); + // contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + darkMode = + new JCheckBox( + "Dark Mode", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))); + darkMode.setToolTipText("This turns dark mode on and off"); + JPanel darkModeRow = new JPanel(); + darkModeRow.setLayout(new BorderLayout()); + darkModeRow.add(darkMode, BorderLayout.WEST); + darkModeRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, darkModeRow.getPreferredSize().height)); + contentPane.add(darkModeRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + contentPane.add(createLeftLabel("Board View Preferences")); + contentPane.add(createLineSeparator()); + showMistakes = + new JCheckBox( + "Show Mistakes", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_MISTAKES))); + showMistakes.setToolTipText( + "If checked this show incorrectly applied rule applications in red on the board"); + JPanel showMistakesRow = new JPanel(); + showMistakesRow.setLayout(new BorderLayout()); + showMistakesRow.add(showMistakes, BorderLayout.WEST); + showMistakesRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); + contentPane.add(showMistakesRow); + + showAnnotations = + new JCheckBox( + "Show Annotations", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_ANNOTATIONS))); + showAnnotations.setToolTipText( + "If checked this show incorrectly applied rule applications in red on the board"); + JPanel showAnnotationsRow = new JPanel(); + showAnnotationsRow.setLayout(new BorderLayout()); + showAnnotationsRow.add(showAnnotations, BorderLayout.WEST); + showAnnotationsRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showAnnotationsRow.getPreferredSize().height)); + contentPane.add(showAnnotationsRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + contentPane.add(createLeftLabel("Tree View Preferences")); + contentPane.add(createLineSeparator()); + + allowDefault = + new JCheckBox( + "Allow Default Rule Applications", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES))); + allowDefault.setEnabled(false); + allowDefault.setToolTipText( + "If checked this automatically applies a rule where it can on the board"); + + JPanel allowDefaultRow = new JPanel(); + allowDefaultRow.setLayout(new BorderLayout()); + allowDefaultRow.add(allowDefault, BorderLayout.WEST); + allowDefaultRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, allowDefaultRow.getPreferredSize().height)); + contentPane.add(allowDefaultRow); + + generateCases = + new JCheckBox( + "Automatically Generate Cases", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_GENERATE_CASES))); + generateCases.setToolTipText( + "If checked this automatically generates all cases for a case rule"); + JPanel generateCasesRow = new JPanel(); + generateCasesRow.setLayout(new BorderLayout()); + generateCasesRow.add(generateCases, BorderLayout.WEST); + generateCasesRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, generateCasesRow.getPreferredSize().height)); + contentPane.add(generateCasesRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + immFeedback = + new JCheckBox( + "Provide Immediate Feedback", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); + immFeedback.setToolTipText( + "If checked this will update the colors of the tree view elements immediately"); + JPanel immFeedbackRow = new JPanel(); + immFeedbackRow.setLayout(new BorderLayout()); + immFeedbackRow.add(immFeedback, BorderLayout.WEST); + immFeedbackRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); + contentPane.add(immFeedbackRow); + + contentPane.add(createLeftLabel("Instructor Preferences")); + contentPane.add(createLineSeparator()); + immFeedback = + new JCheckBox( + "Instructor Mode", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); + immFeedback.setToolTipText("Currently unimplemented, this does nothing right now"); + immFeedbackRow.setLayout(new BorderLayout()); + immFeedbackRow.add(immFeedback, BorderLayout.WEST); + immFeedbackRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); + contentPane.add(immFeedbackRow); + + contentPane.add(createLeftLabel("Color Preferences")); + contentPane.add(createLineSeparator()); + colorBlind = + new JCheckBox( + "Deuteranomaly(red/green colorblindness)", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.COLOR_BLIND))); + + JPanel colorBlindRow = new JPanel(); + colorBlindRow.setLayout(new BorderLayout()); + colorBlindRow.add(colorBlind, BorderLayout.WEST); + colorBlindRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); + contentPane.add(colorBlindRow); + + scrollPane.setViewportView(contentPane); + return scrollPane; + } + + private JScrollPane createPuzzleTab(Puzzle puzzle) { + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + + JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); + + contentPane.add(createLeftLabel("Rules")); + contentPane.add(createLineSeparator()); + + contentPane.add(createLeftLabel("Direct Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getDirectRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + } + + contentPane.add(createLeftLabel("Case Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getCaseRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + } + + contentPane.add(createLeftLabel("Contradiction Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getContradictionRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + } + + scrollPane.setViewportView(contentPane); + return scrollPane; } - // toggle dark mode based on updated NIGHT_MODE variable - toggleDarkMode(prefs); - } + private JPanel createRuleRow(Rule rule) { + JPanel ruleRow = new JPanel(); + ruleRow.setLayout(new BorderLayout()); + + JLabel ruleLabel = new JLabel(rule.getRuleName()); + ruleRow.add(ruleLabel, BorderLayout.WEST); + + JLabel ruleAcc = new JLabel(); + ruleAcc.setHorizontalAlignment(JLabel.CENTER); + ruleAcc.setBorder(MaterialBorders.LIGHT_LINE_BORDER); + ruleAcc.setPreferredSize(new Dimension(60, 20)); + ruleAcc.addMouseListener( + new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + ruleAcc.requestFocusInWindow(); + } + }); + + ruleAcc.addKeyListener( + new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + int keyCode = e.getKeyCode(); + String combo = ""; + if (e.isControlDown()) { + combo += "Ctrl + "; + } else { + if (e.isShiftDown()) { + combo += "Shift + "; + } else { + if (e.isAltDown()) { + combo += "Alt + "; + } + } + } + if (keyCode == KeyEvent.VK_CONTROL + || keyCode == KeyEvent.VK_SHIFT + || keyCode == KeyEvent.VK_ALT) { + return; + } + combo += KeyEvent.getKeyText(keyCode); + ruleAcc.setText(combo); + } + }); + + ruleRow.add(ruleAcc, BorderLayout.EAST); + + ruleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, ruleRow.getPreferredSize().height)); + return ruleRow; + } + + private JPanel createLeftLabel(String text) { + JPanel labelRow = new JPanel(); + labelRow.setLayout(new BorderLayout()); + JLabel label = new JLabel(text); + label.setFont(MaterialFonts.BOLD); + label.setHorizontalAlignment(JLabel.LEFT); + labelRow.add(label, BorderLayout.WEST); + + labelRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, labelRow.getPreferredSize().height)); + return labelRow; + } + + private JSeparator createLineSeparator() { + JSeparator separator = new JSeparator(); + separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5)); + return separator; + } + + public void applyPreferences() { + LegupPreferences prefs = LegupPreferences.getInstance(); + prefs.setUserPref(LegupPreferences.WORK_DIRECTORY, workDirectory.getText()); + prefs.setUserPref( + LegupPreferences.START_FULL_SCREEN, Boolean.toString(fullScreen.isSelected())); + prefs.setUserPref(LegupPreferences.AUTO_UPDATE, Boolean.toString(autoUpdate.isSelected())); + prefs.setUserPref(LegupPreferences.DARK_MODE, Boolean.toString(darkMode.isSelected())); + prefs.setUserPref( + LegupPreferences.SHOW_MISTAKES, Boolean.toString(showMistakes.isSelected())); + prefs.setUserPref( + LegupPreferences.SHOW_ANNOTATIONS, Boolean.toString(showAnnotations.isSelected())); + prefs.setUserPref( + LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); + prefs.setUserPref( + LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(generateCases.isSelected())); + prefs.setUserPref( + LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(immFeedback.isSelected())); + prefs.setUserPref(LegupPreferences.COLOR_BLIND, Boolean.toString(colorBlind.isSelected())); + + if (rulesFrame != null) { + rulesFrame.getCasePanel().updateRules(); + rulesFrame.getDirectRulePanel().updateRules(); + rulesFrame.getContradictionPanel().updateRules(); + } + + // toggle dark mode based on updated NIGHT_MODE variable + toggleDarkMode(prefs); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java b/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java index 99f6b139a..956f83ba4 100644 --- a/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java +++ b/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java @@ -37,1047 +37,1090 @@ import org.apache.logging.log4j.Logger; public class ProofEditorPanel extends LegupPanel implements IHistoryListener { - private static final Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName()); - private JMenuBar mBar; - private TreePanel treePanel; - private FileDialog fileDialog; - private JFrame frame; - private RuleFrame ruleFrame; - private DynamicView dynamicBoardView; - private JSplitPane topHalfPanel, mainPanel; - private TitledBorder boardBorder; - - private JButton[] toolBarButtons; - private JMenu file; - private JMenuItem newPuzzle, - resetPuzzle, - saveProofAs, - saveProofChange, - helpTutorial, - preferences, - exit; - private JMenu edit; - private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen; - - private JMenu view; - - private JMenu proof; - private JMenuItem add, delete, merge, collapse; - private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback; - private JMenu about, help; - private JMenuItem helpLegup, aboutLegup; - - private JToolBar toolBar; - private BoardView boardView; - private JFileChooser folderBrowser; - - private LegupUI legupUI; - - public static final int ALLOW_HINTS = 1; - public static final int ALLOW_DEFAPP = 2; - public static final int ALLOW_FULLAI = 4; - public static final int ALLOW_JUST = 8; - public static final int REQ_STEP_JUST = 16; - public static final int IMD_FEEDBACK = 32; - public static final int INTERN_RO = 64; - public static final int AUTO_JUST = 128; - static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; - private static final String[] PROFILES = { - "No Assistance", - "Rigorous Proof", - "Casual Proof", - "Assisted Proof", - "Guided Proof", - "Training-Wheels Proof", - "No Restrictions" - }; - private static final int[] PROF_FLAGS = { - 0, - ALLOW_JUST | REQ_STEP_JUST, - ALLOW_JUST, - ALLOW_HINTS | ALLOW_JUST | AUTO_JUST, - ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST, - ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO, - ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST - }; - private JMenu proofMode = new JMenu("Proof Mode"); - private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length]; - - private static int CONFIG_INDEX = 0; - - protected JMenu ai = new JMenu("AI"); - protected JMenuItem runAI = new JMenuItem("Run AI to completion"); - protected JMenuItem setpAI = new JMenuItem("Run AI one Step"); - protected JMenuItem testAI = new JMenuItem("Test AI!"); - protected JMenuItem hintAI = new JMenuItem("Hint"); - - public ProofEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.fileDialog = fileDialog; - this.frame = frame; - this.legupUI = legupUI; - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(800, 700)); - } - - @Override - public void makeVisible() { - this.removeAll(); - - setupToolBar(); - setupContent(); - frame.setJMenuBar(getMenuBar()); - } - - public JMenuBar getMenuBar() { - if (mBar != null) return mBar; - mBar = new JMenuBar(); - - file = new JMenu("File"); - newPuzzle = new JMenuItem("Open"); - resetPuzzle = new JMenuItem("Reset Puzzle"); - // genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle generator - saveProofAs = new JMenuItem("Save As"); // create a new file to save - saveProofChange = new JMenuItem("Save"); // save to the current file - preferences = new JMenuItem("Preferences"); - helpTutorial = new JMenuItem("Help"); // jump to web page - exit = new JMenuItem("Exit"); - - edit = new JMenu("Edit"); - undo = new JMenuItem("Undo"); - redo = new JMenuItem("Redo"); - - fitBoardToScreen = new JMenuItem("Fit Board to Screen"); - fitTreeToScreen = new JMenuItem("Fit Tree to Screen"); - - view = new JMenu("View"); - - proof = new JMenu("Proof"); - - String os = LegupUI.getOS(); - - add = new JMenuItem("Add"); - add.addActionListener(a -> treePanel.add()); - if (os.equals("mac")) { - add.setAccelerator( - KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + private static final Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName()); + private JMenuBar mBar; + private TreePanel treePanel; + private FileDialog fileDialog; + private JFrame frame; + private RuleFrame ruleFrame; + private DynamicView dynamicBoardView; + private JSplitPane topHalfPanel, mainPanel; + private TitledBorder boardBorder; + + private JButton[] toolBarButtons; + private JMenu file; + private JMenuItem newPuzzle, + resetPuzzle, + saveProofAs, + saveProofChange, + helpTutorial, + preferences, + exit; + private JMenu edit; + private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen; + + private JMenu view; + + private JMenu proof; + private JMenuItem add, delete, merge, collapse; + private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback; + private JMenu about, help; + private JMenuItem helpLegup, aboutLegup; + + private JToolBar toolBar; + private BoardView boardView; + private JFileChooser folderBrowser; + + private LegupUI legupUI; + + public static final int ALLOW_HINTS = 1; + public static final int ALLOW_DEFAPP = 2; + public static final int ALLOW_FULLAI = 4; + public static final int ALLOW_JUST = 8; + public static final int REQ_STEP_JUST = 16; + public static final int IMD_FEEDBACK = 32; + public static final int INTERN_RO = 64; + public static final int AUTO_JUST = 128; + static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; + private static final String[] PROFILES = { + "No Assistance", + "Rigorous Proof", + "Casual Proof", + "Assisted Proof", + "Guided Proof", + "Training-Wheels Proof", + "No Restrictions" + }; + private static final int[] PROF_FLAGS = { + 0, + ALLOW_JUST | REQ_STEP_JUST, + ALLOW_JUST, + ALLOW_HINTS | ALLOW_JUST | AUTO_JUST, + ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST, + ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO, + ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST + }; + private JMenu proofMode = new JMenu("Proof Mode"); + private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length]; + + private static int CONFIG_INDEX = 0; + + protected JMenu ai = new JMenu("AI"); + protected JMenuItem runAI = new JMenuItem("Run AI to completion"); + protected JMenuItem setpAI = new JMenuItem("Run AI one Step"); + protected JMenuItem testAI = new JMenuItem("Test AI!"); + protected JMenuItem hintAI = new JMenuItem("Hint"); + + public ProofEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.fileDialog = fileDialog; + this.frame = frame; + this.legupUI = legupUI; + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(800, 700)); } - proof.add(add); - - delete = new JMenuItem("Delete"); - delete.addActionListener(a -> treePanel.delete()); - if (os.equals("mac")) { - delete.setAccelerator( - KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); - } - proof.add(delete); - - merge = new JMenuItem("Merge"); - merge.addActionListener(a -> treePanel.merge()); - if (os.equals("mac")) { - merge.setAccelerator( - KeyStroke.getKeyStroke('M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK)); + + @Override + public void makeVisible() { + this.removeAll(); + + setupToolBar(); + setupContent(); + frame.setJMenuBar(getMenuBar()); } - proof.add(merge); - - collapse = new JMenuItem("Collapse"); - collapse.addActionListener(a -> treePanel.collapse()); - if (os.equals("mac")) { - collapse.setAccelerator( - KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); + + public JMenuBar getMenuBar() { + if (mBar != null) return mBar; + mBar = new JMenuBar(); + + file = new JMenu("File"); + newPuzzle = new JMenuItem("Open"); + resetPuzzle = new JMenuItem("Reset Puzzle"); + // genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle + // generator + saveProofAs = new JMenuItem("Save As"); // create a new file to save + saveProofChange = new JMenuItem("Save"); // save to the current file + preferences = new JMenuItem("Preferences"); + helpTutorial = new JMenuItem("Help"); // jump to web page + exit = new JMenuItem("Exit"); + + edit = new JMenu("Edit"); + undo = new JMenuItem("Undo"); + redo = new JMenuItem("Redo"); + + fitBoardToScreen = new JMenuItem("Fit Board to Screen"); + fitTreeToScreen = new JMenuItem("Fit Tree to Screen"); + + view = new JMenu("View"); + + proof = new JMenu("Proof"); + + String os = LegupUI.getOS(); + + add = new JMenuItem("Add"); + add.addActionListener(a -> treePanel.add()); + if (os.equals("mac")) { + add.setAccelerator( + KeyStroke.getKeyStroke( + 'A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + } + proof.add(add); + + delete = new JMenuItem("Delete"); + delete.addActionListener(a -> treePanel.delete()); + if (os.equals("mac")) { + delete.setAccelerator( + KeyStroke.getKeyStroke( + 'D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); + } + proof.add(delete); + + merge = new JMenuItem("Merge"); + merge.addActionListener(a -> treePanel.merge()); + if (os.equals("mac")) { + merge.setAccelerator( + KeyStroke.getKeyStroke( + 'M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK)); + } + proof.add(merge); + + collapse = new JMenuItem("Collapse"); + collapse.addActionListener(a -> treePanel.collapse()); + if (os.equals("mac")) { + collapse.setAccelerator( + KeyStroke.getKeyStroke( + 'C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); + } + collapse.setEnabled(false); + proof.add(collapse); + + allowDefault = + new JCheckBoxMenuItem( + "Allow Default Rule Applications", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES) + .equalsIgnoreCase(Boolean.toString(true))); + allowDefault.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.ALLOW_DEFAULT_RULES, + Boolean.toString(allowDefault.isSelected())); + }); + proof.add(allowDefault); + + caseRuleGen = + new JCheckBoxMenuItem( + "Automatically generate cases for CaseRule", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) + .equalsIgnoreCase(Boolean.toString(true))); + caseRuleGen.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.AUTO_GENERATE_CASES, + Boolean.toString(caseRuleGen.isSelected())); + }); + proof.add(caseRuleGen); + + imdFeedback = + new JCheckBoxMenuItem( + "Provide immediate feedback", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK) + .equalsIgnoreCase(Boolean.toString(true))); + imdFeedback.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.IMMEDIATE_FEEDBACK, + Boolean.toString(imdFeedback.isSelected())); + }); + proof.add(imdFeedback); + + about = new JMenu("About"); + helpLegup = new JMenuItem("Help Legup"); + aboutLegup = new JMenuItem("About Legup"); + + mBar.add(file); + file.add(newPuzzle); + newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke( + 'N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); + } + + file.add(resetPuzzle); + resetPuzzle.addActionListener( + a -> { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle != null) { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeNode rootNode = tree.getRootNode(); + if (rootNode != null) { + int confirmReset = + JOptionPane.showConfirmDialog( + this, + "Reset Puzzle to Root Node?", + "Confirm Reset", + JOptionPane.YES_NO_OPTION); + if (confirmReset == JOptionPane.YES_OPTION) { + + List children = rootNode.getChildren(); + children.forEach( + t -> + puzzle.notifyTreeListeners( + l -> l.onTreeElementRemoved(t))); + children.forEach( + t -> + puzzle.notifyBoardListeners( + l -> l.onTreeElementChanged(t))); + rootNode.clearChildren(); + final TreeViewSelection selection = + new TreeViewSelection( + treePanel.getTreeView().getElementView(rootNode)); + puzzle.notifyTreeListeners( + l -> l.onTreeSelectionChanged(selection)); + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged( + selection + .getFirstSelection() + .getTreeElement())); + GameBoardFacade.getInstance().getHistory().clear(); + } + } + } + }); + if (os.equals("mac")) { + resetPuzzle.setAccelerator( + KeyStroke.getKeyStroke( + 'R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK)); + } + file.addSeparator(); + + file.add(saveProofAs); + saveProofAs.addActionListener((ActionEvent) -> saveProofAs()); + + // save proof as... + if (os.equals("mac")) { + saveProofAs.setAccelerator( + KeyStroke.getKeyStroke( + 'S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); + } + + // save proof change + if (os.equals("mac")) { + saveProofChange.setAccelerator( + KeyStroke.getKeyStroke( + 'A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + } + + file.add(saveProofChange); + saveProofChange.addActionListener((ActionEvent) -> saveProofChange()); + file.addSeparator(); + + // preference + file.add(preferences); + preferences.addActionListener( + a -> { + PreferencesDialog preferencesDialog = + PreferencesDialog.CreateDialogForProofEditor( + this.frame, this.ruleFrame); + }); + file.addSeparator(); + + // help function + if (os.equals("mac")) { + helpTutorial.setAccelerator( + KeyStroke.getKeyStroke( + 'H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); + } + file.add(helpTutorial); + + helpTutorial.addActionListener((ActionEvent) -> helpTutorial()); + file.addSeparator(); + + // exit + file.add(exit); + exit.addActionListener((ActionEvent) -> exitEditor()); + if (os.equals("mac")) { + exit.setAccelerator( + KeyStroke.getKeyStroke( + 'Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); + } + mBar.add(edit); + + edit.add(undo); + undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); + if (os.equals("mac")) { + undo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + } + + edit.add(redo); + + // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) + Action redoAction = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + GameBoardFacade.getInstance().getHistory().redo(); + } + }; + if (os.equals("mac")) { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK), + "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "redoAction"); + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK)); + } else { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), + "redoAction"); + redo.getActionMap().put("redoAction", redoAction); + + // Button in menu will show CTRL-SHIFT-Z as primary keybind + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + } + + edit.add(fitBoardToScreen); + fitBoardToScreen.addActionListener( + (ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); + + edit.add(fitTreeToScreen); + fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen()); + + mBar.add(proof); + + about.add(aboutLegup); + aboutLegup.addActionListener( + l -> { + JOptionPane.showMessageDialog(null, "Version: 5.1.0"); + }); + + about.add(helpLegup); + helpLegup.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + + mBar.add(about); + + return mBar; } - collapse.setEnabled(false); - proof.add(collapse); - - allowDefault = - new JCheckBoxMenuItem( - "Allow Default Rule Applications", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES) - .equalsIgnoreCase(Boolean.toString(true))); - allowDefault.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.ALLOW_DEFAULT_RULES, - Boolean.toString(allowDefault.isSelected())); - }); - proof.add(allowDefault); - - caseRuleGen = - new JCheckBoxMenuItem( - "Automatically generate cases for CaseRule", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) - .equalsIgnoreCase(Boolean.toString(true))); - caseRuleGen.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(caseRuleGen.isSelected())); - }); - proof.add(caseRuleGen); - - imdFeedback = - new JCheckBoxMenuItem( - "Provide immediate feedback", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK) - .equalsIgnoreCase(Boolean.toString(true))); - imdFeedback.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(imdFeedback.isSelected())); - }); - proof.add(imdFeedback); - - about = new JMenu("About"); - helpLegup = new JMenuItem("Help Legup"); - aboutLegup = new JMenuItem("About Legup"); - - mBar.add(file); - file.add(newPuzzle); - newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); + + public void exitEditor() { + // Wipes the puzzle entirely as if LEGUP just started + GameBoardFacade.getInstance().clearPuzzle(); + this.legupUI.displayPanel(0); + treePanel = null; + boardView = null; } - file.add(resetPuzzle); - resetPuzzle.addActionListener( - a -> { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle != null) { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeNode rootNode = tree.getRootNode(); - if (rootNode != null) { - int confirmReset = - JOptionPane.showConfirmDialog( - this, - "Reset Puzzle to Root Node?", - "Confirm Reset", - JOptionPane.YES_NO_OPTION); - if (confirmReset == JOptionPane.YES_OPTION) { - - List children = rootNode.getChildren(); - children.forEach(t -> puzzle.notifyTreeListeners(l -> l.onTreeElementRemoved(t))); - children.forEach(t -> puzzle.notifyBoardListeners(l -> l.onTreeElementChanged(t))); - rootNode.clearChildren(); - final TreeViewSelection selection = - new TreeViewSelection(treePanel.getTreeView().getElementView(rootNode)); - puzzle.notifyTreeListeners(l -> l.onTreeSelectionChanged(selection)); - puzzle.notifyBoardListeners( - listener -> - listener.onTreeElementChanged( - selection.getFirstSelection().getTreeElement())); - GameBoardFacade.getInstance().getHistory().clear(); - } + // File opener + public Object[] promptPuzzle() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + if (facade.getBoard() != null) { + if (noquit("Opening a new puzzle?")) { + return new Object[0]; } - } - }); - if (os.equals("mac")) { - resetPuzzle.setAccelerator( - KeyStroke.getKeyStroke('R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK)); - } - file.addSeparator(); + } - file.add(saveProofAs); - saveProofAs.addActionListener((ActionEvent) -> saveProofAs()); + LegupPreferences preferences = LegupPreferences.getInstance(); + String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); + if (preferences.getSavedPath() != "") { + preferredDirectory = preferences.getSavedPath(); + } - // save proof as... - if (os.equals("mac")) { - saveProofAs.setAccelerator( - KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); - } + File preferredDirectoryFile = new File(preferredDirectory); + JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile); + String fileName = null; + File puzzleFile = null; + + fileBrowser.showOpenDialog(this); + fileBrowser.setVisible(true); + fileBrowser.setCurrentDirectory(new File(preferredDirectory)); + fileBrowser.setDialogTitle("Select Proof File"); + fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fileBrowser.setAcceptAllFileFilterUsed(false); + + File puzzlePath = fileBrowser.getSelectedFile(); + System.out.println(puzzlePath.getAbsolutePath()); + + if (puzzlePath != null) { + fileName = puzzlePath.getAbsolutePath(); + String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator)); + preferences.setSavedPath(lastDirectoryPath); + puzzleFile = puzzlePath; + } else { + // The attempt to prompt a puzzle ended gracefully (cancel) + return null; + } - // save proof change - if (os.equals("mac")) { - saveProofChange.setAccelerator( - KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + return new Object[] {fileName, puzzleFile}; } - file.add(saveProofChange); - saveProofChange.addActionListener((ActionEvent) -> saveProofChange()); - file.addSeparator(); - - // preference - file.add(preferences); - preferences.addActionListener( - a -> { - PreferencesDialog preferencesDialog = - PreferencesDialog.CreateDialogForProofEditor(this.frame, this.ruleFrame); - }); - file.addSeparator(); - - // help function - if (os.equals("mac")) { - helpTutorial.setAccelerator( - KeyStroke.getKeyStroke('H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); + public void loadPuzzle() { + Object[] items = promptPuzzle(); + // Return if items == null (cancel) + if (items == null) { + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + loadPuzzle(fileName, puzzleFile); } - file.add(helpTutorial); - - helpTutorial.addActionListener((ActionEvent) -> helpTutorial()); - file.addSeparator(); - - // exit - file.add(exit); - exit.addActionListener((ActionEvent) -> exitEditor()); - if (os.equals("mac")) { - exit.setAccelerator( - KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); + + public void loadPuzzle(String fileName, File puzzleFile) { + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(1); + GameBoardFacade.getInstance().loadPuzzle(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } catch (InvalidFileFormatException e) { + legupUI.displayPanel(0); + LOGGER.error(e.getMessage()); + if (e.getMessage() + .contains( + "Proof Tree construction error: could not find rule by ID")) { // TO + // DO: make error + // message not + // hardcoded + JOptionPane.showMessageDialog( + null, + "This file runs on an outdated version of Legup\n" + + "and is not compatible with the current version.", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } else { + JOptionPane.showMessageDialog( + null, + "File does not exist or it cannot be read", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } + } + } } - mBar.add(edit); - - edit.add(undo); - undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); - if (os.equals("mac")) { - undo.setAccelerator( - KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + + /** save the proof in the current file */ + private void direct_save() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } } - edit.add(redo); - - // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) - Action redoAction = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - GameBoardFacade.getInstance().getHistory().redo(); - } - }; - if (os.equals("mac")) { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() - + InputEvent.SHIFT_DOWN_MASK), - "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "redoAction"); - redo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); - } else { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), - "redoAction"); - redo.getActionMap().put("redoAction", redoAction); - - // Button in menu will show CTRL-SHIFT-Z as primary keybind - redo.setAccelerator( - KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + /** Create a new file and save proof to it */ + private void saveProofAs() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + + fileDialog.setMode(FileDialog.SAVE); + fileDialog.setTitle("Save As"); + String curFileName = GameBoardFacade.getInstance().getCurFileName(); + if (curFileName == null) { + fileDialog.setDirectory( + LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); + } else { + File curFile = new File(curFileName); + fileDialog.setDirectory(curFile.getParent()); + } + fileDialog.setVisible(true); + + String fileName = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + } + + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } } - edit.add(fitBoardToScreen); - fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); - - edit.add(fitTreeToScreen); - fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen()); - - mBar.add(proof); - - about.add(aboutLegup); - aboutLegup.addActionListener( - l -> { - JOptionPane.showMessageDialog(null, "Version: 5.1.0"); - }); - - about.add(helpLegup); - helpLegup.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop() - .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - - mBar.add(about); - - return mBar; - } - - public void exitEditor() { - // Wipes the puzzle entirely as if LEGUP just started - GameBoardFacade.getInstance().clearPuzzle(); - this.legupUI.displayPanel(0); - treePanel = null; - boardView = null; - } - - // File opener - public Object[] promptPuzzle() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - if (facade.getBoard() != null) { - if (noquit("Opening a new puzzle?")) { - return new Object[0]; - } + // Hyperlink for help button; links to wiki page for tutorials + private void helpTutorial() { + // redirecting to certain help link in wiki + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String puz = puzzle.getName(); + String url; + switch (puz) { + case "LightUp": + url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules"; + break; + case "Nurikabe": + url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules"; + break; + case "TreeTent": + url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules"; + break; + case "Skyscrapers": + url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules"; + break; + case "ShortTruthTable": + url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules"; + break; + default: + url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial"; + } + Runtime rt = Runtime.getRuntime(); + try { + // rt.exec("rundll32 url.dll,FileProtocolHandler "+url); + java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); + } catch (IOException e) { + e.printStackTrace(); + } } - LegupPreferences preferences = LegupPreferences.getInstance(); - String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); - if (preferences.getSavedPath() != "") { - preferredDirectory = preferences.getSavedPath(); + // add the new function need to implement + public void add_drop() { + // add the mouse event then we can use the new listener to implement and + // we should create a need jbuttom for it to ship the rule we select. + JPanel panel = new JPanel(); + JButton moveing_buttom = new JButton(); + moveing_buttom.setFocusPainted(false); + moveing_buttom.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // get the selected rule + } + }); + panel.add(moveing_buttom); } - File preferredDirectoryFile = new File(preferredDirectory); - JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile); - String fileName = null; - File puzzleFile = null; - - fileBrowser.showOpenDialog(this); - fileBrowser.setVisible(true); - fileBrowser.setCurrentDirectory(new File(preferredDirectory)); - fileBrowser.setDialogTitle("Select Proof File"); - fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - fileBrowser.setAcceptAllFileFilterUsed(false); - - File puzzlePath = fileBrowser.getSelectedFile(); - System.out.println(puzzlePath.getAbsolutePath()); - - if (puzzlePath != null) { - fileName = puzzlePath.getAbsolutePath(); - String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator)); - preferences.setSavedPath(lastDirectoryPath); - puzzleFile = puzzlePath; - } else { - // The attempt to prompt a puzzle ended gracefully (cancel) - return null; + // Quick save proof to the current file with a pop window to show "successfully saved" + private void saveProofChange() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + // Save confirmation + JOptionPane.showMessageDialog( + null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } } - return new Object[] {fileName, puzzleFile}; - } + // ask to edu.rpi.legup.save current proof + public boolean noquit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } - public void loadPuzzle() { - Object[] items = promptPuzzle(); - // Return if items == null (cancel) - if (items == null) { - return; + /** Sets the main content for the edu.rpi.legup.user interface */ + protected void setupContent() { + // JPanel consoleBox = new JPanel(new BorderLayout()); + JPanel treeBox = new JPanel(new BorderLayout()); + JPanel ruleBox = new JPanel(new BorderLayout()); + + RuleController ruleController = new RuleController(); + ruleFrame = new RuleFrame(ruleController); + ruleBox.add(ruleFrame, BorderLayout.WEST); + + treePanel = new TreePanel(); + + dynamicBoardView = + new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); + TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + JPanel boardPanel = new JPanel(new BorderLayout()); + topHalfPanel = + new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView); + mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel); + topHalfPanel.setPreferredSize(new Dimension(600, 400)); + mainPanel.setPreferredSize(new Dimension(600, 600)); + + boardPanel.add(mainPanel); + boardPanel.setVisible(true); + boardBorder = BorderFactory.createTitledBorder("Board"); + boardBorder.setTitleJustification(TitledBorder.CENTER); + + ruleBox.add(boardPanel); + treeBox.add(ruleBox); + this.add(treeBox); + // consoleBox.add(treeBox); + // + // getContentPane().add(consoleBox); + + // JPopupPanel popupPanel = new JPopupPanel(); + // setGlassPane(popupPanel); + // popupPanel.setVisible(true); + + mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100); + // frame.pack(); + revalidate(); } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - loadPuzzle(fileName, puzzleFile); - } - - public void loadPuzzle(String fileName, File puzzleFile) { - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(1); - GameBoardFacade.getInstance().loadPuzzle(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } catch (InvalidFileFormatException e) { - legupUI.displayPanel(0); - LOGGER.error(e.getMessage()); - if (e.getMessage() - .contains( - "Proof Tree construction error: could not find rule by ID")) { // TO DO: make error - // message not - // hardcoded - JOptionPane.showMessageDialog( - null, - "This file runs on an outdated version of Legup\nand is not compatible with the current version.", - "Error", - JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } else { - JOptionPane.showMessageDialog( - null, "File does not exist or it cannot be read", "Error", JOptionPane.ERROR_MESSAGE); - loadPuzzle(); + + private void setupToolBar() { + setToolBarButtons(new JButton[ToolbarName.values().length]); + for (int i = 0; i < ToolbarName.values().length; i++) { + String toolBarName = ToolbarName.values()[i].toString(); + URL resourceLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); + + // Scale the image icons down to make the buttons smaller + ImageIcon imageIcon = new ImageIcon(resourceLocation); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, + this.TOOLBAR_ICON_SCALE, + Image.SCALE_SMOOTH)); + + JButton button = new JButton(toolBarName, imageIcon); + button.setFocusPainted(false); + getToolBarButtons()[i] = button; } - } - } - } - /** save the proof in the current file */ - private void direct_save() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + toolBar = new JToolBar(); + toolBar.setFloatable(false); + toolBar.setRollover(true); + + for (int i = 0; i < getToolBarButtons().length; i++) { + for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { + if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { + toolBar.addSeparator(); + } + } + String toolBarName = ToolbarName.values()[i].toString(); + + toolBar.add(getToolBarButtons()[i]); + getToolBarButtons()[i].setToolTipText(toolBarName); + + getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); + getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } - } - } - /** Create a new file and save proof to it */ - private void saveProofAs() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; + // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent + // e) -> + // promptPuzzle()); + // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> + // saveProof()); + // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().undo()); + // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().redo()); + toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener( + (ActionEvent e) -> checkProof()); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); + + toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener( + (ActionEvent e) -> checkProofAll()); + + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true); + + this.add(toolBar, BorderLayout.NORTH); } - fileDialog.setMode(FileDialog.SAVE); - fileDialog.setTitle("Save As"); - String curFileName = GameBoardFacade.getInstance().getCurFileName(); - if (curFileName == null) { - fileDialog.setDirectory( - LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); - } else { - File curFile = new File(curFileName); - fileDialog.setDirectory(curFile.getParent()); + /** + * Sets the toolbar buttons + * + * @param toolBarButtons toolbar buttons + */ + public void setToolBarButtons(JButton[] toolBarButtons) { + this.toolBarButtons = toolBarButtons; } - fileDialog.setVisible(true); - String fileName = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + /** + * Gets the toolbar buttons + * + * @return toolbar buttons + */ + public JButton[] getToolBarButtons() { + return toolBarButtons; } - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + /** Checks the proof for correctness */ + private void checkProof() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + Tree tree = GameBoardFacade.getInstance().getTree(); + Board board = facade.getBoard(); + Board finalBoard = null; + boolean delayStatus = true; // board.evalDelayStatus(); + + repaintAll(); + + Puzzle puzzle = facade.getPuzzleModule(); + + if (puzzle.isPuzzleComplete()) { + // This is for submission which is not integrated yet + /*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); + if (confirm == JOptionPane.YES_OPTION) { + Submission submission = new Submission(board); + submission.submit(); + }*/ + JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct."); + } else { + String message = "\nThe game board is not solved."; + JOptionPane.showMessageDialog( + null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE); } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } } - } - - // Hyperlink for help button; links to wiki page for tutorials - private void helpTutorial() { - // redirecting to certain help link in wiki - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; + + private void repaintAll() { + boardView.repaint(); + treePanel.repaint(); } - String puz = puzzle.getName(); - String url; - switch (puz) { - case "LightUp": - url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules"; - break; - case "Nurikabe": - url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules"; - break; - case "TreeTent": - url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules"; - break; - case "Skyscrapers": - url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules"; - break; - case "ShortTruthTable": - url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules"; - break; - default: - url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial"; + + public void setPuzzleView(Puzzle puzzle) { + this.boardView = puzzle.getBoardView(); + + dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); + this.topHalfPanel.setRightComponent(dynamicBoardView); + this.topHalfPanel.setVisible(true); + String boardType = boardView.getBoard().getClass().getSimpleName(); + boardType = boardType.substring(0, boardType.indexOf("Board")); + TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + this.treePanel.getTreeView().resetView(); + this.treePanel.getTreeView().setTree(puzzle.getTree()); + + puzzle.addTreeListener(treePanel.getTreeView()); + puzzle.addBoardListener(puzzle.getBoardView()); + + ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules()); + ruleFrame.getCasePanel().setRules(puzzle.getCaseRules()); + ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules()); + ruleFrame.getSearchPanel().setSearchBar(puzzle); + + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); + + reloadGui(); } - Runtime rt = Runtime.getRuntime(); - try { - // rt.exec("rundll32 url.dll,FileProtocolHandler "+url); - java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); - } catch (IOException e) { - e.printStackTrace(); + + public void reloadGui() { + repaintTree(); } - } - - // add the new function need to implement - public void add_drop() { - // add the mouse event then we can use the new listener to implement and - // we should create a need jbuttom for it to ship the rule we select. - JPanel panel = new JPanel(); - JButton moveing_buttom = new JButton(); - moveing_buttom.setFocusPainted(false); - moveing_buttom.addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // get the selected rule - } - }); - panel.add(moveing_buttom); - } - - // Quick save proof to the current file with a pop window to show "successfully saved" - private void saveProofChange() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; + + public void repaintTree() { + treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree()); } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + + /** Checks the proof for all files */ + private void checkProofAll() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ + + LegupPreferences preferences = LegupPreferences.getInstance(); + File preferredDirectory = + new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); + folderBrowser = new JFileChooser(preferredDirectory); + + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + + File folder = folderBrowser.getSelectedFile(); + + // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); + + // Go through student folders + for (final File folderEntry : + Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + // Write path + String path = folderEntry.getName(); + traverseDir(folderEntry, writer, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } - exporter.exportPuzzle(fileName); - // Save confirmation - JOptionPane.showMessageDialog( - null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE); - } catch (ExportFileException e) { - e.printStackTrace(); - } + JOptionPane.showMessageDialog(null, "Batch grading complete."); } - } - - // ask to edu.rpi.legup.save current proof - public boolean noquit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - /** Sets the main content for the edu.rpi.legup.user interface */ - protected void setupContent() { - // JPanel consoleBox = new JPanel(new BorderLayout()); - JPanel treeBox = new JPanel(new BorderLayout()); - JPanel ruleBox = new JPanel(new BorderLayout()); - - RuleController ruleController = new RuleController(); - ruleFrame = new RuleFrame(ruleController); - ruleBox.add(ruleFrame, BorderLayout.WEST); - - treePanel = new TreePanel(); - - dynamicBoardView = - new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); - TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - JPanel boardPanel = new JPanel(new BorderLayout()); - topHalfPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView); - mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel); - topHalfPanel.setPreferredSize(new Dimension(600, 400)); - mainPanel.setPreferredSize(new Dimension(600, 600)); - - boardPanel.add(mainPanel); - boardPanel.setVisible(true); - boardBorder = BorderFactory.createTitledBorder("Board"); - boardBorder.setTitleJustification(TitledBorder.CENTER); - - ruleBox.add(boardPanel); - treeBox.add(ruleBox); - this.add(treeBox); - // consoleBox.add(treeBox); - // - // getContentPane().add(consoleBox); - - // JPopupPanel popupPanel = new JPopupPanel(); - // setGlassPane(popupPanel); - // popupPanel.setVisible(true); - - mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100); - // frame.pack(); - revalidate(); - } - - private void setupToolBar() { - setToolBarButtons(new JButton[ToolbarName.values().length]); - for (int i = 0; i < ToolbarName.values().length; i++) { - String toolBarName = ToolbarName.values()[i].toString(); - URL resourceLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); - - // Scale the image icons down to make the buttons smaller - ImageIcon imageIcon = new ImageIcon(resourceLocation); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton button = new JButton(toolBarName, imageIcon); - button.setFocusPainted(false); - getToolBarButtons()[i] = button; + + private boolean basicCheckProof(int[][] origCells) { + return false; } - toolBar = new JToolBar(); - toolBar.setFloatable(false); - toolBar.setRollover(true); + private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { + // Recursively traverse directory + GameBoardFacade facade = GameBoardFacade.getInstance(); - for (int i = 0; i < getToolBarButtons().length; i++) { - for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { - if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { - toolBar.addSeparator(); + // Folder is empty + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,,Ungradeable\n"); + return; } - } - String toolBarName = ToolbarName.values()[i].toString(); - toolBar.add(getToolBarButtons()[i]); - getToolBarButtons()[i].setToolTipText(toolBarName); + // Travese directory, recurse if sub-directory found + // If ungradeable, do not leave a score (0, 1) + for (final File f : Objects.requireNonNull(folder.listFiles())) { + // Recurse + if (f.isDirectory()) { + traverseDir(f, writer, path + "/" + f.getName()); + continue; + } - getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); - getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); + // Set path name + writer.append(path).append(","); + + // Load puzzle, run checker + // If wrong file type, ungradeable + String fName = f.getName(); + String fPath = f.getAbsolutePath(); + File puzzleFile = new File(fPath); + if (puzzleFile.exists()) { + // Try to load file. If invalid, note in csv + try { + // Load puzzle, run checker + GameBoardFacade.getInstance().loadPuzzle(fPath); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + + // Write data + writer.append(fName).append(","); + writer.append(puzzle.getName()).append(","); + if (puzzle.isPuzzleComplete()) { + writer.append("1,Solved\n"); + } else { + writer.append("0,Unsolved\n"); + } + } catch (InvalidFileFormatException e) { + writer.append(fName).append(",Invalid,,Ungradeable\n"); + } + } else { + LOGGER.debug("Failed to run sim"); + } + } } - // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent e) -> - // promptPuzzle()); - // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> - // saveProof()); - // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().undo()); - // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().redo()); - toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener((ActionEvent e) -> checkProof()); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); - - toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener( - (ActionEvent e) -> checkProofAll()); - - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true); - - this.add(toolBar, BorderLayout.NORTH); - } - - /** - * Sets the toolbar buttons - * - * @param toolBarButtons toolbar buttons - */ - public void setToolBarButtons(JButton[] toolBarButtons) { - this.toolBarButtons = toolBarButtons; - } - - /** - * Gets the toolbar buttons - * - * @return toolbar buttons - */ - public JButton[] getToolBarButtons() { - return toolBarButtons; - } - - /** Checks the proof for correctness */ - private void checkProof() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - Tree tree = GameBoardFacade.getInstance().getTree(); - Board board = facade.getBoard(); - Board finalBoard = null; - boolean delayStatus = true; // board.evalDelayStatus(); - - repaintAll(); - - Puzzle puzzle = facade.getPuzzleModule(); - - if (puzzle.isPuzzleComplete()) { - // This is for submission which is not integrated yet - /*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); - if (confirm == JOptionPane.YES_OPTION) { - Submission submission = new Submission(board); - submission.submit(); - }*/ - JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct."); - } else { - String message = "\nThe game board is not solved."; - JOptionPane.showMessageDialog(null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE); + public BoardView getBoardView() { + return boardView; } - } - - private void repaintAll() { - boardView.repaint(); - treePanel.repaint(); - } - - public void setPuzzleView(Puzzle puzzle) { - this.boardView = puzzle.getBoardView(); - - dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); - this.topHalfPanel.setRightComponent(dynamicBoardView); - this.topHalfPanel.setVisible(true); - String boardType = boardView.getBoard().getClass().getSimpleName(); - boardType = boardType.substring(0, boardType.indexOf("Board")); - TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - this.treePanel.getTreeView().resetView(); - this.treePanel.getTreeView().setTree(puzzle.getTree()); - - puzzle.addTreeListener(treePanel.getTreeView()); - puzzle.addBoardListener(puzzle.getBoardView()); - - ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules()); - ruleFrame.getCasePanel().setRules(puzzle.getCaseRules()); - ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules()); - ruleFrame.getSearchPanel().setSearchBar(puzzle); - - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); - - reloadGui(); - } - - public void reloadGui() { - repaintTree(); - } - - public void repaintTree() { - treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree()); - } - - /** Checks the proof for all files */ - private void checkProofAll() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - LegupPreferences preferences = LegupPreferences.getInstance(); - File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); - folderBrowser = new JFileChooser(preferredDirectory); - - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - - File folder = folderBrowser.getSelectedFile(); - - // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); - - // Go through student folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - // Write path - String path = folderEntry.getName(); - traverseDir(folderEntry, writer, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); + public DynamicView getDynamicBoardView() { + return dynamicBoardView; } - JOptionPane.showMessageDialog(null, "Batch grading complete."); - } - private boolean basicCheckProof(int[][] origCells) { - return false; - } + public TreePanel getTreePanel() { + return treePanel; + } - private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { - // Recursively traverse directory - GameBoardFacade facade = GameBoardFacade.getInstance(); + /** + * Called when a action is pushed onto the edu.rpi.legup.history stack + * + * @param command action to push onto the stack + */ + @Override + public void onPushChange(ICommand command) { + LOGGER.info("Pushing " + command.getClass().getSimpleName() + " to stack."); + undo.setEnabled(true); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(true); + redo.setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - // Folder is empty - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,,Ungradeable\n"); - return; + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); } - // Travese directory, recurse if sub-directory found - // If ungradeable, do not leave a score (0, 1) - for (final File f : Objects.requireNonNull(folder.listFiles())) { - // Recurse - if (f.isDirectory()) { - traverseDir(f, writer, path + "/" + f.getName()); - continue; - } - - // Set path name - writer.append(path).append(","); - - // Load puzzle, run checker - // If wrong file type, ungradeable - String fName = f.getName(); - String fPath = f.getAbsolutePath(); - File puzzleFile = new File(fPath); - if (puzzleFile.exists()) { - // Try to load file. If invalid, note in csv - try { - // Load puzzle, run checker - GameBoardFacade.getInstance().loadPuzzle(fPath); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - - // Write data - writer.append(fName).append(","); - writer.append(puzzle.getName()).append(","); - if (puzzle.isPuzzleComplete()) { - writer.append("1,Solved\n"); - } else { - writer.append("0,Unsolved\n"); - } - } catch (InvalidFileFormatException e) { - writer.append(fName).append(",Invalid,,Ungradeable\n"); - } - } else { - LOGGER.debug("Failed to run sim"); - } + /** Called when the history is cleared */ + @Override + public void onClearHistory() { + // undo.setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // redo.setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); } - } - - public BoardView getBoardView() { - return boardView; - } - - public DynamicView getDynamicBoardView() { - return dynamicBoardView; - } - - public TreePanel getTreePanel() { - return treePanel; - } - - /** - * Called when a action is pushed onto the edu.rpi.legup.history stack - * - * @param command action to push onto the stack - */ - @Override - public void onPushChange(ICommand command) { - LOGGER.info("Pushing " + command.getClass().getSimpleName() + " to stack."); - undo.setEnabled(true); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(true); - redo.setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); - } - - /** Called when the history is cleared */ - @Override - public void onClearHistory() { - // undo.setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // redo.setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - } - - /** - * Called when an action is redone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - @Override - public void onRedo(boolean isBottom, boolean isTop) { - undo.setEnabled(!isBottom); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); - redo.setEnabled(!isTop); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); - if (isBottom) { - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } else { - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + + /** + * Called when an action is redone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + @Override + public void onRedo(boolean isBottom, boolean isTop) { + undo.setEnabled(!isBottom); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); + redo.setEnabled(!isTop); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); + if (isBottom) { + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } else { + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + } } - } - - /** - * Called when an action is undone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - @Override - public void onUndo(boolean isBottom, boolean isTop) { - undo.setEnabled(!isBottom); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); - redo.setEnabled(!isTop); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - if (isBottom) { - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } else { - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + + /** + * Called when an action is undone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + @Override + public void onUndo(boolean isBottom, boolean isTop) { + undo.setEnabled(!isBottom); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); + redo.setEnabled(!isTop); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + if (isBottom) { + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } else { + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + } } - } - - /** Submits the proof file */ - private void submit() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - Board board = facade.getBoard(); - boolean delayStatus = true; // board.evalDelayStatus(); - repaintAll(); - - Puzzle pm = facade.getPuzzleModule(); - if (pm.isPuzzleComplete() && delayStatus) { - // 0 means yes, 1 means no (Java's fault...) - int confirm = - JOptionPane.showConfirmDialog( - null, - "Are you sure you wish to submit?", - "Proof Submission", - JOptionPane.YES_NO_OPTION); - if (confirm == 0) { - Submission submission = new Submission(board); - submission.submit(); - } - } else { - JOptionPane.showConfirmDialog( - null, - "Your proof is incorrect! Are you sure you wish to submit?", - "Proof Submission", - JOptionPane.YES_NO_OPTION); - Submission submit = new Submission(board); + + /** Submits the proof file */ + private void submit() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + Board board = facade.getBoard(); + boolean delayStatus = true; // board.evalDelayStatus(); + repaintAll(); + + Puzzle pm = facade.getPuzzleModule(); + if (pm.isPuzzleComplete() && delayStatus) { + // 0 means yes, 1 means no (Java's fault...) + int confirm = + JOptionPane.showConfirmDialog( + null, + "Are you sure you wish to submit?", + "Proof Submission", + JOptionPane.YES_NO_OPTION); + if (confirm == 0) { + Submission submission = new Submission(board); + submission.submit(); + } + } else { + JOptionPane.showConfirmDialog( + null, + "Your proof is incorrect! Are you sure you wish to submit?", + "Proof Submission", + JOptionPane.YES_NO_OPTION); + Submission submit = new Submission(board); + } } - } - public void showStatus(String status, boolean error, int timer) { - // TODO: implement - } + public void showStatus(String status, boolean error, int timer) { + // TODO: implement + } - protected void fitTreeViewToScreen() { - this.treePanel.getTreeView().zoomFit(); - } + protected void fitTreeViewToScreen() { + this.treePanel.getTreeView().zoomFit(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java b/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java index 23b3e728c..b3cd30ffb 100644 --- a/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java +++ b/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java @@ -30,531 +30,550 @@ public class PuzzleEditorPanel extends LegupPanel implements IHistoryListener { - private static final Logger LOGGER = LogManager.getLogger(PuzzleEditorPanel.class.getName()); - private JMenu[] menus; - private JMenuItem helpLegup, aboutLegup; - private JMenuBar menuBar; - private JToolBar toolBar; - private JFrame frame; - private JButton[] buttons; - JSplitPane splitPanel; - private JButton[] toolBarButtons; - private JPanel elementPanel; - private DynamicView dynamicBoardView; - private BoardView boardView; - private TitledBorder boardBorder; - // private JSplitPane splitPanel, topHalfPanel; - private FileDialog fileDialog; - private JMenuItem undo, redo, fitBoardToScreen; - private ElementFrame elementFrame; - private JPanel treePanel; - private LegupUI legupUI; - private EditorElementController editorElementController; - static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; - - public PuzzleEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.fileDialog = fileDialog; - this.frame = frame; - this.legupUI = legupUI; - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(800, 700)); - } - - protected void setupContent() { + private static final Logger LOGGER = LogManager.getLogger(PuzzleEditorPanel.class.getName()); + private JMenu[] menus; + private JMenuItem helpLegup, aboutLegup; + private JMenuBar menuBar; + private JToolBar toolBar; + private JFrame frame; + private JButton[] buttons; JSplitPane splitPanel; - JPanel elementBox = new JPanel(new BorderLayout()); - - editorElementController = new EditorElementController(); - elementFrame = new ElementFrame(editorElementController); - elementBox.add(elementFrame, BorderLayout.WEST); - - dynamicBoardView = - new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); - TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - JPanel boardPanel = new JPanel(new BorderLayout()); - splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, elementFrame, dynamicBoardView); - splitPanel.setPreferredSize(new Dimension(600, 400)); - - boardPanel.add(splitPanel); - boardBorder = BorderFactory.createTitledBorder("Board"); - boardBorder.setTitleJustification(TitledBorder.CENTER); - - elementBox.add(boardPanel); - this.add(elementBox); - - splitPanel.setDividerLocation(splitPanel.getMaximumDividerLocation() + 100); - this.splitPanel = splitPanel; - revalidate(); - } - - public void setMenuBar() { - String os = LegupUI.getOS(); - menuBar = new JMenuBar(); - menus = new JMenu[3]; - - // create menus - - // FILE - menus[0] = new JMenu("File"); - - // file>new - JMenuItem newPuzzle = new JMenuItem("New"); - newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); - } - // file>save - JMenuItem savePuzzle = new JMenuItem("Save As"); - savePuzzle.addActionListener((ActionEvent) -> savePuzzle()); - JMenuItem directSavePuzzle = new JMenuItem("Direct Save Proof "); - directSavePuzzle.addActionListener((ActionEvent) -> direct_save()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); + private JButton[] toolBarButtons; + private JPanel elementPanel; + private DynamicView dynamicBoardView; + private BoardView boardView; + private TitledBorder boardBorder; + // private JSplitPane splitPanel, topHalfPanel; + private FileDialog fileDialog; + private JMenuItem undo, redo, fitBoardToScreen; + private ElementFrame elementFrame; + private JPanel treePanel; + private LegupUI legupUI; + private EditorElementController editorElementController; + static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; + + public PuzzleEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.fileDialog = fileDialog; + this.frame = frame; + this.legupUI = legupUI; + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(800, 700)); } - JMenuItem exit = new JMenuItem("Exit"); - exit.addActionListener((ActionEvent) -> exitEditor()); - if (os.equals("mac")) { - exit.setAccelerator( - KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); - } - menus[0].add(newPuzzle); - menus[0].add(savePuzzle); - menus[0].add(directSavePuzzle); - menus[0].add(exit); - - // EDIT - menus[1] = new JMenu("Edit"); - // edit>undo - undo = new JMenuItem("Undo"); - // edit>redo - redo = new JMenuItem("Redo"); - fitBoardToScreen = new JMenuItem("Fit Board to Screen"); - - menus[1].add(undo); - undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); - if (os.equals("mac")) { - undo.setAccelerator( - KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + protected void setupContent() { + JSplitPane splitPanel; + JPanel elementBox = new JPanel(new BorderLayout()); + + editorElementController = new EditorElementController(); + elementFrame = new ElementFrame(editorElementController); + elementBox.add(elementFrame, BorderLayout.WEST); + + dynamicBoardView = + new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); + TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + JPanel boardPanel = new JPanel(new BorderLayout()); + splitPanel = + new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, elementFrame, dynamicBoardView); + splitPanel.setPreferredSize(new Dimension(600, 400)); + + boardPanel.add(splitPanel); + boardBorder = BorderFactory.createTitledBorder("Board"); + boardBorder.setTitleJustification(TitledBorder.CENTER); + + elementBox.add(boardPanel); + this.add(elementBox); + + splitPanel.setDividerLocation(splitPanel.getMaximumDividerLocation() + 100); + this.splitPanel = splitPanel; + revalidate(); } - menus[1].add(redo); - - // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) - Action redoAction = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - GameBoardFacade.getInstance().getHistory().redo(); - } - }; - if (os.equals("mac")) { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() - + InputEvent.SHIFT_DOWN_MASK), - "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "redoAction"); - redo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); - } else { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), - "redoAction"); - redo.getActionMap().put("redoAction", redoAction); - - // Button in menu will show CTRL-SHIFT-Z as primary keybind - redo.setAccelerator( - KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + public void setMenuBar() { + String os = LegupUI.getOS(); + menuBar = new JMenuBar(); + menus = new JMenu[3]; + + // create menus + + // FILE + menus[0] = new JMenu("File"); + + // file>new + JMenuItem newPuzzle = new JMenuItem("New"); + newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke( + 'N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); + } + // file>save + JMenuItem savePuzzle = new JMenuItem("Save As"); + savePuzzle.addActionListener((ActionEvent) -> savePuzzle()); + JMenuItem directSavePuzzle = new JMenuItem("Direct Save Proof "); + directSavePuzzle.addActionListener((ActionEvent) -> direct_save()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke( + 'D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); + } + + JMenuItem exit = new JMenuItem("Exit"); + exit.addActionListener((ActionEvent) -> exitEditor()); + if (os.equals("mac")) { + exit.setAccelerator( + KeyStroke.getKeyStroke( + 'Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); + } + menus[0].add(newPuzzle); + menus[0].add(savePuzzle); + menus[0].add(directSavePuzzle); + menus[0].add(exit); + + // EDIT + menus[1] = new JMenu("Edit"); + // edit>undo + undo = new JMenuItem("Undo"); + // edit>redo + redo = new JMenuItem("Redo"); + fitBoardToScreen = new JMenuItem("Fit Board to Screen"); + + menus[1].add(undo); + undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); + if (os.equals("mac")) { + undo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + } + + menus[1].add(redo); + + // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) + Action redoAction = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + GameBoardFacade.getInstance().getHistory().redo(); + } + }; + if (os.equals("mac")) { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK), + "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "redoAction"); + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK)); + } else { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), + "redoAction"); + redo.getActionMap().put("redoAction", redoAction); + + // Button in menu will show CTRL-SHIFT-Z as primary keybind + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + } + + menus[1].add(fitBoardToScreen); + fitBoardToScreen.addActionListener( + (ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); + + // HELP + menus[2] = new JMenu("Help"); + helpLegup = new JMenuItem("Help Legup"); + aboutLegup = new JMenuItem("About Legup"); + menus[2].add(helpLegup); + menus[2].add(aboutLegup); + helpLegup.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + menus[2].add(aboutLegup); + aboutLegup.addActionListener( + l -> { + JOptionPane.showMessageDialog(null, "Version: 5.1.0"); + }); + // add menus to menubar + for (JMenu menu : menus) { + menuBar.add(menu); + } + frame.setJMenuBar(menuBar); } - menus[1].add(fitBoardToScreen); - fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); - - // HELP - menus[2] = new JMenu("Help"); - helpLegup = new JMenuItem("Help Legup"); - aboutLegup = new JMenuItem("About Legup"); - menus[2].add(helpLegup); - menus[2].add(aboutLegup); - helpLegup.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop() - .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - menus[2].add(aboutLegup); - aboutLegup.addActionListener( - l -> { - JOptionPane.showMessageDialog(null, "Version: 5.1.0"); - }); - // add menus to menubar - for (JMenu menu : menus) { - menuBar.add(menu); + public void exitEditor() { + // Wipes the puzzle entirely as if LEGUP just started + GameBoardFacade.getInstance().clearPuzzle(); + this.legupUI.displayPanel(0); + treePanel = null; + boardView = null; } - frame.setJMenuBar(menuBar); - } - - public void exitEditor() { - // Wipes the puzzle entirely as if LEGUP just started - GameBoardFacade.getInstance().clearPuzzle(); - this.legupUI.displayPanel(0); - treePanel = null; - boardView = null; - } - - @Override - public void makeVisible() { - this.removeAll(); - - setupToolBar(); - setupContent(); - setMenuBar(); - } - - private void setupToolBar() { - setToolBarButtons(new JButton[ToolbarName.values().length + 1]); - int lastone = 0; - for (int i = 0; i < ToolbarName.values().length - 1; i++) { - String toolBarName = ToolbarName.values()[i].toString(); - URL resourceLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); - - // Scale the image icons down to make the buttons smaller - ImageIcon imageIcon = new ImageIcon(resourceLocation); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton button = new JButton(toolBarName, imageIcon); - button.setFocusPainted(false); - getToolBarButtons()[i] = button; - lastone = i; + + @Override + public void makeVisible() { + this.removeAll(); + + setupToolBar(); + setupContent(); + setMenuBar(); } - URL check_and_save = - ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Check.png"); - ImageIcon imageIcon = new ImageIcon(check_and_save); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton checkandsave = new JButton("check and Save", imageIcon); - checkandsave.setFocusPainted(false); - checkandsave.addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // savePuzzle(); - String filename = savePuzzle(); - File puzzlename = new File(filename); - System.out.println(filename); - - GameBoardFacade.getInstance().getLegupUI().displayPanel(1); - GameBoardFacade.getInstance() - .getLegupUI() - .getProofEditor() - .loadPuzzle(filename, new File(filename)); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzlename.getName()); - } - }); - getToolBarButtons()[lastone + 1] = checkandsave; - System.out.println("it is create new file"); - - toolBar = new JToolBar(); - toolBar.setFloatable(false); - toolBar.setRollover(true); - - for (int i = 0; i < getToolBarButtons().length - 1; i++) { - for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { - if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { - toolBar.addSeparator(); + private void setupToolBar() { + setToolBarButtons(new JButton[ToolbarName.values().length + 1]); + int lastone = 0; + for (int i = 0; i < ToolbarName.values().length - 1; i++) { + String toolBarName = ToolbarName.values()[i].toString(); + URL resourceLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); + + // Scale the image icons down to make the buttons smaller + ImageIcon imageIcon = new ImageIcon(resourceLocation); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, + this.TOOLBAR_ICON_SCALE, + Image.SCALE_SMOOTH)); + + JButton button = new JButton(toolBarName, imageIcon); + button.setFocusPainted(false); + getToolBarButtons()[i] = button; + lastone = i; } - } - String toolBarName = ToolbarName.values()[i].toString(); - toolBar.add(getToolBarButtons()[i]); - getToolBarButtons()[i].setToolTipText(toolBarName); + URL check_and_save = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Check.png"); + ImageIcon imageIcon = new ImageIcon(check_and_save); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, + this.TOOLBAR_ICON_SCALE, + Image.SCALE_SMOOTH)); + + JButton checkandsave = new JButton("check and Save", imageIcon); + checkandsave.setFocusPainted(false); + checkandsave.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // savePuzzle(); + String filename = savePuzzle(); + File puzzlename = new File(filename); + System.out.println(filename); + + GameBoardFacade.getInstance().getLegupUI().displayPanel(1); + GameBoardFacade.getInstance() + .getLegupUI() + .getProofEditor() + .loadPuzzle(filename, new File(filename)); + String puzzleName = + GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzlename.getName()); + } + }); + getToolBarButtons()[lastone + 1] = checkandsave; + System.out.println("it is create new file"); + + toolBar = new JToolBar(); + toolBar.setFloatable(false); + toolBar.setRollover(true); + + for (int i = 0; i < getToolBarButtons().length - 1; i++) { + for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { + if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { + toolBar.addSeparator(); + } + } + String toolBarName = ToolbarName.values()[i].toString(); + + toolBar.add(getToolBarButtons()[i]); + getToolBarButtons()[i].setToolTipText(toolBarName); + + getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); + getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); + } - getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); - getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); + // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent + // e) -> + // promptPuzzle()); + // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> + // saveProof()); + // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().undo()); + // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().redo()); + toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); + + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + + this.add(toolBar, BorderLayout.NORTH); } - // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent e) -> - // promptPuzzle()); - // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> - // saveProof()); - // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().undo()); - // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().redo()); - toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); - - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); - - this.add(toolBar, BorderLayout.NORTH); - } - - public void loadPuzzleFromHome(String game, int rows, int columns) - throws IllegalArgumentException { - GameBoardFacade facade = GameBoardFacade.getInstance(); - try { - facade.loadPuzzle(game, rows, columns); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (RuntimeException e) { - e.printStackTrace(); - LOGGER.error(e.getMessage()); + public void loadPuzzleFromHome(String game, int rows, int columns) + throws IllegalArgumentException { + GameBoardFacade facade = GameBoardFacade.getInstance(); + try { + facade.loadPuzzle(game, rows, columns); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (RuntimeException e) { + e.printStackTrace(); + LOGGER.error(e.getMessage()); + } } - } - - public void loadPuzzleFromHome(String game, String[] statements) { - GameBoardFacade facade = GameBoardFacade.getInstance(); - try { - facade.loadPuzzle(game, statements); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (RuntimeException e) { - e.printStackTrace(); - LOGGER.error(e.getMessage()); + + public void loadPuzzleFromHome(String game, String[] statements) { + GameBoardFacade facade = GameBoardFacade.getInstance(); + try { + facade.loadPuzzle(game, statements); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (RuntimeException e) { + e.printStackTrace(); + LOGGER.error(e.getMessage()); + } } - } - - // File opener - public Object[] promptPuzzle() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - if (facade.getBoard() != null) { - if (noQuit("Opening a new puzzle to edit?")) { - return new Object[0]; - } + + // File opener + public Object[] promptPuzzle() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + if (facade.getBoard() != null) { + if (noQuit("Opening a new puzzle to edit?")) { + return new Object[0]; + } + } + if (fileDialog == null) { + fileDialog = new FileDialog(this.frame); + } + LegupPreferences preferences = LegupPreferences.getInstance(); + String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); + + fileDialog.setMode(FileDialog.LOAD); + fileDialog.setTitle("Select Puzzle"); + fileDialog.setDirectory(preferredDirectory); + fileDialog.setVisible(true); + String fileName = null; + File puzzleFile = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + puzzleFile = new File(fileName); + } else { + // The attempt to prompt a puzzle ended gracefully (cancel) + return null; + } + + return new Object[] {fileName, puzzleFile}; } - if (fileDialog == null) { - fileDialog = new FileDialog(this.frame); + + public void loadPuzzle() { + Object[] items = promptPuzzle(); + // Return if items == null (cancel) + if (items == null) { + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + loadPuzzle(fileName, puzzleFile); } - LegupPreferences preferences = LegupPreferences.getInstance(); - String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); - - fileDialog.setMode(FileDialog.LOAD); - fileDialog.setTitle("Select Puzzle"); - fileDialog.setDirectory(preferredDirectory); - fileDialog.setVisible(true); - String fileName = null; - File puzzleFile = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - puzzleFile = new File(fileName); - } else { - // The attempt to prompt a puzzle ended gracefully (cancel) - return null; + + public void loadPuzzle(String fileName, File puzzleFile) { + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(2); + GameBoardFacade.getInstance().loadPuzzleEditor(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } catch (InvalidFileFormatException e) { + legupUI.displayPanel(0); + LOGGER.error(e.getMessage()); + JOptionPane.showMessageDialog( + null, + "File does not exist, cannot be read, or cannot be edited", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } + } } - return new Object[] {fileName, puzzleFile}; - } + public boolean noQuit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + @Override + public void onPushChange(ICommand command) {} + + @Override + public void onUndo(boolean isBottom, boolean isTop) {} - public void loadPuzzle() { - Object[] items = promptPuzzle(); - // Return if items == null (cancel) - if (items == null) { - return; + @Override + public void onRedo(boolean isBottom, boolean isTop) {} + + @Override + public void onClearHistory() { + // undo.setEnabled(false); + // redo.setEnabled(false); } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - loadPuzzle(fileName, puzzleFile); - } - - public void loadPuzzle(String fileName, File puzzleFile) { - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(2); - GameBoardFacade.getInstance().loadPuzzleEditor(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } catch (InvalidFileFormatException e) { - legupUI.displayPanel(0); - LOGGER.error(e.getMessage()); - JOptionPane.showMessageDialog( - null, - "File does not exist, cannot be read, or cannot be edited", - "Error", - JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } + + public BoardView getBoardView() { + return boardView; } - } - - public boolean noQuit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - @Override - public void onPushChange(ICommand command) {} - - @Override - public void onUndo(boolean isBottom, boolean isTop) {} - - @Override - public void onRedo(boolean isBottom, boolean isTop) {} - - @Override - public void onClearHistory() { - // undo.setEnabled(false); - // redo.setEnabled(false); - } - - public BoardView getBoardView() { - return boardView; - } - - public JButton[] getToolBarButtons() { - return toolBarButtons; - } - - public void setToolBarButtons(JButton[] toolBarButtons) { - this.toolBarButtons = toolBarButtons; - } - - private void repaintAll() { - boardView.repaint(); - } - - public void setPuzzleView(Puzzle puzzle) { - this.boardView = puzzle.getBoardView(); - editorElementController.setElementController(boardView.getElementController()); - dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); - if (this.splitPanel != null) { - this.splitPanel.setRightComponent(dynamicBoardView); - this.splitPanel.setVisible(true); + + public JButton[] getToolBarButtons() { + return toolBarButtons; } - TitledBorder titleBoard = - BorderFactory.createTitledBorder(boardView.getClass().getSimpleName()); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); + public void setToolBarButtons(JButton[] toolBarButtons) { + this.toolBarButtons = toolBarButtons; + } - puzzle.addBoardListener(puzzle.getBoardView()); - System.out.println("Setting elements"); - if (this.elementFrame != null) { - elementFrame.setElements(puzzle); + private void repaintAll() { + boardView.repaint(); } - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); - } + public void setPuzzleView(Puzzle puzzle) { + this.boardView = puzzle.getBoardView(); + editorElementController.setElementController(boardView.getElementController()); + dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); + if (this.splitPanel != null) { + this.splitPanel.setRightComponent(dynamicBoardView); + this.splitPanel.setVisible(true); + } - /** Saves a puzzle */ - private void direct_save() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + TitledBorder titleBoard = + BorderFactory.createTitledBorder(boardView.getClass().getSimpleName()); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + puzzle.addBoardListener(puzzle.getBoardView()); + System.out.println("Setting elements"); + if (this.elementFrame != null) { + elementFrame.setElements(puzzle); } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } - } - } - private String savePuzzle() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return ""; + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); } - // for TreeTent, need to check validity before saving - if (Objects.equals(puzzle.getName(), "TreeTent")) { - if (!puzzle.checkValidity()) { - int input = - JOptionPane.showConfirmDialog( - null, "The puzzle you edited is not " + "valid, would you still like to save? "); - if (input != 0) { - return ""; + /** Saves a puzzle */ + private void direct_save() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } } - } } - if (fileDialog == null) { - fileDialog = new FileDialog(this.frame); - } + private String savePuzzle() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return ""; + } - fileDialog.setMode(FileDialog.SAVE); - fileDialog.setTitle("Save Proof"); - String curFileName = GameBoardFacade.getInstance().getCurFileName(); - if (curFileName == null) { - fileDialog.setDirectory( - LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); - } else { - File curFile = new File(curFileName); - fileDialog.setDirectory(curFile.getParent()); - } - fileDialog.setVisible(true); + // for TreeTent, need to check validity before saving + if (Objects.equals(puzzle.getName(), "TreeTent")) { + if (!puzzle.checkValidity()) { + int input = + JOptionPane.showConfirmDialog( + null, + "The puzzle you edited is not " + + "valid, would you still like to save? "); + if (input != 0) { + return ""; + } + } + } - String fileName = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - } + if (fileDialog == null) { + fileDialog = new FileDialog(this.frame); + } + + fileDialog.setMode(FileDialog.SAVE); + fileDialog.setTitle("Save Proof"); + String curFileName = GameBoardFacade.getInstance().getCurFileName(); + if (curFileName == null) { + fileDialog.setDirectory( + LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); + } else { + File curFile = new File(curFileName); + fileDialog.setDirectory(curFile.getParent()); + } + fileDialog.setVisible(true); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + String fileName = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } + + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } + return fileName; } - return fileName; - } - public DynamicView getDynamicBoardView() { - return dynamicBoardView; - } + public DynamicView getDynamicBoardView() { + return dynamicBoardView; + } } diff --git a/src/main/java/edu/rpi/legup/ui/ScrollView.java b/src/main/java/edu/rpi/legup/ui/ScrollView.java index 5d072ebf5..0bf8335a2 100644 --- a/src/main/java/edu/rpi/legup/ui/ScrollView.java +++ b/src/main/java/edu/rpi/legup/ui/ScrollView.java @@ -7,307 +7,310 @@ import javax.swing.*; public class ScrollView extends JScrollPane { - private static final Logger LOGGER = Logger.getLogger(ScrollView.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ScrollView.class.getName()); - private static final double minScale = 0.25; - private static final double maxScale = 4.0; - private static final double[] levels = {0.25, 1.0 / 3.0, 0.50, 2.0 / 3.0, 1.0, 2.0, 3.0, 4.0}; + private static final double minScale = 0.25; + private static final double maxScale = 4.0; + private static final double[] levels = {0.25, 1.0 / 3.0, 0.50, 2.0 / 3.0, 1.0, 2.0, 3.0, 4.0}; - private Dimension viewSize; - private Dimension zoomSize; - private TreeSet zoomLevels; + private Dimension viewSize; + private Dimension zoomSize; + private TreeSet zoomLevels; - private double scale; + private double scale; - private Controller controller; - private ZoomablePane canvas; - private ZoomWidget widget; + private Controller controller; + private ZoomablePane canvas; + private ZoomWidget widget; - /** - * ScrollView Constructor - creates a ScrollView object using the controller handle the ui events - * - * @param controller controller that handles the ui events - */ - public ScrollView(Controller controller) { - super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS); + /** + * ScrollView Constructor - creates a ScrollView object using the controller handle the ui + * events + * + * @param controller controller that handles the ui events + */ + public ScrollView(Controller controller) { + super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS); - viewSize = new Dimension(); - zoomSize = new Dimension(); - scale = 1.0; + viewSize = new Dimension(); + zoomSize = new Dimension(); + scale = 1.0; - this.canvas = new ZoomablePane(this); + this.canvas = new ZoomablePane(this); - viewport.setView(canvas); + viewport.setView(canvas); - zoomLevels = new TreeSet<>(); - for (Double level : levels) { - zoomLevels.add(level); + zoomLevels = new TreeSet<>(); + for (Double level : levels) { + zoomLevels.add(level); + } + + widget = new ZoomWidget(this); + setCorner(JScrollPane.LOWER_RIGHT_CORNER, widget); + + setWheelScrollingEnabled(false); + + this.controller = controller; + controller.setViewer(this); + canvas.addMouseMotionListener(controller); + canvas.addMouseListener(controller); + viewport.addMouseWheelListener(controller); + viewport.addMouseListener(controller); + viewport.addMouseMotionListener(controller); } - widget = new ZoomWidget(this); - setCorner(JScrollPane.LOWER_RIGHT_CORNER, widget); - - setWheelScrollingEnabled(false); - - this.controller = controller; - controller.setViewer(this); - canvas.addMouseMotionListener(controller); - canvas.addMouseListener(controller); - viewport.addMouseWheelListener(controller); - viewport.addMouseListener(controller); - viewport.addMouseMotionListener(controller); - } - - /** - * Creates a customized viewport for the scroll pane - * - * @return viewport for the scroll pane - */ - @Override - protected JViewport createViewport() { - return new JViewport() { - @Override - protected LayoutManager createLayoutManager() { - return new ViewportLayout() { - @Override - public void layoutContainer(Container parent) { - Point point = viewport.getViewPosition(); - // determine the maximum x and y view positions - int mx = canvas.getWidth() - viewport.getWidth(); - int my = canvas.getHeight() - viewport.getHeight(); - // obey edge boundaries - if (point.x < 0) { - point.x = 0; - } - if (point.x > mx) { - point.x = mx; + /** + * Creates a customized viewport for the scroll pane + * + * @return viewport for the scroll pane + */ + @Override + protected JViewport createViewport() { + return new JViewport() { + @Override + protected LayoutManager createLayoutManager() { + return new ViewportLayout() { + @Override + public void layoutContainer(Container parent) { + Point point = viewport.getViewPosition(); + // determine the maximum x and y view positions + int mx = canvas.getWidth() - viewport.getWidth(); + int my = canvas.getHeight() - viewport.getHeight(); + // obey edge boundaries + if (point.x < 0) { + point.x = 0; + } + if (point.x > mx) { + point.x = mx; + } + if (point.y < 0) { + point.y = 0; + } + if (point.y > my) { + point.y = my; + } + // center margins + if (mx < 0) { + point.x = mx / 2; + } + if (my < 0) { + point.y = my / 2; + } + viewport.setViewPosition(point); + } + }; } - if (point.y < 0) { - point.y = 0; - } - if (point.y > my) { - point.y = my; - } - // center margins - if (mx < 0) { - point.x = mx / 2; + }; + } + + /** Updates zoomSize and view viewSize with the new scale */ + private void updateSize() { + zoomSize.setSize((int) (viewSize.width * scale), (int) (viewSize.height * scale)); + viewport.setViewSize(zoomSize); + } + + /** + * Updates the viewport position + * + * @param point point to set the viewport to + * @param magnification magnification to set the viewport to + */ + public void updatePosition(Point point, double magnification) { + Point position = viewport.getViewPosition(); + position.x = (int) ((double) (point.x + position.x) * magnification - point.x + 0.0); + position.y = (int) ((double) (point.y + position.y) * magnification - point.y + 0.0); + viewport.setViewPosition(position); + } + + /** + * Zooms in or out on a position within the dynamicView + * + * @param n level of zoom - n less than 0 is zoom in, n greater than 0 is zoom out + * @param point position to zoom in on + */ + public void zoom(int n, Point point) { + // if no Point is given, keep current center + if (point == null) { + point = + new Point( + viewport.getWidth() / 2 + viewport.getX(), + viewport.getHeight() / 2 + viewport.getY()); + } + // magnification level + double mag = (double) n * 1.05; + // zoom in + if (n < 0) { + mag = -mag; + // check zoom bounds + if (scale * mag > maxScale) { + mag = maxScale / scale; } - if (my < 0) { - point.y = my / 2; + // update + scale *= mag; + updateSize(); + updatePosition(point, mag); + // zoom out + } else { + mag = 1 / mag; + // check zoom bounds + if (scale * mag < minScale) { + mag = minScale / scale; } - viewport.setViewPosition(point); - } - }; - } - }; - } - - /** Updates zoomSize and view viewSize with the new scale */ - private void updateSize() { - zoomSize.setSize((int) (viewSize.width * scale), (int) (viewSize.height * scale)); - viewport.setViewSize(zoomSize); - } - - /** - * Updates the viewport position - * - * @param point point to set the viewport to - * @param magnification magnification to set the viewport to - */ - public void updatePosition(Point point, double magnification) { - Point position = viewport.getViewPosition(); - position.x = (int) ((double) (point.x + position.x) * magnification - point.x + 0.0); - position.y = (int) ((double) (point.y + position.y) * magnification - point.y + 0.0); - viewport.setViewPosition(position); - } - - /** - * Zooms in or out on a position within the dynamicView - * - * @param n level of zoom - n less than 0 is zoom in, n greater than 0 is zoom out - * @param point position to zoom in on - */ - public void zoom(int n, Point point) { - // if no Point is given, keep current center - if (point == null) { - point = - new Point( - viewport.getWidth() / 2 + viewport.getX(), - viewport.getHeight() / 2 + viewport.getY()); + // update + scale *= mag; + updatePosition(point, mag); + updateSize(); + } + // update the scrollpane and subclass + revalidate(); } - // magnification level - double mag = (double) n * 1.05; - // zoom in - if (n < 0) { - mag = -mag; - // check zoom bounds - if (scale * mag > maxScale) { - mag = maxScale / scale; - } - // update - scale *= mag; - updateSize(); - updatePosition(point, mag); - // zoom out - } else { - mag = 1 / mag; - // check zoom bounds - if (scale * mag < minScale) { - mag = minScale / scale; - } - // update - scale *= mag; - updatePosition(point, mag); - updateSize(); + + public void zoomTo(double newScale) { + // check zoom bounds + if (newScale < minScale) { + newScale = minScale; + } + if (newScale > maxScale) { + newScale = maxScale; + } + if (newScale == scale) { + return; + } + // calculate the newScale and center point + double mag = newScale / scale; + Point p = + new Point( + viewport.getWidth() / 2 + viewport.getX(), + viewport.getHeight() / 2 + viewport.getY()); + + // set scale directly + scale = newScale; + // zoom in + if (mag > 1.0) { + updateSize(); + updatePosition(p, mag); + // zoom out + } else { + updatePosition(p, mag); + updateSize(); + } + // update the scrollpane and subclass + revalidate(); } - // update the scrollpane and subclass - revalidate(); - } - - public void zoomTo(double newScale) { - // check zoom bounds - if (newScale < minScale) { - newScale = minScale; + + /** Get the ideal zoom based on the viewSize */ + public void zoomFit() { + if (viewport.getWidth() != 0 && viewport.getHeight() != 0) { + double fitWidth = (viewport.getWidth() - 8.0) / viewSize.width; + double fitHeight = (viewport.getHeight() - 8.0) / viewSize.height; + + zoomTo(Math.min(fitWidth, fitHeight)); + } + } + + /** Zooms in to the next zoom level */ + public void zoomIn() { + // find the next valid zoom level + Double newScale = zoomLevels.higher(scale); + if (newScale != null) { + zoomTo(newScale); + } } - if (newScale > maxScale) { - newScale = maxScale; + + /** Zooms out to the previous zoom level */ + public void zoomOut() { + // find the next valid zoom level + Double newScale = zoomLevels.lower(scale); + if (newScale != null) { + zoomTo(newScale); + } } - if (newScale == scale) { - return; + + /** + * Converts canvas coordinates to draw coordinates + * + * @param point canvas coordinate + * @return draw coordinate as Point + */ + public Point getActualPoint(Point point) { + return new Point((int) (point.x / scale), (int) (point.y / scale)); } - // calculate the newScale and center point - double mag = newScale / scale; - Point p = - new Point( - viewport.getWidth() / 2 + viewport.getX(), viewport.getHeight() / 2 + viewport.getY()); - - // set scale directly - scale = newScale; - // zoom in - if (mag > 1.0) { - updateSize(); - updatePosition(p, mag); - // zoom out - } else { - updatePosition(p, mag); - updateSize(); + + /** + * Gets the zoom amount + * + * @return zoom scale + */ + public int getZoom() { + return (int) (scale * 100.0); } - // update the scrollpane and subclass - revalidate(); - } - /** Get the ideal zoom based on the viewSize */ - public void zoomFit() { - if (viewport.getWidth() != 0 && viewport.getHeight() != 0) { - double fitWidth = (viewport.getWidth() - 8.0) / viewSize.width; - double fitHeight = (viewport.getHeight() - 8.0) / viewSize.height; + /** + * Gets the scale for the dynamic dynamicView + * + * @return scale of the dynamic dynamicView + */ + public double getScale() { + return scale; + } - zoomTo(Math.min(fitWidth, fitHeight)); + /** + * Sets the background of the viewport + * + * @param c color of the background + */ + public void setBackground(Color c) { + viewport.setBackground(c); } - } - - /** Zooms in to the next zoom level */ - public void zoomIn() { - // find the next valid zoom level - Double newScale = zoomLevels.higher(scale); - if (newScale != null) { - zoomTo(newScale); + + /** + * Gets the dimension of the viewport + * + * @return dimension of the viewport + */ + public Dimension getSize() { + return viewSize; } - } - - /** Zooms out to the previous zoom level */ - public void zoomOut() { - // find the next valid zoom level - Double newScale = zoomLevels.lower(scale); - if (newScale != null) { - zoomTo(newScale); + + /** + * Sets the dimension of the viewport + * + * @param size new dimension of the viewport + */ + public void setSize(Dimension size) { + this.viewSize = size; + updateSize(); + } + + public ZoomablePane getCanvas() { + return canvas; + } + + /** + * Draws the ScrollView + * + * @param graphics2D Graphics2D object used for drawing + */ + protected void draw(Graphics2D graphics2D) { + graphics2D.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics2D.setRenderingHint( + RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + canvas.paint(graphics2D); + } + + /** + * Scroll up or down on the ScrollView + * + * @param mag The magnitude for scroll up positive is scroll up, negative is scroll down, + * recommend to use getWheelRotation() as the mag + */ + public void scroll(int mag) { + Point point = super.viewport.getViewPosition(); + // the point changing speed changes with the scale + point.y += mag * getZoom() / 20; + viewport.setViewPosition(point); + updateSize(); + revalidate(); } - } - - /** - * Converts canvas coordinates to draw coordinates - * - * @param point canvas coordinate - * @return draw coordinate as Point - */ - public Point getActualPoint(Point point) { - return new Point((int) (point.x / scale), (int) (point.y / scale)); - } - - /** - * Gets the zoom amount - * - * @return zoom scale - */ - public int getZoom() { - return (int) (scale * 100.0); - } - - /** - * Gets the scale for the dynamic dynamicView - * - * @return scale of the dynamic dynamicView - */ - public double getScale() { - return scale; - } - - /** - * Sets the background of the viewport - * - * @param c color of the background - */ - public void setBackground(Color c) { - viewport.setBackground(c); - } - - /** - * Gets the dimension of the viewport - * - * @return dimension of the viewport - */ - public Dimension getSize() { - return viewSize; - } - - /** - * Sets the dimension of the viewport - * - * @param size new dimension of the viewport - */ - public void setSize(Dimension size) { - this.viewSize = size; - updateSize(); - } - - public ZoomablePane getCanvas() { - return canvas; - } - - /** - * Draws the ScrollView - * - * @param graphics2D Graphics2D object used for drawing - */ - protected void draw(Graphics2D graphics2D) { - graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics2D.setRenderingHint( - RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); - canvas.paint(graphics2D); - } - - /** - * Scroll up or down on the ScrollView - * - * @param mag The magnitude for scroll up positive is scroll up, negative is scroll down, - * recommend to use getWheelRotation() as the mag - */ - public void scroll(int mag) { - Point point = super.viewport.getViewPosition(); - // the point changing speed changes with the scale - point.y += mag * getZoom() / 20; - viewport.setViewPosition(point); - updateSize(); - revalidate(); - } } diff --git a/src/main/java/edu/rpi/legup/ui/ToolbarName.java b/src/main/java/edu/rpi/legup/ui/ToolbarName.java index 1e0cbe7fb..ba02ebd2e 100644 --- a/src/main/java/edu/rpi/legup/ui/ToolbarName.java +++ b/src/main/java/edu/rpi/legup/ui/ToolbarName.java @@ -1,30 +1,30 @@ package edu.rpi.legup.ui; public enum ToolbarName { - HINT, - CHECK, - SUBMIT, - DIRECTIONS, - CHECK_ALL; + HINT, + CHECK, + SUBMIT, + DIRECTIONS, + CHECK_ALL; - /** - * Gets the String representation of the ToolbarName enum - * - * @return String representing the enum - */ - public String toString() { - String str = super.toString(); - str = str.replace("_", " "); - str = str.toLowerCase(); - str = str.substring(0, 1).toUpperCase() + str.substring(1); - for (int i = 0; i < str.length(); i++) { - if (str.charAt(i) == ' ') { - str = - str.substring(0, i + 1) - + str.substring(i + 1, i + 2).toUpperCase() - + str.substring(i + 2); - } + /** + * Gets the String representation of the ToolbarName enum + * + * @return String representing the enum + */ + public String toString() { + String str = super.toString(); + str = str.replace("_", " "); + str = str.toLowerCase(); + str = str.substring(0, 1).toUpperCase() + str.substring(1); + for (int i = 0; i < str.length(); i++) { + if (str.charAt(i) == ' ') { + str = + str.substring(0, i + 1) + + str.substring(i + 1, i + 2).toUpperCase() + + str.substring(i + 2); + } + } + return str; } - return str; - } } diff --git a/src/main/java/edu/rpi/legup/ui/WrapLayout.java b/src/main/java/edu/rpi/legup/ui/WrapLayout.java index 6251d6f70..1e25b36d2 100644 --- a/src/main/java/edu/rpi/legup/ui/WrapLayout.java +++ b/src/main/java/edu/rpi/legup/ui/WrapLayout.java @@ -6,161 +6,162 @@ /** FlowLayout subclass that fully supports wrapping of components. */ public class WrapLayout extends FlowLayout { - private Dimension preferredLayoutSize; - - /** - * Constructs a new WrapLayout with a left alignment and a default 5-unit horizontal - * and vertical gap. - */ - public WrapLayout() { - super(LEFT); - } - - /** - * Constructs a new FlowLayout with the specified alignment and a default 5-unit - * horizontal and vertical gap. The value of the alignment argument must be one of - * WrapLayout, WrapLayout, or WrapLayout. - * - * @param align the alignment value - */ - public WrapLayout(int align) { - super(align); - } - - /** - * Creates a new flow layout manager with the indicated alignment and the indicated horizontal and - * vertical gaps. - * - *

The value of the alignment argument must be one of WrapLayout, WrapLayout - * , or WrapLayout. - * - * @param align the alignment value - * @param hgap the horizontal gap between components - * @param vgap the vertical gap between components - */ - public WrapLayout(int align, int hgap, int vgap) { - super(align, hgap, vgap); - } - - /** - * Returns the preferred dimensions for this layout given the visible components in the specified - * target container. - * - * @param target the component which needs to be laid out - * @return the preferred dimensions to lay out the subcomponents of the specified container - */ - @Override - public Dimension preferredLayoutSize(Container target) { - return layoutSize(target, true); - } - - /** - * Returns the minimum dimensions needed to layout the visible components contained in the - * specified target container. - * - * @param target the component which needs to be laid out - * @return the minimum dimensions to lay out the subcomponents of the specified container - */ - @Override - public Dimension minimumLayoutSize(Container target) { - Dimension minimum = layoutSize(target, false); - minimum.width -= (getHgap() + 1); - return minimum; - } - - /** - * Returns the minimum or preferred dimension needed to layout the target container. - * - * @param target target to get layout dimension for - * @param preferred should preferred dimension be calculated - * @return the dimension to layout the target container - */ - private Dimension layoutSize(Container target, boolean preferred) { - synchronized (target.getTreeLock()) { - // Each row must fit with the width allocated to the containter. - // When the container width = 0, the preferred width of the container - // has not yet been calculated so lets ask for the maximum. - - int targetWidth = target.getSize().width; - - if (targetWidth == 0) { - targetWidth = Integer.MAX_VALUE; - } - - int hgap = getHgap(); - int vgap = getVgap(); - Insets insets = target.getInsets(); - int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); - int maxWidth = targetWidth - horizontalInsetsAndGap; - - // Fit components into the allowed width - - Dimension dim = new Dimension(0, 0); - int rowWidth = 0; - int rowHeight = 0; - - int nmembers = target.getComponentCount(); - - for (int i = 0; i < nmembers; i++) { - Component m = target.getComponent(i); - - if (m.isVisible()) { - Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); - - // Can't add the component to current row. Start a new row. - - if (rowWidth + d.width > maxWidth) { - addRow(dim, rowWidth, rowHeight); - rowWidth = 0; - rowHeight = 0; - } + private Dimension preferredLayoutSize; + + /** + * Constructs a new WrapLayout with a left alignment and a default 5-unit + * horizontal and vertical gap. + */ + public WrapLayout() { + super(LEFT); + } - // Add a horizontal gap for all components after the first + /** + * Constructs a new FlowLayout with the specified alignment and a default 5-unit + * horizontal and vertical gap. The value of the alignment argument must be one of + * WrapLayout, WrapLayout, or WrapLayout. + * + * @param align the alignment value + */ + public WrapLayout(int align) { + super(align); + } - if (rowWidth != 0) { - rowWidth += hgap; - } + /** + * Creates a new flow layout manager with the indicated alignment and the indicated horizontal + * and vertical gaps. + * + *

The value of the alignment argument must be one of WrapLayout, + * WrapLayout + * , or WrapLayout. + * + * @param align the alignment value + * @param hgap the horizontal gap between components + * @param vgap the vertical gap between components + */ + public WrapLayout(int align, int hgap, int vgap) { + super(align, hgap, vgap); + } - rowWidth += d.width; - rowHeight = Math.max(rowHeight, d.height); - } - } + /** + * Returns the preferred dimensions for this layout given the visible components in the + * specified target container. + * + * @param target the component which needs to be laid out + * @return the preferred dimensions to lay out the subcomponents of the specified container + */ + @Override + public Dimension preferredLayoutSize(Container target) { + return layoutSize(target, true); + } + + /** + * Returns the minimum dimensions needed to layout the visible components contained in the + * specified target container. + * + * @param target the component which needs to be laid out + * @return the minimum dimensions to lay out the subcomponents of the specified container + */ + @Override + public Dimension minimumLayoutSize(Container target) { + Dimension minimum = layoutSize(target, false); + minimum.width -= (getHgap() + 1); + return minimum; + } - addRow(dim, rowWidth, rowHeight); + /** + * Returns the minimum or preferred dimension needed to layout the target container. + * + * @param target target to get layout dimension for + * @param preferred should preferred dimension be calculated + * @return the dimension to layout the target container + */ + private Dimension layoutSize(Container target, boolean preferred) { + synchronized (target.getTreeLock()) { + // Each row must fit with the width allocated to the containter. + // When the container width = 0, the preferred width of the container + // has not yet been calculated so lets ask for the maximum. - dim.width += horizontalInsetsAndGap; - dim.height += insets.top + insets.bottom + vgap * 2; + int targetWidth = target.getSize().width; - // When using a scroll pane or the DecoratedLookAndFeel we need to - // make sure the preferred dimension is less than the dimension of the - // target containter so shrinking the container dimension works - // correctly. Removing the horizontal gap is an easy way to do this. + if (targetWidth == 0) { + targetWidth = Integer.MAX_VALUE; + } - Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); + int hgap = getHgap(); + int vgap = getVgap(); + Insets insets = target.getInsets(); + int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); + int maxWidth = targetWidth - horizontalInsetsAndGap; - if (scrollPane != null) { - dim.width -= (hgap + 1); - } + // Fit components into the allowed width - return dim; - } - } - - /** - * A new row has been completed. Use the dimensions of this row to update the preferred dimension - * for the container. - * - * @param dim update the width and height when appropriate - * @param rowWidth the width of the row to add - * @param rowHeight the height of the row to add - */ - private void addRow(Dimension dim, int rowWidth, int rowHeight) { - dim.width = Math.max(dim.width, rowWidth); - - if (dim.height > 0) { - dim.height += getVgap(); + Dimension dim = new Dimension(0, 0); + int rowWidth = 0; + int rowHeight = 0; + + int nmembers = target.getComponentCount(); + + for (int i = 0; i < nmembers; i++) { + Component m = target.getComponent(i); + + if (m.isVisible()) { + Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); + + // Can't add the component to current row. Start a new row. + + if (rowWidth + d.width > maxWidth) { + addRow(dim, rowWidth, rowHeight); + rowWidth = 0; + rowHeight = 0; + } + + // Add a horizontal gap for all components after the first + + if (rowWidth != 0) { + rowWidth += hgap; + } + + rowWidth += d.width; + rowHeight = Math.max(rowHeight, d.height); + } + } + + addRow(dim, rowWidth, rowHeight); + + dim.width += horizontalInsetsAndGap; + dim.height += insets.top + insets.bottom + vgap * 2; + + // When using a scroll pane or the DecoratedLookAndFeel we need to + // make sure the preferred dimension is less than the dimension of the + // target containter so shrinking the container dimension works + // correctly. Removing the horizontal gap is an easy way to do this. + + Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); + + if (scrollPane != null) { + dim.width -= (hgap + 1); + } + + return dim; + } } - dim.height += rowHeight; - } + /** + * A new row has been completed. Use the dimensions of this row to update the preferred + * dimension for the container. + * + * @param dim update the width and height when appropriate + * @param rowWidth the width of the row to add + * @param rowHeight the height of the row to add + */ + private void addRow(Dimension dim, int rowWidth, int rowHeight) { + dim.width = Math.max(dim.width, rowWidth); + + if (dim.height > 0) { + dim.height += getVgap(); + } + + dim.height += rowHeight; + } } diff --git a/src/main/java/edu/rpi/legup/ui/ZoomWidget.java b/src/main/java/edu/rpi/legup/ui/ZoomWidget.java index 0afe0c2d1..aa5b65c4e 100644 --- a/src/main/java/edu/rpi/legup/ui/ZoomWidget.java +++ b/src/main/java/edu/rpi/legup/ui/ZoomWidget.java @@ -11,46 +11,46 @@ import javax.swing.event.ChangeListener; public class ZoomWidget extends JLabel { - private ScrollView parent; - private PopupSlider palette = new PopupSlider(); - private MouseAdapter open = - new MouseAdapter() { - public void mouseClicked(MouseEvent e) { - palette.slider.setValue(parent.getZoom()); - palette.show(e.getComponent(), 0, 0); - } - }; - - /** - * ZoomWidget Constructor creates a zoom widget for a ScrollView object - * - * @param parent dynamicView to which to the ZoomWidget is applied to - */ - public ZoomWidget(ScrollView parent) { - super(new ImageIcon("zoom.png")); - this.parent = parent; - addMouseListener(open); - } - - /** */ - private class PopupSlider extends JPopupMenu implements ChangeListener { - private static final long serialVersionUID = 8225019381200459814L; - - private JSlider slider; - - public PopupSlider() { - slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 200); - slider.setMajorTickSpacing(25); - slider.setPaintTicks(true); - - add(slider); - slider.addChangeListener(this); + private ScrollView parent; + private PopupSlider palette = new PopupSlider(); + private MouseAdapter open = + new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + palette.slider.setValue(parent.getZoom()); + palette.show(e.getComponent(), 0, 0); + } + }; + + /** + * ZoomWidget Constructor creates a zoom widget for a ScrollView object + * + * @param parent dynamicView to which to the ZoomWidget is applied to + */ + public ZoomWidget(ScrollView parent) { + super(new ImageIcon("zoom.png")); + this.parent = parent; + addMouseListener(open); } - public void stateChanged(ChangeEvent e) { - if (slider.getValueIsAdjusting()) { - parent.zoomTo((double) slider.getValue() / 100.0); - } + /** */ + private class PopupSlider extends JPopupMenu implements ChangeListener { + private static final long serialVersionUID = 8225019381200459814L; + + private JSlider slider; + + public PopupSlider() { + slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 200); + slider.setMajorTickSpacing(25); + slider.setPaintTicks(true); + + add(slider); + slider.addChangeListener(this); + } + + public void stateChanged(ChangeEvent e) { + if (slider.getValueIsAdjusting()) { + parent.zoomTo((double) slider.getValue() / 100.0); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/ZoomablePane.java b/src/main/java/edu/rpi/legup/ui/ZoomablePane.java index 121047448..934d31c53 100644 --- a/src/main/java/edu/rpi/legup/ui/ZoomablePane.java +++ b/src/main/java/edu/rpi/legup/ui/ZoomablePane.java @@ -6,35 +6,35 @@ import javax.swing.*; public class ZoomablePane extends JLayeredPane { - private ScrollView viewer; + private ScrollView viewer; - /** - * ZoomablePane Constructor creates scalable JComponent - * - * @param viewer dynamic dynamicView - */ - public ZoomablePane(ScrollView viewer) { - this.viewer = viewer; - } + /** + * ZoomablePane Constructor creates scalable JComponent + * + * @param viewer dynamic dynamicView + */ + public ZoomablePane(ScrollView viewer) { + this.viewer = viewer; + } - /** - * Paints the JComponents - * - * @param graphics graphics object used to paint the JComponent - */ - public void paint(Graphics graphics) { - Graphics2D graphics2D = (Graphics2D) graphics; - graphics2D.scale(viewer.getScale(), viewer.getScale()); - viewer.draw(graphics2D); - } + /** + * Paints the JComponents + * + * @param graphics graphics object used to paint the JComponent + */ + public void paint(Graphics graphics) { + Graphics2D graphics2D = (Graphics2D) graphics; + graphics2D.scale(viewer.getScale(), viewer.getScale()); + viewer.draw(graphics2D); + } - /** - * Processes an event and sends it to the dynamicView - * - * @param e AWTEvent to process - */ - protected void processEvent(AWTEvent e) { - viewer.dispatchEvent(e); - super.processEvent(e); - } + /** + * Processes an event and sends it to the dynamicView + * + * @param e AWTEvent to process + */ + protected void processEvent(AWTEvent e) { + viewer.dispatchEvent(e); + super.processEvent(e); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java b/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java index f917ef9b0..ca03f1e25 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java @@ -12,197 +12,201 @@ import java.util.ArrayList; public abstract class BoardView extends ScrollView implements IBoardListener { - protected TreeElement treeElement; - protected Board board; - protected ArrayList elementViews; - protected ElementController elementController; - protected ElementSelection selection; - - /** - * BoardView Constructor creates a view for the board object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - * @param elementController controller that handles the ui events - */ - public BoardView(BoardController boardController, ElementController elementController) { - super(boardController); - this.treeElement = null; - this.board = null; - this.elementViews = new ArrayList<>(); - this.elementController = elementController; - this.selection = new ElementSelection(); - - elementController.setBoardView(this); - addMouseListener(elementController); - addMouseMotionListener(elementController); - addKeyListener(elementController); - } - - /** Initializes the initial dimension of the viewport for the BoardView */ - public abstract void initSize(); - - /** - * Gets the dimension of the board view - * - * @return dimension of the board view - */ - protected abstract Dimension getProperSize(); - - /** - * Gets the ElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return ElementView at the specified index - */ - public abstract ElementView getElement(int index); - - /** - * Sets the ElementView list - * - * @param elements ElementView list - */ - public void setElementViews(ArrayList elements) { - elementViews = elements; - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - public ElementView getElement(Point point) { - Point scaledPoint = - new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - return null; - } - - /** - * Gets the ElementSelection for this BoardView - * - * @return the ElementSelection - */ - public ElementSelection getSelection() { - return selection; - } - - /** - * Gets the board associated with this view - * - * @return board - */ - public Board getBoard() { - return board; - } - - /** - * Sets the board associated with this view - * - * @param board board - */ - public void setBoard(Board board) { - if (this.board != board) { - this.board = board; - - if (board instanceof CaseBoard) { - setCasePickable(); - } else { + protected TreeElement treeElement; + protected Board board; + protected ArrayList elementViews; + protected ElementController elementController; + protected ElementSelection selection; + + /** + * BoardView Constructor creates a view for the board object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + * @param elementController controller that handles the ui events + */ + public BoardView(BoardController boardController, ElementController elementController) { + super(boardController); + this.treeElement = null; + this.board = null; + this.elementViews = new ArrayList<>(); + this.elementController = elementController; + this.selection = new ElementSelection(); + + elementController.setBoardView(this); + addMouseListener(elementController); + addMouseMotionListener(elementController); + addKeyListener(elementController); + } + + /** Initializes the initial dimension of the viewport for the BoardView */ + public abstract void initSize(); + + /** + * Gets the dimension of the board view + * + * @return dimension of the board view + */ + protected abstract Dimension getProperSize(); + + /** + * Gets the ElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return ElementView at the specified index + */ + public abstract ElementView getElement(int index); + + /** + * Sets the ElementView list + * + * @param elements ElementView list + */ + public void setElementViews(ArrayList elements) { + elementViews = elements; + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + public ElementView getElement(Point point) { + Point scaledPoint = + new Point( + (int) Math.round(point.x / getScale()), + (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + return null; + } + + /** + * Gets the ElementSelection for this BoardView + * + * @return the ElementSelection + */ + public ElementSelection getSelection() { + return selection; + } + + /** + * Gets the board associated with this view + * + * @return board + */ + public Board getBoard() { + return board; + } + + /** + * Sets the board associated with this view + * + * @param board board + */ + public void setBoard(Board board) { + if (this.board != board) { + this.board = board; + + if (board instanceof CaseBoard) { + setCasePickable(); + } else { + for (ElementView elementView : elementViews) { + elementView.setPuzzleElement( + board.getPuzzleElement(elementView.getPuzzleElement())); + elementView.setShowCasePicker(false); + } + } + } + } + + protected void setCasePickable() { + CaseBoard caseBoard = (CaseBoard) board; + Board baseBoard = caseBoard.getBaseBoard(); + for (ElementView elementView : elementViews) { - elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); - elementView.setShowCasePicker(false); + PuzzleElement puzzleElement = + baseBoard.getPuzzleElement(elementView.getPuzzleElement()); + elementView.setPuzzleElement(puzzleElement); + elementView.setShowCasePicker(true); + elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + } + + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + this.treeElement = treeElement; + setBoard(treeElement.getBoard()); + repaint(); + } + + /** + * Called when the a case board has been added to the view. + * + * @param caseBoard case board to be added + */ + @Override + public void onCaseBoardAdded(CaseBoard caseBoard) { + setBoard(caseBoard); + repaint(); + } + + public TreeElement getTreeElement() { + return this.treeElement; + } + + /** + * Gets the amount of edu.rpi.legup.puzzle elements for this board + * + * @return the amount of edu.rpi.legup.puzzle elements for this board + */ + public int getElementCount() { + return elementViews.size(); + } + + /** + * Gets the PuzzleElements associated with the BoardView + * + * @return list of PuzzleElements + */ + public ArrayList getElementViews() { + return elementViews; + } + + public ElementController getElementController() { + return elementController; + } + + @Override + public void draw(Graphics2D graphics2D) { + drawBoard(graphics2D); + } + + public void drawBoard(Graphics2D graphics2D) { + for (ElementView element : elementViews) { + element.draw(graphics2D); } - } - } - } - - protected void setCasePickable() { - CaseBoard caseBoard = (CaseBoard) board; - Board baseBoard = caseBoard.getBaseBoard(); - - for (ElementView elementView : elementViews) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); - elementView.setPuzzleElement(puzzleElement); - elementView.setShowCasePicker(true); - elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - } - - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - this.treeElement = treeElement; - setBoard(treeElement.getBoard()); - repaint(); - } - - /** - * Called when the a case board has been added to the view. - * - * @param caseBoard case board to be added - */ - @Override - public void onCaseBoardAdded(CaseBoard caseBoard) { - setBoard(caseBoard); - repaint(); - } - - public TreeElement getTreeElement() { - return this.treeElement; - } - - /** - * Gets the amount of edu.rpi.legup.puzzle elements for this board - * - * @return the amount of edu.rpi.legup.puzzle elements for this board - */ - public int getElementCount() { - return elementViews.size(); - } - - /** - * Gets the PuzzleElements associated with the BoardView - * - * @return list of PuzzleElements - */ - public ArrayList getElementViews() { - return elementViews; - } - - public ElementController getElementController() { - return elementController; - } - - @Override - public void draw(Graphics2D graphics2D) { - drawBoard(graphics2D); - } - - public void drawBoard(Graphics2D graphics2D) { - for (ElementView element : elementViews) { - element.draw(graphics2D); - } - } - - /** - * Called when the board puzzleElement changed - * - * @param puzzleElement puzzleElement of the puzzleElement that changed - */ - @Override - public void onBoardDataChanged(PuzzleElement puzzleElement) { - repaint(); - } - - public abstract DataSelectionView getSelectionPopupMenu(); + } + + /** + * Called when the board puzzleElement changed + * + * @param puzzleElement puzzleElement of the puzzleElement that changed + */ + @Override + public void onBoardDataChanged(PuzzleElement puzzleElement) { + repaint(); + } + + public abstract DataSelectionView getSelectionPopupMenu(); } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java b/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java index 3c6e78f5d..cedfa08fe 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java @@ -7,8 +7,8 @@ public class DataSelectionView extends JPopupMenu { - public DataSelectionView(ElementController controller) { - setBackground(Color.GRAY); - setBorder(new BevelBorder(BevelBorder.RAISED)); - } + public DataSelectionView(ElementController controller) { + setBackground(Color.GRAY); + setBorder(new BevelBorder(BevelBorder.RAISED)); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java b/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java index cce569af3..8e6f2cb18 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java @@ -4,71 +4,71 @@ import java.util.ArrayList; public class ElementSelection { - private ArrayList selection; - private ElementView hover; - private Point mousePoint; + private ArrayList selection; + private ElementView hover; + private Point mousePoint; - public ElementSelection() { - this.selection = new ArrayList<>(); - this.hover = null; - this.mousePoint = null; - } + public ElementSelection() { + this.selection = new ArrayList<>(); + this.hover = null; + this.mousePoint = null; + } - public ArrayList getSelection() { - return selection; - } + public ArrayList getSelection() { + return selection; + } - public ElementView getFirstSelection() { - return selection.size() == 0 ? null : selection.get(0); - } + public ElementView getFirstSelection() { + return selection.size() == 0 ? null : selection.get(0); + } - public void toggleSelection(ElementView elementView) { - if (selection.contains(elementView)) { - selection.remove(elementView); - elementView.setSelected(false); - } else { - selection.add(elementView); - elementView.setSelected(true); + public void toggleSelection(ElementView elementView) { + if (selection.contains(elementView)) { + selection.remove(elementView); + elementView.setSelected(false); + } else { + selection.add(elementView); + elementView.setSelected(true); + } } - } - public void newSelection(ElementView elementView) { - clearSelection(); - selection.add(elementView); - elementView.setSelected(true); - } + public void newSelection(ElementView elementView) { + clearSelection(); + selection.add(elementView); + elementView.setSelected(true); + } - public void clearSelection() { - for (ElementView elementView : selection) { - elementView.setSelected(false); + public void clearSelection() { + for (ElementView elementView : selection) { + elementView.setSelected(false); + } + selection.clear(); } - selection.clear(); - } - public ElementView getHover() { - return hover; - } + public ElementView getHover() { + return hover; + } - public void newHover(ElementView newHovered) { - newHovered.setHover(true); - if (hover != null) { - hover.setHover(false); + public void newHover(ElementView newHovered) { + newHovered.setHover(true); + if (hover != null) { + hover.setHover(false); + } + hover = newHovered; } - hover = newHovered; - } - public void clearHover() { - if (hover != null) { - hover.setHover(false); - hover = null; + public void clearHover() { + if (hover != null) { + hover.setHover(false); + hover = null; + } } - } - public Point getMousePoint() { - return mousePoint; - } + public Point getMousePoint() { + return mousePoint; + } - public void setMousePoint(Point point) { - this.mousePoint = point; - } + public void setMousePoint(Point point) { + this.mousePoint = point; + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java b/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java index 6cca76bcd..83b2cb099 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java @@ -10,331 +10,338 @@ import javax.swing.*; public abstract class ElementView implements Shape { - protected int index; - protected Point location; - protected Dimension size; - protected PuzzleElement puzzleElement; - private Color hoverColor; - private Color modifiedColor; - private Color caseColor; - private Color invalidColor; - private boolean showCasePicker; - private boolean isCaseRulePickable; - private boolean isHover; - private boolean isSelected; - - /** - * ElementView Constructor creates a puzzleElement view - * - * @param puzzleElement puzzleElement to which the view uses to draw - */ - public ElementView(PuzzleElement puzzleElement) { - this.puzzleElement = puzzleElement; - this.hoverColor = new Color(0x79, 0x86, 0xCB, 255); - this.modifiedColor = new Color(0x64, 0xDD, 0x17, 255); - this.caseColor = new Color(0x1A, 0x23, 0x7E, 200); - this.invalidColor = new Color(0xf4, 0x43, 0x36, 200); - this.isHover = false; - this.isSelected = false; - this.isCaseRulePickable = false; - } - - /** - * Determines if the specified point is within the ElementView - * - * @param point point to check - * @return true if the point is within the ElementView, false otherwise - */ - public boolean isWithinBounds(Point point) { - return point.x >= location.x - && point.x <= location.x + size.width - && point.y >= location.y - && point.y <= location.y + size.height; - } - - /** - * Draws the puzzle element on the screen - * - * @param graphics2D graphics2D object used for drawing - */ - public void draw(Graphics2D graphics2D) { - drawElement(graphics2D); - if (puzzleElement.isGiven()) { - drawGiven(graphics2D); - } - if (puzzleElement.isModified()) { - drawModified(graphics2D); - } - if (showCasePicker && isCaseRulePickable) { - drawCase(graphics2D); - } - if (isHover) { - drawHover(graphics2D); - } - } - - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 2, size.height - 2)); - - graphics2D.setColor(Color.BLACK); - FontMetrics metrics = graphics2D.getFontMetrics(graphics2D.getFont()); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } - - public void drawGiven(Graphics2D graphics2D) {} - - public void drawHover(Graphics2D graphics2D) { - graphics2D.setColor(hoverColor); - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public void drawModified(Graphics2D graphics2D) { - graphics2D.setColor(puzzleElement.isValid() ? modifiedColor : invalidColor); - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public void drawCase(Graphics2D graphics2D) { - graphics2D.setColor(caseColor); - graphics2D.fill( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public BufferedImage getImage() { - BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics2D = image.createGraphics(); - drawElement(graphics2D); - graphics2D.dispose(); - return image; - } - - /** - * Gets the index of the ElementView - * - * @return index of the ElementView - */ - public int getIndex() { - return index; - } - - /** - * Sets the index of the ElementView - * - * @param index index of the ElementView - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Gets the location of the ElementView - * - * @return location of the ElementView - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the ElementView - * - * @param location location of the ElementView - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Gets the dimension of the ElementView - * - * @return dimension of the ElementView - */ - public Dimension getSize() { - return size; - } - - /** - * Sets the dimension of the ElementView - * - * @param size dimension of the ElementView - */ - public void setSize(Dimension size) { - this.size = size; - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - public PuzzleElement getPuzzleElement() { - return puzzleElement; - } - - /** - * Sets the PuzzleElement associated with this view - * - * @param data PuzzleElement associated with this view - */ - public void setPuzzleElement(PuzzleElement data) { - this.puzzleElement = data; - } - - public boolean isShowCasePicker() { - return showCasePicker; - } - - public void setShowCasePicker(boolean showCasePicker) { - this.showCasePicker = showCasePicker; - } - - /** - * Gets the isCaseRulePickable field to determine if this ElementView should be highlighted in - * some way to indicate if it can be chosen by the CaseRule - * - * @return true if the ElementView can be chosen for the CaseRule, false otherwise - */ - public boolean isCaseRulePickable() { - return isCaseRulePickable; - } - - /** - * Sets the isCaseRulePickable field to determine if this ElementView should be highlighted in - * some way to indicate if it can be chosen by the CaseRule - * - * @param isCaseRulePickable true if the ElementView can be chosen for the CaseRule, false - * otherwise - */ - public void setCaseRulePickable(boolean isCaseRulePickable) { - this.isCaseRulePickable = isCaseRulePickable; - } - - /** - * Gets the high-light color - * - * @return high-light color - */ - public Color getHoverColor() { - return hoverColor; - } - - /** - * Sets the high-light color - * - * @param hoverColor high-light color - */ - public void setHoverColor(Color hoverColor) { - this.hoverColor = hoverColor; - } - - /** - * Gets whether the puzzleElement is currently being hovered over - * - * @return true if the puzzleElement is currently being hover over, false otherwise - */ - public boolean isHover() { - return isHover; - } - - /** - * Sets whether the puzzleElement is being hover over - * - * @param hover true if the puzzleElement is correctly being hover over, false otherwise - */ - public void setHover(boolean hover) { - isHover = hover; - } - - /** - * Gets whether the puzzleElement is being selected - * - * @return tue if the puzzleElement is currently selected, false otherwise - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets whether the puzzleElement is being selected - * - * @param selected tue if the puzzleElement is currently selected, false otherwise - */ - public void setSelected(boolean selected) { - isSelected = selected; - } - - public JMenuItem getSelectionMenuItem() { - JMenuItem item = new JMenuItem(puzzleElement.getData() + ""); - return item; - } - - @Override - public boolean contains(double x, double y) { - return x >= location.x - && x <= location.x + size.width - && y >= location.y - && y <= location.y + size.height; - } - - @Override - public boolean contains(Point2D point) { - return contains(point.getX(), point.getY()); - } - - @Override - public boolean intersects(double x, double y, double width, double height) { - return (x + width >= location.x && x <= location.x + size.width) - || (y + height >= location.y && y <= location.y + size.height); - } - - @Override - public boolean intersects(Rectangle2D rectangle2D) { - return intersects( - rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); - } - - @Override - public boolean contains(double x, double y, double width, double height) { - return (x + width >= location.x && x <= location.x + size.width) - && (y + height >= location.y && y <= location.y + size.height); - } - - @Override - public boolean contains(Rectangle2D rectangle2D) { - return contains( - rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at); - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return new Rectangle(location.x, location.y, size.width, size.height) - .getPathIterator(at, flatness); - } - - @Override - public Rectangle getBounds() { - return new Rectangle(location.x, location.y, size.width, size.height); - } - - @Override - public Rectangle2D getBounds2D() { - return new Rectangle(location.x, location.y, size.width, size.height); - } + protected int index; + protected Point location; + protected Dimension size; + protected PuzzleElement puzzleElement; + private Color hoverColor; + private Color modifiedColor; + private Color caseColor; + private Color invalidColor; + private boolean showCasePicker; + private boolean isCaseRulePickable; + private boolean isHover; + private boolean isSelected; + + /** + * ElementView Constructor creates a puzzleElement view + * + * @param puzzleElement puzzleElement to which the view uses to draw + */ + public ElementView(PuzzleElement puzzleElement) { + this.puzzleElement = puzzleElement; + this.hoverColor = new Color(0x79, 0x86, 0xCB, 255); + this.modifiedColor = new Color(0x64, 0xDD, 0x17, 255); + this.caseColor = new Color(0x1A, 0x23, 0x7E, 200); + this.invalidColor = new Color(0xf4, 0x43, 0x36, 200); + this.isHover = false; + this.isSelected = false; + this.isCaseRulePickable = false; + } + + /** + * Determines if the specified point is within the ElementView + * + * @param point point to check + * @return true if the point is within the ElementView, false otherwise + */ + public boolean isWithinBounds(Point point) { + return point.x >= location.x + && point.x <= location.x + size.width + && point.y >= location.y + && point.y <= location.y + size.height; + } + + /** + * Draws the puzzle element on the screen + * + * @param graphics2D graphics2D object used for drawing + */ + public void draw(Graphics2D graphics2D) { + drawElement(graphics2D); + if (puzzleElement.isGiven()) { + drawGiven(graphics2D); + } + if (puzzleElement.isModified()) { + drawModified(graphics2D); + } + if (showCasePicker && isCaseRulePickable) { + drawCase(graphics2D); + } + if (isHover) { + drawHover(graphics2D); + } + } + + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 2, size.height - 2)); + + graphics2D.setColor(Color.BLACK); + FontMetrics metrics = graphics2D.getFontMetrics(graphics2D.getFont()); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } + + public void drawGiven(Graphics2D graphics2D) {} + + public void drawHover(Graphics2D graphics2D) { + graphics2D.setColor(hoverColor); + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public void drawModified(Graphics2D graphics2D) { + graphics2D.setColor(puzzleElement.isValid() ? modifiedColor : invalidColor); + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public void drawCase(Graphics2D graphics2D) { + graphics2D.setColor(caseColor); + graphics2D.fill( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public BufferedImage getImage() { + BufferedImage image = + new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics2D = image.createGraphics(); + drawElement(graphics2D); + graphics2D.dispose(); + return image; + } + + /** + * Gets the index of the ElementView + * + * @return index of the ElementView + */ + public int getIndex() { + return index; + } + + /** + * Sets the index of the ElementView + * + * @param index index of the ElementView + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Gets the location of the ElementView + * + * @return location of the ElementView + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the ElementView + * + * @param location location of the ElementView + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Gets the dimension of the ElementView + * + * @return dimension of the ElementView + */ + public Dimension getSize() { + return size; + } + + /** + * Sets the dimension of the ElementView + * + * @param size dimension of the ElementView + */ + public void setSize(Dimension size) { + this.size = size; + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + public PuzzleElement getPuzzleElement() { + return puzzleElement; + } + + /** + * Sets the PuzzleElement associated with this view + * + * @param data PuzzleElement associated with this view + */ + public void setPuzzleElement(PuzzleElement data) { + this.puzzleElement = data; + } + + public boolean isShowCasePicker() { + return showCasePicker; + } + + public void setShowCasePicker(boolean showCasePicker) { + this.showCasePicker = showCasePicker; + } + + /** + * Gets the isCaseRulePickable field to determine if this ElementView should be highlighted in + * some way to indicate if it can be chosen by the CaseRule + * + * @return true if the ElementView can be chosen for the CaseRule, false otherwise + */ + public boolean isCaseRulePickable() { + return isCaseRulePickable; + } + + /** + * Sets the isCaseRulePickable field to determine if this ElementView should be highlighted in + * some way to indicate if it can be chosen by the CaseRule + * + * @param isCaseRulePickable true if the ElementView can be chosen for the CaseRule, false + * otherwise + */ + public void setCaseRulePickable(boolean isCaseRulePickable) { + this.isCaseRulePickable = isCaseRulePickable; + } + + /** + * Gets the high-light color + * + * @return high-light color + */ + public Color getHoverColor() { + return hoverColor; + } + + /** + * Sets the high-light color + * + * @param hoverColor high-light color + */ + public void setHoverColor(Color hoverColor) { + this.hoverColor = hoverColor; + } + + /** + * Gets whether the puzzleElement is currently being hovered over + * + * @return true if the puzzleElement is currently being hover over, false otherwise + */ + public boolean isHover() { + return isHover; + } + + /** + * Sets whether the puzzleElement is being hover over + * + * @param hover true if the puzzleElement is correctly being hover over, false otherwise + */ + public void setHover(boolean hover) { + isHover = hover; + } + + /** + * Gets whether the puzzleElement is being selected + * + * @return tue if the puzzleElement is currently selected, false otherwise + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets whether the puzzleElement is being selected + * + * @param selected tue if the puzzleElement is currently selected, false otherwise + */ + public void setSelected(boolean selected) { + isSelected = selected; + } + + public JMenuItem getSelectionMenuItem() { + JMenuItem item = new JMenuItem(puzzleElement.getData() + ""); + return item; + } + + @Override + public boolean contains(double x, double y) { + return x >= location.x + && x <= location.x + size.width + && y >= location.y + && y <= location.y + size.height; + } + + @Override + public boolean contains(Point2D point) { + return contains(point.getX(), point.getY()); + } + + @Override + public boolean intersects(double x, double y, double width, double height) { + return (x + width >= location.x && x <= location.x + size.width) + || (y + height >= location.y && y <= location.y + size.height); + } + + @Override + public boolean intersects(Rectangle2D rectangle2D) { + return intersects( + rectangle2D.getX(), + rectangle2D.getY(), + rectangle2D.getWidth(), + rectangle2D.getHeight()); + } + + @Override + public boolean contains(double x, double y, double width, double height) { + return (x + width >= location.x && x <= location.x + size.width) + && (y + height >= location.y && y <= location.y + size.height); + } + + @Override + public boolean contains(Rectangle2D rectangle2D) { + return contains( + rectangle2D.getX(), + rectangle2D.getY(), + rectangle2D.getWidth(), + rectangle2D.getHeight()); + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at); + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return new Rectangle(location.x, location.y, size.width, size.height) + .getPathIterator(at, flatness); + } + + @Override + public Rectangle getBounds() { + return new Rectangle(location.x, location.y, size.width, size.height); + } + + @Override + public Rectangle2D getBounds2D() { + return new Rectangle(location.x, location.y, size.width, size.height); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java b/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java index 34f41b60d..c40303192 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java @@ -6,80 +6,82 @@ import java.awt.Dimension; public class GridBoardView extends BoardView { - protected Dimension gridSize; - protected Dimension elementSize; + protected Dimension gridSize; + protected Dimension elementSize; - /** - * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - * @param gridSize dimension of the grid - * @param elementController controller that handles the ui events - */ - public GridBoardView( - BoardController boardController, ElementController elementController, Dimension gridSize) { - this(boardController, elementController); - this.gridSize = gridSize; - this.elementSize = new Dimension(30, 30); - initSize(); - } + /** + * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + * @param gridSize dimension of the grid + * @param elementController controller that handles the ui events + */ + public GridBoardView( + BoardController boardController, + ElementController elementController, + Dimension gridSize) { + this(boardController, elementController); + this.gridSize = gridSize; + this.elementSize = new Dimension(30, 30); + initSize(); + } - /** - * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - */ - private GridBoardView(BoardController boardController, ElementController elementController) { - super(boardController, elementController); - setBackground(new Color(0xE0E0E0)); - } + /** + * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + */ + private GridBoardView(BoardController boardController, ElementController elementController) { + super(boardController, elementController); + setBackground(new Color(0xE0E0E0)); + } - /** - * Gets the GridElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return GridElementView at the specified index - */ - public GridElementView getElement(int index) { - if (index < elementViews.size()) { - return (GridElementView) elementViews.get(index); + /** + * Gets the GridElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return GridElementView at the specified index + */ + public GridElementView getElement(int index) { + if (index < elementViews.size()) { + return (GridElementView) elementViews.get(index); + } + return null; } - return null; - } - public GridElementView getElement(int xIndex, int yIndex) { - if (xIndex < gridSize.width && yIndex < gridSize.height) { - return (GridElementView) elementViews.get(yIndex * gridSize.width + xIndex); + public GridElementView getElement(int xIndex, int yIndex) { + if (xIndex < gridSize.width && yIndex < gridSize.height) { + return (GridElementView) elementViews.get(yIndex * gridSize.width + xIndex); + } + return null; } - return null; - } - /** Initializes the initial dimension of the viewport for the GridBoardView */ - @Override - public void initSize() { - setSize(getProperSize()); - zoomFit(); - } + /** Initializes the initial dimension of the viewport for the GridBoardView */ + @Override + public void initSize() { + setSize(getProperSize()); + zoomFit(); + } - /** - * Helper method to determine the proper dimension of the grid view - * - * @return proper dimension of the grid view - */ - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = gridSize.width * elementSize.width; - boardViewSize.height = gridSize.height * elementSize.height; - return boardViewSize; - } + /** + * Helper method to determine the proper dimension of the grid view + * + * @return proper dimension of the grid view + */ + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = gridSize.width * elementSize.width; + boardViewSize.height = gridSize.height * elementSize.height; + return boardViewSize; + } - public DataSelectionView getSelectionPopupMenu() { - return null; - } + public DataSelectionView getSelectionPopupMenu() { + return null; + } - public Dimension getElementSize() { - return this.elementSize; - } + public Dimension getElementSize() { + return this.elementSize; + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java b/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java index 4a3d84261..440b3a693 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java @@ -3,7 +3,7 @@ import edu.rpi.legup.model.gameboard.GridCell; public class GridElementView extends ElementView { - public GridElementView(GridCell cell) { - super(cell); - } + public GridElementView(GridCell cell) { + super(cell); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java b/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java index ee8060e3c..b2d3e31dd 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java @@ -4,28 +4,28 @@ import javax.swing.*; public class SelectionItemView extends JMenuItem { - private PuzzleElement data; + private PuzzleElement data; - public SelectionItemView(PuzzleElement data, Icon icon) { - super(icon); - this.data = data; - } + public SelectionItemView(PuzzleElement data, Icon icon) { + super(icon); + this.data = data; + } - public SelectionItemView(PuzzleElement data, String display) { - super(display); - this.data = data; - } + public SelectionItemView(PuzzleElement data, String display) { + super(display); + this.data = data; + } - public SelectionItemView(PuzzleElement data, int display) { - super(String.valueOf(display)); - this.data = data; - } + public SelectionItemView(PuzzleElement data, int display) { + super(String.valueOf(display)); + this.data = data; + } - public SelectionItemView(PuzzleElement data) { - this(data, (Integer) data.getData()); - } + public SelectionItemView(PuzzleElement data) { + this(data, (Integer) data.getData()); + } - public PuzzleElement getData() { - return data; - } + public PuzzleElement getData() { + return data; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java index 613822c14..8469343f3 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java @@ -10,334 +10,338 @@ import javax.swing.plaf.basic.BasicLookAndFeel; public class LegupLookAndFeel extends BasicLookAndFeel { - /** - * Return a short string that identifies this look and feel, e.g. "CDE/Motif". This string should - * be appropriate for a menu item. Distinct look and feels should have different names, e.g. a - * subclass of MotifLookAndFeel that changes the way a few components are rendered should be - * called "CDE/Motif My Way"; something that would be useful to a user trying to select a L&F - * from a list of names. - * - * @return short identifier for the look and feel - */ - @Override - public String getName() { - return "Legup"; - } - - /** - * Return a string that identifies this look and feel. This string will be used by - * applications/services that want to recognize well known look and feel implementations. - * Presently the well known names are "Motif", "Windows", "Mac", "Metal". Note that a LookAndFeel - * derived from a well known superclass that doesn't make any fundamental changes to the look or - * feel shouldn't override this method. - * - * @return identifier for the look and feel - */ - @Override - public String getID() { - return "Legup Look and Feel"; - } - - /** - * Return a one line description of this look and feel implementation, e.g. "The CDE/Motif Look - * and Feel". This string is intended for the user, e.g. in the title of a window or in a ToolTip - * message. - * - * @return short description for the look and feel - */ - @Override - public String getDescription() { - return "Material design look and feel for Legup"; - } - - /** - * If the underlying platform has a "native" look and feel, and this is an implementation of it, - * return {@code true}. For example, when the underlying platform is Solaris running CDE a - * CDE/Motif look and feel implementation would return {@code true}. - * - * @return {@code true} if this look and feel represents the underlying platform look and feel - */ - @Override - public boolean isNativeLookAndFeel() { - return true; - } - - /** - * Return {@code true} if the underlying platform supports and or permits this look and feel. This - * method returns {@code false} if the look and feel depends on special resources or legal - * agreements that aren't defined for the current platform. - * - * @return {@code true} if this is a supported look and feel - * @see UIManager#setLookAndFeel - */ - @Override - public boolean isSupportedLookAndFeel() { - return true; - } - - /** - * Initializes the look and feel. While this method is public, it should only be invoked by the - * {@code UIManager} when a look and feel is installed as the current look and feel. This method - * is invoked before the {@code UIManager} invokes {@code getDefaults}. This method is intended to - * perform any initialization for the look and feel. Subclasses should do any one-time setup they - * need here, rather than in a static initializer, because look and feel class objects may be - * loaded just to discover that {@code isSupportedLookAndFeel()} returns {@code false}. - * - * @see #uninitialize - * @see UIManager#setLookAndFeel - */ - @Override - public void initialize() { - super.initialize(); - } - - /** - * Populates {@code table} with mappings from {@code uiClassID} to the fully qualified name of the - * ui class. The value for a particular {@code uiClassID} is {@code "javax.swing.plaf.basic.Basic - * + uiClassID"}. For example, the value for the {@code uiClassID} {@code TreeUI} is {@code - * "javax.swing.plaf.basic.BasicTreeUI"}. - * - * @param table the {@code UIDefaults} instance the entries are added to - * @throws NullPointerException if {@code table} is {@code null} - * @see LookAndFeel - * @see #getDefaults - */ - @Override - protected void initClassDefaults(UIDefaults table) { - super.initClassDefaults(table); - - table.put("ButtonUI", MaterialButtonUI.class.getCanonicalName()); - table.put("TextFieldUI", MaterialTextFieldUI.class.getCanonicalName()); - table.put("PasswordFieldUI", MaterialPasswordFieldUI.class.getCanonicalName()); - table.put("TableUI", MaterialTableUI.class.getCanonicalName()); - table.put("TableHeaderUI", MaterialTableHeaderUI.class.getCanonicalName()); - table.put("TreeUI", MaterialTreeUI.class.getCanonicalName()); - table.put("SpinnerUI", MaterialSpinnerUI.class.getCanonicalName()); - table.put("PanelUI", MaterialPanelUI.class.getCanonicalName()); - table.put("LabelUI", MaterialLabelUI.class.getCanonicalName()); - table.put("MenuItemUI", MaterialMenuItemUI.class.getCanonicalName()); - // table.put ("MenuBarUI", .class.getCanonicalName()); - table.put("MenuUI", MaterialMenuUI.class.getCanonicalName()); - table.put("CheckBoxUI", MaterialCheckBoxUI.class.getCanonicalName()); - table.put("RadioButtonUI", MaterialRadioButtonUI.class.getCanonicalName()); - table.put("TabbedPaneUI", MaterialTabbedPaneUI.class.getCanonicalName()); - table.put("ToggleButtonUI", MaterialToggleButtonUI.class.getCanonicalName()); - table.put("ScrollBarUI", MaterialScrollBarUI.class.getCanonicalName()); - table.put("ComboBoxUI", MaterialComboBoxUI.class.getCanonicalName()); - table.put("PopupMenuUI", MaterialPopupMenuUI.class.getCanonicalName()); - table.put("ToolBarUI", MaterialToolBarUI.class.getCanonicalName()); - table.put("SliderUI", MaterialSliderUI.class.getCanonicalName()); - table.put("ProgressBarUI", MaterialProgressBarUI.class.getCanonicalName()); - table.put("RadioButtonMenuItemUI", MaterialRadioButtonMenuItemUI.class.getCanonicalName()); - table.put("CheckBoxMenuItemUI", MaterialCheckBoxMenuItemUI.class.getCanonicalName()); - table.put("TextPaneUI", MaterialTextPaneUI.class.getCanonicalName()); - table.put("EditorPaneUI", MaterialEditorPaneUI.class.getCanonicalName()); - table.put("SeparatorUI", MaterialSeparatorUI.class.getCanonicalName()); - table.put("FileChooserUI", MaterialFileChooserUI.class.getCanonicalName()); - table.put("ToolTipUI", MaterialToolTipUI.class.getCanonicalName()); - table.put("SplitPaneUI", MaterialSplitPaneUI.class.getCanonicalName()); - // table.put ("ColorChooserUI", ); - } - - @Override - protected void initComponentDefaults(UIDefaults table) { - super.initComponentDefaults(table); - - table.put("Button.highlight", MaterialColors.GRAY_300); - table.put("Button.opaque", false); - table.put("Button.border", BorderFactory.createEmptyBorder(7, 17, 7, 17)); - table.put("Button.background", MaterialColors.GRAY_200); - table.put("Button.foreground", Color.BLACK); - table.put("Button.font", MaterialFonts.MEDIUM); - - table.put("CheckBox.font", MaterialFonts.REGULAR); - table.put("CheckBox.background", Color.WHITE); - table.put("CheckBox.foreground", Color.BLACK); - table.put("CheckBox.icon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); - table.put("CheckBox.selectedIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); - - table.put("ComboBox.font", MaterialFonts.REGULAR); - table.put("ComboBox.background", Color.WHITE); - table.put("ComboBox.foreground", Color.BLACK); - table.put( - "ComboBox.border", - BorderFactory.createCompoundBorder( - MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(0, 5, 0, 0))); - table.put("ComboBox.buttonBackground", MaterialColors.GRAY_300); - table.put("ComboBox.selectionBackground", Color.WHITE); - table.put("ComboBox.selectionForeground", Color.BLACK); - table.put("ComboBox.selectedInDropDownBackground", MaterialColors.GRAY_200); - - table.put("Label.font", MaterialFonts.REGULAR); - table.put("Label.background", Color.WHITE); - table.put("Label.foreground", Color.BLACK); - table.put("Label.border", BorderFactory.createEmptyBorder()); - - table.put("Menu.font", MaterialFonts.BOLD); - table.put("Menu.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("Menu.background", Color.WHITE); - table.put("Menu.foreground", Color.BLACK); - table.put("Menu.opaque", true); - table.put("Menu.selectionBackground", MaterialColors.GRAY_200); - table.put("Menu.selectionForeground", Color.BLACK); - table.put("Menu.disabledForeground", new Color(0, 0, 0, 100)); - table.put("Menu.menuPopupOffsetY", 3); - - table.put("MenuBar.font", MaterialFonts.BOLD); - table.put("MenuBar.background", Color.WHITE); - table.put("MenuBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); - table.put("MenuBar.foreground", Color.BLACK); - - table.put("MenuItem.disabledForeground", new Color(0, 0, 0, 100)); - table.put("MenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("MenuItem.selectionForeground", Color.BLACK); - table.put("MenuItem.font", MaterialFonts.MEDIUM); - table.put("MenuItem.background", Color.WHITE); - table.put("MenuItem.foreground", Color.BLACK); - table.put("MenuItem.border", BorderFactory.createEmptyBorder(5, 0, 5, 0)); - - table.put("OptionPane.background", Color.WHITE); - table.put("OptionPane.border", MaterialBorders.DEFAULT_SHADOW_BORDER); - table.put("OptionPane.font", MaterialFonts.REGULAR); - - table.put("Panel.font", MaterialFonts.REGULAR); - table.put("Panel.background", Color.WHITE); - table.put("Panel.border", BorderFactory.createEmptyBorder()); - - table.put("PopupMenu.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("PopupMenu.background", Color.WHITE); - table.put("PopupMenu.foreground", Color.BLACK); - - table.put("RadioButton.font", MaterialFonts.REGULAR); - table.put("RadioButton.background", Color.WHITE); - table.put("RadioButton.foreground", Color.BLACK); - table.put("RadioButton.icon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); - table.put("RadioButton.selectedIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); - - table.put("Spinner.font", MaterialFonts.REGULAR); - table.put("Spinner.background", Color.WHITE); - table.put("Spinner.foreground", Color.BLACK); - table.put("Spinner.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("Spinner.arrowButtonBackground", MaterialColors.GRAY_200); - table.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); - - table.put("ScrollBar.font", MaterialFonts.REGULAR); - table.put("ScrollBar.track", MaterialColors.GRAY_200); - table.put("ScrollBar.thumb", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbDarkShadow", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbHighlight", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbShadow", MaterialColors.GRAY_300); - table.put("ScrollBar.arrowButtonBackground", MaterialColors.GRAY_300); - table.put("ScrollBar.arrowButtonBorder", BorderFactory.createEmptyBorder()); - - table.put("ScrollPane.background", Color.WHITE); - table.put("ScrollPane.border", BorderFactory.createEmptyBorder()); - table.put("ScrollPane.font", MaterialFonts.REGULAR); - - table.put("Slider.font", MaterialFonts.REGULAR); - table.put("Slider.background", Color.WHITE); - table.put("Slider.foreground", MaterialColors.GRAY_700); - table.put("Slider.trackColor", Color.BLACK); - // table.put ("Slider.border", - // BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, - // BorderFactory.createEmptyBorder (5, 5, 5, 5))); - - table.put("SplitPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("SplitPane.background", Color.WHITE); - table.put("SplitPane.dividerSize", 10); - table.put("SplitPaneDivider.border", MaterialBorders.LIGHT_SHADOW_BORDER); - - table.put("TabbedPane.font", MaterialFonts.REGULAR); - table.put("TabbedPane.background", Color.WHITE); - table.put("TabbedPane.foreground", Color.BLACK); - table.put("TabbedPane.border", BorderFactory.createEmptyBorder()); - table.put("TabbedPane.shadow", null); - table.put("TabbedPane.darkShadow", null); - table.put("TabbedPane.highlight", MaterialColors.GRAY_200); - table.put("TabbedPane.borderHighlightColor", MaterialColors.GRAY_300); - - table.put("Table.selectionBackground", MaterialColors.GRAY_100); - table.put("Table.selectionForeground", Color.BLACK); - table.put("Table.background", Color.WHITE); - table.put("Table.font", MaterialFonts.REGULAR); - table.put("Table.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("Table.gridColor", MaterialColors.GRAY_200); - table.put("TableHeader.background", MaterialColors.GRAY_200); - table.put("TableHeader.font", MaterialFonts.BOLD); - table.put( - "TableHeader.cellBorder", - BorderFactory.createCompoundBorder( - MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(5, 5, 5, 5))); - - table.put("TextArea.background", MaterialColors.GRAY_200); - table.put("TextArea.border", BorderFactory.createEmptyBorder()); - table.put("TextArea.foreground", Color.BLACK); - - table.put("ToggleButton.border", BorderFactory.createEmptyBorder()); - table.put("ToggleButton.font", MaterialFonts.REGULAR); - table.put("ToggleButton.background", Color.WHITE); - table.put("ToggleButton.foreground", Color.BLACK); - table.put("ToggleButton.icon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_OFF)); - table.put("ToggleButton.selectedIcon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_ON)); - - table.put("ToolBar.font", MaterialFonts.REGULAR); - table.put("ToolBar.background", Color.WHITE); - table.put("ToolBar.foreground", Color.BLACK); - table.put("ToolBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); - table.put("ToolBar.dockingBackground", MaterialColors.LIGHT_GREEN_A100); - table.put("ToolBar.floatingBackground", MaterialColors.GRAY_200); - - table.put("Tree.font", MaterialFonts.REGULAR); - table.put("Tree.selectionForeground", Color.BLACK); - table.put("Tree.foreground", Color.BLACK); - table.put("Tree.selectionBackground", MaterialColors.GRAY_200); - table.put("Tree.background", Color.WHITE); - table.put("Tree.closedIcon", new ImageIcon(MaterialImages.RIGHT_ARROW)); - table.put("Tree.openIcon", new ImageIcon(MaterialImages.DOWN_ARROW)); - table.put("Tree.selectionBorderColor", null); - - table.put("RadioButtonMenuItem.foreground", Color.BLACK); - table.put("RadioButtonMenuItem.selectionForeground", Color.BLACK); - // If it changes the background of the menuitem it must change this too, irrespective of its - // setting - table.put("RadioButtonMenuItem.background", UIManager.getColor("MenuItem.background")); - table.put("RadioButtonMenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("RadioButtonMenuItem.checkIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); - table.put( - "RadioButtonMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); - - // If it changes the background of the menuitem it must change this too, irrespective of its - // setting - table.put("CheckBoxMenuItem.background", UIManager.getColor("MenuItem.background")); - table.put("CheckBoxMenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("CheckBoxMenuItem.foreground", Color.BLACK); - table.put("CheckBoxMenuItem.selectionForeground", Color.BLACK); - table.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("CheckBoxMenuItem.checkIcon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); - table.put( - "CheckBoxMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); - - table.put("TextPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("TextPane.background", MaterialColors.GRAY_50); - table.put("TextPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); - table.put("TextPane.inactiveForeground", MaterialColors.GRAY_500); - table.put("TextPane.font", MaterialFonts.REGULAR); - - table.put("EditorPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("EditorPane.background", MaterialColors.GRAY_50); - table.put("EditorPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); - table.put("EditorPane.inactiveForeground", MaterialColors.GRAY_500); - table.put("EditorPane.font", MaterialFonts.REGULAR); - - table.put("Separator.background", MaterialColors.GRAY_300); - table.put("Separator.foreground", MaterialColors.GRAY_300); - - table.put("ToolTip.background", MaterialColors.GRAY_500); - table.put("ToolTip.foreground", MaterialColors.GRAY_50); - table.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - - table.put("ColorChooser.background", MaterialColors.WHITE); - table.put("ColorChooser.foreground", MaterialColors.BLACK); - } + /** + * Return a short string that identifies this look and feel, e.g. "CDE/Motif". This string + * should be appropriate for a menu item. Distinct look and feels should have different names, + * e.g. a subclass of MotifLookAndFeel that changes the way a few components are rendered should + * be called "CDE/Motif My Way"; something that would be useful to a user trying to select a + * L&F from a list of names. + * + * @return short identifier for the look and feel + */ + @Override + public String getName() { + return "Legup"; + } + + /** + * Return a string that identifies this look and feel. This string will be used by + * applications/services that want to recognize well known look and feel implementations. + * Presently the well known names are "Motif", "Windows", "Mac", "Metal". Note that a + * LookAndFeel derived from a well known superclass that doesn't make any fundamental changes to + * the look or feel shouldn't override this method. + * + * @return identifier for the look and feel + */ + @Override + public String getID() { + return "Legup Look and Feel"; + } + + /** + * Return a one line description of this look and feel implementation, e.g. "The CDE/Motif Look + * and Feel". This string is intended for the user, e.g. in the title of a window or in a + * ToolTip message. + * + * @return short description for the look and feel + */ + @Override + public String getDescription() { + return "Material design look and feel for Legup"; + } + + /** + * If the underlying platform has a "native" look and feel, and this is an implementation of it, + * return {@code true}. For example, when the underlying platform is Solaris running CDE a + * CDE/Motif look and feel implementation would return {@code true}. + * + * @return {@code true} if this look and feel represents the underlying platform look and feel + */ + @Override + public boolean isNativeLookAndFeel() { + return true; + } + + /** + * Return {@code true} if the underlying platform supports and or permits this look and feel. + * This method returns {@code false} if the look and feel depends on special resources or legal + * agreements that aren't defined for the current platform. + * + * @return {@code true} if this is a supported look and feel + * @see UIManager#setLookAndFeel + */ + @Override + public boolean isSupportedLookAndFeel() { + return true; + } + + /** + * Initializes the look and feel. While this method is public, it should only be invoked by the + * {@code UIManager} when a look and feel is installed as the current look and feel. This method + * is invoked before the {@code UIManager} invokes {@code getDefaults}. This method is intended + * to perform any initialization for the look and feel. Subclasses should do any one-time setup + * they need here, rather than in a static initializer, because look and feel class objects may + * be loaded just to discover that {@code isSupportedLookAndFeel()} returns {@code false}. + * + * @see #uninitialize + * @see UIManager#setLookAndFeel + */ + @Override + public void initialize() { + super.initialize(); + } + + /** + * Populates {@code table} with mappings from {@code uiClassID} to the fully qualified name of + * the ui class. The value for a particular {@code uiClassID} is {@code + * "javax.swing.plaf.basic.Basic + uiClassID"}. For example, the value for the {@code uiClassID} + * {@code TreeUI} is {@code "javax.swing.plaf.basic.BasicTreeUI"}. + * + * @param table the {@code UIDefaults} instance the entries are added to + * @throws NullPointerException if {@code table} is {@code null} + * @see LookAndFeel + * @see #getDefaults + */ + @Override + protected void initClassDefaults(UIDefaults table) { + super.initClassDefaults(table); + + table.put("ButtonUI", MaterialButtonUI.class.getCanonicalName()); + table.put("TextFieldUI", MaterialTextFieldUI.class.getCanonicalName()); + table.put("PasswordFieldUI", MaterialPasswordFieldUI.class.getCanonicalName()); + table.put("TableUI", MaterialTableUI.class.getCanonicalName()); + table.put("TableHeaderUI", MaterialTableHeaderUI.class.getCanonicalName()); + table.put("TreeUI", MaterialTreeUI.class.getCanonicalName()); + table.put("SpinnerUI", MaterialSpinnerUI.class.getCanonicalName()); + table.put("PanelUI", MaterialPanelUI.class.getCanonicalName()); + table.put("LabelUI", MaterialLabelUI.class.getCanonicalName()); + table.put("MenuItemUI", MaterialMenuItemUI.class.getCanonicalName()); + // table.put ("MenuBarUI", .class.getCanonicalName()); + table.put("MenuUI", MaterialMenuUI.class.getCanonicalName()); + table.put("CheckBoxUI", MaterialCheckBoxUI.class.getCanonicalName()); + table.put("RadioButtonUI", MaterialRadioButtonUI.class.getCanonicalName()); + table.put("TabbedPaneUI", MaterialTabbedPaneUI.class.getCanonicalName()); + table.put("ToggleButtonUI", MaterialToggleButtonUI.class.getCanonicalName()); + table.put("ScrollBarUI", MaterialScrollBarUI.class.getCanonicalName()); + table.put("ComboBoxUI", MaterialComboBoxUI.class.getCanonicalName()); + table.put("PopupMenuUI", MaterialPopupMenuUI.class.getCanonicalName()); + table.put("ToolBarUI", MaterialToolBarUI.class.getCanonicalName()); + table.put("SliderUI", MaterialSliderUI.class.getCanonicalName()); + table.put("ProgressBarUI", MaterialProgressBarUI.class.getCanonicalName()); + table.put("RadioButtonMenuItemUI", MaterialRadioButtonMenuItemUI.class.getCanonicalName()); + table.put("CheckBoxMenuItemUI", MaterialCheckBoxMenuItemUI.class.getCanonicalName()); + table.put("TextPaneUI", MaterialTextPaneUI.class.getCanonicalName()); + table.put("EditorPaneUI", MaterialEditorPaneUI.class.getCanonicalName()); + table.put("SeparatorUI", MaterialSeparatorUI.class.getCanonicalName()); + table.put("FileChooserUI", MaterialFileChooserUI.class.getCanonicalName()); + table.put("ToolTipUI", MaterialToolTipUI.class.getCanonicalName()); + table.put("SplitPaneUI", MaterialSplitPaneUI.class.getCanonicalName()); + // table.put ("ColorChooserUI", ); + } + + @Override + protected void initComponentDefaults(UIDefaults table) { + super.initComponentDefaults(table); + + table.put("Button.highlight", MaterialColors.GRAY_300); + table.put("Button.opaque", false); + table.put("Button.border", BorderFactory.createEmptyBorder(7, 17, 7, 17)); + table.put("Button.background", MaterialColors.GRAY_200); + table.put("Button.foreground", Color.BLACK); + table.put("Button.font", MaterialFonts.MEDIUM); + + table.put("CheckBox.font", MaterialFonts.REGULAR); + table.put("CheckBox.background", Color.WHITE); + table.put("CheckBox.foreground", Color.BLACK); + table.put("CheckBox.icon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); + table.put("CheckBox.selectedIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); + + table.put("ComboBox.font", MaterialFonts.REGULAR); + table.put("ComboBox.background", Color.WHITE); + table.put("ComboBox.foreground", Color.BLACK); + table.put( + "ComboBox.border", + BorderFactory.createCompoundBorder( + MaterialBorders.LIGHT_LINE_BORDER, + BorderFactory.createEmptyBorder(0, 5, 0, 0))); + table.put("ComboBox.buttonBackground", MaterialColors.GRAY_300); + table.put("ComboBox.selectionBackground", Color.WHITE); + table.put("ComboBox.selectionForeground", Color.BLACK); + table.put("ComboBox.selectedInDropDownBackground", MaterialColors.GRAY_200); + + table.put("Label.font", MaterialFonts.REGULAR); + table.put("Label.background", Color.WHITE); + table.put("Label.foreground", Color.BLACK); + table.put("Label.border", BorderFactory.createEmptyBorder()); + + table.put("Menu.font", MaterialFonts.BOLD); + table.put("Menu.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("Menu.background", Color.WHITE); + table.put("Menu.foreground", Color.BLACK); + table.put("Menu.opaque", true); + table.put("Menu.selectionBackground", MaterialColors.GRAY_200); + table.put("Menu.selectionForeground", Color.BLACK); + table.put("Menu.disabledForeground", new Color(0, 0, 0, 100)); + table.put("Menu.menuPopupOffsetY", 3); + + table.put("MenuBar.font", MaterialFonts.BOLD); + table.put("MenuBar.background", Color.WHITE); + table.put("MenuBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); + table.put("MenuBar.foreground", Color.BLACK); + + table.put("MenuItem.disabledForeground", new Color(0, 0, 0, 100)); + table.put("MenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("MenuItem.selectionForeground", Color.BLACK); + table.put("MenuItem.font", MaterialFonts.MEDIUM); + table.put("MenuItem.background", Color.WHITE); + table.put("MenuItem.foreground", Color.BLACK); + table.put("MenuItem.border", BorderFactory.createEmptyBorder(5, 0, 5, 0)); + + table.put("OptionPane.background", Color.WHITE); + table.put("OptionPane.border", MaterialBorders.DEFAULT_SHADOW_BORDER); + table.put("OptionPane.font", MaterialFonts.REGULAR); + + table.put("Panel.font", MaterialFonts.REGULAR); + table.put("Panel.background", Color.WHITE); + table.put("Panel.border", BorderFactory.createEmptyBorder()); + + table.put("PopupMenu.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("PopupMenu.background", Color.WHITE); + table.put("PopupMenu.foreground", Color.BLACK); + + table.put("RadioButton.font", MaterialFonts.REGULAR); + table.put("RadioButton.background", Color.WHITE); + table.put("RadioButton.foreground", Color.BLACK); + table.put("RadioButton.icon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); + table.put("RadioButton.selectedIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); + + table.put("Spinner.font", MaterialFonts.REGULAR); + table.put("Spinner.background", Color.WHITE); + table.put("Spinner.foreground", Color.BLACK); + table.put("Spinner.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("Spinner.arrowButtonBackground", MaterialColors.GRAY_200); + table.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); + + table.put("ScrollBar.font", MaterialFonts.REGULAR); + table.put("ScrollBar.track", MaterialColors.GRAY_200); + table.put("ScrollBar.thumb", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbDarkShadow", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbHighlight", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbShadow", MaterialColors.GRAY_300); + table.put("ScrollBar.arrowButtonBackground", MaterialColors.GRAY_300); + table.put("ScrollBar.arrowButtonBorder", BorderFactory.createEmptyBorder()); + + table.put("ScrollPane.background", Color.WHITE); + table.put("ScrollPane.border", BorderFactory.createEmptyBorder()); + table.put("ScrollPane.font", MaterialFonts.REGULAR); + + table.put("Slider.font", MaterialFonts.REGULAR); + table.put("Slider.background", Color.WHITE); + table.put("Slider.foreground", MaterialColors.GRAY_700); + table.put("Slider.trackColor", Color.BLACK); + // table.put ("Slider.border", + // BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, + // BorderFactory.createEmptyBorder (5, 5, 5, 5))); + + table.put("SplitPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("SplitPane.background", Color.WHITE); + table.put("SplitPane.dividerSize", 10); + table.put("SplitPaneDivider.border", MaterialBorders.LIGHT_SHADOW_BORDER); + + table.put("TabbedPane.font", MaterialFonts.REGULAR); + table.put("TabbedPane.background", Color.WHITE); + table.put("TabbedPane.foreground", Color.BLACK); + table.put("TabbedPane.border", BorderFactory.createEmptyBorder()); + table.put("TabbedPane.shadow", null); + table.put("TabbedPane.darkShadow", null); + table.put("TabbedPane.highlight", MaterialColors.GRAY_200); + table.put("TabbedPane.borderHighlightColor", MaterialColors.GRAY_300); + + table.put("Table.selectionBackground", MaterialColors.GRAY_100); + table.put("Table.selectionForeground", Color.BLACK); + table.put("Table.background", Color.WHITE); + table.put("Table.font", MaterialFonts.REGULAR); + table.put("Table.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("Table.gridColor", MaterialColors.GRAY_200); + table.put("TableHeader.background", MaterialColors.GRAY_200); + table.put("TableHeader.font", MaterialFonts.BOLD); + table.put( + "TableHeader.cellBorder", + BorderFactory.createCompoundBorder( + MaterialBorders.LIGHT_LINE_BORDER, + BorderFactory.createEmptyBorder(5, 5, 5, 5))); + + table.put("TextArea.background", MaterialColors.GRAY_200); + table.put("TextArea.border", BorderFactory.createEmptyBorder()); + table.put("TextArea.foreground", Color.BLACK); + + table.put("ToggleButton.border", BorderFactory.createEmptyBorder()); + table.put("ToggleButton.font", MaterialFonts.REGULAR); + table.put("ToggleButton.background", Color.WHITE); + table.put("ToggleButton.foreground", Color.BLACK); + table.put("ToggleButton.icon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_OFF)); + table.put("ToggleButton.selectedIcon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_ON)); + + table.put("ToolBar.font", MaterialFonts.REGULAR); + table.put("ToolBar.background", Color.WHITE); + table.put("ToolBar.foreground", Color.BLACK); + table.put("ToolBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); + table.put("ToolBar.dockingBackground", MaterialColors.LIGHT_GREEN_A100); + table.put("ToolBar.floatingBackground", MaterialColors.GRAY_200); + + table.put("Tree.font", MaterialFonts.REGULAR); + table.put("Tree.selectionForeground", Color.BLACK); + table.put("Tree.foreground", Color.BLACK); + table.put("Tree.selectionBackground", MaterialColors.GRAY_200); + table.put("Tree.background", Color.WHITE); + table.put("Tree.closedIcon", new ImageIcon(MaterialImages.RIGHT_ARROW)); + table.put("Tree.openIcon", new ImageIcon(MaterialImages.DOWN_ARROW)); + table.put("Tree.selectionBorderColor", null); + + table.put("RadioButtonMenuItem.foreground", Color.BLACK); + table.put("RadioButtonMenuItem.selectionForeground", Color.BLACK); + // If it changes the background of the menuitem it must change this too, irrespective of its + // setting + table.put("RadioButtonMenuItem.background", UIManager.getColor("MenuItem.background")); + table.put("RadioButtonMenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("RadioButtonMenuItem.checkIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); + table.put( + "RadioButtonMenuItem.selectedCheckIcon", + new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); + + // If it changes the background of the menuitem it must change this too, irrespective of its + // setting + table.put("CheckBoxMenuItem.background", UIManager.getColor("MenuItem.background")); + table.put("CheckBoxMenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("CheckBoxMenuItem.foreground", Color.BLACK); + table.put("CheckBoxMenuItem.selectionForeground", Color.BLACK); + table.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("CheckBoxMenuItem.checkIcon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); + table.put( + "CheckBoxMenuItem.selectedCheckIcon", + new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); + + table.put("TextPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("TextPane.background", MaterialColors.GRAY_50); + table.put("TextPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); + table.put("TextPane.inactiveForeground", MaterialColors.GRAY_500); + table.put("TextPane.font", MaterialFonts.REGULAR); + + table.put("EditorPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("EditorPane.background", MaterialColors.GRAY_50); + table.put("EditorPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); + table.put("EditorPane.inactiveForeground", MaterialColors.GRAY_500); + table.put("EditorPane.font", MaterialFonts.REGULAR); + + table.put("Separator.background", MaterialColors.GRAY_300); + table.put("Separator.foreground", MaterialColors.GRAY_300); + + table.put("ToolTip.background", MaterialColors.GRAY_500); + table.put("ToolTip.foreground", MaterialColors.GRAY_50); + table.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + table.put("ColorChooser.background", MaterialColors.WHITE); + table.put("ColorChooser.foreground", MaterialColors.BLACK); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java index a0fdc487a..db7d604a0 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java @@ -5,13 +5,13 @@ public class MaterialUIMovement { - private MaterialUIMovement() {} + private MaterialUIMovement() {} - public static void add(JComponent c, Color fadeTo, int steps, int interval) { - new MaterialUITimer(c, fadeTo, steps, interval); - } + public static void add(JComponent c, Color fadeTo, int steps, int interval) { + new MaterialUITimer(c, fadeTo, steps, interval); + } - public static void add(JComponent c, Color fadeTo) { - add(c, fadeTo, 5, 1000 / 30); - } + public static void add(JComponent c, Color fadeTo) { + add(c, fadeTo, 5, 1000 / 30); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java index b5ca8415f..f989185c7 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java @@ -10,99 +10,99 @@ public class MaterialUITimer implements MouseListener, ActionListener { - private Color from, to; - private boolean forward; - private int alpha, steps; - private int[] forwardDeltas, backwardDeltas; - - private JComponent component; - private Timer timer; - - protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { - this.from = component.getBackground(); - this.to = to; - - this.forwardDeltas = new int[4]; - this.backwardDeltas = new int[4]; - - forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; - forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; - forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; - forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; - - backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; - backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; - backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; - backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; - - this.steps = steps; - - this.component = component; - this.component.addMouseListener(this); - timer = new Timer(interval, this); - } - - private Color nextColor() { - int rValue = from.getRed() - alpha * forwardDeltas[0]; - int gValue = from.getGreen() - alpha * forwardDeltas[1]; - int bValue = from.getBlue() - alpha * forwardDeltas[2]; - int aValue = from.getAlpha() - alpha * forwardDeltas[3]; - - return new Color(rValue, gValue, bValue, aValue); - } - - private Color previousColor() { - int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; - int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; - int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; - int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; - - return new Color(rValue, gValue, bValue, aValue); - } - - @Override - public void mousePressed(MouseEvent me) { - alpha = steps - 1; - forward = false; - timer.start(); - - alpha = 0; - forward = true; - timer.start(); - } - - @Override - public void mouseReleased(MouseEvent me) {} - - @Override - public void mouseClicked(MouseEvent me) {} - - @Override - public void mouseExited(MouseEvent me) { - alpha = steps - 1; - forward = false; - timer.start(); - } - - @Override - public void mouseEntered(MouseEvent me) { - alpha = 0; - forward = true; - timer.start(); - } - - @Override - public void actionPerformed(ActionEvent ae) { - if (forward) { - component.setBackground(nextColor()); - ++alpha; - } else { - component.setBackground(previousColor()); - --alpha; + private Color from, to; + private boolean forward; + private int alpha, steps; + private int[] forwardDeltas, backwardDeltas; + + private JComponent component; + private Timer timer; + + protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { + this.from = component.getBackground(); + this.to = to; + + this.forwardDeltas = new int[4]; + this.backwardDeltas = new int[4]; + + forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; + forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; + forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; + forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; + + backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; + backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; + backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; + backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; + + this.steps = steps; + + this.component = component; + this.component.addMouseListener(this); + timer = new Timer(interval, this); + } + + private Color nextColor() { + int rValue = from.getRed() - alpha * forwardDeltas[0]; + int gValue = from.getGreen() - alpha * forwardDeltas[1]; + int bValue = from.getBlue() - alpha * forwardDeltas[2]; + int aValue = from.getAlpha() - alpha * forwardDeltas[3]; + + return new Color(rValue, gValue, bValue, aValue); + } + + private Color previousColor() { + int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; + int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; + int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; + int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; + + return new Color(rValue, gValue, bValue, aValue); + } + + @Override + public void mousePressed(MouseEvent me) { + alpha = steps - 1; + forward = false; + timer.start(); + + alpha = 0; + forward = true; + timer.start(); + } + + @Override + public void mouseReleased(MouseEvent me) {} + + @Override + public void mouseClicked(MouseEvent me) {} + + @Override + public void mouseExited(MouseEvent me) { + alpha = steps - 1; + forward = false; + timer.start(); + } + + @Override + public void mouseEntered(MouseEvent me) { + alpha = 0; + forward = true; + timer.start(); } - if (alpha == steps + 1 || alpha == -1) { - timer.stop(); + @Override + public void actionPerformed(ActionEvent ae) { + if (forward) { + component.setBackground(nextColor()); + ++alpha; + } else { + component.setBackground(previousColor()); + --alpha; + } + + if (alpha == steps + 1 || alpha == -1) { + timer.stop(); + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java index 5fbc8c1aa..debe6e215 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java @@ -12,33 +12,33 @@ public class MaterialButtonUI extends BasicButtonUI { - public static ComponentUI createUI(final JComponent c) { - return new MaterialButtonUI(); - } + public static ComponentUI createUI(final JComponent c) { + return new MaterialButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - AbstractButton button = (AbstractButton) c; - MaterialUIMovement.add(c, MaterialColors.GRAY_300); - button.setOpaque(UIManager.getBoolean("Button.opaque")); - button.setBorder(UIManager.getBorder("Button.border")); - button.setBackground(UIManager.getColor("Button.background")); - button.setForeground(UIManager.getColor("Button.foreground")); - button.setFont(UIManager.getFont("Button.font")); - } + AbstractButton button = (AbstractButton) c; + MaterialUIMovement.add(c, MaterialColors.GRAY_300); + button.setOpaque(UIManager.getBoolean("Button.opaque")); + button.setBorder(UIManager.getBorder("Button.border")); + button.setBackground(UIManager.getColor("Button.background")); + button.setForeground(UIManager.getColor("Button.foreground")); + button.setFont(UIManager.getFont("Button.font")); + } - @Override - public void paint(Graphics g, JComponent c) { - AbstractButton b = (AbstractButton) c; - g = MaterialDrawingUtils.getAliasedGraphics(g); - paintBackground(g, b); - super.paint(g, c); - } + @Override + public void paint(Graphics g, JComponent c) { + AbstractButton b = (AbstractButton) c; + g = MaterialDrawingUtils.getAliasedGraphics(g); + paintBackground(g, b); + super.paint(g, c); + } - private void paintBackground(Graphics g, JComponent c) { - g.setColor(c.getBackground()); - g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 7, 7); - } + private void paintBackground(Graphics g, JComponent c) { + g.setColor(c.getBackground()); + g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 7, 7); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java index 18870c571..8f0df3604 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java @@ -15,48 +15,48 @@ */ public class MaterialCheckBoxMenuItemUI extends BasicCheckBoxMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialCheckBoxMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialCheckBoxMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintMenuItem( - Graphics g, - JComponent c, - Icon checkIcon, - Icon arrowIcon, - Color background, - Color foreground, - int defaultTextIconGap) { - JCheckBoxMenuItem checkBoxMenuItem = (JCheckBoxMenuItem) c; - if (checkBoxMenuItem.isSelected()) { - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - checkBoxMenuItem, - UIManager.getIcon("CheckBoxMenuItem.selectedCheckIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - return; + @Override + protected void paintMenuItem( + Graphics g, + JComponent c, + Icon checkIcon, + Icon arrowIcon, + Color background, + Color foreground, + int defaultTextIconGap) { + JCheckBoxMenuItem checkBoxMenuItem = (JCheckBoxMenuItem) c; + if (checkBoxMenuItem.isSelected()) { + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + checkBoxMenuItem, + UIManager.getIcon("CheckBoxMenuItem.selectedCheckIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + return; + } + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + checkBoxMenuItem, + UIManager.getIcon("CheckBoxMenuItem.checkIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); } - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - checkBoxMenuItem, - UIManager.getIcon("CheckBoxMenuItem.checkIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java index e851617f9..4a9725d52 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java @@ -11,24 +11,24 @@ // TODO cambio colore icone combo box public class MaterialCheckBoxUI extends BasicCheckBoxUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialCheckBoxUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialCheckBoxUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JCheckBox checkBox = (JCheckBox) c; - checkBox.setFont(UIManager.getFont("CheckBox.font")); - checkBox.setBackground(UIManager.getColor("CheckBox.background")); - checkBox.setForeground(UIManager.getColor("CheckBox.foreground")); - checkBox.setIcon(UIManager.getIcon("CheckBox.icon")); - checkBox.setSelectedIcon(UIManager.getIcon("CheckBox.selectedIcon")); - } + JCheckBox checkBox = (JCheckBox) c; + checkBox.setFont(UIManager.getFont("CheckBox.font")); + checkBox.setBackground(UIManager.getColor("CheckBox.background")); + checkBox.setForeground(UIManager.getColor("CheckBox.foreground")); + checkBox.setIcon(UIManager.getIcon("CheckBox.icon")); + checkBox.setSelectedIcon(UIManager.getIcon("CheckBox.selectedIcon")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java index e8e0957e1..73573d8f8 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java @@ -9,20 +9,21 @@ public class MaterialComboBoxRenderer extends BasicComboBoxRenderer { - @Override - public Component getListCellRendererComponent( - JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JComponent component = - (JComponent) - super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + @Override + public Component getListCellRendererComponent( + JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JComponent component = + (JComponent) + super.getListCellRendererComponent( + list, value, index, isSelected, cellHasFocus); - component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - component.setForeground(UIManager.getColor("ComboBox.foreground")); - component.setBackground( - isSelected || cellHasFocus - ? UIManager.getColor("ComboBox.selectedInDropDownBackground") - : UIManager.getColor("ComboBox.background")); + component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + component.setForeground(UIManager.getColor("ComboBox.foreground")); + component.setBackground( + isSelected || cellHasFocus + ? UIManager.getColor("ComboBox.selectedInDropDownBackground") + : UIManager.getColor("ComboBox.background")); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java index 3cd934502..8cd52995b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java @@ -15,42 +15,42 @@ public class MaterialComboBoxUI extends BasicComboBoxUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialComboBoxUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JComboBox comboBox = (JComboBox) c; - comboBox.setFont(UIManager.getFont("ComboBox.font")); - comboBox.setBackground(UIManager.getColor("ComboBox.background")); - comboBox.setForeground(UIManager.getColor("ComboBox.foreground")); - comboBox.setBorder(UIManager.getBorder("ComboBox.border")); - comboBox.setLightWeightPopupEnabled(true); - comboBox.setRenderer(new MaterialComboBoxRenderer()); - } - - @Override - protected JButton createArrowButton() { - Icon icon = UIManager.getIcon("ComboBox.buttonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.SOUTH); + public static ComponentUI createUI(JComponent c) { + return new MaterialComboBoxUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JComboBox comboBox = (JComboBox) c; + comboBox.setFont(UIManager.getFont("ComboBox.font")); + comboBox.setBackground(UIManager.getColor("ComboBox.background")); + comboBox.setForeground(UIManager.getColor("ComboBox.foreground")); + comboBox.setBorder(UIManager.getBorder("ComboBox.border")); + comboBox.setLightWeightPopupEnabled(true); + comboBox.setRenderer(new MaterialComboBoxRenderer()); + } + + @Override + protected JButton createArrowButton() { + Icon icon = UIManager.getIcon("ComboBox.buttonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.SOUTH); + } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ComboBox.buttonBackground")); + button.setBorder(BorderFactory.createEmptyBorder()); + + return button; + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ComboBox.buttonBackground")); - button.setBorder(BorderFactory.createEmptyBorder()); - - return button; - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java index df165a608..786f289bb 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java @@ -9,12 +9,12 @@ */ public class MaterialEditorPaneUI extends BasicEditorPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialEditorPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialEditorPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java index ffcca1064..b8046c569 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java @@ -11,48 +11,48 @@ public class MaterialFileChooserUI extends MetalFileChooserUI { - public MaterialFileChooserUI(JFileChooser fileChooser) { - super(fileChooser); - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialFileChooserUI((JFileChooser) c); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - JFileChooser fileChooser = (JFileChooser) c; - MaterialFileChooserUI ui = (MaterialFileChooserUI) fileChooser.getUI(); - - ui.uninstallIcons(fileChooser); - ui.uninstallComponents(fileChooser); - ui.clearIconCache(); - - ui.computerIcon = new ImageIcon(MaterialImages.COMPUTER); - ui.directoryIcon = new ImageIcon(MaterialImages.FOLDER); - ui.fileIcon = new ImageIcon(MaterialImages.FILE); - ui.floppyDriveIcon = new ImageIcon(MaterialImages.FLOPPY_DRIVE); - ui.hardDriveIcon = new ImageIcon(MaterialImages.HARD_DRIVE); - - ui.homeFolderIcon = new ImageIcon(MaterialImages.HOME); - ui.listViewIcon = new ImageIcon(MaterialImages.LIST); - ui.detailsViewIcon = new ImageIcon(MaterialImages.DETAILS); - ui.newFolderIcon = new ImageIcon(MaterialImages.NEW_FOLDER); - ui.upFolderIcon = new ImageIcon(MaterialImages.BACK_ARROW); - - ui.openButtonText = "OPEN"; - ui.cancelButtonText = "CANCEL"; - ui.helpButtonText = "HELP"; - ui.saveButtonText = "SAVE"; - ui.directoryOpenButtonText = "OPEN"; - ui.updateButtonText = "UPDATE"; - - ui.installComponents(fileChooser); - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + public MaterialFileChooserUI(JFileChooser fileChooser) { + super(fileChooser); + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialFileChooserUI((JFileChooser) c); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + JFileChooser fileChooser = (JFileChooser) c; + MaterialFileChooserUI ui = (MaterialFileChooserUI) fileChooser.getUI(); + + ui.uninstallIcons(fileChooser); + ui.uninstallComponents(fileChooser); + ui.clearIconCache(); + + ui.computerIcon = new ImageIcon(MaterialImages.COMPUTER); + ui.directoryIcon = new ImageIcon(MaterialImages.FOLDER); + ui.fileIcon = new ImageIcon(MaterialImages.FILE); + ui.floppyDriveIcon = new ImageIcon(MaterialImages.FLOPPY_DRIVE); + ui.hardDriveIcon = new ImageIcon(MaterialImages.HARD_DRIVE); + + ui.homeFolderIcon = new ImageIcon(MaterialImages.HOME); + ui.listViewIcon = new ImageIcon(MaterialImages.LIST); + ui.detailsViewIcon = new ImageIcon(MaterialImages.DETAILS); + ui.newFolderIcon = new ImageIcon(MaterialImages.NEW_FOLDER); + ui.upFolderIcon = new ImageIcon(MaterialImages.BACK_ARROW); + + ui.openButtonText = "OPEN"; + ui.cancelButtonText = "CANCEL"; + ui.helpButtonText = "HELP"; + ui.saveButtonText = "SAVE"; + ui.directoryOpenButtonText = "OPEN"; + ui.updateButtonText = "UPDATE"; + + ui.installComponents(fileChooser); + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java index de43761a9..e19fc1fed 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java @@ -10,24 +10,24 @@ public class MaterialLabelUI extends BasicLabelUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialLabelUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialLabelUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JLabel label = (JLabel) c; - label.setOpaque(true); - label.setFont(UIManager.getFont("Label.font")); - label.setBackground(UIManager.getColor("Label.background")); - label.setForeground(UIManager.getColor("Label.foreground")); - label.setBorder(UIManager.getBorder("Label.border")); - } + JLabel label = (JLabel) c; + label.setOpaque(true); + label.setFont(UIManager.getFont("Label.font")); + label.setBackground(UIManager.getColor("Label.background")); + label.setForeground(UIManager.getColor("Label.foreground")); + label.setBorder(UIManager.getBorder("Label.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java index decb5908d..011d61862 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java @@ -10,23 +10,23 @@ public class MaterialMenuBarUI extends BasicMenuBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenuBar menuBar = (JMenuBar) c; - menuBar.setFont(UIManager.getFont("MenuBar.font")); - menuBar.setBackground(UIManager.getColor("MenuBar.background")); - menuBar.setBorder(UIManager.getBorder("MenuBar.border")); - menuBar.setForeground(UIManager.getColor("MenuBar.foreground")); - } + JMenuBar menuBar = (JMenuBar) c; + menuBar.setFont(UIManager.getFont("MenuBar.font")); + menuBar.setBackground(UIManager.getColor("MenuBar.background")); + menuBar.setBorder(UIManager.getBorder("MenuBar.border")); + menuBar.setForeground(UIManager.getColor("MenuBar.foreground")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java index 32b537bd1..a8c572b62 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java @@ -11,25 +11,25 @@ public class MaterialMenuItemUI extends BasicMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenuItem menuItem = (JMenuItem) c; - menuItem.setFont(UIManager.getFont("MenuItem.font")); - menuItem.setBackground(UIManager.getColor("MenuItem.background")); - menuItem.setForeground(UIManager.getColor("MenuItem.foreground")); - menuItem.setHorizontalAlignment(SwingConstants.LEFT); - menuItem.setVerticalAlignment(SwingConstants.CENTER); - menuItem.setBorder(UIManager.getBorder("MenuItem.border")); - } + JMenuItem menuItem = (JMenuItem) c; + menuItem.setFont(UIManager.getFont("MenuItem.font")); + menuItem.setBackground(UIManager.getColor("MenuItem.background")); + menuItem.setForeground(UIManager.getColor("MenuItem.foreground")); + menuItem.setHorizontalAlignment(SwingConstants.LEFT); + menuItem.setVerticalAlignment(SwingConstants.CENTER); + menuItem.setBorder(UIManager.getBorder("MenuItem.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java index d45c3f37f..16c1b9270 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java @@ -10,24 +10,24 @@ public class MaterialMenuUI extends BasicMenuUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenu menu = (JMenu) c; - menu.setFont(UIManager.getFont("Menu.font")); - menu.setBorder(UIManager.getBorder("Menu.border")); - menu.setBackground(UIManager.getColor("Menu.background")); - menu.setForeground(UIManager.getColor("Menu.foreground")); - menu.setOpaque(UIManager.getBoolean("Menu.opaque")); - } + JMenu menu = (JMenu) c; + menu.setFont(UIManager.getFont("Menu.font")); + menu.setBorder(UIManager.getBorder("Menu.border")); + menu.setBackground(UIManager.getColor("Menu.background")); + menu.setForeground(UIManager.getColor("Menu.foreground")); + menu.setOpaque(UIManager.getBoolean("Menu.opaque")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java index 005d439d6..ae7a9be6b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java @@ -10,23 +10,23 @@ public class MaterialPanelUI extends BasicPanelUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialPanelUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialPanelUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JPanel panel = (JPanel) c; - panel.setOpaque(true); - panel.setFont(UIManager.getFont("Panel.font")); - panel.setBackground(UIManager.getColor("Panel.background")); - panel.setBorder(UIManager.getBorder("Panel.border")); - } + JPanel panel = (JPanel) c; + panel.setOpaque(true); + panel.setFont(UIManager.getFont("Panel.font")); + panel.setBackground(UIManager.getColor("Panel.background")); + panel.setBorder(UIManager.getBorder("Panel.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java index 4ba2910cd..d4778402b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java @@ -27,183 +27,192 @@ import javax.swing.text.View; public class MaterialPasswordFieldUI extends BasicPasswordFieldUI - implements FocusListener, PropertyChangeListener { - - private Color focusedBackground; - private Color unfocusedBackground; - private Color focusedSelectionBackground; - private Color unfocusedSelectionBackground; - - public static ComponentUI createUI(JComponent c) { - return new MaterialPasswordFieldUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JPasswordField passwordField = (JPasswordField) c; - passwordField.setOpaque(false); - passwordField.setBorder(BorderFactory.createEmptyBorder(5, 2, 10, 0)); - passwordField.setBackground(MaterialColors.LIGHT_BLUE_400); - - this.focusedBackground = passwordField.getBackground(); - this.unfocusedBackground = MaterialColors.GRAY_200; - - this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); - this.unfocusedSelectionBackground = unfocusedBackground; - } - - @Override - protected void installListeners() { - getComponent().addFocusListener(this); - getComponent().addPropertyChangeListener(this); - } - - @Override - protected void installKeyboardActions() { - super.installKeyboardActions(); - - Action selectAll = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().selectAll(); - } - }; - - Action delete = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (getComponent().getSelectedText() == null) { - int pos = getComponent().getCaretPosition() - 1; - - if (pos >= 0) { - getComponent().select(pos, pos + 1); - getComponent().replaceSelection(""); - } - } else { - getComponent().replaceSelection(""); - } - } - }; - - Action left = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); - } - }; - - Action right = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent() - .setCaretPosition( - Math.min( - getComponent().getText().length(), getComponent().getCaretPosition() + 1)); - } - }; - - // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to getMenuShortcutKeyMaskEx() - getComponent() - .getInputMap() - .put( - KeyStroke.getKeyStroke( - KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "selectAll"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); - - getComponent().getActionMap().put("selectAll", selectAll); - getComponent().getActionMap().put("delete", delete); - getComponent().getActionMap().put("left", left); - getComponent().getActionMap().put("right", right); - } - - @Override - public void paintSafely(Graphics g) { - JPasswordField c = (JPasswordField) getComponent(); - g = MaterialDrawingUtils.getAliasedGraphics(g); - - if (getComponent().hasFocus()) { - c.setBackground(focusedBackground); - c.setSelectionColor(focusedSelectionBackground); - } else { - c.setBackground(unfocusedBackground); - c.setSelectionColor(unfocusedSelectionBackground); + implements FocusListener, PropertyChangeListener { + + private Color focusedBackground; + private Color unfocusedBackground; + private Color focusedSelectionBackground; + private Color unfocusedSelectionBackground; + + public static ComponentUI createUI(JComponent c) { + return new MaterialPasswordFieldUI(); } - int x = getComponent().getInsets().left; - int y = getComponent().getInsets().top; - int w = - getComponent().getWidth() - - getComponent().getInsets().left - - getComponent().getInsets().right; - - g.setColor(c.getBackground()); - g.fillRect(x, c.getHeight() - y, w, 2); - - super.paintSafely(g); - } - - @Override - public void paintBackground(Graphics g) { - super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); - } - - @Override - public void focusGained(FocusEvent e) { - e.getComponent().setBackground(focusedBackground); - } - - @Override - public void focusLost(FocusEvent e) { - e.getComponent().setBackground(unfocusedBackground); - } - - @Override - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName().equals("background")) { - Color newColor = (Color) pce.getNewValue(); - - if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { - this.focusedBackground = (Color) pce.getNewValue(); - this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JPasswordField passwordField = (JPasswordField) c; + passwordField.setOpaque(false); + passwordField.setBorder(BorderFactory.createEmptyBorder(5, 2, 10, 0)); + passwordField.setBackground(MaterialColors.LIGHT_BLUE_400); + + this.focusedBackground = passwordField.getBackground(); + this.unfocusedBackground = MaterialColors.GRAY_200; + + this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); + this.unfocusedSelectionBackground = unfocusedBackground; } - } - @Override - public View create(Element elem) { - return new MaterialPasswordView(elem); - } + @Override + protected void installListeners() { + getComponent().addFocusListener(this); + getComponent().addPropertyChangeListener(this); + } - private static class MaterialPasswordView extends PasswordView { + @Override + protected void installKeyboardActions() { + super.installKeyboardActions(); + + Action selectAll = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().selectAll(); + } + }; + + Action delete = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (getComponent().getSelectedText() == null) { + int pos = getComponent().getCaretPosition() - 1; + + if (pos >= 0) { + getComponent().select(pos, pos + 1); + getComponent().replaceSelection(""); + } + } else { + getComponent().replaceSelection(""); + } + } + }; + + Action left = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.max(0, getComponent().getCaretPosition() - 1)); + } + }; + + Action right = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.min( + getComponent().getText().length(), + getComponent().getCaretPosition() + 1)); + } + }; + + // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to + // getMenuShortcutKeyMaskEx() + getComponent() + .getInputMap() + .put( + KeyStroke.getKeyStroke( + KeyEvent.VK_A, + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "selectAll"); + getComponent() + .getInputMap() + .put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); + + getComponent().getActionMap().put("selectAll", selectAll); + getComponent().getActionMap().put("delete", delete); + getComponent().getActionMap().put("left", left); + getComponent().getActionMap().put("right", right); + } - private MaterialPasswordView(Element elem) { - super(elem); + @Override + public void paintSafely(Graphics g) { + JPasswordField c = (JPasswordField) getComponent(); + g = MaterialDrawingUtils.getAliasedGraphics(g); + + if (getComponent().hasFocus()) { + c.setBackground(focusedBackground); + c.setSelectionColor(focusedSelectionBackground); + } else { + c.setBackground(unfocusedBackground); + c.setSelectionColor(unfocusedSelectionBackground); + } + + int x = getComponent().getInsets().left; + int y = getComponent().getInsets().top; + int w = + getComponent().getWidth() + - getComponent().getInsets().left + - getComponent().getInsets().right; + + g.setColor(c.getBackground()); + g.fillRect(x, c.getHeight() - y, w, 2); + + super.paintSafely(g); + } + + @Override + public void paintBackground(Graphics g) { + super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); } - // depreciated in Java 9 and above - replace method with float drawEchoCharacter(Graphics2D g, - // float x, float y, char c) @Override - protected int drawEchoCharacter(Graphics g, int x, int y, char c) { - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + public void focusGained(FocusEvent e) { + e.getComponent().setBackground(focusedBackground); + } + + @Override + public void focusLost(FocusEvent e) { + e.getComponent().setBackground(unfocusedBackground); + } + + @Override + public void propertyChange(PropertyChangeEvent pce) { + if (pce.getPropertyName().equals("background")) { + Color newColor = (Color) pce.getNewValue(); + + if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { + this.focusedBackground = (Color) pce.getNewValue(); + this.focusedSelectionBackground = + MaterialColors.bleach(this.focusedBackground, 0.3f); + } + } + } + + @Override + public View create(Element elem) { + return new MaterialPasswordView(elem); + } + + private static class MaterialPasswordView extends PasswordView { + + private MaterialPasswordView(Element elem) { + super(elem); + } + + // depreciated in Java 9 and above - replace method with float drawEchoCharacter(Graphics2D + // g, + // float x, float y, char c) + @Override + protected int drawEchoCharacter(Graphics g, int x, int y, char c) { + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - FontMetrics fm = g2.getFontMetrics(); - int r = fm.charWidth(c) - 2; + FontMetrics fm = g2.getFontMetrics(); + int r = fm.charWidth(c) - 2; - g2.setPaint(Color.BLACK); - g2.fillOval(x + 1, y + 5 - fm.getAscent(), r, r); - g2.dispose(); + g2.setPaint(Color.BLACK); + g2.fillOval(x + 1, y + 5 - fm.getAscent(), r, r); + g2.dispose(); - return x + fm.charWidth(c); + return x + fm.charWidth(c); + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java index a864e9a41..d7baaf5df 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java @@ -10,22 +10,22 @@ public class MaterialPopupMenuUI extends BasicPopupMenuUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialPopupMenuUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialPopupMenuUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JPopupMenu popupMenu = (JPopupMenu) c; - popupMenu.setBorder(UIManager.getBorder("PopupMenu.border")); - popupMenu.setBackground(UIManager.getColor("PopupMenu.background")); - popupMenu.setForeground(UIManager.getColor("PopupMenu.foreground")); - } + JPopupMenu popupMenu = (JPopupMenu) c; + popupMenu.setBorder(UIManager.getBorder("PopupMenu.border")); + popupMenu.setBackground(UIManager.getColor("PopupMenu.background")); + popupMenu.setForeground(UIManager.getColor("PopupMenu.foreground")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java index 062204e11..7f91a779f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java @@ -14,22 +14,22 @@ */ public class MaterialProgressBarUI extends BasicProgressBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialProgressBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialProgressBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JProgressBar progressBar = (JProgressBar) c; - progressBar.setBorder(MaterialBorders.LIGHT_LINE_BORDER); - progressBar.setBackground(MaterialColors.GRAY_200); - progressBar.setForeground(MaterialColors.LIGHT_BLUE_400); - } + JProgressBar progressBar = (JProgressBar) c; + progressBar.setBorder(MaterialBorders.LIGHT_LINE_BORDER); + progressBar.setBackground(MaterialColors.GRAY_200); + progressBar.setForeground(MaterialColors.LIGHT_BLUE_400); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java index 92aa97726..69a9cae53 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java @@ -15,51 +15,51 @@ */ public class MaterialRadioButtonMenuItemUI extends BasicRadioButtonMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialRadioButtonMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialRadioButtonMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; - // j.setBackground(MaterialColors.WHITE); - j.setBorder(UIManager.getBorder("MenuItem.border")); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; + // j.setBackground(MaterialColors.WHITE); + j.setBorder(UIManager.getBorder("MenuItem.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintMenuItem( - Graphics g, - JComponent c, - Icon checkIcon, - Icon arrowIcon, - Color background, - Color foreground, - int defaultTextIconGap) { - JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; - if (j.isSelected()) { - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - c, - UIManager.getIcon("RadioButtonMenuItem.selectedCheckIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - return; + @Override + protected void paintMenuItem( + Graphics g, + JComponent c, + Icon checkIcon, + Icon arrowIcon, + Color background, + Color foreground, + int defaultTextIconGap) { + JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; + if (j.isSelected()) { + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + c, + UIManager.getIcon("RadioButtonMenuItem.selectedCheckIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + return; + } + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + c, + UIManager.getIcon("RadioButtonMenuItem.checkIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); } - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - c, - UIManager.getIcon("RadioButtonMenuItem.checkIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java index 517d9086d..6418d4f17 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java @@ -14,24 +14,24 @@ // TODO cambio colore del radio button. public class MaterialRadioButtonUI extends BasicRadioButtonUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialRadioButtonUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialRadioButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JRadioButton radioButton = (JRadioButton) c; - radioButton.setFont(UIManager.getFont("RadioButton.font")); - radioButton.setBackground(UIManager.getColor("RadioButton.background")); - radioButton.setForeground(UIManager.getColor("RadioButton.foreground")); - radioButton.setIcon(UIManager.getIcon("RadioButton.icon")); - radioButton.setSelectedIcon(UIManager.getIcon("RadioButton.selectedIcon")); - } + JRadioButton radioButton = (JRadioButton) c; + radioButton.setFont(UIManager.getFont("RadioButton.font")); + radioButton.setBackground(UIManager.getColor("RadioButton.background")); + radioButton.setForeground(UIManager.getColor("RadioButton.foreground")); + radioButton.setIcon(UIManager.getIcon("RadioButton.icon")); + radioButton.setSelectedIcon(UIManager.getIcon("RadioButton.selectedIcon")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java index c433ddf92..164209b3f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java @@ -16,49 +16,49 @@ public class MaterialScrollBarUI extends BasicScrollBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialScrollBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialScrollBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JScrollBar scrollBar = (JScrollBar) c; - scrollBar.setFont(UIManager.getFont("ScrollBar.font")); - trackColor = UIManager.getColor("ScrollBar.track"); - thumbColor = UIManager.getColor("ScrollBar.thumb"); - thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); - thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); - thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); - } + JScrollBar scrollBar = (JScrollBar) c; + scrollBar.setFont(UIManager.getFont("ScrollBar.font")); + trackColor = UIManager.getColor("ScrollBar.track"); + thumbColor = UIManager.getColor("ScrollBar.thumb"); + thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); + thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); + thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected JButton createDecreaseButton(int orientation) { - JButton button = new BasicArrowButton(orientation); + @Override + protected JButton createDecreaseButton(int orientation) { + JButton button = new BasicArrowButton(orientation); - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); - return button; - } + return button; + } - @Override - protected JButton createIncreaseButton(int orientation) { - JButton button = new BasicArrowButton(orientation); + @Override + protected JButton createIncreaseButton(int orientation) { + JButton button = new BasicArrowButton(orientation); - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); - return button; - } + return button; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java index 36ee98b90..042b53d1b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java @@ -8,17 +8,17 @@ public class MaterialSeparatorUI extends BasicSeparatorUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialSeparatorUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialSeparatorUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java index 3195c05e0..7ac2fe350 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java @@ -13,131 +13,131 @@ // TODO cambio grafica slider public class MaterialSliderUI extends BasicSliderUI { - private static final int NORMAL_THUMB_RADIUS = 6; - private static final int DRAG_THUMB_RADIUS = 10; - private static final Dimension THUMB_SIZE = - new Dimension(DRAG_THUMB_RADIUS * 2, DRAG_THUMB_RADIUS * 2); - - public MaterialSliderUI(JSlider slider) { - super(slider); - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialSliderUI((JSlider) c); - } - - private static void drawCircle(Graphics g, int x, int y, int radius) { - g.fillOval(x - radius, y - radius, radius * 2, radius * 2); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JSlider slider = (JSlider) c; - slider.setFont(UIManager.getFont("Slider.font")); - slider.setBackground(UIManager.getColor("Slider.background")); - slider.setForeground(UIManager.getColor("Slider.foreground")); - slider.setBorder(UIManager.getBorder("Slider.border")); - } - - @Override - public Dimension getThumbSize() { - return THUMB_SIZE; - } - - @Override - public void paintThumb(Graphics g) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - - int cx = thumbRect.x + thumbRect.width / 2; - int cy = thumbRect.y + thumbRect.height / 2; - - if (isDragging()) { - g.setColor(MaterialColors.bleach(slider.getForeground(), 0.5f)); - drawCircle(g, cx, cy, DRAG_THUMB_RADIUS); + private static final int NORMAL_THUMB_RADIUS = 6; + private static final int DRAG_THUMB_RADIUS = 10; + private static final Dimension THUMB_SIZE = + new Dimension(DRAG_THUMB_RADIUS * 2, DRAG_THUMB_RADIUS * 2); + + public MaterialSliderUI(JSlider slider) { + super(slider); + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialSliderUI((JSlider) c); } - g.setColor(slider.getForeground()); - drawCircle(g, cx, cy, NORMAL_THUMB_RADIUS); - - // need to redraw loaded part of progress line - Line loaded = getTrack(true); - g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); - } - - @Override - public void paintTrack(Graphics g) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - - g.setColor(UIManager.getColor("Slider.trackColor")); - Line unloaded = getTrack(false); - g.drawLine(unloaded.x1, unloaded.y1, unloaded.x2, unloaded.y2); - - g.setColor(slider.getForeground()); - Line loaded = getTrack(true); - g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); - } - - private Line getTrack(boolean loaded) { - if (slider.getOrientation() == JSlider.HORIZONTAL) { - Line left = - new Line( - trackRect.x, - thumbRect.y + thumbRect.height / 2, - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2); - Line right = - new Line( - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2, - trackRect.x + trackRect.width, - thumbRect.y + thumbRect.height / 2); - - if (loaded) { - return slider.getInverted() ? right : left; - } else { - return slider.getInverted() ? left : right; - } - } else { - Line top = - new Line( - thumbRect.x + thumbRect.width / 2, - trackRect.y, - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2); - Line bottom = - new Line( - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2, - thumbRect.x + thumbRect.width / 2, - trackRect.y + trackRect.height); - - if (loaded) { - return slider.getInverted() ? top : bottom; - } else { - return slider.getInverted() ? bottom : top; - } + private static void drawCircle(Graphics g, int x, int y, int radius) { + g.fillOval(x - radius, y - radius, radius * 2, radius * 2); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JSlider slider = (JSlider) c; + slider.setFont(UIManager.getFont("Slider.font")); + slider.setBackground(UIManager.getColor("Slider.background")); + slider.setForeground(UIManager.getColor("Slider.foreground")); + slider.setBorder(UIManager.getBorder("Slider.border")); } - } - @Override - public void paintFocus(Graphics g) {} + @Override + public Dimension getThumbSize() { + return THUMB_SIZE; + } + + @Override + public void paintThumb(Graphics g) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + + int cx = thumbRect.x + thumbRect.width / 2; + int cy = thumbRect.y + thumbRect.height / 2; + + if (isDragging()) { + g.setColor(MaterialColors.bleach(slider.getForeground(), 0.5f)); + drawCircle(g, cx, cy, DRAG_THUMB_RADIUS); + } + + g.setColor(slider.getForeground()); + drawCircle(g, cx, cy, NORMAL_THUMB_RADIUS); - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + // need to redraw loaded part of progress line + Line loaded = getTrack(true); + g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + } + + @Override + public void paintTrack(Graphics g) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + + g.setColor(UIManager.getColor("Slider.trackColor")); + Line unloaded = getTrack(false); + g.drawLine(unloaded.x1, unloaded.y1, unloaded.x2, unloaded.y2); + + g.setColor(slider.getForeground()); + Line loaded = getTrack(true); + g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + } + + private Line getTrack(boolean loaded) { + if (slider.getOrientation() == JSlider.HORIZONTAL) { + Line left = + new Line( + trackRect.x, + thumbRect.y + thumbRect.height / 2, + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2); + Line right = + new Line( + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2, + trackRect.x + trackRect.width, + thumbRect.y + thumbRect.height / 2); + + if (loaded) { + return slider.getInverted() ? right : left; + } else { + return slider.getInverted() ? left : right; + } + } else { + Line top = + new Line( + thumbRect.x + thumbRect.width / 2, + trackRect.y, + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2); + Line bottom = + new Line( + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2, + thumbRect.x + thumbRect.width / 2, + trackRect.y + trackRect.height); + + if (loaded) { + return slider.getInverted() ? top : bottom; + } else { + return slider.getInverted() ? bottom : top; + } + } + } + + @Override + public void paintFocus(Graphics g) {} + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - private static class Line { + private static class Line { - int x1, y1, x2, y2; + int x1, y1, x2, y2; - Line(int x1, int y1, int x2, int y2) { - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; + Line(int x1, int y1, int x2, int y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java index 71428661a..ecfcbab17 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java @@ -15,68 +15,68 @@ public class MaterialSpinnerUI extends BasicSpinnerUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialSpinnerUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); + public static ComponentUI createUI(JComponent c) { + return new MaterialSpinnerUI(); + } - JSpinner spinner = (JSpinner) c; - spinner.setOpaque(false); - spinner.setFont(UIManager.getFont("Spinner.font")); - spinner.setBackground(UIManager.getColor("Spinner.background")); - spinner.setForeground(UIManager.getColor("Spinner.foreground")); - spinner.setBorder(UIManager.getBorder("Spinner.border")); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); - @Override - protected JComponent createEditor() { - JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) super.createEditor(); - editor.getTextField().setUI(new MaterialTextFieldUI(false)); + JSpinner spinner = (JSpinner) c; + spinner.setOpaque(false); + spinner.setFont(UIManager.getFont("Spinner.font")); + spinner.setBackground(UIManager.getColor("Spinner.background")); + spinner.setForeground(UIManager.getColor("Spinner.foreground")); + spinner.setBorder(UIManager.getBorder("Spinner.border")); + } - return editor; - } + @Override + protected JComponent createEditor() { + JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) super.createEditor(); + editor.getTextField().setUI(new MaterialTextFieldUI(false)); - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + return editor; + } - @Override - protected Component createNextButton() { - Icon icon = UIManager.getIcon("Spinner.nextButtonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.NORTH); + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); - installNextButtonListeners(button); - return button; - } + @Override + protected Component createNextButton() { + Icon icon = UIManager.getIcon("Spinner.nextButtonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.NORTH); + } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); + installNextButtonListeners(button); - @Override - protected Component createPreviousButton() { - Icon icon = UIManager.getIcon("Spinner.previousButtonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.SOUTH); + return button; } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); - installPreviousButtonListeners(button); - return button; - } + @Override + protected Component createPreviousButton() { + Icon icon = UIManager.getIcon("Spinner.previousButtonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.SOUTH); + } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); + installPreviousButtonListeners(button); + + return button; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java index c33ea201a..0ec5db987 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java @@ -4,20 +4,20 @@ import javax.swing.plaf.basic.BasicSplitPaneUI; public class MaterialSplitPaneDivider extends BasicSplitPaneDivider { - public MaterialSplitPaneDivider(BasicSplitPaneUI ui) { - super(ui); - // oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, - // "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); - // oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, - // "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); - // centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), - // ui, "SplitPane.centerOneTouchButtons", true); - // setLayout(new DividerLayout()); - // setBasicSplitPaneUI(ui); - // orientation = splitPane.getOrientation(); - // setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? - // Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : - // Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); - // setBackground(UIManager.getColor("SplitPane.background")); - } + public MaterialSplitPaneDivider(BasicSplitPaneUI ui) { + super(ui); + // oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, + // "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); + // oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, + // "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); + // centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), + // ui, "SplitPane.centerOneTouchButtons", true); + // setLayout(new DividerLayout()); + // setBasicSplitPaneUI(ui); + // orientation = splitPane.getOrientation(); + // setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? + // Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : + // Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); + // setBackground(UIManager.getColor("SplitPane.background")); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java index d95f3f766..33cee1316 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java @@ -4,24 +4,24 @@ import javax.swing.plaf.basic.BasicSplitPaneUI; public class MaterialSplitPaneUI extends BasicSplitPaneUI { - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JSplitPane splitPane = (JSplitPane) c; - splitPane.setOpaque(false); - splitPane.setBorder(UIManager.getBorder("SplitPane.border")); - splitPane.setBackground(UIManager.getColor("SplitPane.background")); - splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); - } + JSplitPane splitPane = (JSplitPane) c; + splitPane.setOpaque(false); + splitPane.setBorder(UIManager.getBorder("SplitPane.border")); + splitPane.setBackground(UIManager.getColor("SplitPane.background")); + splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); + } - // /** - // * Creates the default divider. - // * - // * @return the default divider - // */ - // @Override - // public BasicSplitPaneDivider createDefaultDivider() { - // return new MaterialSplitPaneDivider(this); - // } + // /** + // * Creates the default divider. + // * + // * @return the default divider + // */ + // @Override + // public BasicSplitPaneDivider createDefaultDivider() { + // return new MaterialSplitPaneDivider(this); + // } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java index bcc6d68f4..878ed8479 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java @@ -11,72 +11,86 @@ public class MaterialTabbedPaneUI extends BasicTabbedPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTabbedPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTabbedPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JTabbedPane tabbedPane = (JTabbedPane) c; - tabbedPane.setOpaque(false); - tabbedPane.setFont(UIManager.getFont("TabbedPane.font")); - tabbedPane.setBackground(UIManager.getColor("TabbedPane.background")); - tabbedPane.setForeground(UIManager.getColor("TabbedPane.foreground")); - tabbedPane.setBorder(UIManager.getBorder("TabbedPane.border")); + JTabbedPane tabbedPane = (JTabbedPane) c; + tabbedPane.setOpaque(false); + tabbedPane.setFont(UIManager.getFont("TabbedPane.font")); + tabbedPane.setBackground(UIManager.getColor("TabbedPane.background")); + tabbedPane.setForeground(UIManager.getColor("TabbedPane.foreground")); + tabbedPane.setBorder(UIManager.getBorder("TabbedPane.border")); - darkShadow = UIManager.getColor("TabbedPane.darkShadow"); - shadow = UIManager.getColor("TabbedPane.shadow"); - lightHighlight = UIManager.getColor("TabbedPane.highlight"); - } + darkShadow = UIManager.getColor("TabbedPane.darkShadow"); + shadow = UIManager.getColor("TabbedPane.shadow"); + lightHighlight = UIManager.getColor("TabbedPane.highlight"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintTabBackground( - Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { - g.setColor(isSelected ? lightHighlight : tabPane.getBackground()); - g.fillRect(x, y, w, h); - } + @Override + protected void paintTabBackground( + Graphics g, + int tabPlacement, + int tabIndex, + int x, + int y, + int w, + int h, + boolean isSelected) { + g.setColor(isSelected ? lightHighlight : tabPane.getBackground()); + g.fillRect(x, y, w, h); + } - @Override - protected void paintTabBorder( - Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { - g.setColor(UIManager.getColor("TabbedPane.borderHighlightColor")); - g.drawRect(x, y, w, h); - } + @Override + protected void paintTabBorder( + Graphics g, + int tabPlacement, + int tabIndex, + int x, + int y, + int w, + int h, + boolean isSelected) { + g.setColor(UIManager.getColor("TabbedPane.borderHighlightColor")); + g.drawRect(x, y, w, h); + } - @Override - protected void paintFocusIndicator( - Graphics g, - int tabPlacement, - Rectangle[] rects, - int tabIndex, - Rectangle iconRect, - Rectangle textRect, - boolean isSelected) { - // do nothing - } + @Override + protected void paintFocusIndicator( + Graphics g, + int tabPlacement, + Rectangle[] rects, + int tabIndex, + Rectangle iconRect, + Rectangle textRect, + boolean isSelected) { + // do nothing + } - @Override - protected void paintTab( - Graphics g, - int tabPlacement, - Rectangle[] rects, - int tabIndex, - Rectangle iconRect, - Rectangle textRect) { - // for some reason tabs aren't painted properly by paint() - super.paintTab( - MaterialDrawingUtils.getAliasedGraphics(g), - tabPlacement, - rects, - tabIndex, - iconRect, - textRect); - } + @Override + protected void paintTab( + Graphics g, + int tabPlacement, + Rectangle[] rects, + int tabIndex, + Rectangle iconRect, + Rectangle textRect) { + // for some reason tabs aren't painted properly by paint() + super.paintTab( + MaterialDrawingUtils.getAliasedGraphics(g), + tabPlacement, + rects, + tabIndex, + iconRect, + textRect); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java index 3f8cdc80b..b4e07e95f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java @@ -7,25 +7,26 @@ public class MaterialTableCellEditor extends DefaultCellEditor { - public MaterialTableCellEditor() { - super(init()); - } + public MaterialTableCellEditor() { + super(init()); + } - private static JTextField init() { - JTextField textField = new JTextField(); - textField.setUI(new MaterialTextFieldUI(false)); + private static JTextField init() { + JTextField textField = new JTextField(); + textField.setUI(new MaterialTextFieldUI(false)); - return textField; - } + return textField; + } - @Override - public Component getTableCellEditorComponent( - JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { - JTextField textField = - (JTextField) - super.getTableCellEditorComponent(table, value, isSelected, rowIndex, vColIndex); - textField.setText(value.toString()); + @Override + public Component getTableCellEditorComponent( + JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { + JTextField textField = + (JTextField) + super.getTableCellEditorComponent( + table, value, isSelected, rowIndex, vColIndex); + textField.setText(value.toString()); - return textField; - } + return textField; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java index 2dd33246a..8fe0438e8 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java @@ -9,19 +9,20 @@ public class MaterialTableCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent( - JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - JComponent component = - (JComponent) - super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JComponent component = + (JComponent) + super.getTableCellRendererComponent( + table, value, isSelected, hasFocus, row, column); - // hides yellow selection highlight - component.setBorder(BorderFactory.createEmptyBorder()); + // hides yellow selection highlight + component.setBorder(BorderFactory.createEmptyBorder()); - this.setHorizontalAlignment(SwingConstants.CENTER); - this.setVerticalAlignment(SwingConstants.CENTER); + this.setHorizontalAlignment(SwingConstants.CENTER); + this.setVerticalAlignment(SwingConstants.CENTER); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java index 458b8062a..01f4db191 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java @@ -9,19 +9,20 @@ public class MaterialTableHeaderCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent( - JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - JComponent component = - (JComponent) - super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - component.setBorder(UIManager.getBorder("TableHeader.cellBorder")); - component.setFont(UIManager.getFont("TableHeader.font")); - component.setBackground(UIManager.getColor("TableHeader.background")); + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JComponent component = + (JComponent) + super.getTableCellRendererComponent( + table, value, isSelected, hasFocus, row, column); + component.setBorder(UIManager.getBorder("TableHeader.cellBorder")); + component.setFont(UIManager.getFont("TableHeader.font")); + component.setBackground(UIManager.getColor("TableHeader.background")); - this.setHorizontalAlignment(SwingConstants.CENTER); - this.setVerticalAlignment(SwingConstants.CENTER); + this.setHorizontalAlignment(SwingConstants.CENTER); + this.setVerticalAlignment(SwingConstants.CENTER); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java index e039aba97..7a1eadb92 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java @@ -9,20 +9,20 @@ public class MaterialTableHeaderUI extends BasicTableHeaderUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTableHeaderUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTableHeaderUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JTableHeader header = (JTableHeader) c; - header.setDefaultRenderer(new MaterialTableHeaderCellRenderer()); - } + JTableHeader header = (JTableHeader) c; + header.setDefaultRenderer(new MaterialTableHeaderCellRenderer()); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java index af3d7fbc5..91c68c973 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java @@ -10,37 +10,37 @@ public class MaterialTableUI extends BasicTableUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTableUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTable table = (JTable) c; - table.setOpaque(false); - table.setSelectionForeground(UIManager.getColor("Table.selectionForeground")); - table.setBackground(UIManager.getColor("Table.background")); - table.setFont(UIManager.getFont("Table.font")); - table.setBorder(UIManager.getBorder("Table.border")); - table.setGridColor(UIManager.getColor("Table.gridColor")); - table.setSelectionBackground(UIManager.getColor("Table.selectionBackground")); - - table.getTableHeader().setResizingAllowed(true); - int rowHeight = UIManager.getInt("Table.rowHeight"); - if (rowHeight > 0) { - table.setRowHeight(rowHeight); - } else { - table.setRowHeight(table.getRowHeight() + 25); + public static ComponentUI createUI(JComponent c) { + return new MaterialTableUI(); } - table.setDefaultRenderer(Object.class, new MaterialTableCellRenderer()); - table.setDefaultEditor(Object.class, new MaterialTableCellEditor()); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTable table = (JTable) c; + table.setOpaque(false); + table.setSelectionForeground(UIManager.getColor("Table.selectionForeground")); + table.setBackground(UIManager.getColor("Table.background")); + table.setFont(UIManager.getFont("Table.font")); + table.setBorder(UIManager.getBorder("Table.border")); + table.setGridColor(UIManager.getColor("Table.gridColor")); + table.setSelectionBackground(UIManager.getColor("Table.selectionBackground")); + + table.getTableHeader().setResizingAllowed(true); + int rowHeight = UIManager.getInt("Table.rowHeight"); + if (rowHeight > 0) { + table.setRowHeight(rowHeight); + } else { + table.setRowHeight(table.getRowHeight() + 25); + } + + table.setDefaultRenderer(Object.class, new MaterialTableCellRenderer()); + table.setDefaultEditor(Object.class, new MaterialTableCellEditor()); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java index 002d3a0be..5cfd2fc88 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java @@ -22,188 +22,196 @@ import javax.swing.plaf.basic.BasicTextFieldUI; public class MaterialTextFieldUI extends BasicTextFieldUI - implements FocusListener, PropertyChangeListener { - - private Color focusedBackground; - private Color unfocusedBackground; - private Color focusedSelectionBackground; - private Color unfocusedSelectionBackground; - private boolean drawLine; - - public MaterialTextFieldUI() { - this(true); - } - - public MaterialTextFieldUI(boolean drawLine) { - super(); - this.drawLine = drawLine; - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialTextFieldUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTextField textField = (JTextField) c; - textField.setOpaque(false); - textField.setBorder( - drawLine - ? BorderFactory.createEmptyBorder(5, 2, 10, 0) - : BorderFactory.createEmptyBorder(2, 2, 2, 2)); - - textField.setBackground(MaterialColors.LIGHT_BLUE_400); - textField.setFont(MaterialFonts.REGULAR); - - this.focusedBackground = textField.getBackground(); - this.unfocusedBackground = MaterialColors.GRAY_200; - - this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); - this.unfocusedSelectionBackground = unfocusedBackground; - } - - @Override - protected void installListeners() { - super.installListeners(); - getComponent().addFocusListener(this); - getComponent().addPropertyChangeListener(this); - } - - @Override - protected void installKeyboardActions() { - super.installKeyboardActions(); - - Action selectAll = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().selectAll(); - } - }; - - Action delete = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (getComponent().getSelectedText() == null) { - int pos = getComponent().getCaretPosition() - 1; - - if (pos >= 0) { - getComponent().select(pos, pos + 1); - getComponent().replaceSelection(""); - } - } else { - getComponent().replaceSelection(""); - } - } - }; - - Action left = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); - } - }; - - Action right = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent() - .setCaretPosition( - Math.min( - getComponent().getText().length(), getComponent().getCaretPosition() + 1)); - } - }; - - Action enter = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - ((JTextField) getComponent()).postActionEvent(); - } - }; - - // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to getMenuShortcutKeyMaskEx() - getComponent() - .getInputMap() - .put( - KeyStroke.getKeyStroke( - KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "selectAll"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); - - getComponent().getActionMap().put("selectAll", selectAll); - getComponent().getActionMap().put("delete", delete); - getComponent().getActionMap().put("left", left); - getComponent().getActionMap().put("right", right); - getComponent().getActionMap().put("enter", enter); - } - - @Override - public void paintSafely(Graphics g) { - JTextField c = (JTextField) getComponent(); - g = MaterialDrawingUtils.getAliasedGraphics(g); - - Color lineColor; - - if (getComponent().hasFocus()) { - lineColor = focusedBackground; - c.setSelectionColor(focusedSelectionBackground); - } else { - lineColor = unfocusedBackground; - c.setSelectionColor(unfocusedSelectionBackground); + implements FocusListener, PropertyChangeListener { + + private Color focusedBackground; + private Color unfocusedBackground; + private Color focusedSelectionBackground; + private Color unfocusedSelectionBackground; + private boolean drawLine; + + public MaterialTextFieldUI() { + this(true); + } + + public MaterialTextFieldUI(boolean drawLine) { + super(); + this.drawLine = drawLine; + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialTextFieldUI(); } - g.setColor(lineColor); - getComponent().setBackground(lineColor); + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTextField textField = (JTextField) c; + textField.setOpaque(false); + textField.setBorder( + drawLine + ? BorderFactory.createEmptyBorder(5, 2, 10, 0) + : BorderFactory.createEmptyBorder(2, 2, 2, 2)); + + textField.setBackground(MaterialColors.LIGHT_BLUE_400); + textField.setFont(MaterialFonts.REGULAR); + + this.focusedBackground = textField.getBackground(); + this.unfocusedBackground = MaterialColors.GRAY_200; + + this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); + this.unfocusedSelectionBackground = unfocusedBackground; + } - if (drawLine) { - int x = getComponent().getInsets().left; - int y = getComponent().getInsets().top; - int w = - getComponent().getWidth() - - getComponent().getInsets().left - - getComponent().getInsets().right; + @Override + protected void installListeners() { + super.installListeners(); + getComponent().addFocusListener(this); + getComponent().addPropertyChangeListener(this); + } - g.fillRect(x, c.getHeight() - y, w, 2); + @Override + protected void installKeyboardActions() { + super.installKeyboardActions(); + + Action selectAll = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().selectAll(); + } + }; + + Action delete = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (getComponent().getSelectedText() == null) { + int pos = getComponent().getCaretPosition() - 1; + + if (pos >= 0) { + getComponent().select(pos, pos + 1); + getComponent().replaceSelection(""); + } + } else { + getComponent().replaceSelection(""); + } + } + }; + + Action left = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.max(0, getComponent().getCaretPosition() - 1)); + } + }; + + Action right = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.min( + getComponent().getText().length(), + getComponent().getCaretPosition() + 1)); + } + }; + + Action enter = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + ((JTextField) getComponent()).postActionEvent(); + } + }; + + // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to + // getMenuShortcutKeyMaskEx() + getComponent() + .getInputMap() + .put( + KeyStroke.getKeyStroke( + KeyEvent.VK_A, + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "selectAll"); + getComponent() + .getInputMap() + .put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); + + getComponent().getActionMap().put("selectAll", selectAll); + getComponent().getActionMap().put("delete", delete); + getComponent().getActionMap().put("left", left); + getComponent().getActionMap().put("right", right); + getComponent().getActionMap().put("enter", enter); } - super.paintSafely(g); - } + @Override + public void paintSafely(Graphics g) { + JTextField c = (JTextField) getComponent(); + g = MaterialDrawingUtils.getAliasedGraphics(g); + + Color lineColor; + + if (getComponent().hasFocus()) { + lineColor = focusedBackground; + c.setSelectionColor(focusedSelectionBackground); + } else { + lineColor = unfocusedBackground; + c.setSelectionColor(unfocusedSelectionBackground); + } + + g.setColor(lineColor); + getComponent().setBackground(lineColor); + + if (drawLine) { + int x = getComponent().getInsets().left; + int y = getComponent().getInsets().top; + int w = + getComponent().getWidth() + - getComponent().getInsets().left + - getComponent().getInsets().right; + + g.fillRect(x, c.getHeight() - y, w, 2); + } - @Override - public void paintBackground(final Graphics g) { - super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); - } + super.paintSafely(g); + } + + @Override + public void paintBackground(final Graphics g) { + super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); + } - @Override - public void focusGained(FocusEvent e) { - e.getComponent().setBackground(focusedBackground); - } + @Override + public void focusGained(FocusEvent e) { + e.getComponent().setBackground(focusedBackground); + } - @Override - public void focusLost(FocusEvent e) { - e.getComponent().setBackground(unfocusedBackground); - } + @Override + public void focusLost(FocusEvent e) { + e.getComponent().setBackground(unfocusedBackground); + } - @Override - public void propertyChange(PropertyChangeEvent pce) { - super.propertyChange(pce); + @Override + public void propertyChange(PropertyChangeEvent pce) { + super.propertyChange(pce); - if (pce.getPropertyName().equals("background")) { - Color newColor = (Color) pce.getNewValue(); + if (pce.getPropertyName().equals("background")) { + Color newColor = (Color) pce.getNewValue(); - if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { - this.focusedBackground = (Color) pce.getNewValue(); - this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); - } + if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { + this.focusedBackground = (Color) pce.getNewValue(); + this.focusedSelectionBackground = + MaterialColors.bleach(this.focusedBackground, 0.3f); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java index 61fba8d33..f70048468 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java @@ -9,12 +9,12 @@ */ public class MaterialTextPaneUI extends BasicTextPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTextPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTextPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java index 42786abba..3749366e9 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java @@ -10,28 +10,28 @@ public class MaterialToggleButtonUI extends BasicToggleButtonUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToggleButtonUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToggleButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JToggleButton toggleButton = (JToggleButton) c; - toggleButton.setBorder(UIManager.getBorder("ToggleButton.border")); - toggleButton.setFont(UIManager.getFont("ToggleButton.font")); - toggleButton.setBackground(UIManager.getColor("ToggleButton.background")); - toggleButton.setForeground(UIManager.getColor("ToggleButton.foreground")); + JToggleButton toggleButton = (JToggleButton) c; + toggleButton.setBorder(UIManager.getBorder("ToggleButton.border")); + toggleButton.setFont(UIManager.getFont("ToggleButton.font")); + toggleButton.setBackground(UIManager.getColor("ToggleButton.background")); + toggleButton.setForeground(UIManager.getColor("ToggleButton.foreground")); - if (toggleButton.getIcon() == null && toggleButton.getSelectedIcon() == null) { - toggleButton.setIcon(UIManager.getIcon("ToggleButton.icon")); - toggleButton.setSelectedIcon(UIManager.getIcon("ToggleButton.selectedIcon")); + if (toggleButton.getIcon() == null && toggleButton.getSelectedIcon() == null) { + toggleButton.setIcon(UIManager.getIcon("ToggleButton.icon")); + toggleButton.setSelectedIcon(UIManager.getIcon("ToggleButton.selectedIcon")); + } } - } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java index 58a752c59..10251eb73 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java @@ -10,28 +10,28 @@ public class MaterialToolBarUI extends BasicToolBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToolBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToolBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - JToolBar toolBar = (JToolBar) c; + @Override + public void installUI(JComponent c) { + super.installUI(c); + JToolBar toolBar = (JToolBar) c; - toolBar.setFont(UIManager.getFont("ToolBar.font")); - toolBar.setBackground(UIManager.getColor("ToolBar.background")); - toolBar.setForeground(UIManager.getColor("ToolBar.foreground")); - toolBar.setBorder(UIManager.getBorder("ToolBar.border")); + toolBar.setFont(UIManager.getFont("ToolBar.font")); + toolBar.setBackground(UIManager.getColor("ToolBar.background")); + toolBar.setForeground(UIManager.getColor("ToolBar.foreground")); + toolBar.setBorder(UIManager.getBorder("ToolBar.border")); - this.dockingBorderColor = null; - this.floatingBorderColor = null; - this.dockingColor = UIManager.getColor("ToolBar.dockingBackground"); - this.floatingColor = UIManager.getColor("ToolBar.floatingBackground"); - } + this.dockingBorderColor = null; + this.floatingBorderColor = null; + this.dockingColor = UIManager.getColor("ToolBar.dockingBackground"); + this.floatingColor = UIManager.getColor("ToolBar.floatingBackground"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java index 2b023c920..87e415e4c 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java @@ -8,17 +8,17 @@ public class MaterialToolTipUI extends BasicToolTipUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToolTipUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToolTipUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java index 6565ca731..ee9b0fcff 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java @@ -11,43 +11,43 @@ public class MaterialTreeCellEditor extends DefaultTreeCellEditor { - private JTextField textField; - - public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { - super(tree, renderer); - init(); - } - - public MaterialTreeCellEditor( - JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { - super(tree, renderer, editor); - init(); - } - - private void init() { - textField = new JTextField(); - textField.setUI(new MaterialTextFieldUI()); - - textField.addKeyListener( - new KeyAdapter() { - @Override - public void keyTyped(KeyEvent e) { - if (e.getKeyChar() == KeyEvent.VK_ENTER) { - stopCellEditing(); - } - } - }); - } - - @Override - public Component getTreeCellEditorComponent( - JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { - textField.setText(value.toString()); - return textField; - } - - @Override - public Object getCellEditorValue() { - return textField.getText(); - } + private JTextField textField; + + public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { + super(tree, renderer); + init(); + } + + public MaterialTreeCellEditor( + JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { + super(tree, renderer, editor); + init(); + } + + private void init() { + textField = new JTextField(); + textField.setUI(new MaterialTextFieldUI()); + + textField.addKeyListener( + new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + if (e.getKeyChar() == KeyEvent.VK_ENTER) { + stopCellEditing(); + } + } + }); + } + + @Override + public Component getTreeCellEditorComponent( + JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { + textField.setText(value.toString()); + return textField; + } + + @Override + public Object getCellEditorValue() { + return textField.getText(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java index f4e85bba2..6ac5acabb 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java @@ -9,37 +9,37 @@ public class MaterialTreeCellRenderer extends DefaultTreeCellRenderer { - public MaterialTreeCellRenderer() { - setTextSelectionColor(UIManager.getColor("Tree.selectionForeground")); - setTextNonSelectionColor(UIManager.getColor("Tree.foreground")); - - setBackgroundSelectionColor(UIManager.getColor("Tree.selectionBackground")); - setBackgroundNonSelectionColor(UIManager.getColor("Tree.background")); - - setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor")); - - setClosedIcon(UIManager.getIcon("Tree.closedIcon")); - setOpenIcon(UIManager.getIcon("Tree.openIcon")); - setLeafIcon(null); - - setFont(UIManager.getFont("Tree.font")); - } - - @Override - public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean isSelected, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { - JComponent component = - (JComponent) - super.getTreeCellRendererComponent( - tree, value, isSelected, expanded, leaf, row, hasFocus); - component.setBorder(BorderFactory.createEmptyBorder(5, 2, 5, 2)); - - return component; - } + public MaterialTreeCellRenderer() { + setTextSelectionColor(UIManager.getColor("Tree.selectionForeground")); + setTextNonSelectionColor(UIManager.getColor("Tree.foreground")); + + setBackgroundSelectionColor(UIManager.getColor("Tree.selectionBackground")); + setBackgroundNonSelectionColor(UIManager.getColor("Tree.background")); + + setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor")); + + setClosedIcon(UIManager.getIcon("Tree.closedIcon")); + setOpenIcon(UIManager.getIcon("Tree.openIcon")); + setLeafIcon(null); + + setFont(UIManager.getFont("Tree.font")); + } + + @Override + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean isSelected, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + JComponent component = + (JComponent) + super.getTreeCellRendererComponent( + tree, value, isSelected, expanded, leaf, row, hasFocus); + component.setBorder(BorderFactory.createEmptyBorder(5, 2, 5, 2)); + + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java index f21b0dfaa..7d38c62f3 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java @@ -12,33 +12,33 @@ public class MaterialTreeUI extends BasicTreeUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTreeUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - JTree tree = (JTree) c; - - DefaultTreeCellRenderer renderer = new MaterialTreeCellRenderer(); - TreeCellEditor editor = new MaterialTreeCellEditor(tree, renderer); - - tree.setCellRenderer(renderer); - tree.setCellEditor(editor); - - tree.setFont(UIManager.getFont("Tree.font")); - tree.setRowHeight(0); - tree.setInvokesStopCellEditing(true); - - MaterialTreeUI ui = (MaterialTreeUI) tree.getUI(); - ui.setLeftChildIndent(10); - ui.setRightChildIndent(10); - } - - @Override - public void paint(Graphics g, JComponent c) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - super.paint(g, c); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTreeUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + JTree tree = (JTree) c; + + DefaultTreeCellRenderer renderer = new MaterialTreeCellRenderer(); + TreeCellEditor editor = new MaterialTreeCellEditor(tree, renderer); + + tree.setCellRenderer(renderer); + tree.setCellEditor(editor); + + tree.setFont(UIManager.getFont("Tree.font")); + tree.setRowHeight(0); + tree.setInvokesStopCellEditing(true); + + MaterialTreeUI ui = (MaterialTreeUI) tree.getUI(); + ui.setLeftChildIndent(10); + ui.setRightChildIndent(10); + } + + @Override + public void paint(Graphics g, JComponent c) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + super.paint(g, c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java index 61eb3c433..ce3244d4d 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java @@ -29,389 +29,410 @@ */ public class DropShadowBorder extends AbstractBorder implements Border { - private static final Map> CACHE = - new HashMap>(); - private Color lineColor; - private int lineWidth; - private int shadowSize; - private float shadowOpacity; - private int cornerSize; - private boolean showTopShadow; - private boolean showLeftShadow; - private boolean showBottomShadow; - private boolean showRightShadow; - - public DropShadowBorder() { - this(UIManager.getColor("Control"), 1, 5); - } - - public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) { - this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true); - } - - public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) { - this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true); - } - - public DropShadowBorder( - Color lineColor, - int lineWidth, - int shadowSize, - float shadowOpacity, - int cornerSize, - boolean showTopShadow, - boolean showLeftShadow, - boolean showBottomShadow, - boolean showRightShadow) { - this.lineColor = lineColor; - this.lineWidth = lineWidth; - this.shadowSize = shadowSize; - this.shadowOpacity = shadowOpacity; - this.cornerSize = cornerSize; - this.showTopShadow = showTopShadow; - this.showLeftShadow = showLeftShadow; - this.showBottomShadow = showBottomShadow; - this.showRightShadow = showRightShadow; - } - - /** */ - public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { - /* - * 1) Get images for this border - * 2) Paint the images for each side of the border that should be painted - */ - Map images = getImages(null); - - // compute the edges of the components -- not including the border - // Insets borderInsets = getBorderInsets (c); - // int leftEdge = x + borderInsets.left - lineWidth; - // int rightEdge = x + width - borderInsets.right; - // int topEdge = y + borderInsets.top - lineWidth; - // int bottomEdge = y + height - borderInsets.bottom; - Graphics2D g2 = (Graphics2D) graphics; - g2.setColor(lineColor); - - // The location and size of the shadows depends on which shadows are being - // drawn. For instance, if the left & bottom shadows are being drawn, then - // the left shadows extends all the way down to the corner, a corner is drawn, - // and then the bottom shadows begins at the corner. If, however, only the - // bottom shadows is drawn, then the bottom-left corner is drawn to the - // right of the corner, and the bottom shadows is somewhat shorter than before. - - Point topLeftShadowPoint = null; - if (showLeftShadow || showTopShadow) { - topLeftShadowPoint = new Point(); - if (showLeftShadow && !showTopShadow) { - topLeftShadowPoint.setLocation(x, y + shadowSize); - } else { - if (showLeftShadow && showTopShadow) { - topLeftShadowPoint.setLocation(x, y); - } else { - if (!showLeftShadow && showTopShadow) { - topLeftShadowPoint.setLocation(x + shadowSize, y); - } - } - } + private static final Map> CACHE = + new HashMap>(); + private Color lineColor; + private int lineWidth; + private int shadowSize; + private float shadowOpacity; + private int cornerSize; + private boolean showTopShadow; + private boolean showLeftShadow; + private boolean showBottomShadow; + private boolean showRightShadow; + + public DropShadowBorder() { + this(UIManager.getColor("Control"), 1, 5); } - Point bottomLeftShadowPoint = null; - if (showLeftShadow || showBottomShadow) { - bottomLeftShadowPoint = new Point(); - if (showLeftShadow && !showBottomShadow) { - bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); - } else { - if (showLeftShadow && showBottomShadow) { - bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); - } else { - if (!showLeftShadow && showBottomShadow) { - bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); - } - } - } + public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) { + this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true); } - Point bottomRightShadowPoint = null; - if (showRightShadow || showBottomShadow) { - bottomRightShadowPoint = new Point(); - if (showRightShadow && !showBottomShadow) { - bottomRightShadowPoint.setLocation( - x + width - shadowSize, y + height - shadowSize - shadowSize); - } else { - if (showRightShadow && showBottomShadow) { - bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); - } else { - if (!showRightShadow && showBottomShadow) { - bottomRightShadowPoint.setLocation( - x + width - shadowSize - shadowSize, y + height - shadowSize); - } + public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) { + this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true); + } + + public DropShadowBorder( + Color lineColor, + int lineWidth, + int shadowSize, + float shadowOpacity, + int cornerSize, + boolean showTopShadow, + boolean showLeftShadow, + boolean showBottomShadow, + boolean showRightShadow) { + this.lineColor = lineColor; + this.lineWidth = lineWidth; + this.shadowSize = shadowSize; + this.shadowOpacity = shadowOpacity; + this.cornerSize = cornerSize; + this.showTopShadow = showTopShadow; + this.showLeftShadow = showLeftShadow; + this.showBottomShadow = showBottomShadow; + this.showRightShadow = showRightShadow; + } + + /** */ + public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { + /* + * 1) Get images for this border + * 2) Paint the images for each side of the border that should be painted + */ + Map images = getImages(null); + + // compute the edges of the components -- not including the border + // Insets borderInsets = getBorderInsets (c); + // int leftEdge = x + borderInsets.left - lineWidth; + // int rightEdge = x + width - borderInsets.right; + // int topEdge = y + borderInsets.top - lineWidth; + // int bottomEdge = y + height - borderInsets.bottom; + Graphics2D g2 = (Graphics2D) graphics; + g2.setColor(lineColor); + + // The location and size of the shadows depends on which shadows are being + // drawn. For instance, if the left & bottom shadows are being drawn, then + // the left shadows extends all the way down to the corner, a corner is drawn, + // and then the bottom shadows begins at the corner. If, however, only the + // bottom shadows is drawn, then the bottom-left corner is drawn to the + // right of the corner, and the bottom shadows is somewhat shorter than before. + + Point topLeftShadowPoint = null; + if (showLeftShadow || showTopShadow) { + topLeftShadowPoint = new Point(); + if (showLeftShadow && !showTopShadow) { + topLeftShadowPoint.setLocation(x, y + shadowSize); + } else { + if (showLeftShadow && showTopShadow) { + topLeftShadowPoint.setLocation(x, y); + } else { + if (!showLeftShadow && showTopShadow) { + topLeftShadowPoint.setLocation(x + shadowSize, y); + } + } + } + } + + Point bottomLeftShadowPoint = null; + if (showLeftShadow || showBottomShadow) { + bottomLeftShadowPoint = new Point(); + if (showLeftShadow && !showBottomShadow) { + bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); + } else { + if (showLeftShadow && showBottomShadow) { + bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); + } else { + if (!showLeftShadow && showBottomShadow) { + bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); + } + } + } + } + + Point bottomRightShadowPoint = null; + if (showRightShadow || showBottomShadow) { + bottomRightShadowPoint = new Point(); + if (showRightShadow && !showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize, y + height - shadowSize - shadowSize); + } else { + if (showRightShadow && showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize, y + height - shadowSize); + } else { + if (!showRightShadow && showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize - shadowSize, y + height - shadowSize); + } + } + } + } + + Point topRightShadowPoint = null; + if (showRightShadow || showTopShadow) { + topRightShadowPoint = new Point(); + if (showRightShadow && !showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize); + } else { + if (showRightShadow && showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize, y); + } else { + if (!showRightShadow && showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); + } + } + } + } + + if (showLeftShadow) { + Rectangle leftShadowRect = + new Rectangle( + x, + (int) (topLeftShadowPoint.getY() + shadowSize), + shadowSize, + (int) + (bottomLeftShadowPoint.getY() + - topLeftShadowPoint.getY() + - shadowSize)); + g2.drawImage( + images.get(Position.LEFT) + .getScaledInstance( + leftShadowRect.width, leftShadowRect.height, Image.SCALE_FAST), + leftShadowRect.x, + leftShadowRect.y, + null); + } + + if (showBottomShadow) { + Rectangle bottomShadowRect = + new Rectangle( + (int) (bottomLeftShadowPoint.getX() + shadowSize), + y + height - shadowSize, + (int) + (bottomRightShadowPoint.getX() + - bottomLeftShadowPoint.getX() + - shadowSize), + shadowSize); + g2.drawImage( + images.get(Position.BOTTOM) + .getScaledInstance( + bottomShadowRect.width, + bottomShadowRect.height, + Image.SCALE_FAST), + bottomShadowRect.x, + bottomShadowRect.y, + null); + } + + if (showRightShadow) { + Rectangle rightShadowRect = + new Rectangle( + x + width - shadowSize, + (int) (topRightShadowPoint.getY() + shadowSize), + shadowSize, + (int) + (bottomRightShadowPoint.getY() + - topRightShadowPoint.getY() + - shadowSize)); + g2.drawImage( + images.get(Position.RIGHT) + .getScaledInstance( + rightShadowRect.width, + rightShadowRect.height, + Image.SCALE_FAST), + rightShadowRect.x, + rightShadowRect.y, + null); + } + + if (showTopShadow) { + Rectangle topShadowRect = + new Rectangle( + (int) topLeftShadowPoint.getX() + shadowSize, + y, + (int) + (topRightShadowPoint.getX() + - topLeftShadowPoint.getX() + - shadowSize), + shadowSize); + g2.drawImage( + images.get(Position.TOP) + .getScaledInstance( + topShadowRect.width, topShadowRect.height, Image.SCALE_FAST), + topShadowRect.x, + topShadowRect.y, + null); + } + + if (showLeftShadow || showTopShadow) { + g2.drawImage( + images.get(Position.TOP_LEFT), + null, + (int) topLeftShadowPoint.getX(), + (int) topLeftShadowPoint.getY()); + } + if (showLeftShadow || showBottomShadow) { + g2.drawImage( + images.get(Position.BOTTOM_LEFT), + null, + (int) bottomLeftShadowPoint.getX(), + (int) bottomLeftShadowPoint.getY()); + } + if (showRightShadow || showBottomShadow) { + g2.drawImage( + images.get(Position.BOTTOM_RIGHT), + null, + (int) bottomRightShadowPoint.getX(), + (int) bottomRightShadowPoint.getY()); + } + if (showRightShadow || showTopShadow) { + g2.drawImage( + images.get(Position.TOP_RIGHT), + null, + (int) topRightShadowPoint.getX(), + (int) topRightShadowPoint.getY()); } - } } - Point topRightShadowPoint = null; - if (showRightShadow || showTopShadow) { - topRightShadowPoint = new Point(); - if (showRightShadow && !showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize); - } else { - if (showRightShadow && showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize, y); - } else { - if (!showRightShadow && showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); - } + private Map getImages(Graphics2D g2) { + // first, check to see if an image for this size has already been rendered + // if so, use the cache. Else, draw and save + Map images = CACHE.get(shadowSize); + if (images == null) { + images = new HashMap(); + + /* + * Do draw a drop shadows, I have to: + * 1) Create a rounded rectangle + * 2) Create a BufferedImage to draw the rounded rect in + * 3) Translate the graphics for the image, so that the rectangle + * is centered in the drawn space. The border around the rectangle + * needs to be shadowWidth wide, so that there is space for the + * shadows to be drawn. + * 4) Draw the rounded rect as black, with an opacity of 50% + * 5) Create the BLUR_KERNEL + * 6) Blur the image + * 7) copy off the corners, sides, etc into images to be used for + * drawing the Border + */ + int rectWidth = cornerSize + 1; + RoundRectangle2D rect = + new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); + int imageWidth = rectWidth + shadowSize * 2; + BufferedImage image = + new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); + Graphics2D buffer = (Graphics2D) image.getGraphics(); + buffer.setRenderingHint( + RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + buffer.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + buffer.setRenderingHint( + RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + buffer.setRenderingHint( + RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_ON); + buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); + buffer.translate(shadowSize, shadowSize); + buffer.fill(rect); + float blurry = 1.0f / (float) (shadowSize * shadowSize); // 1.0f / (float)(shadowSize * + // shadowSize); + float[] blurKernel = new float[shadowSize * shadowSize]; + for (int i = 0; i < blurKernel.length; i++) { + blurKernel[i] = blurry; + } + ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); + BufferedImage targetImage = + new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); + ((Graphics2D) targetImage.getGraphics()) + .drawImage(image, blur, -(shadowSize / 2), -(shadowSize / 2)); + + int x = 1; + int y = 1; + int w = shadowSize; + int h = shadowSize; + images.put(Position.TOP_LEFT, targetImage.getSubimage(x, y, w, h)); + x = 1; + y = h; + w = shadowSize; + h = 1; + images.put(Position.LEFT, targetImage.getSubimage(x, y, w, h)); + x = 1; + y = rectWidth; + w = shadowSize; + h = shadowSize; + images.put(Position.BOTTOM_LEFT, targetImage.getSubimage(x, y, w, h)); + x = cornerSize + 1; + y = rectWidth; + w = 1; + h = shadowSize; + images.put(Position.BOTTOM, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = x; + w = shadowSize; + h = shadowSize; + images.put(Position.BOTTOM_RIGHT, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = cornerSize + 1; + w = shadowSize; + h = 1; + images.put(Position.RIGHT, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = 1; + w = shadowSize; + h = shadowSize; + images.put(Position.TOP_RIGHT, targetImage.getSubimage(x, y, w, h)); + x = shadowSize; + y = 1; + w = 1; + h = shadowSize; + images.put(Position.TOP, targetImage.getSubimage(x, y, w, h)); + + buffer.dispose(); + image.flush(); } - } + return images; + } + + /** */ + public Insets getBorderInsets(Component c) { + int top = 4 + (showTopShadow ? lineWidth + shadowSize : lineWidth); + int left = 4 + (showLeftShadow ? lineWidth + shadowSize : lineWidth); + int bottom = 4 + (showBottomShadow ? lineWidth + shadowSize : lineWidth); + int right = 4 + (showRightShadow ? lineWidth + shadowSize : lineWidth); + + return new Insets(top, left, bottom, right); } - if (showLeftShadow) { - Rectangle leftShadowRect = - new Rectangle( - x, - (int) (topLeftShadowPoint.getY() + shadowSize), - shadowSize, - (int) (bottomLeftShadowPoint.getY() - topLeftShadowPoint.getY() - shadowSize)); - g2.drawImage( - images - .get(Position.LEFT) - .getScaledInstance(leftShadowRect.width, leftShadowRect.height, Image.SCALE_FAST), - leftShadowRect.x, - leftShadowRect.y, - null); + /** */ + public boolean isBorderOpaque() { + return true; } - if (showBottomShadow) { - Rectangle bottomShadowRect = - new Rectangle( - (int) (bottomLeftShadowPoint.getX() + shadowSize), - y + height - shadowSize, - (int) (bottomRightShadowPoint.getX() - bottomLeftShadowPoint.getX() - shadowSize), - shadowSize); - g2.drawImage( - images - .get(Position.BOTTOM) - .getScaledInstance(bottomShadowRect.width, bottomShadowRect.height, Image.SCALE_FAST), - bottomShadowRect.x, - bottomShadowRect.y, - null); + public boolean isShowTopShadow() { + return showTopShadow; } - if (showRightShadow) { - Rectangle rightShadowRect = - new Rectangle( - x + width - shadowSize, - (int) (topRightShadowPoint.getY() + shadowSize), - shadowSize, - (int) (bottomRightShadowPoint.getY() - topRightShadowPoint.getY() - shadowSize)); - g2.drawImage( - images - .get(Position.RIGHT) - .getScaledInstance(rightShadowRect.width, rightShadowRect.height, Image.SCALE_FAST), - rightShadowRect.x, - rightShadowRect.y, - null); + public boolean isShowLeftShadow() { + return showLeftShadow; } - if (showTopShadow) { - Rectangle topShadowRect = - new Rectangle( - (int) topLeftShadowPoint.getX() + shadowSize, - y, - (int) (topRightShadowPoint.getX() - topLeftShadowPoint.getX() - shadowSize), - shadowSize); - g2.drawImage( - images - .get(Position.TOP) - .getScaledInstance(topShadowRect.width, topShadowRect.height, Image.SCALE_FAST), - topShadowRect.x, - topShadowRect.y, - null); + public boolean isShowRightShadow() { + return showRightShadow; } - if (showLeftShadow || showTopShadow) { - g2.drawImage( - images.get(Position.TOP_LEFT), - null, - (int) topLeftShadowPoint.getX(), - (int) topLeftShadowPoint.getY()); + public boolean isShowBottomShadow() { + return showBottomShadow; } - if (showLeftShadow || showBottomShadow) { - g2.drawImage( - images.get(Position.BOTTOM_LEFT), - null, - (int) bottomLeftShadowPoint.getX(), - (int) bottomLeftShadowPoint.getY()); + + public int getLineWidth() { + return lineWidth; } - if (showRightShadow || showBottomShadow) { - g2.drawImage( - images.get(Position.BOTTOM_RIGHT), - null, - (int) bottomRightShadowPoint.getX(), - (int) bottomRightShadowPoint.getY()); + + public Color getLineColor() { + return lineColor; } - if (showRightShadow || showTopShadow) { - g2.drawImage( - images.get(Position.TOP_RIGHT), - null, - (int) topRightShadowPoint.getX(), - (int) topRightShadowPoint.getY()); + + public int getShadowSize() { + return shadowSize; } - } - - private Map getImages(Graphics2D g2) { - // first, check to see if an image for this size has already been rendered - // if so, use the cache. Else, draw and save - Map images = CACHE.get(shadowSize); - if (images == null) { - images = new HashMap(); - - /* - * Do draw a drop shadows, I have to: - * 1) Create a rounded rectangle - * 2) Create a BufferedImage to draw the rounded rect in - * 3) Translate the graphics for the image, so that the rectangle - * is centered in the drawn space. The border around the rectangle - * needs to be shadowWidth wide, so that there is space for the - * shadows to be drawn. - * 4) Draw the rounded rect as black, with an opacity of 50% - * 5) Create the BLUR_KERNEL - * 6) Blur the image - * 7) copy off the corners, sides, etc into images to be used for - * drawing the Border - */ - int rectWidth = cornerSize + 1; - RoundRectangle2D rect = - new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); - int imageWidth = rectWidth + shadowSize * 2; - BufferedImage image = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); - Graphics2D buffer = (Graphics2D) image.getGraphics(); - buffer.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - buffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - buffer.setRenderingHint( - RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - buffer.setRenderingHint( - RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); - buffer.translate(shadowSize, shadowSize); - buffer.fill(rect); - float blurry = - 1.0f / (float) (shadowSize * shadowSize); // 1.0f / (float)(shadowSize * shadowSize); - float[] blurKernel = new float[shadowSize * shadowSize]; - for (int i = 0; i < blurKernel.length; i++) { - blurKernel[i] = blurry; - } - ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); - BufferedImage targetImage = - new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); - ((Graphics2D) targetImage.getGraphics()) - .drawImage(image, blur, -(shadowSize / 2), -(shadowSize / 2)); - - int x = 1; - int y = 1; - int w = shadowSize; - int h = shadowSize; - images.put(Position.TOP_LEFT, targetImage.getSubimage(x, y, w, h)); - x = 1; - y = h; - w = shadowSize; - h = 1; - images.put(Position.LEFT, targetImage.getSubimage(x, y, w, h)); - x = 1; - y = rectWidth; - w = shadowSize; - h = shadowSize; - images.put(Position.BOTTOM_LEFT, targetImage.getSubimage(x, y, w, h)); - x = cornerSize + 1; - y = rectWidth; - w = 1; - h = shadowSize; - images.put(Position.BOTTOM, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = x; - w = shadowSize; - h = shadowSize; - images.put(Position.BOTTOM_RIGHT, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = cornerSize + 1; - w = shadowSize; - h = 1; - images.put(Position.RIGHT, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = 1; - w = shadowSize; - h = shadowSize; - images.put(Position.TOP_RIGHT, targetImage.getSubimage(x, y, w, h)); - x = shadowSize; - y = 1; - w = 1; - h = shadowSize; - images.put(Position.TOP, targetImage.getSubimage(x, y, w, h)); - - buffer.dispose(); - image.flush(); + + public float getShadowOpacity() { + return shadowOpacity; + } + + public int getCornerSize() { + return cornerSize; + } + + private enum Position { + TOP, + TOP_LEFT, + LEFT, + BOTTOM_LEFT, + BOTTOM, + BOTTOM_RIGHT, + RIGHT, + TOP_RIGHT } - return images; - } - - /** */ - public Insets getBorderInsets(Component c) { - int top = 4 + (showTopShadow ? lineWidth + shadowSize : lineWidth); - int left = 4 + (showLeftShadow ? lineWidth + shadowSize : lineWidth); - int bottom = 4 + (showBottomShadow ? lineWidth + shadowSize : lineWidth); - int right = 4 + (showRightShadow ? lineWidth + shadowSize : lineWidth); - - return new Insets(top, left, bottom, right); - } - - /** */ - public boolean isBorderOpaque() { - return true; - } - - public boolean isShowTopShadow() { - return showTopShadow; - } - - public boolean isShowLeftShadow() { - return showLeftShadow; - } - - public boolean isShowRightShadow() { - return showRightShadow; - } - - public boolean isShowBottomShadow() { - return showBottomShadow; - } - - public int getLineWidth() { - return lineWidth; - } - - public Color getLineColor() { - return lineColor; - } - - public int getShadowSize() { - return shadowSize; - } - - public float getShadowOpacity() { - return shadowOpacity; - } - - public int getCornerSize() { - return cornerSize; - } - - private enum Position { - TOP, - TOP_LEFT, - LEFT, - BOTTOM_LEFT, - BOTTOM, - BOTTOM_RIGHT, - RIGHT, - TOP_RIGHT - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java index 049ce78af..8c2e3eeec 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java @@ -6,15 +6,15 @@ public class MaterialBorders { - public static final Border LIGHT_LINE_BORDER = - BorderFactory.createLineBorder(MaterialColors.GRAY_200, 1); - public static final Border THICK_LINE_BORDER = - BorderFactory.createLineBorder(MaterialColors.GRAY_200, 2); + public static final Border LIGHT_LINE_BORDER = + BorderFactory.createLineBorder(MaterialColors.GRAY_200, 1); + public static final Border THICK_LINE_BORDER = + BorderFactory.createLineBorder(MaterialColors.GRAY_200, 2); - public static final Border LIGHT_SHADOW_BORDER = - new DropShadowBorder(Color.BLACK, 0, 4, 0.3f, 12, true, true, true, true); - public static final Border DEFAULT_SHADOW_BORDER = - new DropShadowBorder(Color.BLACK, 5, 5, 0.3f, 12, true, true, true, true); + public static final Border LIGHT_SHADOW_BORDER = + new DropShadowBorder(Color.BLACK, 0, 4, 0.3f, 12, true, true, true, true); + public static final Border DEFAULT_SHADOW_BORDER = + new DropShadowBorder(Color.BLACK, 5, 5, 0.3f, 12, true, true, true, true); - private MaterialBorders() {} + private MaterialBorders() {} } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java index f9678d403..00cb0720a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java @@ -3,270 +3,270 @@ import java.awt.*; public class MaterialColors { - public static final Color RED_50 = new Color(255, 235, 238); - public static final Color RED_100 = new Color(255, 205, 210); - public static final Color RED_200 = new Color(239, 154, 154); - public static final Color RED_300 = new Color(229, 115, 115); - public static final Color RED_400 = new Color(239, 83, 80); - public static final Color RED_500 = new Color(244, 67, 54); - public static final Color RED_600 = new Color(229, 57, 53); - public static final Color RED_700 = new Color(211, 47, 47); - public static final Color RED_800 = new Color(198, 40, 40); - public static final Color RED_900 = new Color(183, 28, 28); - public static final Color RED_A100 = new Color(255, 138, 128); - public static final Color RED_A200 = new Color(255, 82, 82); - public static final Color RED_A400 = new Color(255, 23, 68); - public static final Color RED_A700 = new Color(213, 0, 0); - public static final Color PINK_50 = new Color(252, 228, 236); - public static final Color PINK_100 = new Color(248, 187, 208); - public static final Color PINK_200 = new Color(244, 143, 177); - public static final Color PINK_300 = new Color(240, 98, 146); - public static final Color PINK_400 = new Color(236, 64, 122); - public static final Color PINK_500 = new Color(233, 30, 99); - public static final Color PINK_600 = new Color(216, 27, 96); - public static final Color PINK_700 = new Color(194, 24, 91); - public static final Color PINK_800 = new Color(173, 20, 87); - public static final Color PINK_900 = new Color(136, 14, 79); - public static final Color PINK_A100 = new Color(255, 128, 171); - public static final Color PINK_A200 = new Color(255, 64, 129); - public static final Color PINK_A400 = new Color(245, 0, 87); - public static final Color PINK_A700 = new Color(197, 17, 98); - public static final Color PURPLE_50 = new Color(243, 229, 245); - public static final Color PURPLE_100 = new Color(225, 190, 231); - public static final Color PURPLE_200 = new Color(206, 147, 216); - public static final Color PURPLE_300 = new Color(186, 104, 200); - public static final Color PURPLE_400 = new Color(171, 71, 188); - public static final Color PURPLE_500 = new Color(156, 39, 176); - public static final Color PURPLE_600 = new Color(142, 36, 170); - public static final Color PURPLE_700 = new Color(123, 31, 162); - public static final Color PURPLE_800 = new Color(106, 27, 154); - public static final Color PURPLE_900 = new Color(74, 20, 140); - public static final Color PURPLE_A100 = new Color(234, 128, 252); - public static final Color PURPLE_A200 = new Color(224, 64, 251); - public static final Color PURPLE_A400 = new Color(213, 0, 249); - public static final Color PURPLE_A700 = new Color(170, 0, 255); - public static final Color DEEP_PURPLE_50 = new Color(237, 231, 246); - public static final Color DEEP_PURPLE_100 = new Color(209, 196, 233); - public static final Color DEEP_PURPLE_200 = new Color(179, 157, 219); - public static final Color DEEP_PURPLE_300 = new Color(149, 117, 205); - public static final Color DEEP_PURPLE_400 = new Color(126, 87, 194); - public static final Color DEEP_PURPLE_500 = new Color(103, 58, 183); - public static final Color DEEP_PURPLE_600 = new Color(94, 53, 177); - public static final Color DEEP_PURPLE_700 = new Color(81, 45, 168); - public static final Color DEEP_PURPLE_800 = new Color(69, 39, 160); - public static final Color DEEP_PURPLE_900 = new Color(49, 27, 146); - public static final Color DEEP_PURPLE_A100 = new Color(179, 136, 255); - public static final Color DEEP_PURPLE_A200 = new Color(124, 77, 255); - public static final Color DEEP_PURPLE_A400 = new Color(101, 31, 255); - public static final Color DEEP_PURPLE_A700 = new Color(98, 0, 234); - public static final Color INDIGO_50 = new Color(232, 234, 246); - public static final Color INDIGO_100 = new Color(197, 202, 233); - public static final Color INDIGO_200 = new Color(159, 168, 218); - public static final Color INDIGO_300 = new Color(121, 134, 203); - public static final Color INDIGO_400 = new Color(92, 107, 192); - public static final Color INDIGO_500 = new Color(63, 81, 181); - public static final Color INDIGO_600 = new Color(57, 73, 171); - public static final Color INDIGO_700 = new Color(48, 63, 159); - public static final Color INDIGO_800 = new Color(40, 53, 147); - public static final Color INDIGO_900 = new Color(26, 35, 126); - public static final Color INDIGO_A100 = new Color(140, 158, 255); - public static final Color INDIGO_A200 = new Color(83, 109, 254); - public static final Color INDIGO_A400 = new Color(61, 90, 254); - public static final Color INDIGO_A700 = new Color(48, 79, 254); - public static final Color BLUE_50 = new Color(227, 242, 253); - public static final Color BLUE_100 = new Color(187, 222, 251); - public static final Color BLUE_200 = new Color(144, 202, 249); - public static final Color BLUE_300 = new Color(100, 181, 246); - public static final Color BLUE_400 = new Color(66, 165, 245); - public static final Color BLUE_500 = new Color(33, 150, 243); - public static final Color BLUE_600 = new Color(30, 136, 229); - public static final Color BLUE_700 = new Color(25, 118, 210); - public static final Color BLUE_800 = new Color(21, 101, 192); - public static final Color BLUE_900 = new Color(13, 71, 161); - public static final Color BLUE_A100 = new Color(130, 177, 255); - public static final Color BLUE_A200 = new Color(68, 138, 255); - public static final Color BLUE_A400 = new Color(41, 121, 255); - public static final Color BLUE_A700 = new Color(41, 98, 255); - public static final Color LIGHT_BLUE_50 = new Color(225, 245, 254); - public static final Color LIGHT_BLUE_100 = new Color(179, 229, 252); - public static final Color LIGHT_BLUE_200 = new Color(129, 212, 250); - public static final Color LIGHT_BLUE_300 = new Color(79, 195, 247); - public static final Color LIGHT_BLUE_400 = new Color(41, 182, 246); - public static final Color LIGHT_BLUE_500 = new Color(3, 169, 244); - public static final Color LIGHT_BLUE_600 = new Color(3, 155, 229); - public static final Color LIGHT_BLUE_700 = new Color(2, 136, 209); - public static final Color LIGHT_BLUE_800 = new Color(2, 119, 189); - public static final Color LIGHT_BLUE_900 = new Color(1, 87, 155); - public static final Color LIGHT_BLUE_A100 = new Color(128, 216, 255); - public static final Color LIGHT_BLUE_A200 = new Color(64, 196, 255); - public static final Color LIGHT_BLUE_A400 = new Color(0, 176, 255); - public static final Color LIGHT_BLUE_A700 = new Color(0, 145, 234); - public static final Color CYAN_50 = new Color(224, 247, 250); - public static final Color CYAN_100 = new Color(178, 235, 242); - public static final Color CYAN_200 = new Color(128, 222, 234); - public static final Color CYAN_300 = new Color(77, 208, 225); - public static final Color CYAN_400 = new Color(38, 198, 218); - public static final Color CYAN_500 = new Color(0, 188, 212); - public static final Color CYAN_600 = new Color(0, 172, 193); - public static final Color CYAN_700 = new Color(0, 151, 167); - public static final Color CYAN_800 = new Color(0, 131, 143); - public static final Color CYAN_900 = new Color(0, 96, 100); - public static final Color CYAN_A100 = new Color(132, 255, 255); - public static final Color CYAN_A200 = new Color(24, 255, 255); - public static final Color CYAN_A400 = new Color(0, 229, 255); - public static final Color CYAN_A700 = new Color(0, 184, 212); - public static final Color TEAL_50 = new Color(224, 242, 241); - public static final Color TEAL_100 = new Color(178, 223, 219); - public static final Color TEAL_200 = new Color(128, 203, 196); - public static final Color TEAL_300 = new Color(77, 182, 172); - public static final Color TEAL_400 = new Color(38, 166, 154); - public static final Color TEAL_500 = new Color(0, 150, 136); - public static final Color TEAL_600 = new Color(0, 137, 123); - public static final Color TEAL_700 = new Color(0, 121, 107); - public static final Color TEAL_800 = new Color(0, 105, 92); - public static final Color TEAL_900 = new Color(0, 77, 64); - public static final Color TEAL_A100 = new Color(167, 255, 235); - public static final Color TEAL_A200 = new Color(100, 255, 218); - public static final Color TEAL_A400 = new Color(29, 233, 182); - public static final Color TEAL_A700 = new Color(0, 191, 165); - public static final Color GREEN_50 = new Color(232, 245, 233); - public static final Color GREEN_100 = new Color(200, 230, 201); - public static final Color GREEN_200 = new Color(165, 214, 167); - public static final Color GREEN_300 = new Color(129, 199, 132); - public static final Color GREEN_400 = new Color(102, 187, 106); - public static final Color GREEN_500 = new Color(76, 175, 80); - public static final Color GREEN_600 = new Color(67, 160, 71); - public static final Color GREEN_700 = new Color(56, 142, 60); - public static final Color GREEN_800 = new Color(46, 125, 50); - public static final Color GREEN_900 = new Color(27, 94, 32); - public static final Color GREEN_A100 = new Color(185, 246, 202); - public static final Color GREEN_A200 = new Color(105, 240, 174); - public static final Color GREEN_A400 = new Color(0, 230, 118); - public static final Color GREEN_A700 = new Color(0, 200, 83); - public static final Color LIGHT_GREEN_50 = new Color(241, 248, 233); - public static final Color LIGHT_GREEN_100 = new Color(220, 237, 200); - public static final Color LIGHT_GREEN_200 = new Color(197, 225, 165); - public static final Color LIGHT_GREEN_300 = new Color(174, 213, 129); - public static final Color LIGHT_GREEN_400 = new Color(156, 204, 101); - public static final Color LIGHT_GREEN_500 = new Color(139, 195, 74); - public static final Color LIGHT_GREEN_600 = new Color(124, 179, 66); - public static final Color LIGHT_GREEN_700 = new Color(104, 159, 56); - public static final Color LIGHT_GREEN_800 = new Color(85, 139, 47); - public static final Color LIGHT_GREEN_900 = new Color(51, 105, 30); - public static final Color LIGHT_GREEN_A100 = new Color(204, 255, 144); - public static final Color LIGHT_GREEN_A200 = new Color(178, 255, 89); - public static final Color LIGHT_GREEN_A400 = new Color(118, 255, 3); - public static final Color LIGHT_GREEN_A700 = new Color(100, 221, 23); - public static final Color LIME_50 = new Color(249, 251, 231); - public static final Color LIME_100 = new Color(240, 244, 195); - public static final Color LIME_200 = new Color(230, 238, 156); - public static final Color LIME_300 = new Color(220, 231, 117); - public static final Color LIME_400 = new Color(212, 225, 87); - public static final Color LIME_500 = new Color(205, 220, 57); - public static final Color LIME_600 = new Color(192, 202, 51); - public static final Color LIME_700 = new Color(175, 180, 43); - public static final Color LIME_800 = new Color(158, 157, 36); - public static final Color LIME_900 = new Color(130, 119, 23); - public static final Color LIME_A100 = new Color(244, 255, 129); - public static final Color LIME_A200 = new Color(238, 255, 65); - public static final Color LIME_A400 = new Color(198, 255, 0); - public static final Color LIME_A700 = new Color(174, 234, 0); - public static final Color YELLOW_50 = new Color(255, 253, 231); - public static final Color YELLOW_100 = new Color(255, 249, 196); - public static final Color YELLOW_200 = new Color(255, 245, 157); - public static final Color YELLOW_300 = new Color(255, 241, 118); - public static final Color YELLOW_400 = new Color(255, 238, 88); - public static final Color YELLOW_500 = new Color(255, 235, 59); - public static final Color YELLOW_600 = new Color(253, 216, 53); - public static final Color YELLOW_700 = new Color(251, 192, 45); - public static final Color YELLOW_800 = new Color(249, 168, 37); - public static final Color YELLOW_900 = new Color(245, 127, 23); - public static final Color YELLOW_A100 = new Color(255, 255, 141); - public static final Color YELLOW_A200 = new Color(255, 255, 0); - public static final Color YELLOW_A400 = new Color(255, 234, 0); - public static final Color YELLOW_A700 = new Color(255, 214, 0); - public static final Color AMBER_50 = new Color(255, 248, 225); - public static final Color AMBER_100 = new Color(255, 236, 179); - public static final Color AMBER_200 = new Color(255, 224, 130); - public static final Color AMBER_300 = new Color(255, 213, 79); - public static final Color AMBER_400 = new Color(255, 202, 40); - public static final Color AMBER_500 = new Color(255, 193, 7); - public static final Color AMBER_600 = new Color(255, 179, 0); - public static final Color AMBER_700 = new Color(255, 160, 0); - public static final Color AMBER_800 = new Color(255, 143, 0); - public static final Color AMBER_900 = new Color(255, 111, 0); - public static final Color AMBER_A100 = new Color(255, 229, 127); - public static final Color AMBER_A200 = new Color(255, 215, 64); - public static final Color AMBER_A400 = new Color(255, 196, 0); - public static final Color AMBER_A700 = new Color(255, 171, 0); - public static final Color ORANGE_50 = new Color(255, 243, 224); - public static final Color ORANGE_100 = new Color(255, 224, 178); - public static final Color ORANGE_200 = new Color(255, 204, 128); - public static final Color ORANGE_300 = new Color(255, 183, 77); - public static final Color ORANGE_400 = new Color(255, 167, 38); - public static final Color ORANGE_500 = new Color(255, 152, 0); - public static final Color ORANGE_600 = new Color(251, 140, 0); - public static final Color ORANGE_700 = new Color(245, 124, 0); - public static final Color ORANGE_800 = new Color(239, 108, 0); - public static final Color ORANGE_900 = new Color(230, 81, 0); - public static final Color ORANGE_A100 = new Color(255, 209, 128); - public static final Color ORANGE_A200 = new Color(255, 171, 64); - public static final Color ORANGE_A400 = new Color(255, 145, 0); - public static final Color ORANGE_A700 = new Color(255, 109, 0); - public static final Color DEEP_ORANGE_50 = new Color(251, 233, 231); - public static final Color DEEP_ORANGE_100 = new Color(255, 204, 188); - public static final Color DEEP_ORANGE_200 = new Color(255, 171, 145); - public static final Color DEEP_ORANGE_300 = new Color(255, 138, 101); - public static final Color DEEP_ORANGE_400 = new Color(255, 112, 67); - public static final Color DEEP_ORANGE_500 = new Color(255, 87, 34); - public static final Color DEEP_ORANGE_600 = new Color(244, 81, 30); - public static final Color DEEP_ORANGE_700 = new Color(230, 74, 25); - public static final Color DEEP_ORANGE_800 = new Color(216, 67, 21); - public static final Color DEEP_ORANGE_900 = new Color(191, 54, 12); - public static final Color DEEP_ORANGE_A100 = new Color(255, 158, 128); - public static final Color DEEP_ORANGE_A200 = new Color(255, 110, 64); - public static final Color DEEP_ORANGE_A400 = new Color(255, 61, 0); - public static final Color DEEP_ORANGE_A700 = new Color(221, 44, 0); - public static final Color BROWN_50 = new Color(239, 235, 233); - public static final Color BROWN_100 = new Color(215, 204, 200); - public static final Color BROWN_200 = new Color(188, 170, 164); - public static final Color BROWN_300 = new Color(161, 136, 127); - public static final Color BROWN_400 = new Color(141, 110, 99); - public static final Color BROWN_500 = new Color(121, 85, 72); - public static final Color BROWN_600 = new Color(109, 76, 65); - public static final Color BROWN_700 = new Color(93, 64, 55); - public static final Color BROWN_800 = new Color(78, 52, 46); - public static final Color BROWN_900 = new Color(62, 39, 35); - public static final Color GRAY_50 = new Color(250, 250, 250); - public static final Color GRAY_100 = new Color(245, 245, 245); - public static final Color GRAY_200 = new Color(238, 238, 238); - public static final Color GRAY_300 = new Color(224, 224, 224); - public static final Color GRAY_400 = new Color(189, 189, 189); - public static final Color GRAY_500 = new Color(158, 158, 158); - public static final Color GRAY_600 = new Color(117, 117, 117); - public static final Color GRAY_700 = new Color(97, 97, 97); - public static final Color GRAY_800 = new Color(66, 66, 66); - public static final Color GRAY_900 = new Color(33, 33, 33); - public static final Color BLUE_GRAY_50 = new Color(236, 239, 241); - public static final Color BLUE_GRAY_100 = new Color(207, 216, 220); - public static final Color BLUE_GRAY_200 = new Color(176, 190, 197); - public static final Color BLUE_GRAY_300 = new Color(144, 164, 174); - public static final Color BLUE_GRAY_400 = new Color(120, 144, 156); - public static final Color BLUE_GRAY_500 = new Color(96, 125, 139); - public static final Color BLUE_GRAY_600 = new Color(84, 110, 122); - public static final Color BLUE_GRAY_700 = new Color(69, 90, 100); - public static final Color BLUE_GRAY_800 = new Color(55, 71, 79); - public static final Color BLUE_GRAY_900 = new Color(38, 50, 56); - public static final Color BLACK = new Color(0, 0, 0); - public static final Color WHITE = new Color(255, 255, 255); - public static final Color TRANSPARENT = new Color(0, 0, 0, 255); + public static final Color RED_50 = new Color(255, 235, 238); + public static final Color RED_100 = new Color(255, 205, 210); + public static final Color RED_200 = new Color(239, 154, 154); + public static final Color RED_300 = new Color(229, 115, 115); + public static final Color RED_400 = new Color(239, 83, 80); + public static final Color RED_500 = new Color(244, 67, 54); + public static final Color RED_600 = new Color(229, 57, 53); + public static final Color RED_700 = new Color(211, 47, 47); + public static final Color RED_800 = new Color(198, 40, 40); + public static final Color RED_900 = new Color(183, 28, 28); + public static final Color RED_A100 = new Color(255, 138, 128); + public static final Color RED_A200 = new Color(255, 82, 82); + public static final Color RED_A400 = new Color(255, 23, 68); + public static final Color RED_A700 = new Color(213, 0, 0); + public static final Color PINK_50 = new Color(252, 228, 236); + public static final Color PINK_100 = new Color(248, 187, 208); + public static final Color PINK_200 = new Color(244, 143, 177); + public static final Color PINK_300 = new Color(240, 98, 146); + public static final Color PINK_400 = new Color(236, 64, 122); + public static final Color PINK_500 = new Color(233, 30, 99); + public static final Color PINK_600 = new Color(216, 27, 96); + public static final Color PINK_700 = new Color(194, 24, 91); + public static final Color PINK_800 = new Color(173, 20, 87); + public static final Color PINK_900 = new Color(136, 14, 79); + public static final Color PINK_A100 = new Color(255, 128, 171); + public static final Color PINK_A200 = new Color(255, 64, 129); + public static final Color PINK_A400 = new Color(245, 0, 87); + public static final Color PINK_A700 = new Color(197, 17, 98); + public static final Color PURPLE_50 = new Color(243, 229, 245); + public static final Color PURPLE_100 = new Color(225, 190, 231); + public static final Color PURPLE_200 = new Color(206, 147, 216); + public static final Color PURPLE_300 = new Color(186, 104, 200); + public static final Color PURPLE_400 = new Color(171, 71, 188); + public static final Color PURPLE_500 = new Color(156, 39, 176); + public static final Color PURPLE_600 = new Color(142, 36, 170); + public static final Color PURPLE_700 = new Color(123, 31, 162); + public static final Color PURPLE_800 = new Color(106, 27, 154); + public static final Color PURPLE_900 = new Color(74, 20, 140); + public static final Color PURPLE_A100 = new Color(234, 128, 252); + public static final Color PURPLE_A200 = new Color(224, 64, 251); + public static final Color PURPLE_A400 = new Color(213, 0, 249); + public static final Color PURPLE_A700 = new Color(170, 0, 255); + public static final Color DEEP_PURPLE_50 = new Color(237, 231, 246); + public static final Color DEEP_PURPLE_100 = new Color(209, 196, 233); + public static final Color DEEP_PURPLE_200 = new Color(179, 157, 219); + public static final Color DEEP_PURPLE_300 = new Color(149, 117, 205); + public static final Color DEEP_PURPLE_400 = new Color(126, 87, 194); + public static final Color DEEP_PURPLE_500 = new Color(103, 58, 183); + public static final Color DEEP_PURPLE_600 = new Color(94, 53, 177); + public static final Color DEEP_PURPLE_700 = new Color(81, 45, 168); + public static final Color DEEP_PURPLE_800 = new Color(69, 39, 160); + public static final Color DEEP_PURPLE_900 = new Color(49, 27, 146); + public static final Color DEEP_PURPLE_A100 = new Color(179, 136, 255); + public static final Color DEEP_PURPLE_A200 = new Color(124, 77, 255); + public static final Color DEEP_PURPLE_A400 = new Color(101, 31, 255); + public static final Color DEEP_PURPLE_A700 = new Color(98, 0, 234); + public static final Color INDIGO_50 = new Color(232, 234, 246); + public static final Color INDIGO_100 = new Color(197, 202, 233); + public static final Color INDIGO_200 = new Color(159, 168, 218); + public static final Color INDIGO_300 = new Color(121, 134, 203); + public static final Color INDIGO_400 = new Color(92, 107, 192); + public static final Color INDIGO_500 = new Color(63, 81, 181); + public static final Color INDIGO_600 = new Color(57, 73, 171); + public static final Color INDIGO_700 = new Color(48, 63, 159); + public static final Color INDIGO_800 = new Color(40, 53, 147); + public static final Color INDIGO_900 = new Color(26, 35, 126); + public static final Color INDIGO_A100 = new Color(140, 158, 255); + public static final Color INDIGO_A200 = new Color(83, 109, 254); + public static final Color INDIGO_A400 = new Color(61, 90, 254); + public static final Color INDIGO_A700 = new Color(48, 79, 254); + public static final Color BLUE_50 = new Color(227, 242, 253); + public static final Color BLUE_100 = new Color(187, 222, 251); + public static final Color BLUE_200 = new Color(144, 202, 249); + public static final Color BLUE_300 = new Color(100, 181, 246); + public static final Color BLUE_400 = new Color(66, 165, 245); + public static final Color BLUE_500 = new Color(33, 150, 243); + public static final Color BLUE_600 = new Color(30, 136, 229); + public static final Color BLUE_700 = new Color(25, 118, 210); + public static final Color BLUE_800 = new Color(21, 101, 192); + public static final Color BLUE_900 = new Color(13, 71, 161); + public static final Color BLUE_A100 = new Color(130, 177, 255); + public static final Color BLUE_A200 = new Color(68, 138, 255); + public static final Color BLUE_A400 = new Color(41, 121, 255); + public static final Color BLUE_A700 = new Color(41, 98, 255); + public static final Color LIGHT_BLUE_50 = new Color(225, 245, 254); + public static final Color LIGHT_BLUE_100 = new Color(179, 229, 252); + public static final Color LIGHT_BLUE_200 = new Color(129, 212, 250); + public static final Color LIGHT_BLUE_300 = new Color(79, 195, 247); + public static final Color LIGHT_BLUE_400 = new Color(41, 182, 246); + public static final Color LIGHT_BLUE_500 = new Color(3, 169, 244); + public static final Color LIGHT_BLUE_600 = new Color(3, 155, 229); + public static final Color LIGHT_BLUE_700 = new Color(2, 136, 209); + public static final Color LIGHT_BLUE_800 = new Color(2, 119, 189); + public static final Color LIGHT_BLUE_900 = new Color(1, 87, 155); + public static final Color LIGHT_BLUE_A100 = new Color(128, 216, 255); + public static final Color LIGHT_BLUE_A200 = new Color(64, 196, 255); + public static final Color LIGHT_BLUE_A400 = new Color(0, 176, 255); + public static final Color LIGHT_BLUE_A700 = new Color(0, 145, 234); + public static final Color CYAN_50 = new Color(224, 247, 250); + public static final Color CYAN_100 = new Color(178, 235, 242); + public static final Color CYAN_200 = new Color(128, 222, 234); + public static final Color CYAN_300 = new Color(77, 208, 225); + public static final Color CYAN_400 = new Color(38, 198, 218); + public static final Color CYAN_500 = new Color(0, 188, 212); + public static final Color CYAN_600 = new Color(0, 172, 193); + public static final Color CYAN_700 = new Color(0, 151, 167); + public static final Color CYAN_800 = new Color(0, 131, 143); + public static final Color CYAN_900 = new Color(0, 96, 100); + public static final Color CYAN_A100 = new Color(132, 255, 255); + public static final Color CYAN_A200 = new Color(24, 255, 255); + public static final Color CYAN_A400 = new Color(0, 229, 255); + public static final Color CYAN_A700 = new Color(0, 184, 212); + public static final Color TEAL_50 = new Color(224, 242, 241); + public static final Color TEAL_100 = new Color(178, 223, 219); + public static final Color TEAL_200 = new Color(128, 203, 196); + public static final Color TEAL_300 = new Color(77, 182, 172); + public static final Color TEAL_400 = new Color(38, 166, 154); + public static final Color TEAL_500 = new Color(0, 150, 136); + public static final Color TEAL_600 = new Color(0, 137, 123); + public static final Color TEAL_700 = new Color(0, 121, 107); + public static final Color TEAL_800 = new Color(0, 105, 92); + public static final Color TEAL_900 = new Color(0, 77, 64); + public static final Color TEAL_A100 = new Color(167, 255, 235); + public static final Color TEAL_A200 = new Color(100, 255, 218); + public static final Color TEAL_A400 = new Color(29, 233, 182); + public static final Color TEAL_A700 = new Color(0, 191, 165); + public static final Color GREEN_50 = new Color(232, 245, 233); + public static final Color GREEN_100 = new Color(200, 230, 201); + public static final Color GREEN_200 = new Color(165, 214, 167); + public static final Color GREEN_300 = new Color(129, 199, 132); + public static final Color GREEN_400 = new Color(102, 187, 106); + public static final Color GREEN_500 = new Color(76, 175, 80); + public static final Color GREEN_600 = new Color(67, 160, 71); + public static final Color GREEN_700 = new Color(56, 142, 60); + public static final Color GREEN_800 = new Color(46, 125, 50); + public static final Color GREEN_900 = new Color(27, 94, 32); + public static final Color GREEN_A100 = new Color(185, 246, 202); + public static final Color GREEN_A200 = new Color(105, 240, 174); + public static final Color GREEN_A400 = new Color(0, 230, 118); + public static final Color GREEN_A700 = new Color(0, 200, 83); + public static final Color LIGHT_GREEN_50 = new Color(241, 248, 233); + public static final Color LIGHT_GREEN_100 = new Color(220, 237, 200); + public static final Color LIGHT_GREEN_200 = new Color(197, 225, 165); + public static final Color LIGHT_GREEN_300 = new Color(174, 213, 129); + public static final Color LIGHT_GREEN_400 = new Color(156, 204, 101); + public static final Color LIGHT_GREEN_500 = new Color(139, 195, 74); + public static final Color LIGHT_GREEN_600 = new Color(124, 179, 66); + public static final Color LIGHT_GREEN_700 = new Color(104, 159, 56); + public static final Color LIGHT_GREEN_800 = new Color(85, 139, 47); + public static final Color LIGHT_GREEN_900 = new Color(51, 105, 30); + public static final Color LIGHT_GREEN_A100 = new Color(204, 255, 144); + public static final Color LIGHT_GREEN_A200 = new Color(178, 255, 89); + public static final Color LIGHT_GREEN_A400 = new Color(118, 255, 3); + public static final Color LIGHT_GREEN_A700 = new Color(100, 221, 23); + public static final Color LIME_50 = new Color(249, 251, 231); + public static final Color LIME_100 = new Color(240, 244, 195); + public static final Color LIME_200 = new Color(230, 238, 156); + public static final Color LIME_300 = new Color(220, 231, 117); + public static final Color LIME_400 = new Color(212, 225, 87); + public static final Color LIME_500 = new Color(205, 220, 57); + public static final Color LIME_600 = new Color(192, 202, 51); + public static final Color LIME_700 = new Color(175, 180, 43); + public static final Color LIME_800 = new Color(158, 157, 36); + public static final Color LIME_900 = new Color(130, 119, 23); + public static final Color LIME_A100 = new Color(244, 255, 129); + public static final Color LIME_A200 = new Color(238, 255, 65); + public static final Color LIME_A400 = new Color(198, 255, 0); + public static final Color LIME_A700 = new Color(174, 234, 0); + public static final Color YELLOW_50 = new Color(255, 253, 231); + public static final Color YELLOW_100 = new Color(255, 249, 196); + public static final Color YELLOW_200 = new Color(255, 245, 157); + public static final Color YELLOW_300 = new Color(255, 241, 118); + public static final Color YELLOW_400 = new Color(255, 238, 88); + public static final Color YELLOW_500 = new Color(255, 235, 59); + public static final Color YELLOW_600 = new Color(253, 216, 53); + public static final Color YELLOW_700 = new Color(251, 192, 45); + public static final Color YELLOW_800 = new Color(249, 168, 37); + public static final Color YELLOW_900 = new Color(245, 127, 23); + public static final Color YELLOW_A100 = new Color(255, 255, 141); + public static final Color YELLOW_A200 = new Color(255, 255, 0); + public static final Color YELLOW_A400 = new Color(255, 234, 0); + public static final Color YELLOW_A700 = new Color(255, 214, 0); + public static final Color AMBER_50 = new Color(255, 248, 225); + public static final Color AMBER_100 = new Color(255, 236, 179); + public static final Color AMBER_200 = new Color(255, 224, 130); + public static final Color AMBER_300 = new Color(255, 213, 79); + public static final Color AMBER_400 = new Color(255, 202, 40); + public static final Color AMBER_500 = new Color(255, 193, 7); + public static final Color AMBER_600 = new Color(255, 179, 0); + public static final Color AMBER_700 = new Color(255, 160, 0); + public static final Color AMBER_800 = new Color(255, 143, 0); + public static final Color AMBER_900 = new Color(255, 111, 0); + public static final Color AMBER_A100 = new Color(255, 229, 127); + public static final Color AMBER_A200 = new Color(255, 215, 64); + public static final Color AMBER_A400 = new Color(255, 196, 0); + public static final Color AMBER_A700 = new Color(255, 171, 0); + public static final Color ORANGE_50 = new Color(255, 243, 224); + public static final Color ORANGE_100 = new Color(255, 224, 178); + public static final Color ORANGE_200 = new Color(255, 204, 128); + public static final Color ORANGE_300 = new Color(255, 183, 77); + public static final Color ORANGE_400 = new Color(255, 167, 38); + public static final Color ORANGE_500 = new Color(255, 152, 0); + public static final Color ORANGE_600 = new Color(251, 140, 0); + public static final Color ORANGE_700 = new Color(245, 124, 0); + public static final Color ORANGE_800 = new Color(239, 108, 0); + public static final Color ORANGE_900 = new Color(230, 81, 0); + public static final Color ORANGE_A100 = new Color(255, 209, 128); + public static final Color ORANGE_A200 = new Color(255, 171, 64); + public static final Color ORANGE_A400 = new Color(255, 145, 0); + public static final Color ORANGE_A700 = new Color(255, 109, 0); + public static final Color DEEP_ORANGE_50 = new Color(251, 233, 231); + public static final Color DEEP_ORANGE_100 = new Color(255, 204, 188); + public static final Color DEEP_ORANGE_200 = new Color(255, 171, 145); + public static final Color DEEP_ORANGE_300 = new Color(255, 138, 101); + public static final Color DEEP_ORANGE_400 = new Color(255, 112, 67); + public static final Color DEEP_ORANGE_500 = new Color(255, 87, 34); + public static final Color DEEP_ORANGE_600 = new Color(244, 81, 30); + public static final Color DEEP_ORANGE_700 = new Color(230, 74, 25); + public static final Color DEEP_ORANGE_800 = new Color(216, 67, 21); + public static final Color DEEP_ORANGE_900 = new Color(191, 54, 12); + public static final Color DEEP_ORANGE_A100 = new Color(255, 158, 128); + public static final Color DEEP_ORANGE_A200 = new Color(255, 110, 64); + public static final Color DEEP_ORANGE_A400 = new Color(255, 61, 0); + public static final Color DEEP_ORANGE_A700 = new Color(221, 44, 0); + public static final Color BROWN_50 = new Color(239, 235, 233); + public static final Color BROWN_100 = new Color(215, 204, 200); + public static final Color BROWN_200 = new Color(188, 170, 164); + public static final Color BROWN_300 = new Color(161, 136, 127); + public static final Color BROWN_400 = new Color(141, 110, 99); + public static final Color BROWN_500 = new Color(121, 85, 72); + public static final Color BROWN_600 = new Color(109, 76, 65); + public static final Color BROWN_700 = new Color(93, 64, 55); + public static final Color BROWN_800 = new Color(78, 52, 46); + public static final Color BROWN_900 = new Color(62, 39, 35); + public static final Color GRAY_50 = new Color(250, 250, 250); + public static final Color GRAY_100 = new Color(245, 245, 245); + public static final Color GRAY_200 = new Color(238, 238, 238); + public static final Color GRAY_300 = new Color(224, 224, 224); + public static final Color GRAY_400 = new Color(189, 189, 189); + public static final Color GRAY_500 = new Color(158, 158, 158); + public static final Color GRAY_600 = new Color(117, 117, 117); + public static final Color GRAY_700 = new Color(97, 97, 97); + public static final Color GRAY_800 = new Color(66, 66, 66); + public static final Color GRAY_900 = new Color(33, 33, 33); + public static final Color BLUE_GRAY_50 = new Color(236, 239, 241); + public static final Color BLUE_GRAY_100 = new Color(207, 216, 220); + public static final Color BLUE_GRAY_200 = new Color(176, 190, 197); + public static final Color BLUE_GRAY_300 = new Color(144, 164, 174); + public static final Color BLUE_GRAY_400 = new Color(120, 144, 156); + public static final Color BLUE_GRAY_500 = new Color(96, 125, 139); + public static final Color BLUE_GRAY_600 = new Color(84, 110, 122); + public static final Color BLUE_GRAY_700 = new Color(69, 90, 100); + public static final Color BLUE_GRAY_800 = new Color(55, 71, 79); + public static final Color BLUE_GRAY_900 = new Color(38, 50, 56); + public static final Color BLACK = new Color(0, 0, 0); + public static final Color WHITE = new Color(255, 255, 255); + public static final Color TRANSPARENT = new Color(0, 0, 0, 255); - private MaterialColors() {} + private MaterialColors() {} - public static Color bleach(Color color, float amount) { - int red = (int) ((color.getRed() * (1 - amount) / 255 + amount) * 255); - int green = (int) ((color.getGreen() * (1 - amount) / 255 + amount) * 255); - int blue = (int) ((color.getBlue() * (1 - amount) / 255 + amount) * 255); - return new Color(red, green, blue); - } + public static Color bleach(Color color, float amount) { + int red = (int) ((color.getRed() * (1 - amount) / 255 + amount) * 255); + int green = (int) ((color.getGreen() * (1 - amount) / 255 + amount) * 255); + int blue = (int) ((color.getBlue() * (1 - amount) / 255 + amount) * 255); + return new Color(red, green, blue); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java index 30c4fdeda..f5e209b0d 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java @@ -8,28 +8,28 @@ public class MaterialDrawingUtils { - static { - System.setProperty("awt.useSystemAAFontSettings", "on"); - System.setProperty("swing.aatext", "true"); - System.setProperty("sun.java2d.xrender", "true"); - } + static { + System.setProperty("awt.useSystemAAFontSettings", "on"); + System.setProperty("swing.aatext", "true"); + System.setProperty("sun.java2d.xrender", "true"); + } - public static Graphics getAliasedGraphics(Graphics g) { - Map hints = - (Map) - Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); - if (hints != null) { - hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + public static Graphics getAliasedGraphics(Graphics g) { + Map hints = + (Map) + Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); + if (hints != null) { + hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - Graphics2D g2d = (Graphics2D) g; - g2d.addRenderingHints(hints); + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(hints); - // g2d.addRenderingHints (new RenderingHints (RenderingHints.KEY_ANTIALIASING, - // RenderingHints.VALUE_ANTIALIAS_ON)); - return g2d; - } else { - // Desktop hints not supported on this platform - return g; + // g2d.addRenderingHints (new RenderingHints (RenderingHints.KEY_ANTIALIASING, + // RenderingHints.VALUE_ANTIALIAS_ON)); + return g2d; + } else { + // Desktop hints not supported on this platform + return g; + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java index cb6a79f86..e5d1de56c 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java @@ -9,51 +9,52 @@ public class MaterialFonts { - private static final Map fontSettings = new HashMap<>(); - - public static final Font BLACK = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Black.ttf"); - public static final Font BLACK_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BlackItalic.ttf"); - public static final Font BOLD = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Bold.ttf"); - public static final Font BOLD_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BoldItalic.ttf"); - public static final Font ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Italic.ttf"); - public static final Font LIGHT = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Light.ttf"); - public static final Font LIGHT_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-LightItalic.ttf"); - public static final Font MEDIUM = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Medium.ttf"); - public static final Font MEDIUM_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-MediumItalic.ttf"); - public static final Font REGULAR = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf"); - public static final Font THIN = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Thin.ttf"); - public static final Font THIN_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-ThinItalic.ttf"); - - private static Font loadFont(String fontPath) { - if (fontSettings.isEmpty()) { - fontSettings.put(TextAttribute.SIZE, 14f); - fontSettings.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + private static final Map fontSettings = new HashMap<>(); + + public static final Font BLACK = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Black.ttf"); + public static final Font BLACK_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BlackItalic.ttf"); + public static final Font BOLD = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Bold.ttf"); + public static final Font BOLD_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BoldItalic.ttf"); + public static final Font ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Italic.ttf"); + public static final Font LIGHT = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Light.ttf"); + public static final Font LIGHT_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-LightItalic.ttf"); + public static final Font MEDIUM = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Medium.ttf"); + public static final Font MEDIUM_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-MediumItalic.ttf"); + public static final Font REGULAR = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf"); + public static final Font THIN = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Thin.ttf"); + public static final Font THIN_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-ThinItalic.ttf"); + + private static Font loadFont(String fontPath) { + if (fontSettings.isEmpty()) { + fontSettings.put(TextAttribute.SIZE, 14f); + fontSettings.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + } + + try (InputStream inputStream = MaterialFonts.class.getResourceAsStream(fontPath)) { + return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(fontSettings); + } catch (IOException | FontFormatException e) { + e.printStackTrace(); + throw new RuntimeException("Font " + fontPath + " wasn't loaded"); + } } - try (InputStream inputStream = MaterialFonts.class.getResourceAsStream(fontPath)) { - return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(fontSettings); - } catch (IOException | FontFormatException e) { - e.printStackTrace(); - throw new RuntimeException("Font " + fontPath + " wasn't loaded"); + public static Font getRegularFont(float size) { + final Map map = new HashMap<>(); + map.put(TextAttribute.SIZE, size); + map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + + try (InputStream inputStream = + MaterialFonts.class.getResourceAsStream( + "/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf")) { + return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(map); + } catch (IOException | FontFormatException e) { + e.printStackTrace(); + throw new RuntimeException("Font regular wasn't loaded"); + } } - } - - public static Font getRegularFont(float size) { - final Map map = new HashMap<>(); - map.put(TextAttribute.SIZE, size); - map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); - - try (InputStream inputStream = - MaterialFonts.class.getResourceAsStream("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf")) { - return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(map); - } catch (IOException | FontFormatException e) { - e.printStackTrace(); - throw new RuntimeException("Font regular wasn't loaded"); - } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java index 93abff7a2..a1a716c76 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java @@ -7,41 +7,43 @@ public class MaterialImages { - public static final BufferedImage RIGHT_ARROW = loadImg("/edu/rpi/legup/imgs/right_arrow.png"); - public static final BufferedImage DOWN_ARROW = loadImg("/edu/rpi/legup/imgs/down_arrow.png"); - public static final BufferedImage UP_ARROW = loadImg("/edu/rpi/legup/imgs/up_arrow.png"); - public static final BufferedImage PAINTED_CHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/painted_checked_box.png"); - public static final BufferedImage OUTLINED_CHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/outlined_checked_box.png"); - public static final BufferedImage UNCHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/unchecked_box.png"); - public static final BufferedImage RADIO_BUTTON_ON = - loadImg("/edu/rpi/legup/imgs/radio_button_on.png"); - public static final BufferedImage RADIO_BUTTON_OFF = - loadImg("/edu/rpi/legup/imgs/radio_button_off.png"); - public static final BufferedImage TOGGLE_BUTTON_ON = loadImg("/edu/rpi/legup/imgs/toggle_on.png"); - public static final BufferedImage TOGGLE_BUTTON_OFF = - loadImg("/edu/rpi/legup/imgs/toggle_off.png"); - public static final BufferedImage BACK_ARROW = loadImg("/edu/rpi/legup/imgs/back_arrow.png"); - public static final BufferedImage COMPUTER = loadImg("/edu/rpi/legup/imgs/computer.png"); - public static final BufferedImage FILE = loadImg("/edu/rpi/legup/imgs/file.png"); - public static final BufferedImage FLOPPY_DRIVE = loadImg("/edu/rpi/legup/imgs/floppy_drive.png"); - public static final BufferedImage FOLDER = loadImg("/edu/rpi/legup/imgs/folder.png"); - public static final BufferedImage HARD_DRIVE = loadImg("/edu/rpi/legup/imgs/hard_drive.png"); - public static final BufferedImage HOME = loadImg("/edu/rpi/legup/imgs/home.png"); - public static final BufferedImage LIST = loadImg("/edu/rpi/legup/imgs/list.png"); - public static final BufferedImage NEW_FOLDER = loadImg("/edu/rpi/legup/imgs/new_folder.png"); - public static final BufferedImage DETAILS = loadImg("/edu/rpi/legup/imgs/details.png"); + public static final BufferedImage RIGHT_ARROW = loadImg("/edu/rpi/legup/imgs/right_arrow.png"); + public static final BufferedImage DOWN_ARROW = loadImg("/edu/rpi/legup/imgs/down_arrow.png"); + public static final BufferedImage UP_ARROW = loadImg("/edu/rpi/legup/imgs/up_arrow.png"); + public static final BufferedImage PAINTED_CHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/painted_checked_box.png"); + public static final BufferedImage OUTLINED_CHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/outlined_checked_box.png"); + public static final BufferedImage UNCHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/unchecked_box.png"); + public static final BufferedImage RADIO_BUTTON_ON = + loadImg("/edu/rpi/legup/imgs/radio_button_on.png"); + public static final BufferedImage RADIO_BUTTON_OFF = + loadImg("/edu/rpi/legup/imgs/radio_button_off.png"); + public static final BufferedImage TOGGLE_BUTTON_ON = + loadImg("/edu/rpi/legup/imgs/toggle_on.png"); + public static final BufferedImage TOGGLE_BUTTON_OFF = + loadImg("/edu/rpi/legup/imgs/toggle_off.png"); + public static final BufferedImage BACK_ARROW = loadImg("/edu/rpi/legup/imgs/back_arrow.png"); + public static final BufferedImage COMPUTER = loadImg("/edu/rpi/legup/imgs/computer.png"); + public static final BufferedImage FILE = loadImg("/edu/rpi/legup/imgs/file.png"); + public static final BufferedImage FLOPPY_DRIVE = + loadImg("/edu/rpi/legup/imgs/floppy_drive.png"); + public static final BufferedImage FOLDER = loadImg("/edu/rpi/legup/imgs/folder.png"); + public static final BufferedImage HARD_DRIVE = loadImg("/edu/rpi/legup/imgs/hard_drive.png"); + public static final BufferedImage HOME = loadImg("/edu/rpi/legup/imgs/home.png"); + public static final BufferedImage LIST = loadImg("/edu/rpi/legup/imgs/list.png"); + public static final BufferedImage NEW_FOLDER = loadImg("/edu/rpi/legup/imgs/new_folder.png"); + public static final BufferedImage DETAILS = loadImg("/edu/rpi/legup/imgs/details.png"); - private MaterialImages() {} + private MaterialImages() {} - private static BufferedImage loadImg(String imgPath) { - try (InputStream inputStream = MaterialImages.class.getResourceAsStream(imgPath)) { - return ImageIO.read(inputStream); - } catch (IOException e) { - e.printStackTrace(); - throw new RuntimeException("Image " + imgPath + " wasn't loaded"); + private static BufferedImage loadImg(String imgPath) { + try (InputStream inputStream = MaterialImages.class.getResourceAsStream(imgPath)) { + return ImageIO.read(inputStream); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Image " + imgPath + " wasn't loaded"); + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java index c3c70db31..1fb0a16ab 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java @@ -3,18 +3,18 @@ import javax.swing.ImageIcon; public class CaseRulePanel extends RulePanel { - /** - * CaseRulePanel Constructor creates a CaseRulePanel - * - * @param ruleFrame rule frame that this CaseRulePanel is contained in - */ - CaseRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Case Rules.gif")); - this.name = "Case Rules"; - this.toolTip = "Case Rules"; - } + /** + * CaseRulePanel Constructor creates a CaseRulePanel + * + * @param ruleFrame rule frame that this CaseRulePanel is contained in + */ + CaseRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Case Rules.gif")); + this.name = "Case Rules"; + this.toolTip = "Case Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java index 1e7d6066c..ae9444db2 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java @@ -6,16 +6,16 @@ public class CaseRuleSelectionView extends JPanel { - public CaseRuleSelectionView(RuleButton ruleButton) { - setLayout(new WrapLayout()); - Button button1 = new Button(ruleButton.getX() + ", " + ruleButton.getY()); - button1.setSize(50, 50); - Button button2 = new Button("How"); - button2.setSize(50, 50); + public CaseRuleSelectionView(RuleButton ruleButton) { + setLayout(new WrapLayout()); + Button button1 = new Button(ruleButton.getX() + ", " + ruleButton.getY()); + button1.setSize(50, 50); + Button button2 = new Button("How"); + button2.setSize(50, 50); - add(button1); - add(button2); + add(button1); + add(button2); - revalidate(); - } + revalidate(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java index 5f5fb6aaf..f695491fb 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java @@ -3,18 +3,18 @@ import javax.swing.*; public class ContradictionRulePanel extends RulePanel { - /** - * ContradictionRulePanel Constructor creates a ContradictionRulePanel - * - * @param ruleFrame rule frame that this ContradictionRulePanel is contained in - */ - ContradictionRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Contradictions.gif")); - this.name = "Contradiction Rules"; - this.toolTip = "Contradiction Rules"; - } + /** + * ContradictionRulePanel Constructor creates a ContradictionRulePanel + * + * @param ruleFrame rule frame that this ContradictionRulePanel is contained in + */ + ContradictionRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Contradictions.gif")); + this.name = "Contradiction Rules"; + this.toolTip = "Contradiction Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java index a89811a64..2795f2df7 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java @@ -5,20 +5,20 @@ import org.apache.logging.log4j.Logger; public class DirectRulePanel extends RulePanel { - private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); - /** - * DirectRulePanel Constructor creates a basic rule panel - * - * @param ruleFrame rule frame that this basic rule panel is contained in - */ - DirectRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Direct Rules"; - this.toolTip = "Direct Rules"; - } + /** + * DirectRulePanel Constructor creates a basic rule panel + * + * @param ruleFrame rule frame that this basic rule panel is contained in + */ + DirectRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Direct Rules"; + this.toolTip = "Direct Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java index 6100b6964..e9c274250 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java @@ -4,36 +4,36 @@ import javax.swing.*; public class RuleButton extends JButton { - private Rule rule; + private Rule rule; - /** - * RuleButton Constructor - creates a button for a rule - * - * @param rule rule to create the button - */ - RuleButton(Rule rule) { - super( - rule.getRuleName(), - rule.getImageIcon()); // display rules' name under rule when load the icon - this.rule = rule; - this.setFocusPainted(false); - } + /** + * RuleButton Constructor - creates a button for a rule + * + * @param rule rule to create the button + */ + RuleButton(Rule rule) { + super( + rule.getRuleName(), + rule.getImageIcon()); // display rules' name under rule when load the icon + this.rule = rule; + this.setFocusPainted(false); + } - /** - * Gets the Rule from this button - * - * @return Rule from this button - */ - public Rule getRule() { - return rule; - } + /** + * Gets the Rule from this button + * + * @return Rule from this button + */ + public Rule getRule() { + return rule; + } - /** - * Sets the Rule for this button - * - * @param rule Rule for this button - */ - void setRule(Rule rule) { - this.rule = rule; - } + /** + * Sets the Rule for this button + * + * @param rule Rule for this button + */ + void setRule(Rule rule) { + this.rule = rule; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java index 2f31f24dc..6279f93a4 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java @@ -11,165 +11,168 @@ import javax.swing.border.TitledBorder; public class RuleFrame extends JPanel { - private static final String checkBox = " \u2714 "; - private static final String xBox = " \u2718 "; - private static final String htmlHead = ""; - private static final String htmlTail = ""; - - private DirectRulePanel DirectRulePanel; - private ContradictionRulePanel contradictionPanel; - private CaseRulePanel casePanel; - - private SearchBarPanel searchPanel; - - private JTabbedPane tabbedPane; - private JLabel status; - private ButtonGroup buttonGroup; - - private RuleController controller; - - public RuleFrame(RuleController controller) { - - MaterialTabbedPaneUI tabOverride = - new MaterialTabbedPaneUI() { - // this prevents the tabs from moving around when you select them - @Override - protected boolean shouldRotateTabRuns(int i) { - return false; - } - }; - - this.controller = controller; - - this.tabbedPane = new JTabbedPane(); - this.tabbedPane.setUI(tabOverride); - this.status = new JLabel(); - this.buttonGroup = new ButtonGroup(); - - DirectRulePanel = new DirectRulePanel(this); - JScrollPane newbrp = new JScrollPane(DirectRulePanel); - newbrp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab( - DirectRulePanel.getName(), DirectRulePanel.getIcon(), newbrp, DirectRulePanel.getToolTip()); - - casePanel = new CaseRulePanel(this); - JScrollPane newcp = new JScrollPane(casePanel); - newcp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(casePanel.name, casePanel.icon, newcp, casePanel.toolTip); - - contradictionPanel = new ContradictionRulePanel(this); - JScrollPane newp = new JScrollPane(contradictionPanel); - newp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab( - contradictionPanel.name, contradictionPanel.icon, newp, contradictionPanel.toolTip); - - searchPanel = new SearchBarPanel(this); - JScrollPane newsp = new JScrollPane(searchPanel); - newsp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(searchPanel.name, searchPanel.icon, newsp, searchPanel.toolTip); - - setLayout(new BorderLayout()); - setMinimumSize(new Dimension(250, 256)); - setPreferredSize(new Dimension(355, 256)); - - add(tabbedPane); - add(status, BorderLayout.SOUTH); - - TitledBorder title = BorderFactory.createTitledBorder("Rules"); - title.setTitleJustification(TitledBorder.CENTER); - setBorder(title); - } - - /** - * Gets the button group for the rule frame - * - * @return button group - */ - public ButtonGroup getButtonGroup() { - return buttonGroup; - } - - public void setSelectionByRule(Rule rule) { - DirectRulePanel.setSelectionByRule(rule); - casePanel.setSelectionByRule(rule); - contradictionPanel.setSelectionByRule(rule); - } - - /** Reset the rules button and status string */ - public void resetRuleButtons() { - resetStatus(); - } - - /** Reset the status label to the empty string */ - public void resetStatus() { - // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().updateStatus(); - } - - /** Resets the dimension of the rule frame */ - public void resetSize() { - int buttonWidth = - ((RulePanel) tabbedPane.getSelectedComponent()).getRuleButtons()[0].getWidth(); - this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); - } - - /** - * Set the status label to a value. Use resetStatus to clear it. - * - * @param check true iff we want a check box, if false we'll have a red x box - * @param text the text we're setting the label to display - */ - public void setStatus(boolean check, String text) { - String box = (check ? checkBox : xBox); - // status.setText(htmlHead + box + text + htmlTail); - // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().getStatus().setText(htmlHead + box + text + htmlTail); - } - - /** - * Sets all the rules for the rule frame - * - * @param puzzle edu.rpi.legup.puzzle game - */ - public void setRules(Puzzle puzzle) { - DirectRulePanel.setRules(puzzle.getDirectRules()); - contradictionPanel.setRules(puzzle.getContradictionRules()); - casePanel.setRules(puzzle.getCaseRules()); - } - - /** - * Board puzzleElement has changed - * - * @param board board state - */ - public void boardDataChanged(Board board) { - this.resetStatus(); - } - - /** - * Gets the RuleController for this RuleFrame - * - * @return rule controller - */ - public RuleController getController() { - return controller; - } - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - public DirectRulePanel getDirectRulePanel() { - return DirectRulePanel; - } - - public CaseRulePanel getCasePanel() { - return casePanel; - } - - public ContradictionRulePanel getContradictionPanel() { - return contradictionPanel; - } - - public SearchBarPanel getSearchPanel() { - return searchPanel; - } + private static final String checkBox = " \u2714 "; + private static final String xBox = " \u2718 "; + private static final String htmlHead = ""; + private static final String htmlTail = ""; + + private DirectRulePanel DirectRulePanel; + private ContradictionRulePanel contradictionPanel; + private CaseRulePanel casePanel; + + private SearchBarPanel searchPanel; + + private JTabbedPane tabbedPane; + private JLabel status; + private ButtonGroup buttonGroup; + + private RuleController controller; + + public RuleFrame(RuleController controller) { + + MaterialTabbedPaneUI tabOverride = + new MaterialTabbedPaneUI() { + // this prevents the tabs from moving around when you select them + @Override + protected boolean shouldRotateTabRuns(int i) { + return false; + } + }; + + this.controller = controller; + + this.tabbedPane = new JTabbedPane(); + this.tabbedPane.setUI(tabOverride); + this.status = new JLabel(); + this.buttonGroup = new ButtonGroup(); + + DirectRulePanel = new DirectRulePanel(this); + JScrollPane newbrp = new JScrollPane(DirectRulePanel); + newbrp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab( + DirectRulePanel.getName(), + DirectRulePanel.getIcon(), + newbrp, + DirectRulePanel.getToolTip()); + + casePanel = new CaseRulePanel(this); + JScrollPane newcp = new JScrollPane(casePanel); + newcp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab(casePanel.name, casePanel.icon, newcp, casePanel.toolTip); + + contradictionPanel = new ContradictionRulePanel(this); + JScrollPane newp = new JScrollPane(contradictionPanel); + newp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab( + contradictionPanel.name, contradictionPanel.icon, newp, contradictionPanel.toolTip); + + searchPanel = new SearchBarPanel(this); + JScrollPane newsp = new JScrollPane(searchPanel); + newsp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab(searchPanel.name, searchPanel.icon, newsp, searchPanel.toolTip); + + setLayout(new BorderLayout()); + setMinimumSize(new Dimension(250, 256)); + setPreferredSize(new Dimension(355, 256)); + + add(tabbedPane); + add(status, BorderLayout.SOUTH); + + TitledBorder title = BorderFactory.createTitledBorder("Rules"); + title.setTitleJustification(TitledBorder.CENTER); + setBorder(title); + } + + /** + * Gets the button group for the rule frame + * + * @return button group + */ + public ButtonGroup getButtonGroup() { + return buttonGroup; + } + + public void setSelectionByRule(Rule rule) { + DirectRulePanel.setSelectionByRule(rule); + casePanel.setSelectionByRule(rule); + contradictionPanel.setSelectionByRule(rule); + } + + /** Reset the rules button and status string */ + public void resetRuleButtons() { + resetStatus(); + } + + /** Reset the status label to the empty string */ + public void resetStatus() { + // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().updateStatus(); + } + + /** Resets the dimension of the rule frame */ + public void resetSize() { + int buttonWidth = + ((RulePanel) tabbedPane.getSelectedComponent()).getRuleButtons()[0].getWidth(); + this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); + } + + /** + * Set the status label to a value. Use resetStatus to clear it. + * + * @param check true iff we want a check box, if false we'll have a red x box + * @param text the text we're setting the label to display + */ + public void setStatus(boolean check, String text) { + String box = (check ? checkBox : xBox); + // status.setText(htmlHead + box + text + htmlTail); + // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().getStatus().setText(htmlHead + box + text + htmlTail); + } + + /** + * Sets all the rules for the rule frame + * + * @param puzzle edu.rpi.legup.puzzle game + */ + public void setRules(Puzzle puzzle) { + DirectRulePanel.setRules(puzzle.getDirectRules()); + contradictionPanel.setRules(puzzle.getContradictionRules()); + casePanel.setRules(puzzle.getCaseRules()); + } + + /** + * Board puzzleElement has changed + * + * @param board board state + */ + public void boardDataChanged(Board board) { + this.resetStatus(); + } + + /** + * Gets the RuleController for this RuleFrame + * + * @return rule controller + */ + public RuleController getController() { + return controller; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public DirectRulePanel getDirectRulePanel() { + return DirectRulePanel; + } + + public CaseRulePanel getCasePanel() { + return casePanel; + } + + public ContradictionRulePanel getContradictionPanel() { + return contradictionPanel; + } + + public SearchBarPanel getSearchPanel() { + return searchPanel; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java index 50bd8a110..5d985d5c2 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java @@ -10,336 +10,343 @@ import javax.swing.*; public abstract class RulePanel extends JPanel { - protected ImageIcon icon; - protected String name; - protected String toolTip; - - protected RuleButton[] ruleButtons; - protected JPanel searchBarPanel; - JTextField textField; - protected RuleFrame ruleFrame; - protected List rules; - - /** - * RulePanel Constructor creates a RulePanel - * - * @param ruleFrame rule frame that this RulePanel is contained in - */ - public RulePanel(RuleFrame ruleFrame) { - this.ruleFrame = ruleFrame; - this.rules = new ArrayList<>(); - setLayout(new WrapLayout()); - } - - /** - * Gets the rule rule buttons - * - * @return rule ruleButtons - */ - public RuleButton[] getRuleButtons() { - return ruleButtons; - } - - /** - * Sets the rules for this rule panel - * - * @param rules list of the rules - */ - public void setRules(List rules) { - this.rules = rules; - clearButtons(); - - ruleButtons = new RuleButton[rules.size()]; - - for (int i = 0; i < rules.size(); i++) { - Rule rule = rules.get(i); - - ruleButtons[i] = new RuleButton(rule); - ruleButtons[i].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[i].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[i].setVerticalTextPosition(JButton.BOTTOM); - - ruleFrame.getButtonGroup().add(ruleButtons[i]); - ruleButtons[i].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); // showing description - ruleButtons[i].addActionListener(ruleFrame.getController()); - add(ruleButtons[i]); + protected ImageIcon icon; + protected String name; + protected String toolTip; + + protected RuleButton[] ruleButtons; + protected JPanel searchBarPanel; + JTextField textField; + protected RuleFrame ruleFrame; + protected List rules; + + /** + * RulePanel Constructor creates a RulePanel + * + * @param ruleFrame rule frame that this RulePanel is contained in + */ + public RulePanel(RuleFrame ruleFrame) { + this.ruleFrame = ruleFrame; + this.rules = new ArrayList<>(); + setLayout(new WrapLayout()); } - revalidate(); - } - public void updateRules() { - for (Rule rule : rules) { - rule.loadImage(); + /** + * Gets the rule rule buttons + * + * @return rule ruleButtons + */ + public RuleButton[] getRuleButtons() { + return ruleButtons; } - setRules(rules); - } - - /** - * Search a certain rule in all the puzzles and set it for the searchBarPanel - * - * @param puzzle puzzle where the rule is being searched for - * @param ruleName rule that is being compared to each puzzle - *

This function is the searching algorithm for "public void setSearchBar(Puzzle - * allPuzzle)" (below) - *

It takes two param Puzzle puzzle and String ruleName puzzle contains rules, this - * function will compare each rule of puzzle with ruleName, to find exact same, similar rules, - * or all the rules with same start letter (if input is a signal letter) - */ - public void searchForRule(Puzzle puzzle, String ruleName) { - - List> allrules = new ArrayList>(3); - allrules.add(0, puzzle.getDirectRules()); - allrules.add(1, puzzle.getCaseRules()); - allrules.add(2, puzzle.getContradictionRules()); - - ruleButtons = new RuleButton[100]; - int similarfound = 0; - - for (int i = 0; i < allrules.size(); i++) { - for (int j = 0; j < allrules.get(i).size(); j++) { - Rule rule = allrules.get(i).get(j); - if ((ruleName).equals(rule.getRuleName().toUpperCase())) { - - ruleButtons[0] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[0]); - - ruleButtons[0].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[0].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[0].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[0].setToolTipText(rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[0].addActionListener(ruleFrame.getController()); - add(ruleButtons[0]); - revalidate(); - return; - - } else { - if (similarityCheck(ruleName, rule.getRuleName().toUpperCase()) > 0.2) { - ruleButtons[similarfound] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); - - ruleButtons[similarfound].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[similarfound].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[similarfound].addActionListener(ruleFrame.getController()); - add(ruleButtons[similarfound]); - similarfound += 1; - revalidate(); - } else { - if ((ruleName.charAt(0)) == (rule.getRuleName().toUpperCase()).charAt(0)) { - ruleButtons[similarfound] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); - - ruleButtons[similarfound].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[similarfound].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[similarfound].addActionListener(ruleFrame.getController()); - add(ruleButtons[similarfound]); - similarfound += 1; - revalidate(); - } - } + + /** + * Sets the rules for this rule panel + * + * @param rules list of the rules + */ + public void setRules(List rules) { + this.rules = rules; + clearButtons(); + + ruleButtons = new RuleButton[rules.size()]; + + for (int i = 0; i < rules.size(); i++) { + Rule rule = rules.get(i); + + ruleButtons[i] = new RuleButton(rule); + ruleButtons[i].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[i].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[i].setVerticalTextPosition(JButton.BOTTOM); + + ruleFrame.getButtonGroup().add(ruleButtons[i]); + ruleButtons[i].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); // showing description + ruleButtons[i].addActionListener(ruleFrame.getController()); + add(ruleButtons[i]); } - } + revalidate(); } - if (ruleButtons[0] == null) { - JOptionPane.showMessageDialog( - null, "Please input the correct rule name", "Confirm", JOptionPane.INFORMATION_MESSAGE); - } - } - - /** - * Calculates the similarity (a number within 0 and 1) between two strings. This function will - * take two para String s1 and String s2, which s1 is the user's input and s2 is the compared - * really rule name - * - * @param s1 user's input - * @param s2 the compared really rule name - * @return a similarity degree between 0 and 1 similarityCheck will use a helper function to - * calculate a similarity degree(from 0 to 1). closer to 0 means less similar, and closer to 1 - * means more similar. - */ - public static double similarityCheck(String s1, String s2) { - String longer = s1, shorter = s2; - if (s1.length() < s2.length()) { // longer should always have greater length - longer = s2; - shorter = s1; - } - int longerLength = longer.length(); - if (longerLength == 0) { - return 1.0; /* both strings are zero length */ + public void updateRules() { + for (Rule rule : rules) { + rule.loadImage(); + } + setRules(rules); } - return (longerLength - editDistance(longer, shorter)) / (double) longerLength; - } - - /** - * Help function for similarityCheck(); - * - * @param s1 user's input - * @param s2 the compared really rule name - * @return a similarity degree between 0 and 1 - */ - public static int editDistance(String s1, String s2) { - s1 = s1.toLowerCase(); - s2 = s2.toLowerCase(); - - int[] costs = new int[s2.length() + 1]; - for (int i = 0; i <= s1.length(); i++) { - int lastValue = i; - for (int j = 0; j <= s2.length(); j++) { - if (i == 0) { - costs[j] = j; - } else { - if (j > 0) { - int newValue = costs[j - 1]; - if (s1.charAt(i - 1) != s2.charAt(j - 1)) { - newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; + + /** + * Search a certain rule in all the puzzles and set it for the searchBarPanel + * + * @param puzzle puzzle where the rule is being searched for + * @param ruleName rule that is being compared to each puzzle + *

This function is the searching algorithm for "public void setSearchBar(Puzzle + * allPuzzle)" (below) + *

It takes two param Puzzle puzzle and String ruleName puzzle contains rules, this + * function will compare each rule of puzzle with ruleName, to find exact same, similar + * rules, or all the rules with same start letter (if input is a signal letter) + */ + public void searchForRule(Puzzle puzzle, String ruleName) { + + List> allrules = new ArrayList>(3); + allrules.add(0, puzzle.getDirectRules()); + allrules.add(1, puzzle.getCaseRules()); + allrules.add(2, puzzle.getContradictionRules()); + + ruleButtons = new RuleButton[100]; + int similarfound = 0; + + for (int i = 0; i < allrules.size(); i++) { + for (int j = 0; j < allrules.get(i).size(); j++) { + Rule rule = allrules.get(i).get(j); + if ((ruleName).equals(rule.getRuleName().toUpperCase())) { + + ruleButtons[0] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[0]); + + ruleButtons[0].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[0].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[0].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[0].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[0].addActionListener(ruleFrame.getController()); + add(ruleButtons[0]); + revalidate(); + return; + + } else { + if (similarityCheck(ruleName, rule.getRuleName().toUpperCase()) > 0.2) { + ruleButtons[similarfound] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); + + ruleButtons[similarfound].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[similarfound].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[similarfound].addActionListener(ruleFrame.getController()); + add(ruleButtons[similarfound]); + similarfound += 1; + revalidate(); + } else { + if ((ruleName.charAt(0)) == (rule.getRuleName().toUpperCase()).charAt(0)) { + ruleButtons[similarfound] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); + + ruleButtons[similarfound].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[similarfound].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[similarfound].addActionListener(ruleFrame.getController()); + add(ruleButtons[similarfound]); + similarfound += 1; + revalidate(); + } + } + } } - costs[j - 1] = lastValue; - lastValue = newValue; - } } - } - if (i > 0) { - costs[s2.length()] = lastValue; - } + + if (ruleButtons[0] == null) { + JOptionPane.showMessageDialog( + null, + "Please input the correct rule name", + "Confirm", + JOptionPane.INFORMATION_MESSAGE); + } } - return costs[s2.length()]; - } - - /** - * Sets the search bar for SearchBarPanel search bar allows user to input a name to get relative - * rules once a name is entered and click ok will load (a/several) rule icon, which has all the - * functions just as other rule icons. - * - * @param allPuzzle name of rule input - */ - public void setSearchBar(Puzzle allPuzzle) { - - searchBarPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 6, 6)); - - textField = new JTextField(); - ruleFrame.addComponentListener( - new ComponentAdapter() { - public void componentResized(ComponentEvent componentEvent) { - Component c = componentEvent.getComponent(); - textField.setColumns((8 + (c.getWidth() - 250) / 10) - 1); - } - }); - - add(searchBarPanel); - JLabel findLabel = new JLabel("Search:"); - searchBarPanel.add(findLabel); - searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); - searchBarPanel.add(textField); - searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); - JButton findButton = new JButton("Go"); - ActionListener action = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent event) { - if (ruleButtons != null) { - for (int i = 0; i != ruleButtons.length; i++) { - if (ruleButtons[i] == null) { - continue; + + /** + * Calculates the similarity (a number within 0 and 1) between two strings. This function will + * take two para String s1 and String s2, which s1 is the user's input and s2 is the compared + * really rule name + * + * @param s1 user's input + * @param s2 the compared really rule name + * @return a similarity degree between 0 and 1 similarityCheck will use a helper function to + * calculate a similarity degree(from 0 to 1). closer to 0 means less similar, and closer to + * 1 means more similar. + */ + public static double similarityCheck(String s1, String s2) { + String longer = s1, shorter = s2; + if (s1.length() < s2.length()) { // longer should always have greater length + longer = s2; + shorter = s1; + } + int longerLength = longer.length(); + if (longerLength == 0) { + return 1.0; /* both strings are zero length */ + } + return (longerLength - editDistance(longer, shorter)) / (double) longerLength; + } + + /** + * Help function for similarityCheck(); + * + * @param s1 user's input + * @param s2 the compared really rule name + * @return a similarity degree between 0 and 1 + */ + public static int editDistance(String s1, String s2) { + s1 = s1.toLowerCase(); + s2 = s2.toLowerCase(); + + int[] costs = new int[s2.length() + 1]; + for (int i = 0; i <= s1.length(); i++) { + int lastValue = i; + for (int j = 0; j <= s2.length(); j++) { + if (i == 0) { + costs[j] = j; + } else { + if (j > 0) { + int newValue = costs[j - 1]; + if (s1.charAt(i - 1) != s2.charAt(j - 1)) { + newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; + } + costs[j - 1] = lastValue; + lastValue = newValue; + } } - ruleButtons[i].removeActionListener(ruleFrame.getController()); - } } - String inputRule = textField.getText().toUpperCase().trim(); + if (i > 0) { + costs[s2.length()] = lastValue; + } + } + return costs[s2.length()]; + } - if (!inputRule.isEmpty()) { - if (ruleButtons != null) { + /** + * Sets the search bar for SearchBarPanel search bar allows user to input a name to get relative + * rules once a name is entered and click ok will load (a/several) rule icon, which has all the + * functions just as other rule icons. + * + * @param allPuzzle name of rule input + */ + public void setSearchBar(Puzzle allPuzzle) { + + searchBarPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 6, 6)); + + textField = new JTextField(); + ruleFrame.addComponentListener( + new ComponentAdapter() { + public void componentResized(ComponentEvent componentEvent) { + Component c = componentEvent.getComponent(); + textField.setColumns((8 + (c.getWidth() - 250) / 10) - 1); + } + }); + + add(searchBarPanel); + JLabel findLabel = new JLabel("Search:"); + searchBarPanel.add(findLabel); + searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); + searchBarPanel.add(textField); + searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); + JButton findButton = new JButton("Go"); + ActionListener action = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + if (ruleButtons != null) { + for (int i = 0; i != ruleButtons.length; i++) { + if (ruleButtons[i] == null) { + continue; + } + ruleButtons[i].removeActionListener(ruleFrame.getController()); + } + } + String inputRule = textField.getText().toUpperCase().trim(); + + if (!inputRule.isEmpty()) { + if (ruleButtons != null) { + + for (int x = 0; x < ruleButtons.length; ++x) { + if (ruleButtons[x] == null) { + continue; + } + remove(ruleButtons[x]); + } + } + searchForRule(allPuzzle, inputRule); + } else { + JOptionPane.showMessageDialog( + null, + "Please give a name", + "Confirm", + JOptionPane.INFORMATION_MESSAGE); + } + } + }; + textField.addActionListener(action); + findButton.addActionListener(action); + searchBarPanel.add(findButton); + } - for (int x = 0; x < ruleButtons.length; ++x) { - if (ruleButtons[x] == null) { - continue; - } - remove(ruleButtons[x]); + /** + * Sets the selection by the specified rule + * + * @param rule rule to set the selection to + */ + public void setSelectionByRule(Rule rule) { + if (ruleButtons != null) { + for (int i = 0; i < ruleButtons.length; i++) { + if (rules.get(i).equals(rule)) { + ruleButtons[i].setSelected(true); + break; } - } - searchForRule(allPuzzle, inputRule); - } else { - JOptionPane.showMessageDialog( - null, "Please give a name", "Confirm", JOptionPane.INFORMATION_MESSAGE); } - } - }; - textField.addActionListener(action); - findButton.addActionListener(action); - searchBarPanel.add(findButton); - } - - /** - * Sets the selection by the specified rule - * - * @param rule rule to set the selection to - */ - public void setSelectionByRule(Rule rule) { - if (ruleButtons != null) { - for (int i = 0; i < ruleButtons.length; i++) { - if (rules.get(i).equals(rule)) { - ruleButtons[i].setSelected(true); - break; } - } } - } - - /** Clears the rule buttons off this panel */ - protected void clearButtons() { - if (ruleButtons != null) { - removeAll(); - for (int x = 0; x < ruleButtons.length; ++x) { - ruleButtons[x].removeActionListener(ruleFrame.getController()); - } + + /** Clears the rule buttons off this panel */ + protected void clearButtons() { + if (ruleButtons != null) { + removeAll(); + for (int x = 0; x < ruleButtons.length; ++x) { + ruleButtons[x].removeActionListener(ruleFrame.getController()); + } + } + } + + /** + * Gets the rules associated with this panel + * + * @return the rules + */ + public List getRules() { + return rules; + } + + public ImageIcon getIcon() { + return icon; + } + + public void setIcon(ImageIcon icon) { + this.icon = icon; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + public String getToolTip() { + return toolTip; + } + + public void setToolTip(String toolTip) { + this.toolTip = toolTip; } - } - - /** - * Gets the rules associated with this panel - * - * @return the rules - */ - public List getRules() { - return rules; - } - - public ImageIcon getIcon() { - return icon; - } - - public void setIcon(ImageIcon icon) { - this.icon = icon; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getToolTip() { - return toolTip; - } - - public void setToolTip(String toolTip) { - this.toolTip = toolTip; - } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java index b0dddc2c7..aba4707cd 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java @@ -3,19 +3,19 @@ import javax.swing.*; public class SearchBarPanel extends RulePanel { - /** - * SearchBarPanel Constructor creates a SearchBarPanel - * - * @param ruleFrame rule frame that this SearchBarPanel is contained in - *

This class is used to create a panel named "search bar" - */ - SearchBarPanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Zoom In.png")); - this.name = "Search Rules"; - this.toolTip = "Search Rules"; - } + /** + * SearchBarPanel Constructor creates a SearchBarPanel + * + * @param ruleFrame rule frame that this SearchBarPanel is contained in + *

This class is used to create a panel named "search bar" + */ + SearchBarPanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Zoom In.png")); + this.name = "Search Rules"; + this.toolTip = "Search Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java index 00b8ec0bb..33c04717d 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java @@ -5,169 +5,169 @@ import java.awt.*; public abstract class TreeElementView implements Shape { - protected TreeElement treeElement; - protected double span; - protected int depth; - protected boolean isSelected; - protected boolean isHover; - protected TreeElementType type; - protected boolean isVisible; - protected boolean isCollapsed; - - /** - * TreeElementView Constructor creates a tree puzzleElement view - * - * @param type tree puzzleElement type - * @param treeElement tree puzzleElement puzzleElement associated with this view - */ - protected TreeElementView(TreeElementType type, TreeElement treeElement) { - this.type = type; - this.treeElement = treeElement; - this.isSelected = false; - this.isHover = false; - this.isVisible = true; - } - - /** - * Draws the tree puzzleElement view - * - * @param graphics2D graphics2D object used to draw the tree puzzleElement view - */ - public abstract void draw(Graphics2D graphics2D); - - /** - * Gets the span for the sub tree rooted at this view - * - * @return span bounded y span - */ - public double getSpan() { - return span; - } - - /** - * Sets the span for the sub tree rooted at this view. - * - * @param span bounded y span - */ - public void setSpan(double span) { - this.span = span; - } - - /** - * Gets the depth of this tree puzzleElement in the tree - * - * @return depth of this tree puzzleElement - */ - public int getDepth() { - return depth; - } - - /** - * Sets the depth of this tree puzzleElement in the tree - * - * @param depth depth of this tree puzzleElement - */ - public void setDepth(int depth) { - this.depth = depth; - } - - /** - * Gets the tree puzzleElement type for this view - * - * @return tree puzzleElement type - */ - public TreeElementType getType() { - return type; - } - - /** - * Gets the tree puzzleElement associated with this view - * - * @return tree puzzleElement associated with this view - */ - public TreeElement getTreeElement() { - return treeElement; - } - - /** - * Sets the tree puzzleElement associated with this view - * - * @param treeElement tree puzzleElement associated with this view - */ - public void setTreeElement(TreeElement treeElement) { - this.treeElement = treeElement; - } - - /** - * Gets the mouse selection - * - * @return mouse selection - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets the mouse selection - * - * @param isSelected mouse selection - */ - public void setSelected(boolean isSelected) { - this.isSelected = isSelected; - } - - /** - * Gets the mouse hover - * - * @return mouse hover - */ - public boolean isHover() { - return isHover; - } - - /** - * Sets the mouse hover - * - * @param isHovered mouse hover - */ - public void setHover(boolean isHovered) { - this.isHover = isHovered; - } - - /** - * Gets the visibility of the tree puzzleElement. Tells the TreeView whether or not to draw the - * tree puzzleElement - * - * @return visibility of the tree puzzleElement - */ - public boolean isVisible() { - return isVisible; - } - - /** - * Sets the visibility of the tree puzzleElement - * - * @param isVisible visibility of the tree puzzleElement - */ - public void setVisible(boolean isVisible) { - this.isVisible = isVisible; - } - - /** - * Is this tree node view collapsed in the view - * - * @return true if the node is collapsed, false otherwise - */ - public boolean isCollapsed() { - return isCollapsed; - } - - /** - * Sets the tree node view collapsed field - * - * @param isCollapsed true if the node is collapsed, false otherwise - */ - public void setCollapsed(boolean isCollapsed) { - this.isCollapsed = isCollapsed; - } + protected TreeElement treeElement; + protected double span; + protected int depth; + protected boolean isSelected; + protected boolean isHover; + protected TreeElementType type; + protected boolean isVisible; + protected boolean isCollapsed; + + /** + * TreeElementView Constructor creates a tree puzzleElement view + * + * @param type tree puzzleElement type + * @param treeElement tree puzzleElement puzzleElement associated with this view + */ + protected TreeElementView(TreeElementType type, TreeElement treeElement) { + this.type = type; + this.treeElement = treeElement; + this.isSelected = false; + this.isHover = false; + this.isVisible = true; + } + + /** + * Draws the tree puzzleElement view + * + * @param graphics2D graphics2D object used to draw the tree puzzleElement view + */ + public abstract void draw(Graphics2D graphics2D); + + /** + * Gets the span for the sub tree rooted at this view + * + * @return span bounded y span + */ + public double getSpan() { + return span; + } + + /** + * Sets the span for the sub tree rooted at this view. + * + * @param span bounded y span + */ + public void setSpan(double span) { + this.span = span; + } + + /** + * Gets the depth of this tree puzzleElement in the tree + * + * @return depth of this tree puzzleElement + */ + public int getDepth() { + return depth; + } + + /** + * Sets the depth of this tree puzzleElement in the tree + * + * @param depth depth of this tree puzzleElement + */ + public void setDepth(int depth) { + this.depth = depth; + } + + /** + * Gets the tree puzzleElement type for this view + * + * @return tree puzzleElement type + */ + public TreeElementType getType() { + return type; + } + + /** + * Gets the tree puzzleElement associated with this view + * + * @return tree puzzleElement associated with this view + */ + public TreeElement getTreeElement() { + return treeElement; + } + + /** + * Sets the tree puzzleElement associated with this view + * + * @param treeElement tree puzzleElement associated with this view + */ + public void setTreeElement(TreeElement treeElement) { + this.treeElement = treeElement; + } + + /** + * Gets the mouse selection + * + * @return mouse selection + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets the mouse selection + * + * @param isSelected mouse selection + */ + public void setSelected(boolean isSelected) { + this.isSelected = isSelected; + } + + /** + * Gets the mouse hover + * + * @return mouse hover + */ + public boolean isHover() { + return isHover; + } + + /** + * Sets the mouse hover + * + * @param isHovered mouse hover + */ + public void setHover(boolean isHovered) { + this.isHover = isHovered; + } + + /** + * Gets the visibility of the tree puzzleElement. Tells the TreeView whether or not to draw the + * tree puzzleElement + * + * @return visibility of the tree puzzleElement + */ + public boolean isVisible() { + return isVisible; + } + + /** + * Sets the visibility of the tree puzzleElement + * + * @param isVisible visibility of the tree puzzleElement + */ + public void setVisible(boolean isVisible) { + this.isVisible = isVisible; + } + + /** + * Is this tree node view collapsed in the view + * + * @return true if the node is collapsed, false otherwise + */ + public boolean isCollapsed() { + return isCollapsed; + } + + /** + * Sets the tree node view collapsed field + * + * @param isCollapsed true if the node is collapsed, false otherwise + */ + public void setCollapsed(boolean isCollapsed) { + this.isCollapsed = isCollapsed; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java index dbb4dfcb4..990d96620 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java @@ -8,285 +8,305 @@ import java.util.ArrayList; public class TreeNodeView extends TreeElementView { - static final int RADIUS = 25; - static final int DIAMETER = 2 * RADIUS; - - private static final Stroke MAIN_STROKE = new BasicStroke(3); - private static final Stroke SELECTION_STROKE = new BasicStroke(2); - - private static final Color NODE_COLOR_ROOT = new Color(100, 100, 100); - private static final Color NODE_MINOR_COLOR_ROOT = new Color(75, 75, 75); - - private static final Color NODE_COLOR_DEFAULT = new Color(0xFFEB3B); - private static final Color NODE_MINOR_COLOR_DEFAULT = new Color(216, 197, 52); - - private static final Color NODE_COLOR_CONTRADICTION = new Color(178, 10, 16); - private static final Color NODE_MINOR_COLOR_CONTRADICTION = new Color(119, 13, 16); - - private static final Color OUTLINE_COLOR = new Color(0x212121); - private static final Color SELECTION_COLOR = new Color(0x1E88E5); - private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); - - private static final Color HOVER_COLOR = new Color(0x90CAF9); - private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); - - private Point location; - - private TreeTransitionView parentView; - private ArrayList childrenViews; - - private boolean isCollapsed; - private boolean isContradictoryState; - - /** - * TreeNodeView Constructor creates a node for display - * - * @param treeNode treeElement associated with this transition - */ - public TreeNodeView(TreeNode treeNode) { - super(TreeElementType.NODE, treeNode); - this.treeElement = treeNode; - this.location = new Point(); - this.parentView = null; - this.childrenViews = new ArrayList<>(); - this.isCollapsed = false; - this.isContradictoryState = false; - this.isVisible = true; - } - - /** - * Draws the TreeNodeView - * - * @param graphics2D graphics2D used for drawing - */ - public void draw(Graphics2D graphics2D) { - if (isVisible() && treeElement != null) { - if (getTreeElement().getParent() != null - && getTreeElement().getParent().isJustified() - && getTreeElement().getParent().getRule().getRuleType() == RuleType.CONTRADICTION) { - isContradictoryState = true; - graphics2D.setColor(NODE_COLOR_CONTRADICTION); - graphics2D.drawLine( - location.x - RADIUS, location.y - RADIUS, location.x + RADIUS, location.y + RADIUS); - graphics2D.drawLine( - location.x + RADIUS, location.y - RADIUS, location.x - RADIUS, location.y + RADIUS); - } else { - isContradictoryState = false; - graphics2D.setStroke(MAIN_STROKE); - boolean isContraBranch = getTreeElement().isContradictoryBranch(); - - if (isSelected) { - graphics2D.setColor(SELECTION_COLOR); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_SELECTION_COLOR); - graphics2D.drawOval( - location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); - } else { - if (isHover) { - graphics2D.setColor(HOVER_COLOR); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_HOVER_COLOR); - graphics2D.drawOval( - location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); - } else { - graphics2D.setColor(isContraBranch ? NODE_COLOR_CONTRADICTION : NODE_COLOR_DEFAULT); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - } + static final int RADIUS = 25; + static final int DIAMETER = 2 * RADIUS; + + private static final Stroke MAIN_STROKE = new BasicStroke(3); + private static final Stroke SELECTION_STROKE = new BasicStroke(2); + + private static final Color NODE_COLOR_ROOT = new Color(100, 100, 100); + private static final Color NODE_MINOR_COLOR_ROOT = new Color(75, 75, 75); + + private static final Color NODE_COLOR_DEFAULT = new Color(0xFFEB3B); + private static final Color NODE_MINOR_COLOR_DEFAULT = new Color(216, 197, 52); + + private static final Color NODE_COLOR_CONTRADICTION = new Color(178, 10, 16); + private static final Color NODE_MINOR_COLOR_CONTRADICTION = new Color(119, 13, 16); + + private static final Color OUTLINE_COLOR = new Color(0x212121); + private static final Color SELECTION_COLOR = new Color(0x1E88E5); + private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); + + private static final Color HOVER_COLOR = new Color(0x90CAF9); + private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); + + private Point location; + + private TreeTransitionView parentView; + private ArrayList childrenViews; + + private boolean isCollapsed; + private boolean isContradictoryState; + + /** + * TreeNodeView Constructor creates a node for display + * + * @param treeNode treeElement associated with this transition + */ + public TreeNodeView(TreeNode treeNode) { + super(TreeElementType.NODE, treeNode); + this.treeElement = treeNode; + this.location = new Point(); + this.parentView = null; + this.childrenViews = new ArrayList<>(); + this.isCollapsed = false; + this.isContradictoryState = false; + this.isVisible = true; + } + + /** + * Draws the TreeNodeView + * + * @param graphics2D graphics2D used for drawing + */ + public void draw(Graphics2D graphics2D) { + if (isVisible() && treeElement != null) { + if (getTreeElement().getParent() != null + && getTreeElement().getParent().isJustified() + && getTreeElement().getParent().getRule().getRuleType() + == RuleType.CONTRADICTION) { + isContradictoryState = true; + graphics2D.setColor(NODE_COLOR_CONTRADICTION); + graphics2D.drawLine( + location.x - RADIUS, + location.y - RADIUS, + location.x + RADIUS, + location.y + RADIUS); + graphics2D.drawLine( + location.x + RADIUS, + location.y - RADIUS, + location.x - RADIUS, + location.y + RADIUS); + } else { + isContradictoryState = false; + graphics2D.setStroke(MAIN_STROKE); + boolean isContraBranch = getTreeElement().isContradictoryBranch(); + + if (isSelected) { + graphics2D.setColor(SELECTION_COLOR); + graphics2D.fillOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_SELECTION_COLOR); + graphics2D.drawOval( + location.x - RADIUS - 4, + location.y - RADIUS - 4, + DIAMETER + 8, + DIAMETER + 8); + } else { + if (isHover) { + graphics2D.setColor(HOVER_COLOR); + graphics2D.fillOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_HOVER_COLOR); + graphics2D.drawOval( + location.x - RADIUS - 4, + location.y - RADIUS - 4, + DIAMETER + 8, + DIAMETER + 8); + } else { + graphics2D.setColor( + isContraBranch ? NODE_COLOR_CONTRADICTION : NODE_COLOR_DEFAULT); + graphics2D.fillOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + } + } + } } - } } - } - - public boolean isContradictoryState() { - return isContradictoryState; - } - - /** - * Gets the list of children views associated with this tree node - * - * @return list of children views for this tree node - */ - public ArrayList getChildrenViews() { - return childrenViews; - } - - /** - * Sets the list of children views associated with this tree node - * - * @param childrenViews list of children views for this tree node - */ - public void setChildrenViews(ArrayList childrenViews) { - this.childrenViews = childrenViews; - } - - /** - * Adds a TreeTransitionView to the list of children views - * - * @param nodeView TreeTransitionView to add to the list of children views - */ - public void addChildrenView(TreeTransitionView nodeView) { - childrenViews.add(nodeView); - } - - /** - * Removes a TreeTransitionView from the list of children views - * - * @param nodeView TreeTransitionView to remove from the list of children views - */ - public void removeChildrenView(TreeTransitionView nodeView) { - childrenViews.remove(nodeView); - } - - /** - * Sets the parent tree transition view - * - * @param parentView parent tree transition view - */ - public void setParentView(TreeTransitionView parentView) { - this.parentView = parentView; - } - - /** - * Gets the parent tree transition view - * - * @return parent tree transition view - */ - public TreeTransitionView getParentView() { - return parentView; - } - - /** - * Gets the tree node associated with this view - * - * @return tree node - */ - public TreeNode getTreeElement() { - return (TreeNode) treeElement; - } - - /** - * Gets the location of the tree node - * - * @return location of the tree node - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the tree node - * - * @param location location of the tree node - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Gets the x location of the tree node - * - * @return x location - */ - public int getX() { - return location.x; - } - - /** - * Sets the x location of the tree node - * - * @param x x location - */ - public void setX(int x) { - location.x = x; - } - - /** - * Gets the y location of the tree node - * - * @return y location - */ - public int getY() { - return location.y; - } - - /** - * Sets the y location of the tree node - * - * @param y y location - */ - public void setY(int y) { - location.y = y; - } - - /** - * Gets the radius of the tree node - * - * @return radius - */ - public int getRadius() { - return RADIUS; - } - - @Override - public Rectangle getBounds() { - return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); - } - - @Override - public Rectangle2D getBounds2D() { - return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); - } - - @Override - public boolean contains(double x, double y) { - return Math.sqrt(Math.pow(x - location.x, 2) + Math.pow(y - location.y, 2)) <= RADIUS; - } - - @Override - public boolean contains(Point2D p) { - return contains(p.getX(), p.getY()); - } - - @Override - public boolean intersects(double x, double y, double w, double h) { - return false; - } - - @Override - public boolean intersects(Rectangle2D r) { - return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); - } - - @Override - public boolean contains(double x, double y, double w, double h) { - return false; - } - - @Override - public boolean contains(Rectangle2D r) { - return false; - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return null; - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return null; - } + + public boolean isContradictoryState() { + return isContradictoryState; + } + + /** + * Gets the list of children views associated with this tree node + * + * @return list of children views for this tree node + */ + public ArrayList getChildrenViews() { + return childrenViews; + } + + /** + * Sets the list of children views associated with this tree node + * + * @param childrenViews list of children views for this tree node + */ + public void setChildrenViews(ArrayList childrenViews) { + this.childrenViews = childrenViews; + } + + /** + * Adds a TreeTransitionView to the list of children views + * + * @param nodeView TreeTransitionView to add to the list of children views + */ + public void addChildrenView(TreeTransitionView nodeView) { + childrenViews.add(nodeView); + } + + /** + * Removes a TreeTransitionView from the list of children views + * + * @param nodeView TreeTransitionView to remove from the list of children views + */ + public void removeChildrenView(TreeTransitionView nodeView) { + childrenViews.remove(nodeView); + } + + /** + * Sets the parent tree transition view + * + * @param parentView parent tree transition view + */ + public void setParentView(TreeTransitionView parentView) { + this.parentView = parentView; + } + + /** + * Gets the parent tree transition view + * + * @return parent tree transition view + */ + public TreeTransitionView getParentView() { + return parentView; + } + + /** + * Gets the tree node associated with this view + * + * @return tree node + */ + public TreeNode getTreeElement() { + return (TreeNode) treeElement; + } + + /** + * Gets the location of the tree node + * + * @return location of the tree node + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the tree node + * + * @param location location of the tree node + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Gets the x location of the tree node + * + * @return x location + */ + public int getX() { + return location.x; + } + + /** + * Sets the x location of the tree node + * + * @param x x location + */ + public void setX(int x) { + location.x = x; + } + + /** + * Gets the y location of the tree node + * + * @return y location + */ + public int getY() { + return location.y; + } + + /** + * Sets the y location of the tree node + * + * @param y y location + */ + public void setY(int y) { + location.y = y; + } + + /** + * Gets the radius of the tree node + * + * @return radius + */ + public int getRadius() { + return RADIUS; + } + + @Override + public Rectangle getBounds() { + return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); + } + + @Override + public Rectangle2D getBounds2D() { + return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); + } + + @Override + public boolean contains(double x, double y) { + return Math.sqrt(Math.pow(x - location.x, 2) + Math.pow(y - location.y, 2)) <= RADIUS; + } + + @Override + public boolean contains(Point2D p) { + return contains(p.getX(), p.getY()); + } + + @Override + public boolean intersects(double x, double y, double w, double h) { + return false; + } + + @Override + public boolean intersects(Rectangle2D r) { + return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); + } + + @Override + public boolean contains(double x, double y, double w, double h) { + return false; + } + + @Override + public boolean contains(Rectangle2D r) { + return false; + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return null; + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java index f73ab02fe..b6a29f2b5 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java @@ -18,123 +18,123 @@ import javax.swing.border.TitledBorder; public class TreePanel extends JPanel { - public boolean modifiedSinceSave = false; - public boolean modifiedSinceUndoPush = false; - public int updateStatusTimer = 0; + public boolean modifiedSinceSave = false; + public boolean modifiedSinceUndoPush = false; + public int updateStatusTimer = 0; - private JPanel main; - private TreeView treeView; - private TreeToolbarPanel toolbar; - // private LegupUI legupUI; + private JPanel main; + private TreeView treeView; + private TreeToolbarPanel toolbar; + // private LegupUI legupUI; - private JLabel status; + private JLabel status; - public TreePanel(/*LegupUI legupUI*/ ) { - // this.legupUI = legupUI; + public TreePanel(/*LegupUI legupUI*/ ) { + // this.legupUI = legupUI; - main = new JPanel(); + main = new JPanel(); - main.setLayout(new BorderLayout()); + main.setLayout(new BorderLayout()); - TreeController treeController = new TreeController(); - treeView = new TreeView(treeController); - treeController.setViewer(treeView); + TreeController treeController = new TreeController(); + treeView = new TreeView(treeController); + treeController.setViewer(treeView); - toolbar = new TreeToolbarPanel(this); + toolbar = new TreeToolbarPanel(this); - DynamicView dynamicTreeView = new DynamicView(treeView, DynamicViewType.PROOF_TREE); - main.add(dynamicTreeView, BorderLayout.CENTER); - dynamicTreeView.add(toolbar, BorderLayout.WEST); + DynamicView dynamicTreeView = new DynamicView(treeView, DynamicViewType.PROOF_TREE); + main.add(dynamicTreeView, BorderLayout.CENTER); + dynamicTreeView.add(toolbar, BorderLayout.WEST); - status = new JLabel(); - status.setPreferredSize(new Dimension(150, 15)); - dynamicTreeView.getZoomWrapper().add(status, BorderLayout.CENTER); + status = new JLabel(); + status.setPreferredSize(new Dimension(150, 15)); + dynamicTreeView.getZoomWrapper().add(status, BorderLayout.CENTER); - TitledBorder title = BorderFactory.createTitledBorder("Proof Tree"); - title.setTitleJustification(TitledBorder.CENTER); - main.setBorder(title); + TitledBorder title = BorderFactory.createTitledBorder("Proof Tree"); + title.setTitleJustification(TitledBorder.CENTER); + main.setBorder(title); - setLayout(new BorderLayout()); - add(main); + setLayout(new BorderLayout()); + add(main); - updateStatusTimer = 0; - } + updateStatusTimer = 0; + } + + public void repaintTreeView(Tree tree) { + treeView.updateTreeView(tree); + } - public void repaintTreeView(Tree tree) { - treeView.updateTreeView(tree); - } + public void boardDataChanged(Board board) { + modifiedSinceSave = true; + modifiedSinceUndoPush = true; + updateStatus(); + // colorTransitions(); + } - public void boardDataChanged(Board board) { - modifiedSinceSave = true; - modifiedSinceUndoPush = true; - updateStatus(); - // colorTransitions(); - } + public void updateStatus() { + updateStatusTimer = ((updateStatusTimer - 1) > 0) ? (updateStatusTimer - 1) : 0; + if (updateStatusTimer > 0) { + return; + } + this.status.setText(""); + } - public void updateStatus() { - updateStatusTimer = ((updateStatusTimer - 1) > 0) ? (updateStatusTimer - 1) : 0; - if (updateStatusTimer > 0) { - return; + public void updateStatus(String statusString) { + status.setForeground(Color.BLACK); + status.setFont(MaterialFonts.REGULAR); + status.setText(statusString); } - this.status.setText(""); - } - - public void updateStatus(String statusString) { - status.setForeground(Color.BLACK); - status.setFont(MaterialFonts.REGULAR); - status.setText(statusString); - } - - public void updateError(String error) { - status.setForeground(Color.RED); - status.setFont(MaterialFonts.ITALIC); - status.setText(error); - } - - public TreeView getTreeView() { - return treeView; - } - - public void add() { - TreeViewSelection selection = treeView.getSelection(); - - AddTreeElementCommand add = new AddTreeElementCommand(selection); - if (add.canExecute()) { - add.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(add); - } else { - updateError(add.getError()); + + public void updateError(String error) { + status.setForeground(Color.RED); + status.setFont(MaterialFonts.ITALIC); + status.setText(error); + } + + public TreeView getTreeView() { + return treeView; + } + + public void add() { + TreeViewSelection selection = treeView.getSelection(); + + AddTreeElementCommand add = new AddTreeElementCommand(selection); + if (add.canExecute()) { + add.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(add); + } else { + updateError(add.getError()); + } } - } - public void delete() { - TreeViewSelection selection = treeView.getSelection(); + public void delete() { + TreeViewSelection selection = treeView.getSelection(); - DeleteTreeElementCommand del = new DeleteTreeElementCommand(selection); - if (del.canExecute()) { - del.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(del); - } else { - updateError(del.getError()); + DeleteTreeElementCommand del = new DeleteTreeElementCommand(selection); + if (del.canExecute()) { + del.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(del); + } else { + updateError(del.getError()); + } } - } - public void merge() { - TreeViewSelection selection = treeView.getSelection(); + public void merge() { + TreeViewSelection selection = treeView.getSelection(); - ICommand merge = new MergeCommand(selection); - if (merge.canExecute()) { - merge.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(merge); - } else { - updateError(merge.getError()); + ICommand merge = new MergeCommand(selection); + if (merge.canExecute()) { + merge.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(merge); + } else { + updateError(merge.getError()); + } } - } - public void collapse() { - TreeViewSelection selection = treeView.getSelection(); - for (TreeElementView view : selection.getSelectedViews()) { - view.setCollapsed(!view.isCollapsed()); + public void collapse() { + TreeViewSelection selection = treeView.getSelection(); + for (TreeElementView view : selection.getSelectedViews()) { + view.setCollapsed(!view.isCollapsed()); + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java index 45bf518b2..002092155 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java @@ -5,18 +5,18 @@ public class TreeToolBarButton extends JButton { - private TreeToolBarName name; - private final Dimension MINIMUM_DIMENSION = new Dimension(60, 60); + private TreeToolBarName name; + private final Dimension MINIMUM_DIMENSION = new Dimension(60, 60); - public TreeToolBarButton(ImageIcon imageIcon, TreeToolBarName name) { - super(imageIcon); - this.name = name; - this.setSize(MINIMUM_DIMENSION.width, MINIMUM_DIMENSION.height); - this.setMinimumSize(this.MINIMUM_DIMENSION); - this.setFocusPainted(false); - } + public TreeToolBarButton(ImageIcon imageIcon, TreeToolBarName name) { + super(imageIcon); + this.name = name; + this.setSize(MINIMUM_DIMENSION.width, MINIMUM_DIMENSION.height); + this.setMinimumSize(this.MINIMUM_DIMENSION); + this.setFocusPainted(false); + } - public TreeToolBarName getToolBarName() { - return name; - } + public TreeToolBarName getToolBarName() { + return name; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java index d1a009b7e..c805021be 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java @@ -1,8 +1,8 @@ package edu.rpi.legup.ui.proofeditorui.treeview; public enum TreeToolBarName { - ADD_CHILD, - DEL_CHILD, - MERGE, - COLLAPSE + ADD_CHILD, + DEL_CHILD, + MERGE, + COLLAPSE } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java index 3923de25b..8f3ebfc23 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java @@ -4,50 +4,58 @@ import javax.swing.*; public class TreeToolbarPanel extends JPanel { - private TreePanel treePanel; - private TreeToolBarButton addChild, delChild, merge, collapse; - - /** - * TreeToolbarPanel Constructor - creates the tree tool mBar panel - * - * @param treePanel treePanel input - */ - public TreeToolbarPanel(TreePanel treePanel) { - this.treePanel = treePanel; - this.setLayout(new GridLayout(4, 1, 0, 2)); - - addChild = - new TreeToolBarButton( - new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/AddChild.png")), - TreeToolBarName.ADD_CHILD); - delChild = - new TreeToolBarButton( - new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/DelChild.png")), - TreeToolBarName.DEL_CHILD); - merge = - new TreeToolBarButton( - new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Merge.png")), - TreeToolBarName.MERGE); - collapse = - new TreeToolBarButton( - new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Collapse.png")), - TreeToolBarName.COLLAPSE); - - add(addChild); - addChild.addActionListener(a -> treePanel.add()); - addChild.setToolTipText("Add tree element"); - - add(delChild); - delChild.addActionListener(a -> treePanel.delete()); - delChild.setToolTipText("Remove selected tree elements"); - - add(merge); - merge.addActionListener(a -> treePanel.merge()); - merge.setToolTipText("Merge selected tree nodes"); - - add(collapse); - collapse.addActionListener(a -> treePanel.collapse()); - collapse.setToolTipText("Collapse nodes"); - collapse.setEnabled(false); - } + private TreePanel treePanel; + private TreeToolBarButton addChild, delChild, merge, collapse; + + /** + * TreeToolbarPanel Constructor - creates the tree tool mBar panel + * + * @param treePanel treePanel input + */ + public TreeToolbarPanel(TreePanel treePanel) { + this.treePanel = treePanel; + this.setLayout(new GridLayout(4, 1, 0, 2)); + + addChild = + new TreeToolBarButton( + new ImageIcon( + ClassLoader.getSystemResource( + "edu/rpi/legup/images/Legup/AddChild.png")), + TreeToolBarName.ADD_CHILD); + delChild = + new TreeToolBarButton( + new ImageIcon( + ClassLoader.getSystemResource( + "edu/rpi/legup/images/Legup/DelChild.png")), + TreeToolBarName.DEL_CHILD); + merge = + new TreeToolBarButton( + new ImageIcon( + ClassLoader.getSystemResource( + "edu/rpi/legup/images/Legup/Merge.png")), + TreeToolBarName.MERGE); + collapse = + new TreeToolBarButton( + new ImageIcon( + ClassLoader.getSystemResource( + "edu/rpi/legup/images/Legup/Collapse.png")), + TreeToolBarName.COLLAPSE); + + add(addChild); + addChild.addActionListener(a -> treePanel.add()); + addChild.setToolTipText("Add tree element"); + + add(delChild); + delChild.addActionListener(a -> treePanel.delete()); + delChild.setToolTipText("Remove selected tree elements"); + + add(merge); + merge.addActionListener(a -> treePanel.merge()); + merge.setToolTipText("Merge selected tree nodes"); + + add(collapse); + collapse.addActionListener(a -> treePanel.collapse()); + collapse.setToolTipText("Collapse nodes"); + collapse.setEnabled(false); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java index 652514be6..b022ac596 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java @@ -11,344 +11,344 @@ import java.util.List; public class TreeTransitionView extends TreeElementView { - static final int RADIUS = 25; - static final int DIAMETER = 2 * RADIUS; - static final int GAP = 5; - - private static final Stroke MAIN_STROKE = new BasicStroke(3); - private static final Stroke SELECTION_STROKE = new BasicStroke(2); - - private static final Color OUTLINE_COLOR = Color.BLACK; - private static final Color CORRECT_COLOR = Color.GREEN; - private static final Color INCORRECT_COLOR = Color.RED; - private static final Color DEFAULT_COLOR = Color.GRAY; - private static final Color X_COLOR = Color.RED; - - private static final Color CORRECT_COLOR_COLORBLIND = new Color(0, 0, 255); - private static final Color INCORRECT_COLOR_COLORBLIND = new Color(255, 0, 0); - - private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); - - private static final Color HOVER_COLOR = new Color(0x90CAF9); - private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); - - private TreeNodeView childView; - private ArrayList parentViews; - private Polygon arrowhead; - - private List lineStartPoints; - private Point lineEndPoint; - - private Point endPoint; - - /** - * TreeTransitionView Constructor creates a transition arrow for display - * - * @param transition tree transition associated with this view - */ - public TreeTransitionView(TreeTransition transition) { - super(TreeElementType.TRANSITION, transition); - this.parentViews = new ArrayList<>(); - this.isCollapsed = false; - this.endPoint = new Point(); - this.lineStartPoints = new ArrayList<>(); - this.lineEndPoint = new Point(); - } - - /** - * TreeTransitionView Constructor creates a transition arrow for display - * - * @param transition tree transition associated with this view - * @param parentView TreeNodeView of the parent associated with this transition - */ - public TreeTransitionView(TreeTransition transition, TreeNodeView parentView) { - this(transition); - this.parentViews.add(parentView); - this.lineStartPoints.add(new Point()); - } - - /** - * Draws the TreeTransitionView - * - * @param graphics2D graphics2D used for drawing - */ - public void draw(Graphics2D graphics2D) { - arrowhead = createTransitionTriangle(RADIUS); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.setStroke(MAIN_STROKE); - - for (Point lineStartPoint : lineStartPoints) { - CubicCurve2D c = new CubicCurve2D.Double(); - double ctrlx1 = lineEndPoint.x - 25; - double ctrly1 = lineStartPoint.y; - double ctrlx2 = lineEndPoint.x - 25; - double ctrly2 = lineEndPoint.y; - - c.setCurve( - lineStartPoint.x, - lineStartPoint.y, - ctrlx1, - ctrly1, - ctrlx2, - ctrly2, - lineEndPoint.x, - lineEndPoint.y); - graphics2D.draw(c); + static final int RADIUS = 25; + static final int DIAMETER = 2 * RADIUS; + static final int GAP = 5; + + private static final Stroke MAIN_STROKE = new BasicStroke(3); + private static final Stroke SELECTION_STROKE = new BasicStroke(2); + + private static final Color OUTLINE_COLOR = Color.BLACK; + private static final Color CORRECT_COLOR = Color.GREEN; + private static final Color INCORRECT_COLOR = Color.RED; + private static final Color DEFAULT_COLOR = Color.GRAY; + private static final Color X_COLOR = Color.RED; + + private static final Color CORRECT_COLOR_COLORBLIND = new Color(0, 0, 255); + private static final Color INCORRECT_COLOR_COLORBLIND = new Color(255, 0, 0); + + private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); + + private static final Color HOVER_COLOR = new Color(0x90CAF9); + private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); + + private TreeNodeView childView; + private ArrayList parentViews; + private Polygon arrowhead; + + private List lineStartPoints; + private Point lineEndPoint; + + private Point endPoint; + + /** + * TreeTransitionView Constructor creates a transition arrow for display + * + * @param transition tree transition associated with this view + */ + public TreeTransitionView(TreeTransition transition) { + super(TreeElementType.TRANSITION, transition); + this.parentViews = new ArrayList<>(); + this.isCollapsed = false; + this.endPoint = new Point(); + this.lineStartPoints = new ArrayList<>(); + this.lineEndPoint = new Point(); } - LegupPreferences prefs = LegupPreferences.getInstance(); - boolean colorBlind = prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true"); - - if (isSelected) { - Color c = DEFAULT_COLOR; - if (getTreeElement().isJustified()) { - if (getTreeElement().isCorrect()) { - if (colorBlind) { - c = CORRECT_COLOR_COLORBLIND; - } else { - c = CORRECT_COLOR; - } - } else { - if (colorBlind) { - c = INCORRECT_COLOR_COLORBLIND; - } else { - c = INCORRECT_COLOR; - } + /** + * TreeTransitionView Constructor creates a transition arrow for display + * + * @param transition tree transition associated with this view + * @param parentView TreeNodeView of the parent associated with this transition + */ + public TreeTransitionView(TreeTransition transition, TreeNodeView parentView) { + this(transition); + this.parentViews.add(parentView); + this.lineStartPoints.add(new Point()); + } + + /** + * Draws the TreeTransitionView + * + * @param graphics2D graphics2D used for drawing + */ + public void draw(Graphics2D graphics2D) { + arrowhead = createTransitionTriangle(RADIUS); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.setStroke(MAIN_STROKE); + + for (Point lineStartPoint : lineStartPoints) { + CubicCurve2D c = new CubicCurve2D.Double(); + double ctrlx1 = lineEndPoint.x - 25; + double ctrly1 = lineStartPoint.y; + double ctrlx2 = lineEndPoint.x - 25; + double ctrly2 = lineEndPoint.y; + + c.setCurve( + lineStartPoint.x, + lineStartPoint.y, + ctrlx1, + ctrly1, + ctrlx2, + ctrly2, + lineEndPoint.x, + lineEndPoint.y); + graphics2D.draw(c); } - } - graphics2D.setColor(c); - graphics2D.fillPolygon(arrowhead); + LegupPreferences prefs = LegupPreferences.getInstance(); + boolean colorBlind = prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true"); + + if (isSelected) { + Color c = DEFAULT_COLOR; + if (getTreeElement().isJustified()) { + if (getTreeElement().isCorrect()) { + if (colorBlind) { + c = CORRECT_COLOR_COLORBLIND; + } else { + c = CORRECT_COLOR; + } + } else { + if (colorBlind) { + c = INCORRECT_COLOR_COLORBLIND; + } else { + c = INCORRECT_COLOR; + } + } + } + graphics2D.setColor(c); - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); + graphics2D.fillPolygon(arrowhead); - Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); - selection_triangle.translate(7, 0); + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_SELECTION_COLOR); - graphics2D.drawPolygon(selection_triangle); - } else { - if (isHover) { - graphics2D.setColor(HOVER_COLOR); - graphics2D.fillPolygon(arrowhead); + Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); + selection_triangle.translate(7, 0); - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); - - Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); - selection_triangle.translate(7, 0); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_HOVER_COLOR); - graphics2D.drawPolygon(selection_triangle); - } else { - Color c = DEFAULT_COLOR; - if (getTreeElement().isJustified()) { - if (getTreeElement().isCorrect()) { - if (colorBlind) { - c = CORRECT_COLOR_COLORBLIND; - } else { - c = CORRECT_COLOR; - } - } else { - if (colorBlind) { - c = INCORRECT_COLOR_COLORBLIND; + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_SELECTION_COLOR); + graphics2D.drawPolygon(selection_triangle); + } else { + if (isHover) { + graphics2D.setColor(HOVER_COLOR); + graphics2D.fillPolygon(arrowhead); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); + + Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); + selection_triangle.translate(7, 0); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_HOVER_COLOR); + graphics2D.drawPolygon(selection_triangle); } else { - c = INCORRECT_COLOR; + Color c = DEFAULT_COLOR; + if (getTreeElement().isJustified()) { + if (getTreeElement().isCorrect()) { + if (colorBlind) { + c = CORRECT_COLOR_COLORBLIND; + } else { + c = CORRECT_COLOR; + } + } else { + if (colorBlind) { + c = INCORRECT_COLOR_COLORBLIND; + } else { + c = INCORRECT_COLOR; + } + } + } + graphics2D.setColor(c); + graphics2D.fillPolygon(arrowhead); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); } - } } - graphics2D.setColor(c); - graphics2D.fillPolygon(arrowhead); + } - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); - } + /** Constructs the arrowhead shape from the start and end points */ + private Polygon createTransitionTriangle(int radius) { + double thetaArrow = Math.toRadians(30); + + int point1X = endPoint.x; + int point1Y = endPoint.y; + + int point2X = point1X - radius; + int point2Y = point1Y + (int) Math.round(radius / (2 * cos(thetaArrow))); + + int point3X = point1X - radius; + int point3Y = point1Y - (int) Math.round(radius / (2 * cos(thetaArrow))); + + lineEndPoint.x = point2X; + lineEndPoint.y = (point3Y - point2Y) / 2 + point2Y; + + Polygon tri = new Polygon(); + tri.addPoint(point1X, point1Y); + tri.addPoint(point2X, point2Y); + tri.addPoint(point3X, point3Y); + + return tri; + } + + /** + * Gets the TreeElement associated with this view + * + * @return the TreeElement associated with this view + */ + public TreeTransition getTreeElement() { + return (TreeTransition) treeElement; + } + + /** + * Gets the TreeNodeView child view + * + * @return TreeNodeView child view + */ + public TreeNodeView getChildView() { + return childView; + } + + /** + * Sets the TreeNodeView child view + * + * @param childView TreeNodeView child view + */ + public void setChildView(TreeNodeView childView) { + this.childView = childView; + } + + /** + * Gets the list of parent views associated with this tree transition view + * + * @return list of parent views for this tree transition view + */ + public ArrayList getParentViews() { + return parentViews; } - } - - /** Constructs the arrowhead shape from the start and end points */ - private Polygon createTransitionTriangle(int radius) { - double thetaArrow = Math.toRadians(30); - - int point1X = endPoint.x; - int point1Y = endPoint.y; - - int point2X = point1X - radius; - int point2Y = point1Y + (int) Math.round(radius / (2 * cos(thetaArrow))); - - int point3X = point1X - radius; - int point3Y = point1Y - (int) Math.round(radius / (2 * cos(thetaArrow))); - - lineEndPoint.x = point2X; - lineEndPoint.y = (point3Y - point2Y) / 2 + point2Y; - - Polygon tri = new Polygon(); - tri.addPoint(point1X, point1Y); - tri.addPoint(point2X, point2Y); - tri.addPoint(point3X, point3Y); - - return tri; - } - - /** - * Gets the TreeElement associated with this view - * - * @return the TreeElement associated with this view - */ - public TreeTransition getTreeElement() { - return (TreeTransition) treeElement; - } - - /** - * Gets the TreeNodeView child view - * - * @return TreeNodeView child view - */ - public TreeNodeView getChildView() { - return childView; - } - - /** - * Sets the TreeNodeView child view - * - * @param childView TreeNodeView child view - */ - public void setChildView(TreeNodeView childView) { - this.childView = childView; - } - - /** - * Gets the list of parent views associated with this tree transition view - * - * @return list of parent views for this tree transition view - */ - public ArrayList getParentViews() { - return parentViews; - } - - /** - * Sets the list of parent views associated with this tree transition view - * - * @param parentViews list of parent views for this tree transition view - */ - public void setParentViews(ArrayList parentViews) { - this.parentViews = parentViews; - this.lineStartPoints.clear(); - for (TreeNodeView parentView : this.parentViews) { - this.lineStartPoints.add(new Point()); + + /** + * Sets the list of parent views associated with this tree transition view + * + * @param parentViews list of parent views for this tree transition view + */ + public void setParentViews(ArrayList parentViews) { + this.parentViews = parentViews; + this.lineStartPoints.clear(); + for (TreeNodeView parentView : this.parentViews) { + this.lineStartPoints.add(new Point()); + } + } + + /** + * Adds a TreeNodeView to the list of parent views + * + * @param nodeView TreeNodeView to add to the list of parent views + */ + public void addParentView(TreeNodeView nodeView) { + parentViews.add(nodeView); + lineStartPoints.add(new Point()); } - } - - /** - * Adds a TreeNodeView to the list of parent views - * - * @param nodeView TreeNodeView to add to the list of parent views - */ - public void addParentView(TreeNodeView nodeView) { - parentViews.add(nodeView); - lineStartPoints.add(new Point()); - } - - /** - * Removes a TreeNodeView from the list of parent views - * - * @param nodeView TreeNodeView to remove from the list of parent views - */ - public void removeParentView(TreeNodeView nodeView) { - int index = parentViews.indexOf(nodeView); - parentViews.remove(nodeView); - if (index != -1) { - lineStartPoints.remove(index); + + /** + * Removes a TreeNodeView from the list of parent views + * + * @param nodeView TreeNodeView to remove from the list of parent views + */ + public void removeParentView(TreeNodeView nodeView) { + int index = parentViews.indexOf(nodeView); + parentViews.remove(nodeView); + if (index != -1) { + lineStartPoints.remove(index); + } + } + + public Point getEndPoint() { + return endPoint; + } + + public void setEndPoint(Point endPoint) { + this.endPoint = endPoint; + } + + public int getEndX() { + return endPoint.x; + } + + public void setEndX(int x) { + this.endPoint.x = x; + } + + public int getEndY() { + return endPoint.y; + } + + public void setEndY(int y) { + this.endPoint.y = y; + } + + public List getLineStartPoints() { + return lineStartPoints; + } + + public void setLineStartPoints(List lineStartPoints) { + this.lineStartPoints = lineStartPoints; + } + + public Point getLineStartPoint(int index) { + return index < lineStartPoints.size() ? lineStartPoints.get(index) : null; + } + + @Override + public Rectangle getBounds() { + return arrowhead.getBounds(); + } + + @Override + public Rectangle2D getBounds2D() { + return arrowhead.getBounds2D(); + } + + @Override + public boolean contains(double x, double y) { + return arrowhead.contains(x, y); + } + + @Override + public boolean contains(Point2D p) { + return arrowhead != null && arrowhead.contains(p); + } + + @Override + public boolean intersects(double x, double y, double w, double h) { + return arrowhead.intersects(x, y, w, h); + } + + @Override + public boolean intersects(Rectangle2D r) { + return arrowhead.intersects(r); + } + + @Override + public boolean contains(double x, double y, double w, double h) { + return arrowhead.contains(x, y, w, h); + } + + @Override + public boolean contains(Rectangle2D r) { + return arrowhead.contains(r); + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return arrowhead.getPathIterator(at); + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return arrowhead.getPathIterator(at, flatness); } - } - - public Point getEndPoint() { - return endPoint; - } - - public void setEndPoint(Point endPoint) { - this.endPoint = endPoint; - } - - public int getEndX() { - return endPoint.x; - } - - public void setEndX(int x) { - this.endPoint.x = x; - } - - public int getEndY() { - return endPoint.y; - } - - public void setEndY(int y) { - this.endPoint.y = y; - } - - public List getLineStartPoints() { - return lineStartPoints; - } - - public void setLineStartPoints(List lineStartPoints) { - this.lineStartPoints = lineStartPoints; - } - - public Point getLineStartPoint(int index) { - return index < lineStartPoints.size() ? lineStartPoints.get(index) : null; - } - - @Override - public Rectangle getBounds() { - return arrowhead.getBounds(); - } - - @Override - public Rectangle2D getBounds2D() { - return arrowhead.getBounds2D(); - } - - @Override - public boolean contains(double x, double y) { - return arrowhead.contains(x, y); - } - - @Override - public boolean contains(Point2D p) { - return arrowhead != null && arrowhead.contains(p); - } - - @Override - public boolean intersects(double x, double y, double w, double h) { - return arrowhead.intersects(x, y, w, h); - } - - @Override - public boolean intersects(Rectangle2D r) { - return arrowhead.intersects(r); - } - - @Override - public boolean contains(double x, double y, double w, double h) { - return arrowhead.contains(x, y, w, h); - } - - @Override - public boolean contains(Rectangle2D r) { - return arrowhead.contains(r); - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return arrowhead.getPathIterator(at); - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return arrowhead.getPathIterator(at, flatness); - } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java index b46090fed..f491009b4 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java @@ -27,855 +27,885 @@ import org.apache.logging.log4j.Logger; public class TreeView extends ScrollView implements ITreeListener { - private static final Logger LOGGER = LogManager.getLogger(TreeView.class.getName()); - - private static final int TRANS_GAP = 5; - - private static final int NODE_GAP_WIDTH = 70; - private static final int NODE_GAP_HEIGHT = 15; - - private static final int BORDER_GAP_HEIGHT = 20; - private static final int BORDER_GAP_WIDTH = 20; - - private static final int BORDER_SPACING = 100; - - private TreeNodeView nodeHover; - - private ArrayList currentStateBoxes; - private Rectangle bounds = new Rectangle(0, 0, 0, 0); - - private Tree tree; - private TreeNodeView rootNodeView; - private Map viewMap; - private Dimension dimension; - - private TreeViewSelection selection; - - public TreeView(TreeController treeController) { - super(treeController); - currentStateBoxes = new ArrayList<>(); - setSize(dimension = new Dimension(100, 200)); - setPreferredSize(new Dimension(640, 160)); - - viewMap = new HashMap<>(); - - selection = new TreeViewSelection(); - } - - public TreeViewSelection getSelection() { - return selection; - } - - /** - * Gets the tree node puzzleElement that the mouse is hovering over - * - * @return tree node puzzleElement that the mouse is hovering over - */ - public TreeNodeView getNodeHover() { - return nodeHover; - } - - /** - * Sets the tree node puzzleElement that the mouse is hovering over - * - * @param nodeHover tree node puzzleElement the mouse is hovering over - */ - public void setNodeHover(TreeNodeView nodeHover) { - this.nodeHover = nodeHover; - } - - /** - * Gets the TreeElementView by the specified point or null if no view exists at the specified - * point - * - * @param point location to query for a view - * @return TreeElementView at the point specified, otherwise null - */ - public TreeElementView getTreeElementView(Point point) { - return getTreeElementView(point, rootNodeView); - } - - /** - * Recursively gets the TreeElementView by the specified point or null if no view exists at the - * specified point or the view specified is null - * - * @param point location to query for a view - * @param elementView view to determine if the point is contained within it - * @return TreeElementView at the point specified, otherwise null - */ - private TreeElementView getTreeElementView(Point point, TreeElementView elementView) { - if (elementView == null) { - return null; - } else { - if (elementView.contains(point) && elementView.isVisible()) { - if (elementView.getType() == NODE && ((TreeNodeView) elementView).isContradictoryState()) { - return null; - } - return elementView; - } else { - if (elementView.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) elementView; - for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { - TreeElementView view = getTreeElementView(point, transitionView); - if (view != null) { - return view; - } - } + private static final Logger LOGGER = LogManager.getLogger(TreeView.class.getName()); + + private static final int TRANS_GAP = 5; + + private static final int NODE_GAP_WIDTH = 70; + private static final int NODE_GAP_HEIGHT = 15; + + private static final int BORDER_GAP_HEIGHT = 20; + private static final int BORDER_GAP_WIDTH = 20; + + private static final int BORDER_SPACING = 100; + + private TreeNodeView nodeHover; + + private ArrayList currentStateBoxes; + private Rectangle bounds = new Rectangle(0, 0, 0, 0); + + private Tree tree; + private TreeNodeView rootNodeView; + private Map viewMap; + private Dimension dimension; + + private TreeViewSelection selection; + + public TreeView(TreeController treeController) { + super(treeController); + currentStateBoxes = new ArrayList<>(); + setSize(dimension = new Dimension(100, 200)); + setPreferredSize(new Dimension(640, 160)); + + viewMap = new HashMap<>(); + + selection = new TreeViewSelection(); + } + + public TreeViewSelection getSelection() { + return selection; + } + + /** + * Gets the tree node puzzleElement that the mouse is hovering over + * + * @return tree node puzzleElement that the mouse is hovering over + */ + public TreeNodeView getNodeHover() { + return nodeHover; + } + + /** + * Sets the tree node puzzleElement that the mouse is hovering over + * + * @param nodeHover tree node puzzleElement the mouse is hovering over + */ + public void setNodeHover(TreeNodeView nodeHover) { + this.nodeHover = nodeHover; + } + + /** + * Gets the TreeElementView by the specified point or null if no view exists at the specified + * point + * + * @param point location to query for a view + * @return TreeElementView at the point specified, otherwise null + */ + public TreeElementView getTreeElementView(Point point) { + return getTreeElementView(point, rootNodeView); + } + + /** + * Recursively gets the TreeElementView by the specified point or null if no view exists at the + * specified point or the view specified is null + * + * @param point location to query for a view + * @param elementView view to determine if the point is contained within it + * @return TreeElementView at the point specified, otherwise null + */ + private TreeElementView getTreeElementView(Point point, TreeElementView elementView) { + if (elementView == null) { + return null; } else { - TreeTransitionView transitionView = (TreeTransitionView) elementView; - return getTreeElementView(point, transitionView.getChildView()); - } - } - } - return null; - } - - public void updateTreeView(Tree tree) { - this.tree = tree; - if (selection.getSelectedViews().size() == 0) { - selection.newSelection(new TreeNodeView(tree.getRootNode())); - } - repaint(); - } - - /** - * Sets the tree associated with this TreeView - * - * @param tree tree - */ - public void setTree(Tree tree) { - this.tree = tree; - } - - public void updateTreeSize() { - if (GameBoardFacade.getInstance().getTree() == null) { - return; - } - setSize(bounds.getSize()); - } - - public void reset() { - if (bounds.x != 0 || bounds.y != 0) { - updateTreeSize(); - } - } - - public void zoomFit() { - double fitWidth = (viewport.getWidth() - 8.0) / (getSize().width - 200); - double fitHeight = (viewport.getHeight() - 8.0) / (getSize().height - 120); - zoomTo(Math.min(fitWidth, fitHeight)); - viewport.setViewPosition(new Point(0, viewport.getHeight() / 2)); - } - - /** - * Creates a customized viewport for the scroll pane - * - * @return viewport for the scroll pane - */ - @Override - protected JViewport createViewport() { - return new JViewport() { - @Override - protected LayoutManager createLayoutManager() { - return new ViewportLayout() { - @Override - public void layoutContainer(Container parent) { - Point point = viewport.getViewPosition(); - // determine the maximum x and y view positions - int mx = getCanvas().getWidth() - viewport.getWidth(); - int my = getCanvas().getHeight() - viewport.getHeight(); - // obey edge boundaries - if (point.x < 0) { - point.x = 0; - } - if (point.x > mx) { - point.x = mx; - } - if (point.y < 0) { - point.y = 0; - } - if (point.y > my) { - point.y = my; - } - // center margins - if (mx < 0) { - point.x = 0; - } - if (my < 0) { - point.y = my / 2; + if (elementView.contains(point) && elementView.isVisible()) { + if (elementView.getType() == NODE + && ((TreeNodeView) elementView).isContradictoryState()) { + return null; + } + return elementView; + } else { + if (elementView.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) elementView; + for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { + TreeElementView view = getTreeElementView(point, transitionView); + if (view != null) { + return view; + } + } + } else { + TreeTransitionView transitionView = (TreeTransitionView) elementView; + return getTreeElementView(point, transitionView.getChildView()); + } } - viewport.setViewPosition(point); - } - }; - } - }; - } - - public void draw(Graphics2D graphics2D) { - currentStateBoxes.clear(); - Tree tree = GameBoardFacade.getInstance().getTree(); - if (tree != null) { - // setSize(bounds.getDimension()); - graphics2D.setRenderingHint( - RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics2D.setRenderingHint( - RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - - drawTree(graphics2D); - - dimension.width += BORDER_SPACING; - setSize(dimension); - // graphics2D.drawRect(0,0, dimension.width, dimension.height); - - if (selection.getHover() != null) { - drawMouseOver(graphics2D); - } - } - } - - public void zoomReset() { - zoomTo(1.0); - viewport.setViewPosition(new Point(0, 0)); - } - - private void redrawTree(Graphics2D graphics2D, TreeNodeView nodeView) { - if (nodeView != null) { - nodeView.draw(graphics2D); - for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { - transitionView.draw(graphics2D); - redrawTree(graphics2D, transitionView.getChildView()); - } - } - } - - public void removeTreeElement(TreeElementView view) { - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - nodeView.getParentView().setChildView(null); - } else { - TreeTransitionView transitionView = (TreeTransitionView) view; - transitionView - .getParentViews() - .forEach((TreeNodeView n) -> n.removeChildrenView(transitionView)); - } - } - - /** - * When the edu.rpi.legup.user hovers over the transition, draws the corresponding rules image - * - * @param g the graphics to use to draw - */ - public void drawMouseOver(Graphics2D g) { - if (selection.getHover().getType() == TRANSITION - && ((TreeTransitionView) selection.getHover()).getTreeElement().isJustified()) { - TreeTransition transition = (TreeTransition) selection.getHover().treeElement; - int imgWidth = 100; - int imgHeight = 100; - - BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); - image.createGraphics().drawImage(transition.getRule().getImageIcon().getImage(), 0, 0, null); - Point mousePoint = selection.getMousePoint(); - g.drawImage(image, mousePoint.x, mousePoint.y - 50, imgWidth, imgHeight, null); - } - } - - public void resetView() { - this.tree = null; - this.rootNodeView = null; - this.selection.clearSelection(); - this.selection.clearHover(); - } - - /** - * Called when a tree puzzleElement is added to the tree - * - * @param treeElement TreeElement that was added to the tree - */ - @Override - public void onTreeElementAdded(TreeElement treeElement) { - if (treeElement.getType() == NODE) { - addTreeNode((TreeNode) treeElement); - } else { - addTreeTransition((TreeTransition) treeElement); - } - repaint(); - } - - /** - * Called when a tree puzzleElement is removed from the tree - * - * @param element TreeElement that was removed to the tree - */ - @Override - public void onTreeElementRemoved(TreeElement element) { - if (element.getType() == NODE) { - TreeNode node = (TreeNode) element; - TreeNodeView nodeView = (TreeNodeView) viewMap.get(node); - - nodeView.getParentView().setChildView(null); - removeTreeNode(node); - } else { - TreeTransition trans = (TreeTransition) element; - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - - // unlock ancestor elements if case rule deleted - Rule rule = trans.getRule(); - for (TreeNode node : trans.getParents()) { - - // only if the last case of a case rule will be deleted - if (!(rule instanceof CaseRule && node.getChildren().isEmpty())) { - continue; } + return null; + } + + public void updateTreeView(Tree tree) { + this.tree = tree; + if (selection.getSelectedViews().size() == 0) { + selection.newSelection(new TreeNodeView(tree.getRootNode())); + } + repaint(); + } + + /** + * Sets the tree associated with this TreeView + * + * @param tree tree + */ + public void setTree(Tree tree) { + this.tree = tree; + } + + public void updateTreeSize() { + if (GameBoardFacade.getInstance().getTree() == null) { + return; + } + setSize(bounds.getSize()); + } - CaseRule caseRule = (CaseRule) rule; - // set dependent elements to be modifiable by ancestors (if not dependent on others) - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - - for (PuzzleElement pelement : - caseRule.dependentElements(node.getBoard(), trans.getSelection())) { - // decrement, unlock if 0 cases depended - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); - oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); - if (oldElement.getCasesDepended() != 0) { - continue; + public void reset() { + if (bounds.x != 0 || bounds.y != 0) { + updateTreeSize(); + } + } + + public void zoomFit() { + double fitWidth = (viewport.getWidth() - 8.0) / (getSize().width - 200); + double fitHeight = (viewport.getHeight() - 8.0) / (getSize().height - 120); + zoomTo(Math.min(fitWidth, fitHeight)); + viewport.setViewPosition(new Point(0, viewport.getHeight() / 2)); + } + + /** + * Creates a customized viewport for the scroll pane + * + * @return viewport for the scroll pane + */ + @Override + protected JViewport createViewport() { + return new JViewport() { + @Override + protected LayoutManager createLayoutManager() { + return new ViewportLayout() { + @Override + public void layoutContainer(Container parent) { + Point point = viewport.getViewPosition(); + // determine the maximum x and y view positions + int mx = getCanvas().getWidth() - viewport.getWidth(); + int my = getCanvas().getHeight() - viewport.getHeight(); + // obey edge boundaries + if (point.x < 0) { + point.x = 0; + } + if (point.x > mx) { + point.x = mx; + } + if (point.y < 0) { + point.y = 0; + } + if (point.y > my) { + point.y = my; + } + // center margins + if (mx < 0) { + point.x = 0; + } + if (my < 0) { + point.y = my / 2; + } + viewport.setViewPosition(point); + } + }; } + }; + } - // set modifiable if started modifiable - boolean modifiable = - tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); + public void draw(Graphics2D graphics2D) { + currentStateBoxes.clear(); + Tree tree = GameBoardFacade.getInstance().getTree(); + if (tree != null) { + // setSize(bounds.getDimension()); + graphics2D.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics2D.setRenderingHint( + RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - // unmodifiable if already modified - TreeNode modNode = ancestor.getParent().getParents().get(0); - while (modNode.getParent() != null) { - Board modBoard = modNode.getParent().getBoard(); - if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { - modifiable = false; - break; - } - modNode = modNode.getParent().getParents().get(0); + drawTree(graphics2D); + + dimension.width += BORDER_SPACING; + setSize(dimension); + // graphics2D.drawRect(0,0, dimension.width, dimension.height); + + if (selection.getHover() != null) { + drawMouseOver(graphics2D); } - oldElement.setModifiable(modifiable); - } } - } - - transView.getParentViews().forEach(n -> n.removeChildrenView(transView)); - removeTreeTransition(trans); - } - repaint(); - } - - /** - * Called when the tree selection was changed - * - * @param selection tree selection that was changed - */ - @Override - public void onTreeSelectionChanged(TreeViewSelection selection) { - this.selection.getSelectedViews().forEach(v -> v.setSelected(false)); - selection.getSelectedViews().forEach(v -> v.setSelected(true)); - this.selection = selection; - repaint(); - } - - /** Called when the model has finished updating the tree. */ - @Override - public void onUpdateTree() { - repaint(); - } - - /** - * Gets the TreeElementView by the corresponding TreeElement associated with it - * - * @param element TreeElement of the view - * @return TreeElementView of the TreeElement associated with it - */ - public TreeElementView getElementView(TreeElement element) { - return viewMap.get(element); - } - - private void removeTreeNode(TreeNode node) { - viewMap.remove(node); - List children = node.getChildren(); - - // if child is a case rule, unlock ancestor elements - if (!children.isEmpty()) { - Rule rule = children.get(0).getRule(); - if (rule instanceof CaseRule) { - CaseRule caseRule = (CaseRule) rule; - // set dependent elements to be modifiable by ancestors (if not dependent on others) - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement pelement : - caseRule.dependentElements(node.getBoard(), children.get(0).getSelection())) { - // decrement, unlock if 0 cases depended - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); - oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); - if (oldElement.getCasesDepended() == 0) { - continue; - } + } - // set modifiable if started modifiable - boolean modifiable = - tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); + public void zoomReset() { + zoomTo(1.0); + viewport.setViewPosition(new Point(0, 0)); + } - // unmodifiable if already modified - TreeNode modNode = ancestor.getParent().getParents().get(0); - while (modNode.getParent() != null) { - Board modBoard = modNode.getParent().getBoard(); - if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { - modifiable = false; - break; - } - modNode = modNode.getParent().getParents().get(0); + private void redrawTree(Graphics2D graphics2D, TreeNodeView nodeView) { + if (nodeView != null) { + nodeView.draw(graphics2D); + for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { + transitionView.draw(graphics2D); + redrawTree(graphics2D, transitionView.getChildView()); } - oldElement.setModifiable(modifiable); - } } - } - } - node.getChildren().forEach(t -> removeTreeTransition(t)); - } - - private void removeTreeTransition(TreeTransition trans) { - viewMap.remove(trans); - if (trans.getChildNode() != null) { - removeTreeNode(trans.getChildNode()); - } - } - - private void addTreeNode(TreeNode node) { - TreeTransition parent = node.getParent(); - - TreeNodeView nodeView = new TreeNodeView(node); - TreeTransitionView parentView = (TreeTransitionView) viewMap.get(parent); - - nodeView.setParentView(parentView); - parentView.setChildView(nodeView); - - viewMap.put(node, nodeView); - - if (!node.getChildren().isEmpty()) { - - // if adding a case rule, lock dependent ancestor elements - Rule rule = node.getChildren().get(0).getRule(); - if (rule instanceof CaseRule) { - CaseRule caseRule = (CaseRule) rule; - - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement element : - caseRule.dependentElements( - node.getBoard(), node.getChildren().get(0).getSelection())) { - // increment and lock - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); - oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); - oldElement.setModifiable(false); - } + } + + public void removeTreeElement(TreeElementView view) { + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + nodeView.getParentView().setChildView(null); + } else { + TreeTransitionView transitionView = (TreeTransitionView) view; + transitionView + .getParentViews() + .forEach((TreeNodeView n) -> n.removeChildrenView(transitionView)); + } + } + + /** + * When the edu.rpi.legup.user hovers over the transition, draws the corresponding rules image + * + * @param g the graphics to use to draw + */ + public void drawMouseOver(Graphics2D g) { + if (selection.getHover().getType() == TRANSITION + && ((TreeTransitionView) selection.getHover()).getTreeElement().isJustified()) { + TreeTransition transition = (TreeTransition) selection.getHover().treeElement; + int imgWidth = 100; + int imgHeight = 100; + + BufferedImage image = + new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); + image.createGraphics() + .drawImage(transition.getRule().getImageIcon().getImage(), 0, 0, null); + Point mousePoint = selection.getMousePoint(); + g.drawImage(image, mousePoint.x, mousePoint.y - 50, imgWidth, imgHeight, null); } - } - - node.getChildren().forEach(t -> addTreeTransition(t)); - } - } - - private void addTreeTransition(TreeTransition trans) { - List parents = trans.getParents(); - - TreeTransitionView transView = new TreeTransitionView(trans); - for (TreeNode parent : parents) { - TreeNodeView parentNodeView = (TreeNodeView) viewMap.get(parent); - transView.addParentView(parentNodeView); - parentNodeView.addChildrenView(transView); - - // if transition is a new case rule, lock dependent ancestor elements - Rule rule = trans.getRule(); - if (rule instanceof CaseRule && parent.getChildren().size() == 1) { - CaseRule caseRule = (CaseRule) rule; - - List ancestors = parent.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement element : - caseRule.dependentElements(parent.getBoard(), trans.getSelection())) { - // increment and lock - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); - oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); - oldElement.setModifiable(false); - } + } + + public void resetView() { + this.tree = null; + this.rootNodeView = null; + this.selection.clearSelection(); + this.selection.clearHover(); + } + + /** + * Called when a tree puzzleElement is added to the tree + * + * @param treeElement TreeElement that was added to the tree + */ + @Override + public void onTreeElementAdded(TreeElement treeElement) { + if (treeElement.getType() == NODE) { + addTreeNode((TreeNode) treeElement); + } else { + addTreeTransition((TreeTransition) treeElement); } - } + repaint(); } - viewMap.put(trans, transView); + /** + * Called when a tree puzzleElement is removed from the tree + * + * @param element TreeElement that was removed to the tree + */ + @Override + public void onTreeElementRemoved(TreeElement element) { + if (element.getType() == NODE) { + TreeNode node = (TreeNode) element; + TreeNodeView nodeView = (TreeNodeView) viewMap.get(node); + + nodeView.getParentView().setChildView(null); + removeTreeNode(node); + } else { + TreeTransition trans = (TreeTransition) element; + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + + // unlock ancestor elements if case rule deleted + Rule rule = trans.getRule(); + for (TreeNode node : trans.getParents()) { + + // only if the last case of a case rule will be deleted + if (!(rule instanceof CaseRule && node.getChildren().isEmpty())) { + continue; + } + + CaseRule caseRule = (CaseRule) rule; + // set dependent elements to be modifiable by ancestors (if not dependent on others) + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + + for (PuzzleElement pelement : + caseRule.dependentElements(node.getBoard(), trans.getSelection())) { + // decrement, unlock if 0 cases depended + PuzzleElement oldElement = + ancestor.getParent().getBoard().getPuzzleElement(pelement); + oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); + if (oldElement.getCasesDepended() != 0) { + continue; + } + + // set modifiable if started modifiable + boolean modifiable = + tree.getRootNode() + .getBoard() + .getPuzzleElement(oldElement) + .isModifiable(); + + // unmodifiable if already modified + TreeNode modNode = ancestor.getParent().getParents().get(0); + while (modNode.getParent() != null) { + Board modBoard = modNode.getParent().getBoard(); + if (modBoard.getModifiedData() + .contains(modBoard.getPuzzleElement(oldElement))) { + modifiable = false; + break; + } + modNode = modNode.getParent().getParents().get(0); + } + oldElement.setModifiable(modifiable); + } + } + } - if (trans.getChildNode() != null) { - addTreeNode(trans.getChildNode()); + transView.getParentViews().forEach(n -> n.removeChildrenView(transView)); + removeTreeTransition(trans); + } + repaint(); } - } - /// New Draw Methods + /** + * Called when the tree selection was changed + * + * @param selection tree selection that was changed + */ + @Override + public void onTreeSelectionChanged(TreeViewSelection selection) { + this.selection.getSelectedViews().forEach(v -> v.setSelected(false)); + selection.getSelectedViews().forEach(v -> v.setSelected(true)); + this.selection = selection; + repaint(); + } - public void drawTree(Graphics2D graphics2D) { - if (tree == null) { - LOGGER.error("Unable to draw tree."); - } else { - if (rootNodeView == null) { - rootNodeView = new TreeNodeView(tree.getRootNode()); + /** Called when the model has finished updating the tree. */ + @Override + public void onUpdateTree() { + repaint(); + } - LOGGER.debug("Creating new views for tree view."); - createViews(rootNodeView); + /** + * Gets the TreeElementView by the corresponding TreeElement associated with it + * + * @param element TreeElement of the view + * @return TreeElementView of the TreeElement associated with it + */ + public TreeElementView getElementView(TreeElement element) { + return viewMap.get(element); + } - selection.newSelection(rootNodeView); - } + private void removeTreeNode(TreeNode node) { + viewMap.remove(node); + List children = node.getChildren(); + + // if child is a case rule, unlock ancestor elements + if (!children.isEmpty()) { + Rule rule = children.get(0).getRule(); + if (rule instanceof CaseRule) { + CaseRule caseRule = (CaseRule) rule; + // set dependent elements to be modifiable by ancestors (if not dependent on others) + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement pelement : + caseRule.dependentElements( + node.getBoard(), children.get(0).getSelection())) { + // decrement, unlock if 0 cases depended + PuzzleElement oldElement = + ancestor.getParent().getBoard().getPuzzleElement(pelement); + oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); + if (oldElement.getCasesDepended() == 0) { + continue; + } + + // set modifiable if started modifiable + boolean modifiable = + tree.getRootNode() + .getBoard() + .getPuzzleElement(oldElement) + .isModifiable(); + + // unmodifiable if already modified + TreeNode modNode = ancestor.getParent().getParents().get(0); + while (modNode.getParent() != null) { + Board modBoard = modNode.getParent().getBoard(); + if (modBoard.getModifiedData() + .contains(modBoard.getPuzzleElement(oldElement))) { + modifiable = false; + break; + } + modNode = modNode.getParent().getParents().get(0); + } + oldElement.setModifiable(modifiable); + } + } + } + } + node.getChildren().forEach(t -> removeTreeTransition(t)); + } - dimension = new Dimension(0, 0); - calcSpan(rootNodeView); - rootNodeView.setSpan(rootNodeView.getSpan() + DIAMETER + BORDER_SPACING); + private void removeTreeTransition(TreeTransition trans) { + viewMap.remove(trans); + if (trans.getChildNode() != null) { + removeTreeNode(trans.getChildNode()); + } + } - calculateViewLocations(rootNodeView, 0); - dimension.height = (int) rootNodeView.getSpan(); + private void addTreeNode(TreeNode node) { + TreeTransition parent = node.getParent(); + + TreeNodeView nodeView = new TreeNodeView(node); + TreeTransitionView parentView = (TreeTransitionView) viewMap.get(parent); + + nodeView.setParentView(parentView); + parentView.setChildView(nodeView); + + viewMap.put(node, nodeView); + + if (!node.getChildren().isEmpty()) { + + // if adding a case rule, lock dependent ancestor elements + Rule rule = node.getChildren().get(0).getRule(); + if (rule instanceof CaseRule) { + CaseRule caseRule = (CaseRule) rule; + + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement element : + caseRule.dependentElements( + node.getBoard(), node.getChildren().get(0).getSelection())) { + // increment and lock + PuzzleElement oldElement = + ancestor.getParent().getBoard().getPuzzleElement(element); + oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); + oldElement.setModifiable(false); + } + } + } - redrawTree(graphics2D, rootNodeView); - LOGGER.debug("DrawTree: dimensions - " + dimension.width + "x" + dimension.height); + node.getChildren().forEach(t -> addTreeTransition(t)); + } } - } - public void createViews(TreeNodeView nodeView) { - if (nodeView != null) { - viewMap.put(nodeView.getTreeElement(), nodeView); + private void addTreeTransition(TreeTransition trans) { + List parents = trans.getParents(); + + TreeTransitionView transView = new TreeTransitionView(trans); + for (TreeNode parent : parents) { + TreeNodeView parentNodeView = (TreeNodeView) viewMap.get(parent); + transView.addParentView(parentNodeView); + parentNodeView.addChildrenView(transView); + + // if transition is a new case rule, lock dependent ancestor elements + Rule rule = trans.getRule(); + if (rule instanceof CaseRule && parent.getChildren().size() == 1) { + CaseRule caseRule = (CaseRule) rule; + + List ancestors = parent.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement element : + caseRule.dependentElements(parent.getBoard(), trans.getSelection())) { + // increment and lock + PuzzleElement oldElement = + ancestor.getParent().getBoard().getPuzzleElement(element); + oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); + oldElement.setModifiable(false); + } + } + } + } - TreeNode node = nodeView.getTreeElement(); - for (TreeTransition trans : node.getChildren()) { - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - if (transView != null) { - nodeView.addChildrenView(transView); - transView.addParentView(nodeView); - break; + viewMap.put(trans, transView); + + if (trans.getChildNode() != null) { + addTreeNode(trans.getChildNode()); } - transView = new TreeTransitionView(trans); + } - viewMap.put(transView.getTreeElement(), transView); + /// New Draw Methods - transView.addParentView(nodeView); - nodeView.addChildrenView(transView); + public void drawTree(Graphics2D graphics2D) { + if (tree == null) { + LOGGER.error("Unable to draw tree."); + } else { + if (rootNodeView == null) { + rootNodeView = new TreeNodeView(tree.getRootNode()); - TreeNode childNode = trans.getChildNode(); - if (childNode != null) { - TreeNodeView childNodeView = new TreeNodeView(childNode); - viewMap.put(childNodeView.getTreeElement(), childNodeView); + LOGGER.debug("Creating new views for tree view."); + createViews(rootNodeView); - childNodeView.setParentView(transView); - transView.setChildView(childNodeView); + selection.newSelection(rootNodeView); + } + + dimension = new Dimension(0, 0); + calcSpan(rootNodeView); + rootNodeView.setSpan(rootNodeView.getSpan() + DIAMETER + BORDER_SPACING); - createViews(childNodeView); + calculateViewLocations(rootNodeView, 0); + dimension.height = (int) rootNodeView.getSpan(); + + redrawTree(graphics2D, rootNodeView); + LOGGER.debug("DrawTree: dimensions - " + dimension.width + "x" + dimension.height); } - } } - } - - public void calculateViewLocations(TreeNodeView nodeView, int depth) { - nodeView.setDepth(depth); - int xLoc = (NODE_GAP_WIDTH + DIAMETER) * depth + DIAMETER; - nodeView.setX(xLoc); - dimension.width = Math.max(dimension.width, xLoc); - TreeTransitionView parentTransView = nodeView.getParentView(); - int yLoc = parentTransView == null ? (int) nodeView.getSpan() / 2 : parentTransView.getEndY(); - nodeView.setY(yLoc); + public void createViews(TreeNodeView nodeView) { + if (nodeView != null) { + viewMap.put(nodeView.getTreeElement(), nodeView); - ArrayList children = nodeView.getChildrenViews(); - switch (children.size()) { - case 0: - break; - case 1: - { - TreeTransitionView childView = children.get(0); + TreeNode node = nodeView.getTreeElement(); + for (TreeTransition trans : node.getChildren()) { + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + if (transView != null) { + nodeView.addChildrenView(transView); + transView.addParentView(nodeView); + break; + } + transView = new TreeTransitionView(trans); - List parentsViews = childView.getParentViews(); - if (parentsViews.size() == 1) { - childView.setEndY(yLoc); + viewMap.put(transView.getTreeElement(), transView); - childView.setDepth(depth); + transView.addParentView(nodeView); + nodeView.addChildrenView(transView); - Point lineStartPoint = childView.getLineStartPoint(0); - lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = yLoc; - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + TreeNode childNode = trans.getChildNode(); + if (childNode != null) { + TreeNodeView childNodeView = new TreeNodeView(childNode); + viewMap.put(childNodeView.getTreeElement(), childNodeView); - dimension.width = Math.max(dimension.width, childView.getEndX()); + childNodeView.setParentView(transView); + transView.setChildView(childNodeView); - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } else { - if (parentsViews.size() > 1 && parentsViews.get(parentsViews.size() - 1) == nodeView) { - int yAvg = 0; - for (int i = 0; i < parentsViews.size(); i++) { - TreeNodeView parentNodeView = parentsViews.get(i); - depth = Math.max(depth, parentNodeView.getDepth()); - yAvg += parentNodeView.getY(); - - Point lineStartPoint = childView.getLineStartPoint(i); - lineStartPoint.x = parentNodeView.getX() + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = parentNodeView.getY(); - } - yAvg /= parentsViews.size(); - childView.setEndY(yAvg); - - childView.setDepth(depth); - - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - - dimension.width = Math.max(dimension.width, childView.getEndX()); - - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } + createViews(childNodeView); + } } - } - break; } - default: - { - int span = 0; - for (TreeTransitionView childView : children) { - span += childView.getSpan(); - } - - span = (int) ((nodeView.getSpan() - span) / 2); - for (int i = 0; i < children.size(); i++) { - TreeTransitionView childView = children.get(i); - - childView.setDepth(depth); - - Point lineStartPoint = childView.getLineStartPoint(0); - lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = yLoc; - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - childView.setEndY( - yLoc - (int) (nodeView.getSpan() / 2) + span + (int) (childView.getSpan() / 2)); - - span += childView.getSpan(); - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } - break; + } + + public void calculateViewLocations(TreeNodeView nodeView, int depth) { + nodeView.setDepth(depth); + int xLoc = (NODE_GAP_WIDTH + DIAMETER) * depth + DIAMETER; + nodeView.setX(xLoc); + dimension.width = Math.max(dimension.width, xLoc); + + TreeTransitionView parentTransView = nodeView.getParentView(); + int yLoc = + parentTransView == null ? (int) nodeView.getSpan() / 2 : parentTransView.getEndY(); + nodeView.setY(yLoc); + + ArrayList children = nodeView.getChildrenViews(); + switch (children.size()) { + case 0: + break; + case 1: + { + TreeTransitionView childView = children.get(0); + + List parentsViews = childView.getParentViews(); + if (parentsViews.size() == 1) { + childView.setEndY(yLoc); + + childView.setDepth(depth); + + Point lineStartPoint = childView.getLineStartPoint(0); + lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = yLoc; + childView.setEndX( + (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + + dimension.width = Math.max(dimension.width, childView.getEndX()); + + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } + } else { + if (parentsViews.size() > 1 + && parentsViews.get(parentsViews.size() - 1) == nodeView) { + int yAvg = 0; + for (int i = 0; i < parentsViews.size(); i++) { + TreeNodeView parentNodeView = parentsViews.get(i); + depth = Math.max(depth, parentNodeView.getDepth()); + yAvg += parentNodeView.getY(); + + Point lineStartPoint = childView.getLineStartPoint(i); + lineStartPoint.x = parentNodeView.getX() + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = parentNodeView.getY(); + } + yAvg /= parentsViews.size(); + childView.setEndY(yAvg); + + childView.setDepth(depth); + + childView.setEndX( + (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + + RADIUS + - TRANS_GAP / 2); + + dimension.width = Math.max(dimension.width, childView.getEndX()); + + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } + } + } + break; + } + default: + { + int span = 0; + for (TreeTransitionView childView : children) { + span += childView.getSpan(); + } + + span = (int) ((nodeView.getSpan() - span) / 2); + for (int i = 0; i < children.size(); i++) { + TreeTransitionView childView = children.get(i); + + childView.setDepth(depth); + + Point lineStartPoint = childView.getLineStartPoint(0); + lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = yLoc; + childView.setEndX( + (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + childView.setEndY( + yLoc + - (int) (nodeView.getSpan() / 2) + + span + + (int) (childView.getSpan() / 2)); + + span += childView.getSpan(); + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } + } + break; + } } } - } - - public void calcSpan(TreeElementView view) { - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - TreeNode node = nodeView.getTreeElement(); - if (nodeView.getChildrenViews().size() == 0) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - if (nodeView.getChildrenViews().size() == 1) { - TreeTransitionView childView = nodeView.getChildrenViews().get(0); - calcSpan(childView); - if (childView.getParentViews().size() > 1) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - nodeView.setSpan(childView.getSpan()); - } - } else { - DisjointSets branches = node.findMergingBranches(); - List children = node.getChildren(); - if (node == children.get(0).getParents().get(0)) { - reorderBranches(node, branches); - ArrayList newChildrenViews = new ArrayList<>(); - for (TreeTransition trans : node.getChildren()) { - newChildrenViews.add((TreeTransitionView) viewMap.get(trans)); + public void calcSpan(TreeElementView view) { + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + TreeNode node = nodeView.getTreeElement(); + if (nodeView.getChildrenViews().size() == 0) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + if (nodeView.getChildrenViews().size() == 1) { + TreeTransitionView childView = nodeView.getChildrenViews().get(0); + calcSpan(childView); + if (childView.getParentViews().size() > 1) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + nodeView.setSpan(childView.getSpan()); + } + } else { + DisjointSets branches = node.findMergingBranches(); + List children = node.getChildren(); + + if (node == children.get(0).getParents().get(0)) { + reorderBranches(node, branches); + ArrayList newChildrenViews = new ArrayList<>(); + for (TreeTransition trans : node.getChildren()) { + newChildrenViews.add((TreeTransitionView) viewMap.get(trans)); + } + nodeView.setChildrenViews(newChildrenViews); + } + + List> mergingSets = branches.getAllSets(); + + double span = 0.0; + for (Set mergeSet : mergingSets) { + if (mergeSet.size() > 1) { + TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); + TreeTransitionView mergePointView = + (TreeTransitionView) viewMap.get(mergePoint); + double subSpan = 0.0; + for (TreeTransition branch : mergeSet) { + TreeTransitionView branchView = + (TreeTransitionView) viewMap.get(branch); + subCalcSpan(branchView, mergePointView); + subSpan += branchView.getSpan(); + } + calcSpan(mergePointView); + span += Math.max(mergePointView.getSpan(), subSpan); + } else { + TreeTransition trans = mergeSet.iterator().next(); + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + calcSpan(transView); + span += transView.getSpan(); + } + } + nodeView.setSpan(span); + } } - nodeView.setChildrenViews(newChildrenViews); - } - - List> mergingSets = branches.getAllSets(); - - double span = 0.0; - for (Set mergeSet : mergingSets) { - if (mergeSet.size() > 1) { - TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); - TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); - double subSpan = 0.0; - for (TreeTransition branch : mergeSet) { - TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); - subCalcSpan(branchView, mergePointView); - subSpan += branchView.getSpan(); - } - calcSpan(mergePointView); - span += Math.max(mergePointView.getSpan(), subSpan); + } else { + TreeTransitionView transView = (TreeTransitionView) view; + TreeNodeView nodeView = transView.getChildView(); + if (nodeView == null) { + transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); } else { - TreeTransition trans = mergeSet.iterator().next(); - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - calcSpan(transView); - span += transView.getSpan(); + calcSpan(nodeView); + transView.setSpan(nodeView.getSpan()); } - } - nodeView.setSpan(span); } - } - } else { - TreeTransitionView transView = (TreeTransitionView) view; - TreeNodeView nodeView = transView.getChildView(); - if (nodeView == null) { - transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - calcSpan(nodeView); - transView.setSpan(nodeView.getSpan()); - } - } - } - - /** - * Calculates the sub span of a given sub tree rooted at the specified view and stops at the tree - * puzzleElement view specified as stop. Stop tree puzzleElement is NOT included in the span - * calculation - * - * @param view - * @param stop - */ - private void subCalcSpan(TreeElementView view, TreeElementView stop) { - // safe-guard for infinite loop - if (view == stop) { - return; - } - - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - TreeNode node = nodeView.getTreeElement(); - if (nodeView.getChildrenViews().size() == 0) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - if (nodeView.getChildrenViews().size() == 1) { - TreeTransitionView childView = nodeView.getChildrenViews().get(0); - if (childView == stop) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - subCalcSpan(childView, stop); - if (childView.getParentViews().size() > 1) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } + + /** + * Calculates the sub span of a given sub tree rooted at the specified view and stops at the + * tree puzzleElement view specified as stop. Stop tree puzzleElement is NOT included in the + * span calculation + * + * @param view + * @param stop + */ + private void subCalcSpan(TreeElementView view, TreeElementView stop) { + // safe-guard for infinite loop + if (view == stop) { + return; + } + + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + TreeNode node = nodeView.getTreeElement(); + if (nodeView.getChildrenViews().size() == 0) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); } else { - nodeView.setSpan(childView.getSpan()); + if (nodeView.getChildrenViews().size() == 1) { + TreeTransitionView childView = nodeView.getChildrenViews().get(0); + if (childView == stop) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + subCalcSpan(childView, stop); + if (childView.getParentViews().size() > 1) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + nodeView.setSpan(childView.getSpan()); + } + } + } else { + DisjointSets branches = node.findMergingBranches(); + List children = node.getChildren(); + + if (node == children.get(0).getParents().get(0)) { + reorderBranches(node, branches); + } + + List> mergingSets = branches.getAllSets(); + + double span = 0.0; + for (Set mergeSet : mergingSets) { + if (mergeSet.size() > 1) { + TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); + TreeTransitionView mergePointView = + (TreeTransitionView) viewMap.get(mergePoint); + double subSpan = 0.0; + for (TreeTransition branch : mergeSet) { + TreeTransitionView branchView = + (TreeTransitionView) viewMap.get(branch); + subCalcSpan(branchView, mergePointView); + subSpan += branchView.getSpan(); + } + subCalcSpan(mergePointView, stop); + span += Math.max(mergePointView.getSpan(), subSpan); + } else { + TreeTransition trans = mergeSet.iterator().next(); + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + subCalcSpan(transView, stop); + span += transView.getSpan(); + } + } + + nodeView.setSpan(span); + } } - } } else { - DisjointSets branches = node.findMergingBranches(); - List children = node.getChildren(); - - if (node == children.get(0).getParents().get(0)) { - reorderBranches(node, branches); - } - - List> mergingSets = branches.getAllSets(); - - double span = 0.0; - for (Set mergeSet : mergingSets) { - if (mergeSet.size() > 1) { - TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); - TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); - double subSpan = 0.0; - for (TreeTransition branch : mergeSet) { - TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); - subCalcSpan(branchView, mergePointView); - subSpan += branchView.getSpan(); - } - subCalcSpan(mergePointView, stop); - span += Math.max(mergePointView.getSpan(), subSpan); + TreeTransitionView transView = (TreeTransitionView) view; + TreeNodeView nodeView = transView.getChildView(); + if (nodeView == null || nodeView == stop) { + transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); } else { - TreeTransition trans = mergeSet.iterator().next(); - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - subCalcSpan(transView, stop); - span += transView.getSpan(); + calcSpan(nodeView); + transView.setSpan(nodeView.getSpan()); } - } + } + } - nodeView.setSpan(span); + /** + * Reorders branches such that merging branches are sequentially grouped together and + * transitions are kept in relative order in the list of child transitions of the specified node + * + * @param node root node of the branches + * @param branches DisjointSets of the child branches of the specified node which determine + * which branches merge + */ + private void reorderBranches(TreeNode node, DisjointSets branches) { + List children = node.getChildren(); + List> mergingSets = branches.getAllSets(); + + List> newOrder = new ArrayList<>(); + for (Set set : mergingSets) { + List mergeBranch = new ArrayList<>(); + newOrder.add(mergeBranch); + children.forEach( + t -> { + if (set.contains(t)) { + mergeBranch.add(t); + } + }); + mergeBranch.sort( + (TreeTransition t1, TreeTransition t2) -> + children.indexOf(t1) <= children.indexOf(t2) ? -1 : 1); } - } - } else { - TreeTransitionView transView = (TreeTransitionView) view; - TreeNodeView nodeView = transView.getChildView(); - if (nodeView == null || nodeView == stop) { - transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - calcSpan(nodeView); - transView.setSpan(nodeView.getSpan()); - } - } - } - - /** - * Reorders branches such that merging branches are sequentially grouped together and transitions - * are kept in relative order in the list of child transitions of the specified node - * - * @param node root node of the branches - * @param branches DisjointSets of the child branches of the specified node which determine which - * branches merge - */ - private void reorderBranches(TreeNode node, DisjointSets branches) { - List children = node.getChildren(); - List> mergingSets = branches.getAllSets(); - - List> newOrder = new ArrayList<>(); - for (Set set : mergingSets) { - List mergeBranch = new ArrayList<>(); - newOrder.add(mergeBranch); - children.forEach( - t -> { - if (set.contains(t)) { - mergeBranch.add(t); - } - }); - mergeBranch.sort( - (TreeTransition t1, TreeTransition t2) -> - children.indexOf(t1) <= children.indexOf(t2) ? -1 : 1); - } - - newOrder.sort( - (List b1, List b2) -> { - int low1 = -1; - int low2 = -1; - for (TreeTransition t1 : b1) { - int curIndex = children.indexOf(t1); - if (low1 == -1 || curIndex < low1) { - low1 = curIndex; - } - } - for (TreeTransition t1 : b2) { - int curIndex = children.indexOf(t1); - if (low1 == -1 || curIndex < low1) { - low1 = curIndex; - } - } - return low1 < low2 ? -1 : 1; - }); - - List newChildren = new ArrayList<>(); - newOrder.forEach(l -> newChildren.addAll(l)); - node.setChildren(newChildren); - } + + newOrder.sort( + (List b1, List b2) -> { + int low1 = -1; + int low2 = -1; + for (TreeTransition t1 : b1) { + int curIndex = children.indexOf(t1); + if (low1 == -1 || curIndex < low1) { + low1 = curIndex; + } + } + for (TreeTransition t1 : b2) { + int curIndex = children.indexOf(t1); + if (low1 == -1 || curIndex < low1) { + low1 = curIndex; + } + } + return low1 < low2 ? -1 : 1; + }); + + List newChildren = new ArrayList<>(); + newOrder.forEach(l -> newChildren.addAll(l)); + node.setChildren(newChildren); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java index e8eddaa6c..71a65b49e 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java @@ -5,160 +5,161 @@ import java.util.List; public class TreeViewSelection { - private ArrayList selectedViews; - private TreeElementView hover; - private Point mousePoint; - - /** TreeViewSelection Constructor creates a tree view selection */ - public TreeViewSelection() { - this.selectedViews = new ArrayList<>(); - this.hover = null; - this.mousePoint = null; - } - - /** - * TreeViewSelection Constructor creates a tree view selection with a selected view - * - * @param view selected view - */ - public TreeViewSelection(TreeElementView view) { - this(); - this.selectedViews.add(view); - } - - /** - * TreeViewSelection Constructor creates a tree view selection with a list of selected views - * - * @param views list of selected views - */ - public TreeViewSelection(List views) { - this(); - this.selectedViews.addAll(views); - } - - /** - * Gets the list of selected tree puzzleElement views - * - * @return list of selected tree puzzleElement views - */ - public List getSelectedViews() { - return selectedViews; - } - - /** - * Gets the first selectedViews in the list of views - * - * @return first selectedViews in the list of views - */ - public TreeElementView getFirstSelection() { - return selectedViews.size() == 0 ? null : selectedViews.get(0); - } - - /** - * Toggles a tree puzzleElement view selectedViews - * - * @param treeElementView a tree puzzleElement view to toggle - */ - public void toggleSelection(TreeElementView treeElementView) { - if (selectedViews.contains(treeElementView)) { - selectedViews.remove(treeElementView); - treeElementView.setSelected(false); - } else { - selectedViews.add(treeElementView); - treeElementView.setSelected(true); + private ArrayList selectedViews; + private TreeElementView hover; + private Point mousePoint; + + /** TreeViewSelection Constructor creates a tree view selection */ + public TreeViewSelection() { + this.selectedViews = new ArrayList<>(); + this.hover = null; + this.mousePoint = null; } - } - - /** - * Adds a tree puzzleElement view selectedViews - * - * @param treeElementView a tree puzzleElement view to add - */ - public void addToSelection(TreeElementView treeElementView) { - if (!selectedViews.contains(treeElementView)) { - selectedViews.add(treeElementView); - treeElementView.setSelected(true); + + /** + * TreeViewSelection Constructor creates a tree view selection with a selected view + * + * @param view selected view + */ + public TreeViewSelection(TreeElementView view) { + this(); + this.selectedViews.add(view); + } + + /** + * TreeViewSelection Constructor creates a tree view selection with a list of selected views + * + * @param views list of selected views + */ + public TreeViewSelection(List views) { + this(); + this.selectedViews.addAll(views); + } + + /** + * Gets the list of selected tree puzzleElement views + * + * @return list of selected tree puzzleElement views + */ + public List getSelectedViews() { + return selectedViews; + } + + /** + * Gets the first selectedViews in the list of views + * + * @return first selectedViews in the list of views + */ + public TreeElementView getFirstSelection() { + return selectedViews.size() == 0 ? null : selectedViews.get(0); + } + + /** + * Toggles a tree puzzleElement view selectedViews + * + * @param treeElementView a tree puzzleElement view to toggle + */ + public void toggleSelection(TreeElementView treeElementView) { + if (selectedViews.contains(treeElementView)) { + selectedViews.remove(treeElementView); + treeElementView.setSelected(false); + } else { + selectedViews.add(treeElementView); + treeElementView.setSelected(true); + } + } + + /** + * Adds a tree puzzleElement view selectedViews + * + * @param treeElementView a tree puzzleElement view to add + */ + public void addToSelection(TreeElementView treeElementView) { + if (!selectedViews.contains(treeElementView)) { + selectedViews.add(treeElementView); + treeElementView.setSelected(true); + } + } + + /** + * Creates a new selectedViews and add the specified tree puzzleElement view + * + * @param treeElementView tree puzzleElement view + */ + public void newSelection(TreeElementView treeElementView) { + clearSelection(); + selectedViews.add(treeElementView); + treeElementView.setSelected(true); + } + + /** Clears all selected views */ + public void clearSelection() { + for (TreeElementView treeElementView : selectedViews) { + treeElementView.setSelected(false); + } + selectedViews.clear(); + } + + /** + * Gets tree puzzleElement view that the mouse is hovering over or null is no such view exists + * + * @return tree puzzleElement view that the mouse is hovering over or null is no such view + * exists + */ + public TreeElementView getHover() { + return hover; + } + + /** + * Clears the previous hover and sets the specified tree puzzleElement view to the new hover + * + * @param newHovered tree puzzleElement view for the new hover + */ + public void newHover(TreeElementView newHovered) { + newHovered.setHover(true); + if (hover != null) { + hover.setHover(false); + } + hover = newHovered; + } + + /** Clears the current hover tree puzzleElement view */ + public void clearHover() { + if (hover != null) { + hover.setHover(false); + hover = null; + } } - } - - /** - * Creates a new selectedViews and add the specified tree puzzleElement view - * - * @param treeElementView tree puzzleElement view - */ - public void newSelection(TreeElementView treeElementView) { - clearSelection(); - selectedViews.add(treeElementView); - treeElementView.setSelected(true); - } - - /** Clears all selected views */ - public void clearSelection() { - for (TreeElementView treeElementView : selectedViews) { - treeElementView.setSelected(false); + + /** + * Gets the current mouse location relative to the tree view + * + * @return the current mouse location relative to the tree view + */ + public Point getMousePoint() { + return mousePoint; } - selectedViews.clear(); - } - - /** - * Gets tree puzzleElement view that the mouse is hovering over or null is no such view exists - * - * @return tree puzzleElement view that the mouse is hovering over or null is no such view exists - */ - public TreeElementView getHover() { - return hover; - } - - /** - * Clears the previous hover and sets the specified tree puzzleElement view to the new hover - * - * @param newHovered tree puzzleElement view for the new hover - */ - public void newHover(TreeElementView newHovered) { - newHovered.setHover(true); - if (hover != null) { - hover.setHover(false); + + /** + * Sets the current mouse location relative to the tree view + * + * @param point the current mouse location relative to the tree view + */ + public void setMousePoint(Point point) { + this.mousePoint = point; } - hover = newHovered; - } - - /** Clears the current hover tree puzzleElement view */ - public void clearHover() { - if (hover != null) { - hover.setHover(false); - hover = null; + + /** + * Copies the TreeViewSelection + * + * @return a copy of this TreeViewSelection + */ + @SuppressWarnings("unchecked") + public TreeViewSelection copy() { + TreeViewSelection cpy = new TreeViewSelection(); + cpy.selectedViews = (ArrayList) selectedViews.clone(); + cpy.hover = hover; + cpy.mousePoint = mousePoint; + return cpy; } - } - - /** - * Gets the current mouse location relative to the tree view - * - * @return the current mouse location relative to the tree view - */ - public Point getMousePoint() { - return mousePoint; - } - - /** - * Sets the current mouse location relative to the tree view - * - * @param point the current mouse location relative to the tree view - */ - public void setMousePoint(Point point) { - this.mousePoint = point; - } - - /** - * Copies the TreeViewSelection - * - * @return a copy of this TreeViewSelection - */ - @SuppressWarnings("unchecked") - public TreeViewSelection copy() { - TreeViewSelection cpy = new TreeViewSelection(); - cpy.selectedViews = (ArrayList) selectedViews.clone(); - cpy.hover = hover; - cpy.mousePoint = mousePoint; - return cpy; - } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java index 4c7098765..552d517b9 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java @@ -7,31 +7,31 @@ public class ElementButton extends JButton { - private Element element; - private final Border originalBorder; - - ElementButton(Element e) { - super(e.getImageIcon()); - this.element = e; - this.originalBorder = this.getBorder(); - this.setFocusPainted(false); - } - - public Element getElement() { - return element; - } - - public void setElement(Element e) { - this.element = e; - } - - public void setBorderToSelected() { - Border newBorderIn = BorderFactory.createLineBorder(new Color(20, 140, 70), 2, true); - Border newBorder = BorderFactory.createCompoundBorder(newBorderIn, this.originalBorder); - this.setBorder(newBorder); - } - - public void resetBorder() { - this.setBorder(this.originalBorder); - } + private Element element; + private final Border originalBorder; + + ElementButton(Element e) { + super(e.getImageIcon()); + this.element = e; + this.originalBorder = this.getBorder(); + this.setFocusPainted(false); + } + + public Element getElement() { + return element; + } + + public void setElement(Element e) { + this.element = e; + } + + public void setBorderToSelected() { + Border newBorderIn = BorderFactory.createLineBorder(new Color(20, 140, 70), 2, true); + Border newBorder = BorderFactory.createCompoundBorder(newBorderIn, this.originalBorder); + this.setBorder(newBorder); + } + + public void resetBorder() { + this.setBorder(this.originalBorder); + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java index 2a7119abb..e0524f84d 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java @@ -8,91 +8,92 @@ import javax.swing.border.TitledBorder; public class ElementFrame extends JPanel { - private static final String checkBox = " \u2714 "; - private static final String xBox = " \u2718 "; - private static final String htmlHead = ""; - private static final String htmlTail = ""; - - private PlaceableElementPanel placeableElementPanel; - private NonPlaceableElementPanel nonPlaceableElementPanel; - private JTabbedPane tabbedPane; - private ButtonGroup buttonGroup; - - private EditorElementController controller; - - public ElementFrame(EditorElementController controller) { - this.controller = controller; - MaterialTabbedPaneUI tabOverride = - new MaterialTabbedPaneUI() { - // this prevents the tabs from moving around when you select them - @Override - protected boolean shouldRotateTabRuns(int i) { - return false; - } - }; - - this.tabbedPane = new JTabbedPane(); - tabbedPane.setUI(tabOverride); - JLabel status = new JLabel("", SwingConstants.CENTER); - this.buttonGroup = new ButtonGroup(); - - nonPlaceableElementPanel = new NonPlaceableElementPanel(this); - // nonPlaceableElementPanel.setMinimumSize(new Dimension(100,200)); - tabbedPane.addTab( - nonPlaceableElementPanel.getName(), - nonPlaceableElementPanel.getIcon(), - new JScrollPane(nonPlaceableElementPanel), - nonPlaceableElementPanel.getToolTip()); - - placeableElementPanel = new PlaceableElementPanel(this); - // placeableElementPanel.setMinimuSize(new Dimension(100,200)); - tabbedPane.addTab( - placeableElementPanel.getName(), - placeableElementPanel.getIcon(), - new JScrollPane(placeableElementPanel), - placeableElementPanel.getToolTip()); - tabbedPane.setTabPlacement(JTabbedPane.TOP); - - setLayout(new BorderLayout()); - setMinimumSize(new Dimension(250, 256)); - setPreferredSize(new Dimension(330, 256)); - - add(tabbedPane); - add(status, BorderLayout.SOUTH); - - TitledBorder title = BorderFactory.createTitledBorder("Elements"); - title.setTitleJustification(TitledBorder.CENTER); - setBorder(title); - } - - public ButtonGroup getButtonGroup() { - return buttonGroup; - } - - public void resetSize() { - int buttonWidth = - ((ElementPanel) tabbedPane.getSelectedComponent()).getElementButtons()[0].getWidth(); - this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); - } - - public void setElements(Puzzle puzzle) { - nonPlaceableElementPanel.setElements(puzzle.getNonPlaceableElements()); - placeableElementPanel.setElements(puzzle.getPlaceableElements()); - } - - public EditorElementController getController() { - return controller; - } - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - public NonPlaceableElementPanel getNonPlaceableElementPanel() { - return nonPlaceableElementPanel; - } - - public PlaceableElementPanel getPlaceableElementPanel() { - return placeableElementPanel; - } + private static final String checkBox = " \u2714 "; + private static final String xBox = " \u2718 "; + private static final String htmlHead = ""; + private static final String htmlTail = ""; + + private PlaceableElementPanel placeableElementPanel; + private NonPlaceableElementPanel nonPlaceableElementPanel; + private JTabbedPane tabbedPane; + private ButtonGroup buttonGroup; + + private EditorElementController controller; + + public ElementFrame(EditorElementController controller) { + this.controller = controller; + MaterialTabbedPaneUI tabOverride = + new MaterialTabbedPaneUI() { + // this prevents the tabs from moving around when you select them + @Override + protected boolean shouldRotateTabRuns(int i) { + return false; + } + }; + + this.tabbedPane = new JTabbedPane(); + tabbedPane.setUI(tabOverride); + JLabel status = new JLabel("", SwingConstants.CENTER); + this.buttonGroup = new ButtonGroup(); + + nonPlaceableElementPanel = new NonPlaceableElementPanel(this); + // nonPlaceableElementPanel.setMinimumSize(new Dimension(100,200)); + tabbedPane.addTab( + nonPlaceableElementPanel.getName(), + nonPlaceableElementPanel.getIcon(), + new JScrollPane(nonPlaceableElementPanel), + nonPlaceableElementPanel.getToolTip()); + + placeableElementPanel = new PlaceableElementPanel(this); + // placeableElementPanel.setMinimuSize(new Dimension(100,200)); + tabbedPane.addTab( + placeableElementPanel.getName(), + placeableElementPanel.getIcon(), + new JScrollPane(placeableElementPanel), + placeableElementPanel.getToolTip()); + tabbedPane.setTabPlacement(JTabbedPane.TOP); + + setLayout(new BorderLayout()); + setMinimumSize(new Dimension(250, 256)); + setPreferredSize(new Dimension(330, 256)); + + add(tabbedPane); + add(status, BorderLayout.SOUTH); + + TitledBorder title = BorderFactory.createTitledBorder("Elements"); + title.setTitleJustification(TitledBorder.CENTER); + setBorder(title); + } + + public ButtonGroup getButtonGroup() { + return buttonGroup; + } + + public void resetSize() { + int buttonWidth = + ((ElementPanel) tabbedPane.getSelectedComponent()) + .getElementButtons()[0].getWidth(); + this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); + } + + public void setElements(Puzzle puzzle) { + nonPlaceableElementPanel.setElements(puzzle.getNonPlaceableElements()); + placeableElementPanel.setElements(puzzle.getPlaceableElements()); + } + + public EditorElementController getController() { + return controller; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public NonPlaceableElementPanel getNonPlaceableElementPanel() { + return nonPlaceableElementPanel; + } + + public PlaceableElementPanel getPlaceableElementPanel() { + return placeableElementPanel; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java index 725bafe3b..46198e226 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java @@ -7,74 +7,75 @@ import javax.swing.*; public abstract class ElementPanel extends JPanel { - protected ImageIcon icon; - protected String name; - protected String toolTip; - protected ElementButton[] elementButtons; - protected ElementFrame elementFrame; - protected List elements; + protected ImageIcon icon; + protected String name; + protected String toolTip; + protected ElementButton[] elementButtons; + protected ElementFrame elementFrame; + protected List elements; - public ElementPanel(ElementFrame eFrame) { - this.elementFrame = eFrame; - this.elements = new ArrayList<>(); - setLayout(new WrapLayout()); - } + public ElementPanel(ElementFrame eFrame) { + this.elementFrame = eFrame; + this.elements = new ArrayList<>(); + setLayout(new WrapLayout()); + } - public void setElements(List elements) { - this.elements = elements; - clearButtons(); + public void setElements(List elements) { + this.elements = elements; + clearButtons(); - elementButtons = new ElementButton[elements.size()]; - System.out.println("adding " + elements.size() + " elements to panel"); - for (int i = 0; i < elements.size(); i++) { - Element element = elements.get(i); - elementButtons[i] = new ElementButton(element); - elementFrame.getButtonGroup().add(elementButtons[i]); - System.out.printf("added button: %d, element %s\n", i, element.getElementName()); + elementButtons = new ElementButton[elements.size()]; + System.out.println("adding " + elements.size() + " elements to panel"); + for (int i = 0; i < elements.size(); i++) { + Element element = elements.get(i); + elementButtons[i] = new ElementButton(element); + elementFrame.getButtonGroup().add(elementButtons[i]); + System.out.printf("added button: %d, element %s\n", i, element.getElementName()); - elementButtons[i].setToolTipText(element.getElementName() + ": " + element.getDescription()); - elementButtons[i].addActionListener(elementFrame.getController()); - add(elementButtons[i]); + elementButtons[i].setToolTipText( + element.getElementName() + ": " + element.getDescription()); + elementButtons[i].addActionListener(elementFrame.getController()); + add(elementButtons[i]); + } + revalidate(); } - revalidate(); - } - protected void clearButtons() { - if (elementButtons != null) { - removeAll(); - for (int x = 0; x < elementButtons.length; ++x) { - elementButtons[x].removeActionListener(elementFrame.getController()); - } + protected void clearButtons() { + if (elementButtons != null) { + removeAll(); + for (int x = 0; x < elementButtons.length; ++x) { + elementButtons[x].removeActionListener(elementFrame.getController()); + } + } } - } - public ElementButton[] getElementButtons() { - return elementButtons; - } + public ElementButton[] getElementButtons() { + return elementButtons; + } - public ImageIcon getIcon() { - return icon; - } + public ImageIcon getIcon() { + return icon; + } - public void setIcon(ImageIcon icon) { - this.icon = icon; - } + public void setIcon(ImageIcon icon) { + this.icon = icon; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public void setName(String name) { - this.name = name; - } + @Override + public void setName(String name) { + this.name = name; + } - public String getToolTip() { - return toolTip; - } + public String getToolTip() { + return toolTip; + } - public void setToolTip(String toolTip) { - this.toolTip = toolTip; - } + public void setToolTip(String toolTip) { + this.toolTip = toolTip; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java index b6d447c8f..00b4f5379 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java @@ -3,13 +3,13 @@ import javax.swing.*; public class NonPlaceableElementPanel extends ElementPanel { - public NonPlaceableElementPanel(ElementFrame elementFrame) { - super(elementFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Non-Placeable Elements"; - this.toolTip = "Non-Placeable Elements"; - } + public NonPlaceableElementPanel(ElementFrame elementFrame) { + super(elementFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Non-Placeable Elements"; + this.toolTip = "Non-Placeable Elements"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java index 2d9a09962..088e18f8c 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java @@ -3,13 +3,13 @@ import javax.swing.*; public class PlaceableElementPanel extends ElementPanel { - public PlaceableElementPanel(ElementFrame elementFrame) { - super(elementFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Placeable Elements"; - this.toolTip = "Placeable Elements"; - } + public PlaceableElementPanel(ElementFrame elementFrame) { + super(elementFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Placeable Elements"; + this.toolTip = "Placeable Elements"; + } } diff --git a/src/main/java/edu/rpi/legup/user/Submission.java b/src/main/java/edu/rpi/legup/user/Submission.java index 2fe174946..42373d2ec 100644 --- a/src/main/java/edu/rpi/legup/user/Submission.java +++ b/src/main/java/edu/rpi/legup/user/Submission.java @@ -3,7 +3,7 @@ import edu.rpi.legup.model.gameboard.Board; public class Submission { - public Submission(Board board) {} + public Submission(Board board) {} - public void submit() {} + public void submit() {} } diff --git a/src/main/java/edu/rpi/legup/user/UsageStatistics.java b/src/main/java/edu/rpi/legup/user/UsageStatistics.java index 80867e445..0bc5d1c62 100644 --- a/src/main/java/edu/rpi/legup/user/UsageStatistics.java +++ b/src/main/java/edu/rpi/legup/user/UsageStatistics.java @@ -11,43 +11,43 @@ public class UsageStatistics { - private static final String url = "https://legup-3b4a5.firebaseio.com/databases/test.json"; + private static final String url = "https://legup-3b4a5.firebaseio.com/databases/test.json"; - public UsageStatistics() {} - - public boolean sendErrorReport() { - try { - HttpClient httpclient = new DefaultHttpClient(); - - HttpPost httppost = new HttpPost(url); - - // Request parameters and other properties. - httppost.setEntity(new StringEntity("{\"test\": \"jeff\"}")); - // List params = new ArrayList<>(2); - // params.add(new BasicNameValuePair("param-1", "12345")); - // params.add(new BasicNameValuePair("param-2", "Hello!")); - // httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); - - // Execute and get the response. - HttpResponse response = httpclient.execute(httppost); - HttpEntity entity = response.getEntity(); - - if (entity != null) { - InputStream instream = entity.getContent(); + public UsageStatistics() {} + public boolean sendErrorReport() { try { - // System.err.println(new String(instream.readAllBytes())); - } finally { - instream.close(); + HttpClient httpclient = new DefaultHttpClient(); + + HttpPost httppost = new HttpPost(url); + + // Request parameters and other properties. + httppost.setEntity(new StringEntity("{\"test\": \"jeff\"}")); + // List params = new ArrayList<>(2); + // params.add(new BasicNameValuePair("param-1", "12345")); + // params.add(new BasicNameValuePair("param-2", "Hello!")); + // httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + + // Execute and get the response. + HttpResponse response = httpclient.execute(httppost); + HttpEntity entity = response.getEntity(); + + if (entity != null) { + InputStream instream = entity.getContent(); + + try { + // System.err.println(new String(instream.readAllBytes())); + } finally { + instream.close(); + } + } + } catch (IOException e) { + return false; } - } - } catch (IOException e) { - return false; + return false; } - return false; - } - public static void main(String[] args) { - new UsageStatistics().sendErrorReport(); - } + public static void main(String[] args) { + new UsageStatistics().sendErrorReport(); + } } diff --git a/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java b/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java index c52264674..14b68ba40 100644 --- a/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java +++ b/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java @@ -7,66 +7,72 @@ import java.util.Set; public final class ConnectedRegions { - public static List> getConnectedRegions( - int boundaryCell, int[][] cells, int width, int height) { - Set boundaryCells = new HashSet<>(); - boundaryCells.add(boundaryCell); - return getConnectedRegions(boundaryCells, cells, width, height); - } + public static List> getConnectedRegions( + int boundaryCell, int[][] cells, int width, int height) { + Set boundaryCells = new HashSet<>(); + boundaryCells.add(boundaryCell); + return getConnectedRegions(boundaryCells, cells, width, height); + } - public static List> getConnectedRegions( - Set boundaryCells, int[][] cells, int width, int height) { - boolean[][] visited = new boolean[height][width]; - List> results = new ArrayList<>(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - Set region = floodfill(boundaryCells, cells, visited, width, height, x, y); - if (region.size() > 0) { - results.add(region); + public static List> getConnectedRegions( + Set boundaryCells, int[][] cells, int width, int height) { + boolean[][] visited = new boolean[height][width]; + List> results = new ArrayList<>(); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + Set region = floodfill(boundaryCells, cells, visited, width, height, x, y); + if (region.size() > 0) { + results.add(region); + } + } } - } + return results; } - return results; - } - public static boolean regionContains(int toFind, int[][] cells, Set region) { - for (Point p : region) { - if (cells[p.y][p.x] == toFind) { - return true; - } + public static boolean regionContains(int toFind, int[][] cells, Set region) { + for (Point p : region) { + if (cells[p.y][p.x] == toFind) { + return true; + } + } + return false; } - return false; - } - - public static Set getRegionAroundPoint( - Point p, int boundaryCell, int[][] cells, int width, int height) { - Set boundaryCells = new HashSet<>(); - boundaryCells.add(boundaryCell); - return getRegionAroundPoint(p, boundaryCells, cells, width, height); - } - public static Set getRegionAroundPoint( - Point p, Set boundaryCells, int[][] cells, int width, int height) { - return floodfill(boundaryCells, cells, new boolean[height][width], width, height, p.x, p.y); - } - - private static Set floodfill( - Set boundaryCells, int[][] cells, boolean[][] visited, int w, int h, int x, int y) { - HashSet result = new HashSet<>(); - if ((x < 0) || (x >= w)) { - return result; + public static Set getRegionAroundPoint( + Point p, int boundaryCell, int[][] cells, int width, int height) { + Set boundaryCells = new HashSet<>(); + boundaryCells.add(boundaryCell); + return getRegionAroundPoint(p, boundaryCells, cells, width, height); } - if ((y < 0) || (y >= h)) { - return result; + + public static Set getRegionAroundPoint( + Point p, Set boundaryCells, int[][] cells, int width, int height) { + return floodfill(boundaryCells, cells, new boolean[height][width], width, height, p.x, p.y); } - if (!visited[y][x] && (!boundaryCells.contains(cells[y][x]))) { - result.add(new Point(x, y)); - visited[y][x] = true; - for (int delta = -1; delta < 2; delta += 2) { - result.addAll(floodfill(boundaryCells, cells, visited, w, h, x + delta, y)); - result.addAll(floodfill(boundaryCells, cells, visited, w, h, x, y + delta)); - } + + private static Set floodfill( + Set boundaryCells, + int[][] cells, + boolean[][] visited, + int w, + int h, + int x, + int y) { + HashSet result = new HashSet<>(); + if ((x < 0) || (x >= w)) { + return result; + } + if ((y < 0) || (y >= h)) { + return result; + } + if (!visited[y][x] && (!boundaryCells.contains(cells[y][x]))) { + result.add(new Point(x, y)); + visited[y][x] = true; + for (int delta = -1; delta < 2; delta += 2) { + result.addAll(floodfill(boundaryCells, cells, visited, w, h, x + delta, y)); + result.addAll(floodfill(boundaryCells, cells, visited, w, h, x, y + delta)); + } + } + return result; } - return result; - } } diff --git a/src/main/java/edu/rpi/legup/utility/DisjointSets.java b/src/main/java/edu/rpi/legup/utility/DisjointSets.java index da2dcb408..f33b8993c 100644 --- a/src/main/java/edu/rpi/legup/utility/DisjointSets.java +++ b/src/main/java/edu/rpi/legup/utility/DisjointSets.java @@ -3,164 +3,164 @@ import java.util.*; public class DisjointSets { - private Map parents; - private Map depths; - private Map> sets; + private Map parents; + private Map depths; + private Map> sets; - /** DisjointSets Constructor creates an empty DisjointSets */ - public DisjointSets() { - this.parents = new HashMap<>(); - this.depths = new HashMap<>(); - this.sets = new HashMap<>(); - } + /** DisjointSets Constructor creates an empty DisjointSets */ + public DisjointSets() { + this.parents = new HashMap<>(); + this.depths = new HashMap<>(); + this.sets = new HashMap<>(); + } - /** - * Creates a unique set that contains the specified puzzleElement. If the specified puzzleElement - * is null or another set already contains that puzzleElement, this method returns false, - * indicating that a set was not created - * - * @param u puzzleElement to create the set from - * @return true if the set was created, false otherwise - */ - public boolean createSet(T u) { - if (u == null || parents.containsKey(u)) { - return false; - } else { - parents.put(u, u); - depths.put(u, 0); - Set newSet = new HashSet<>(); - newSet.add(u); - sets.put(u, newSet); - return true; + /** + * Creates a unique set that contains the specified puzzleElement. If the specified + * puzzleElement is null or another set already contains that puzzleElement, this method returns + * false, indicating that a set was not created + * + * @param u puzzleElement to create the set from + * @return true if the set was created, false otherwise + */ + public boolean createSet(T u) { + if (u == null || parents.containsKey(u)) { + return false; + } else { + parents.put(u, u); + depths.put(u, 0); + Set newSet = new HashSet<>(); + newSet.add(u); + sets.put(u, newSet); + return true; + } } - } - /** - * Finds and returns the representative set puzzleElement of the set that the specified - * puzzleElement contains - * - * @param p puzzleElement of the set of which to find - * @return representative set puzzleElement or null if the specified puzzleElement is null or is - * not in the DisjointSets - */ - public T find(T p) { - if (p == null || parents.get(p) == null) { - return null; - } else { - if (p != parents.get(p)) { - parents.put(p, find(parents.get(p))); - } + /** + * Finds and returns the representative set puzzleElement of the set that the specified + * puzzleElement contains + * + * @param p puzzleElement of the set of which to find + * @return representative set puzzleElement or null if the specified puzzleElement is null or is + * not in the DisjointSets + */ + public T find(T p) { + if (p == null || parents.get(p) == null) { + return null; + } else { + if (p != parents.get(p)) { + parents.put(p, find(parents.get(p))); + } + } + return parents.get(p); } - return parents.get(p); - } - /** - * Unions two sets together. If the set are non-null and disjoint, then it returns true, false - * otherwise - * - * @param p set one - * @param q set two - * @return returns true if sets are non-null and disjoint, false otherwise - */ - public boolean union(T p, T q) { - T pid = find(p); - T qid = find(q); - if (pid == null || qid == null || pid == qid) { - return false; - } else { - if (depths.get(pid) > depths.get(qid)) { - parents.put(qid, pid); - sets.get(pid).addAll(sets.get(qid)); - sets.remove(qid); - } else { - parents.put(pid, qid); - sets.get(qid).addAll(sets.get(pid)); - sets.remove(pid); - if (depths.get(pid) == depths.get(qid)) { - depths.put(qid, depths.get(qid) + 1); + /** + * Unions two sets together. If the set are non-null and disjoint, then it returns true, false + * otherwise + * + * @param p set one + * @param q set two + * @return returns true if sets are non-null and disjoint, false otherwise + */ + public boolean union(T p, T q) { + T pid = find(p); + T qid = find(q); + if (pid == null || qid == null || pid == qid) { + return false; + } else { + if (depths.get(pid) > depths.get(qid)) { + parents.put(qid, pid); + sets.get(pid).addAll(sets.get(qid)); + sets.remove(qid); + } else { + parents.put(pid, qid); + sets.get(qid).addAll(sets.get(pid)); + sets.remove(pid); + if (depths.get(pid) == depths.get(qid)) { + depths.put(qid, depths.get(qid) + 1); + } + } + return true; } - } - return true; } - } - /** - * Unions to elements together, if either puzzleElement is not already in the DisjointSets, it - * creates a set for the puzzleElement then unions the sets together. If either puzzleElement is - * null, no action is taken. - * - * @param p puzzleElement one - * @param q puzzleElement two - */ - public void addAndUnion(T p, T q) { - if (p != null && q != null) { - T pid = find(p); - if (pid == null) { - createSet(p); - } - T qid = find(q); - if (qid == null) { - createSet(q); - } - union(p, q); + /** + * Unions to elements together, if either puzzleElement is not already in the DisjointSets, it + * creates a set for the puzzleElement then unions the sets together. If either puzzleElement is + * null, no action is taken. + * + * @param p puzzleElement one + * @param q puzzleElement two + */ + public void addAndUnion(T p, T q) { + if (p != null && q != null) { + T pid = find(p); + if (pid == null) { + createSet(p); + } + T qid = find(q); + if (qid == null) { + createSet(q); + } + union(p, q); + } } - } - /** - * Determines whether the specified puzzleElement is in the DisjointSets - * - * @param u puzzleElement to check - * @return true if the DisjointSets contains the specified puzzleElement, false otherwise - */ - public boolean contains(T u) { - return parents.containsKey(u); - } + /** + * Determines whether the specified puzzleElement is in the DisjointSets + * + * @param u puzzleElement to check + * @return true if the DisjointSets contains the specified puzzleElement, false otherwise + */ + public boolean contains(T u) { + return parents.containsKey(u); + } - /** - * Gets the set of elements that the specified puzzleElement is contained in, or null if no such - * set exists. - * - * @param p puzzleElement to get the set of - * @return the set of elements that the specified puzzleElement if contained in, or null if no - * such set exists - */ - public Set getSet(T p) { - T pid = find(p); - if (pid != null) { - return new HashSet<>(sets.get(pid)); - } else { - return null; + /** + * Gets the set of elements that the specified puzzleElement is contained in, or null if no such + * set exists. + * + * @param p puzzleElement to get the set of + * @return the set of elements that the specified puzzleElement if contained in, or null if no + * such set exists + */ + public Set getSet(T p) { + T pid = find(p); + if (pid != null) { + return new HashSet<>(sets.get(pid)); + } else { + return null; + } } - } - /** - * Gets a list of all of the sets in the DisjointSets - * - * @return list of the sets in the DisjointSets - */ - public List> getAllSets() { - ArrayList> list = new ArrayList<>(); - for (T e : sets.keySet()) { - list.add(new HashSet<>(sets.get(e))); + /** + * Gets a list of all of the sets in the DisjointSets + * + * @return list of the sets in the DisjointSets + */ + public List> getAllSets() { + ArrayList> list = new ArrayList<>(); + for (T e : sets.keySet()) { + list.add(new HashSet<>(sets.get(e))); + } + return list; } - return list; - } - /** - * Gets the number of disjoint sets - * - * @return the number of disjoint sets - */ - public int setCount() { - return sets.size(); - } + /** + * Gets the number of disjoint sets + * + * @return the number of disjoint sets + */ + public int setCount() { + return sets.size(); + } - /** - * Gets the total number of elements among all sets in the DisjointSets - * - * @return the number of elements in the DisjointSets - */ - public int size() { - return parents.size(); - } + /** + * Gets the total number of elements among all sets in the DisjointSets + * + * @return the number of elements in the DisjointSets + */ + public int size() { + return parents.size(); + } } diff --git a/src/main/java/edu/rpi/legup/utility/Entry.java b/src/main/java/edu/rpi/legup/utility/Entry.java index 9cff78750..0686f0dbf 100644 --- a/src/main/java/edu/rpi/legup/utility/Entry.java +++ b/src/main/java/edu/rpi/legup/utility/Entry.java @@ -1,53 +1,53 @@ package edu.rpi.legup.utility; public class Entry { - private K key; - private V value; + private K key; + private V value; - /** - * Entry Constructor creates a key value pair - * - * @param key key - * @param value value - */ - public Entry(K key, V value) { - this.key = key; - this.value = value; - } + /** + * Entry Constructor creates a key value pair + * + * @param key key + * @param value value + */ + public Entry(K key, V value) { + this.key = key; + this.value = value; + } - /** - * Gets the key - * - * @return key - */ - public K getKey() { - return key; - } + /** + * Gets the key + * + * @return key + */ + public K getKey() { + return key; + } - /** - * Sets the key - * - * @param key key - */ - public void setKey(K key) { - this.key = key; - } + /** + * Sets the key + * + * @param key key + */ + public void setKey(K key) { + this.key = key; + } - /** - * Gets the value - * - * @return value - */ - public V getValue() { - return value; - } + /** + * Gets the value + * + * @return value + */ + public V getValue() { + return value; + } - /** - * Set the value - * - * @param value value - */ - public void setValue(V value) { - this.value = value; - } + /** + * Set the value + * + * @param value value + */ + public void setValue(V value) { + this.value = value; + } } diff --git a/src/main/java/edu/rpi/legup/utility/LegupUtils.java b/src/main/java/edu/rpi/legup/utility/LegupUtils.java index cde415f6a..94f119a5e 100644 --- a/src/main/java/edu/rpi/legup/utility/LegupUtils.java +++ b/src/main/java/edu/rpi/legup/utility/LegupUtils.java @@ -14,85 +14,91 @@ public class LegupUtils { - private static final Logger LOGGER = Logger.getLogger(LegupUtils.class.getName()); + private static final Logger LOGGER = Logger.getLogger(LegupUtils.class.getName()); - /** - * Scans all classes accessible from the context class loader which belong to the given package - * and subpackages. - * - * @param packageName The base package - * @return The classes - * @throws ClassNotFoundException if class is not in package - * @throws IOException if file is not found - */ - public static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - assert classLoader != null; - String path = packageName.replace('.', '/'); + /** + * Scans all classes accessible from the context class loader which belong to the given package + * and subpackages. + * + * @param packageName The base package + * @return The classes + * @throws ClassNotFoundException if class is not in package + * @throws IOException if file is not found + */ + public static Class[] getClasses(String packageName) + throws ClassNotFoundException, IOException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + assert classLoader != null; + String path = packageName.replace('.', '/'); - URL url = LegupUtils.class.getProtectionDomain().getCodeSource().getLocation(); - String jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); - if (jarPath.contains(".jar")) { - List css = findClassesZip(jarPath, path); - return css.toArray(new Class[css.size()]); - } + URL url = LegupUtils.class.getProtectionDomain().getCodeSource().getLocation(); + String jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); + if (jarPath.contains(".jar")) { + List css = findClassesZip(jarPath, path); + return css.toArray(new Class[css.size()]); + } - Enumeration resources = classLoader.getResources(path); - List dirs = new ArrayList<>(); - while (resources.hasMoreElements()) { - URL resource = resources.nextElement(); - dirs.add(new File(resource.getFile())); - } + Enumeration resources = classLoader.getResources(path); + List dirs = new ArrayList<>(); + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + dirs.add(new File(resource.getFile())); + } - ArrayList classes = new ArrayList<>(); - for (File directory : dirs) { - classes.addAll(findClasses(directory, packageName)); + ArrayList classes = new ArrayList<>(); + for (File directory : dirs) { + classes.addAll(findClasses(directory, packageName)); + } + return classes.toArray(new Class[classes.size()]); } - return classes.toArray(new Class[classes.size()]); - } - /** - * Recursive method used to find all classes in a given directory and subdirs. - * - * @param directory The base directory - * @param packageName The package name for classes found inside the base directory - * @return The classes - * @throws ClassNotFoundException - */ - private static List findClasses(File directory, String packageName) - throws ClassNotFoundException { - List classes = new ArrayList<>(); - if (!directory.exists()) { - return classes; - } - File[] files = directory.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - assert !file.getName().contains("."); - classes.addAll(findClasses(file, packageName + "." + file.getName())); - } else { - if (file.getName().endsWith(".class")) { - classes.add( - Class.forName( - packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); + /** + * Recursive method used to find all classes in a given directory and subdirs. + * + * @param directory The base directory + * @param packageName The package name for classes found inside the base directory + * @return The classes + * @throws ClassNotFoundException + */ + private static List findClasses(File directory, String packageName) + throws ClassNotFoundException { + List classes = new ArrayList<>(); + if (!directory.exists()) { + return classes; } - } + File[] files = directory.listFiles(); + for (File file : files) { + if (file.isDirectory()) { + assert !file.getName().contains("."); + classes.addAll(findClasses(file, packageName + "." + file.getName())); + } else { + if (file.getName().endsWith(".class")) { + classes.add( + Class.forName( + packageName + + '.' + + file.getName() + .substring(0, file.getName().length() - 6))); + } + } + } + return classes; } - return classes; - } - private static List findClassesZip(String path, String packageName) - throws IOException, ClassNotFoundException { - List classes = new ArrayList<>(); - ZipInputStream zip = new ZipInputStream(new FileInputStream(path)); - for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { - if (!entry.isDirectory() - && entry.getName().endsWith(".class") - && entry.getName().startsWith(packageName)) { - String className = entry.getName().replace('/', '.'); - classes.add(Class.forName(className.substring(0, className.length() - ".class".length()))); - } + private static List findClassesZip(String path, String packageName) + throws IOException, ClassNotFoundException { + List classes = new ArrayList<>(); + ZipInputStream zip = new ZipInputStream(new FileInputStream(path)); + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + if (!entry.isDirectory() + && entry.getName().endsWith(".class") + && entry.getName().startsWith(packageName)) { + String className = entry.getName().replace('/', '.'); + classes.add( + Class.forName( + className.substring(0, className.length() - ".class".length()))); + } + } + return classes; } - return classes; - } } diff --git a/src/main/java/edu/rpi/legup/utility/Logger.java b/src/main/java/edu/rpi/legup/utility/Logger.java index d423043e7..67048e5b4 100644 --- a/src/main/java/edu/rpi/legup/utility/Logger.java +++ b/src/main/java/edu/rpi/legup/utility/Logger.java @@ -12,33 +12,35 @@ public class Logger { - private static final String LEGUP_HOME = - System.getProperty("user.home") + File.separator + ".legup" + File.separator; + private static final String LEGUP_HOME = + System.getProperty("user.home") + File.separator + ".legup" + File.separator; - public static void initLogger() { - LoggerContext context = (LoggerContext) LogManager.getContext(false); - Configuration config = context.getConfiguration(); - ConsoleAppender consoleAppender = config.getAppender("console"); - PatternLayout consolePattern = (PatternLayout) consoleAppender.getLayout(); - TimeBasedTriggeringPolicy triggeringPolicy = - TimeBasedTriggeringPolicy.newBuilder().withInterval(1).withModulate(true).build(); - PatternLayout patternLayout = - PatternLayout.newBuilder().withPattern(consolePattern.getConversionPattern()).build(); - RollingFileAppender rollingFileAppender = - RollingFileAppender.newBuilder() - .setName("fileLogger") - .withFileName(LEGUP_HOME + "legup.log") - .withFilePattern(LEGUP_HOME + "legup-%d{yyyy-MM-dd}.log.gz") - .withPolicy(triggeringPolicy) - .setLayout(patternLayout) - .setConfiguration(config) - .build(); - rollingFileAppender.start(); - config.addAppender(rollingFileAppender); - LoggerConfig rootLogger = config.getRootLogger(); - rootLogger.addAppender(config.getAppender("fileLogger"), null, null); - context.updateLoggers(); + public static void initLogger() { + LoggerContext context = (LoggerContext) LogManager.getContext(false); + Configuration config = context.getConfiguration(); + ConsoleAppender consoleAppender = config.getAppender("console"); + PatternLayout consolePattern = (PatternLayout) consoleAppender.getLayout(); + TimeBasedTriggeringPolicy triggeringPolicy = + TimeBasedTriggeringPolicy.newBuilder().withInterval(1).withModulate(true).build(); + PatternLayout patternLayout = + PatternLayout.newBuilder() + .withPattern(consolePattern.getConversionPattern()) + .build(); + RollingFileAppender rollingFileAppender = + RollingFileAppender.newBuilder() + .setName("fileLogger") + .withFileName(LEGUP_HOME + "legup.log") + .withFilePattern(LEGUP_HOME + "legup-%d{yyyy-MM-dd}.log.gz") + .withPolicy(triggeringPolicy) + .setLayout(patternLayout) + .setConfiguration(config) + .build(); + rollingFileAppender.start(); + config.addAppender(rollingFileAppender); + LoggerConfig rootLogger = config.getRootLogger(); + rootLogger.addAppender(config.getAppender("fileLogger"), null, null); + context.updateLoggers(); - System.setProperty("sun.java2d.noddraw", Boolean.TRUE.toString()); - } + System.setProperty("sun.java2d.noddraw", Boolean.TRUE.toString()); + } } diff --git a/src/test/java/legup/MockGameBoardFacade.java b/src/test/java/legup/MockGameBoardFacade.java index a1505455c..f4f1db938 100644 --- a/src/test/java/legup/MockGameBoardFacade.java +++ b/src/test/java/legup/MockGameBoardFacade.java @@ -6,37 +6,37 @@ import edu.rpi.legup.model.Puzzle; public class MockGameBoardFacade extends GameBoardFacade { - protected MockGameBoardFacade() { - super(); - Config config = null; - try { - config = new Config(); - } catch (InvalidConfigException e) { - System.exit(1); + protected MockGameBoardFacade() { + super(); + Config config = null; + try { + config = new Config(); + } catch (InvalidConfigException e) { + System.exit(1); + } + setConfig(config); } - setConfig(config); - } - /** - * Gets the singleton instance of GameBoardFacade - * - * @return single instance of GameBoardFacade - */ - public static synchronized GameBoardFacade getInstance() { - if (instance == null) { - instance = new MockGameBoardFacade(); + /** + * Gets the singleton instance of GameBoardFacade + * + * @return single instance of GameBoardFacade + */ + public static synchronized GameBoardFacade getInstance() { + if (instance == null) { + instance = new MockGameBoardFacade(); + } + return instance; } - return instance; - } - @Override - public void initializeUI() {} + @Override + public void initializeUI() {} - @Override - public void setPuzzle(Puzzle puzzle) { - this.puzzle = puzzle; - } + @Override + public void setPuzzle(Puzzle puzzle) { + this.puzzle = puzzle; + } - @Override - public void setWindowTitle(String puzzleName, String fileName) {} + @Override + public void setWindowTitle(String puzzleName, String fileName) {} } diff --git a/src/test/java/legup/TestRunner.java b/src/test/java/legup/TestRunner.java index c8c43bcda..40cc5fa6c 100644 --- a/src/test/java/legup/TestRunner.java +++ b/src/test/java/legup/TestRunner.java @@ -11,96 +11,96 @@ /** This class runs all of the tests for the project without needing to run build scripts. */ public class TestRunner { - public static void main(String[] args) { - // Battleship Tests - Result result1 = JUnitCore.runClasses(AdjacentShipsContradictionRuleTest.class); - printTestResults(result1); - Result result2 = JUnitCore.runClasses(FinishWithShipsDirectRuleTests.class); - printTestResults(result2); + public static void main(String[] args) { + // Battleship Tests + Result result1 = JUnitCore.runClasses(AdjacentShipsContradictionRuleTest.class); + printTestResults(result1); + Result result2 = JUnitCore.runClasses(FinishWithShipsDirectRuleTests.class); + printTestResults(result2); - // Lightup Tests - Result result3 = JUnitCore.runClasses(BulbsInPathContradictionRuleTest.class); - printTestResults(result3); - Result result4 = JUnitCore.runClasses(CannotLightACellContradictionRuleTest.class); - printTestResults(result4); - Result result5 = JUnitCore.runClasses(EmptyCellinLightDirectRuleTest.class); - printTestResults(result5); - Result result6 = JUnitCore.runClasses(EmptyCornersDirectRuleTest.class); - printTestResults(result6); - Result result7 = JUnitCore.runClasses(FinishWithBulbsDirectRuleTest.class); - printTestResults(result7); - Result result8 = JUnitCore.runClasses(LightOrEmptyCaseRuleTest.class); - printTestResults(result8); - Result result9 = JUnitCore.runClasses(MustLightDirectRuleTest.class); - printTestResults(result9); - Result result10 = JUnitCore.runClasses(SatisfyNumberCaseRuleTest.class); - printTestResults(result10); - Result result11 = JUnitCore.runClasses(TooFewBulbsContradictionRuleTest.class); - printTestResults(result11); - Result result12 = JUnitCore.runClasses(TooManyBulbsContradictionRuleTest.class); - printTestResults(result12); + // Lightup Tests + Result result3 = JUnitCore.runClasses(BulbsInPathContradictionRuleTest.class); + printTestResults(result3); + Result result4 = JUnitCore.runClasses(CannotLightACellContradictionRuleTest.class); + printTestResults(result4); + Result result5 = JUnitCore.runClasses(EmptyCellinLightDirectRuleTest.class); + printTestResults(result5); + Result result6 = JUnitCore.runClasses(EmptyCornersDirectRuleTest.class); + printTestResults(result6); + Result result7 = JUnitCore.runClasses(FinishWithBulbsDirectRuleTest.class); + printTestResults(result7); + Result result8 = JUnitCore.runClasses(LightOrEmptyCaseRuleTest.class); + printTestResults(result8); + Result result9 = JUnitCore.runClasses(MustLightDirectRuleTest.class); + printTestResults(result9); + Result result10 = JUnitCore.runClasses(SatisfyNumberCaseRuleTest.class); + printTestResults(result10); + Result result11 = JUnitCore.runClasses(TooFewBulbsContradictionRuleTest.class); + printTestResults(result11); + Result result12 = JUnitCore.runClasses(TooManyBulbsContradictionRuleTest.class); + printTestResults(result12); - // nurikabe tests - Result result13 = JUnitCore.runClasses(BlackBetweenRegionsDirectRuleTest.class); - printTestResults(result13); - Result result14 = JUnitCore.runClasses(BlackBottleNeckDirectRuleTest.class); - printTestResults(result14); - Result result15 = JUnitCore.runClasses(BlackOrWhiteCaseRuleTest.class); - printTestResults(result15); - Result result16 = JUnitCore.runClasses(BlackSquareContradictionRuleTest.class); - printTestResults(result16); - Result result17 = JUnitCore.runClasses(CornerBlackDirectRuleTest.class); - printTestResults(result17); - Result result18 = JUnitCore.runClasses(FillinBlackDirectRuleTest.class); - printTestResults(result18); - Result result19 = JUnitCore.runClasses(FillinWhiteDirectRuleTest.class); - printTestResults(result19); - Result result20 = JUnitCore.runClasses(IsolateBlackContradictionRuleTest.class); - printTestResults(result20); - Result result21 = JUnitCore.runClasses(MultipleNumbersContradictionRuleTest.class); - printTestResults(result21); - Result result22 = JUnitCore.runClasses(NoNumbersContradictionRuleTest.class); - printTestResults(result22); - Result result23 = JUnitCore.runClasses(PreventBlackSquareDirectRuleTest.class); - printTestResults(result23); - Result result24 = JUnitCore.runClasses(SurroundRegionDirectRuleTest.class); - printTestResults(result24); - Result result25 = JUnitCore.runClasses(TooFewSpacesContradictionRuleTest.class); - printTestResults(result25); - Result result26 = JUnitCore.runClasses(TooManySpacesContradictionRuleTest.class); - printTestResults(result26); - Result result27 = JUnitCore.runClasses(WhiteBottleNeckDirectRuleTest.class); - printTestResults(result27); + // nurikabe tests + Result result13 = JUnitCore.runClasses(BlackBetweenRegionsDirectRuleTest.class); + printTestResults(result13); + Result result14 = JUnitCore.runClasses(BlackBottleNeckDirectRuleTest.class); + printTestResults(result14); + Result result15 = JUnitCore.runClasses(BlackOrWhiteCaseRuleTest.class); + printTestResults(result15); + Result result16 = JUnitCore.runClasses(BlackSquareContradictionRuleTest.class); + printTestResults(result16); + Result result17 = JUnitCore.runClasses(CornerBlackDirectRuleTest.class); + printTestResults(result17); + Result result18 = JUnitCore.runClasses(FillinBlackDirectRuleTest.class); + printTestResults(result18); + Result result19 = JUnitCore.runClasses(FillinWhiteDirectRuleTest.class); + printTestResults(result19); + Result result20 = JUnitCore.runClasses(IsolateBlackContradictionRuleTest.class); + printTestResults(result20); + Result result21 = JUnitCore.runClasses(MultipleNumbersContradictionRuleTest.class); + printTestResults(result21); + Result result22 = JUnitCore.runClasses(NoNumbersContradictionRuleTest.class); + printTestResults(result22); + Result result23 = JUnitCore.runClasses(PreventBlackSquareDirectRuleTest.class); + printTestResults(result23); + Result result24 = JUnitCore.runClasses(SurroundRegionDirectRuleTest.class); + printTestResults(result24); + Result result25 = JUnitCore.runClasses(TooFewSpacesContradictionRuleTest.class); + printTestResults(result25); + Result result26 = JUnitCore.runClasses(TooManySpacesContradictionRuleTest.class); + printTestResults(result26); + Result result27 = JUnitCore.runClasses(WhiteBottleNeckDirectRuleTest.class); + printTestResults(result27); - // Treetent - Result result28 = JUnitCore.runClasses(EmptyFieldDirectRuleTest.class); - printTestResults(result28); - Result result29 = JUnitCore.runClasses(FinishWithGrassDirectRuleTest.class); - printTestResults(result29); - Result result30 = JUnitCore.runClasses(FinishWithTentsDirectRuleTest.class); - printTestResults(result30); - Result result31 = JUnitCore.runClasses(LastCampingSpotDirectRuleTest.class); - printTestResults(result31); - Result result32 = JUnitCore.runClasses(NoTentForTreeContradictionRuleTest.class); - printTestResults(result32); - Result result33 = JUnitCore.runClasses(NoTreeForTentContradictionRuleTest.class); - printTestResults(result33); - Result result34 = JUnitCore.runClasses(SurroundTentWithGrassDirectRuleTest.class); - printTestResults(result34); - Result result35 = JUnitCore.runClasses(TreeForTentDirectRuleTest.class); - printTestResults(result35); - Result result36 = JUnitCore.runClasses(TentOrGrassCaseRuleTest.class); - printTestResults(result36); - } - - private static void printTestResults(Result result) { - for (Failure failure : result.getFailures()) { - System.out.println(failure.toString()); + // Treetent + Result result28 = JUnitCore.runClasses(EmptyFieldDirectRuleTest.class); + printTestResults(result28); + Result result29 = JUnitCore.runClasses(FinishWithGrassDirectRuleTest.class); + printTestResults(result29); + Result result30 = JUnitCore.runClasses(FinishWithTentsDirectRuleTest.class); + printTestResults(result30); + Result result31 = JUnitCore.runClasses(LastCampingSpotDirectRuleTest.class); + printTestResults(result31); + Result result32 = JUnitCore.runClasses(NoTentForTreeContradictionRuleTest.class); + printTestResults(result32); + Result result33 = JUnitCore.runClasses(NoTreeForTentContradictionRuleTest.class); + printTestResults(result33); + Result result34 = JUnitCore.runClasses(SurroundTentWithGrassDirectRuleTest.class); + printTestResults(result34); + Result result35 = JUnitCore.runClasses(TreeForTentDirectRuleTest.class); + printTestResults(result35); + Result result36 = JUnitCore.runClasses(TentOrGrassCaseRuleTest.class); + printTestResults(result36); } - System.out.println("Tests run: " + result.getRunCount()); - System.out.println("Tests failed: " + result.getFailureCount()); - System.out.println("All tests passed: " + result.wasSuccessful()); - System.out.println(); - } + private static void printTestResults(Result result) { + for (Failure failure : result.getFailures()) { + System.out.println(failure.toString()); + } + + System.out.println("Tests run: " + result.getRunCount()); + System.out.println("Tests failed: " + result.getFailureCount()); + System.out.println("All tests passed: " + result.wasSuccessful()); + System.out.println(); + } } diff --git a/src/test/java/legup/TestUtilities.java b/src/test/java/legup/TestUtilities.java index a5349197c..83ce773d4 100644 --- a/src/test/java/legup/TestUtilities.java +++ b/src/test/java/legup/TestUtilities.java @@ -8,13 +8,13 @@ import edu.rpi.legup.save.InvalidFileFormatException; public final class TestUtilities { - public static void importTestBoard(String fileName, Puzzle puzzle) - throws InvalidFileFormatException { - puzzle.importPuzzle(ClassLoader.getSystemResourceAsStream(fileName)); - Tree tree = puzzle.getTree(); - TreeNode rootNode = tree.getRootNode(); - Board board = rootNode.getBoard().copy(); - TreeTransition transition = new TreeTransition(rootNode, board); - rootNode.getChildren().add(transition); - } + public static void importTestBoard(String fileName, Puzzle puzzle) + throws InvalidFileFormatException { + puzzle.importPuzzle(ClassLoader.getSystemResourceAsStream(fileName)); + Tree tree = puzzle.getTree(); + TreeNode rootNode = tree.getRootNode(); + Board board = rootNode.getBoard().copy(); + TreeTransition transition = new TreeTransition(rootNode, board); + rootNode.getChildren().add(transition); + } } diff --git a/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java b/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java index 350b6b0e7..08b6633db 100644 --- a/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java +++ b/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java @@ -14,57 +14,60 @@ import org.junit.Test; public class AdjacentShipsContradictionRuleTest { - private static final AdjacentShipsContradictionRule RULE = new AdjacentShipsContradictionRule(); + private static final AdjacentShipsContradictionRule RULE = new AdjacentShipsContradictionRule(); - private static Battleship battleship; + private static Battleship battleship; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - battleship = new Battleship(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + battleship = new Battleship(); + } - @Test - public void OrthogonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/AdjacentShipsContradictionRule/OrthogonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void OrthogonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/AdjacentShipsContradictionRule/OrthogonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - } + Assert.assertNotNull(RULE.checkContradiction(board)); + } - @Test - public void InvalidOrthogonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" - + "/AdjacentShipsContradictionRule" - + "/InvalidOrthogonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void InvalidOrthogonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/AdjacentShipsContradictionRule" + + "/InvalidOrthogonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - } + Assert.assertNull(RULE.checkContradiction(board)); + } - @Test - public void DiagonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/AdjacentShipsContradictionRule" + "/DiagonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void DiagonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/AdjacentShipsContradictionRule" + + "/DiagonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - } + Assert.assertNull(RULE.checkContradiction(board)); + } } diff --git a/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java b/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java index a0cf6dc61..1548445fd 100644 --- a/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java +++ b/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java @@ -10,61 +10,62 @@ import org.junit.*; public class FinishWithShipsDirectRuleTests { - private static final FinishWithShipsDirectRule RULE = new FinishWithShipsDirectRule(); + private static final FinishWithShipsDirectRule RULE = new FinishWithShipsDirectRule(); - private static Battleship battleship; + private static Battleship battleship; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - battleship = new Battleship(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + battleship = new Battleship(); + } - // @Test - public void HorizontalValidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalValidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void HorizontalValidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalValidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } + Assert.assertNull(RULE.checkRule(transition)); + } - // @Test - public void VerticaValidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalValidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void VerticaValidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalValidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } + Assert.assertNull(RULE.checkRule(transition)); + } - // @Test - public void HorizontalInvalidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalInvalidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void HorizontalInvalidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/FinishWithShipsBasicRuleTests/HorizontalInvalidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - } + Assert.assertNotNull(RULE.checkRule(transition)); + } - // @Test - public void VerticalInvalidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalInvalidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void VerticalInvalidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalInvalidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - } + Assert.assertNotNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java index b2357b157..316a86f43 100644 --- a/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java @@ -12,78 +12,82 @@ import org.junit.Test; public class BulbsInPathContradictionRuleTest { - private static final BulbsInPathContradictionRule RULE = new BulbsInPathContradictionRule(); - private static LightUp lightUp; + private static final BulbsInPathContradictionRule RULE = new BulbsInPathContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void BulbsInPathContradictionRule_LightInHorizontalPath() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInHorizontalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_LightInHorizontalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInHorizontalPath", + lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + } - @Test - public void BulbsInPathContradictionRule_LightInVerticalPath() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInVerticalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_LightInVerticalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInVerticalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } - @Test - public void BulbsInPathContradictionRule_BlockInVerticalPath() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInVerticalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_BlockInVerticalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInVerticalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } - @Test - public void BulbsInPathContradictionRule_BlockInHorizontalPath() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInHorizontalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_BlockInHorizontalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInHorizontalPath", + lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } } diff --git a/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java index 84dc80c83..6db42d39b 100644 --- a/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java @@ -12,83 +12,83 @@ import org.junit.Test; public class CannotLightACellContradictionRuleTest { - private static final CannotLightACellContradictionRule RULE = - new CannotLightACellContradictionRule(); - private static LightUp lightUp; + private static final CannotLightACellContradictionRule RULE = + new CannotLightACellContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - // extensive full testing of null and non-null in a 5x5 board - public void FullLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/FullLightTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // extensive full testing of null and non-null in a 5x5 board + public void FullLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/FullLightTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm it is impossible to light up these squares - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); + // confirm it is impossible to light up these squares + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); - // confirm these are not required to be lit because they are already lit or unable to be - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); - } + // confirm these are not required to be lit because they are already lit or unable to be + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); + } - @Test - // simple contradiction testing for null and non-null in a 3x3 board - public void CannotLightMiddleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/CannotLight", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // simple contradiction testing for null and non-null in a 3x3 board + public void CannotLightMiddleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/CannotLight", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm it is impossible to light up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to light up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } - @Test - public void CanLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/CanLightTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void CanLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/CanLightTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is not a contradiction somewhere on the board - Assert.assertNotNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is not a contradiction somewhere on the board + Assert.assertNotNull(RULE.checkContradiction(board)); - // confirm that these cells can be lit, are already lit, or that they are just black blocks - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); - } + // confirm that these cells can be lit, are already lit, or that they are just black blocks + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); + } } diff --git a/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java index 289d17e5d..264cf928c 100644 --- a/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java @@ -14,90 +14,92 @@ import org.junit.Test; public class EmptyCellinLightDirectRuleTest { - private static final EmptyCellinLightDirectRule RULE = new EmptyCellinLightDirectRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - @Test - // tests a 3x3 board with with a 0 black tile in the center and lightbulbs in top left and bototm - // right - // confirms the rest of the tiles must be empty - public void EmptyCellinLightDirectRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/EmptyCellinLightDirectRule/EmptyCells", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); - - // change the board's cells considering the emptycellinlight rule - LightUpCell cell2 = board.getCell(1, 0); - cell2.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell2); - - LightUpCell cell3 = board.getCell(0, 1); - cell3.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell3); - - LightUpCell cell4 = board.getCell(2, 0); - cell4.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell4); - - LightUpCell cell5 = board.getCell(0, 2); - cell5.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell5); - - LightUpCell cell6 = board.getCell(1, 2); - cell6.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell6); - - LightUpCell cell7 = board.getCell(2, 1); - cell7.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell7); - - LightUpCell cell8 = board.getCell(3, 0); - cell8.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell8); - - LightUpCell cell9 = board.getCell(3, 2); - cell9.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell9); - - LightUpCell cell10 = board.getCell(2, 3); - cell10.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell10); - - LightUpCell cell11 = board.getCell(0, 3); - cell11.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell11); - - // confirm there is a logical following of the EmptyCellinLight rule - Assert.assertNull(RULE.checkRule(transition)); - - // cells (0,0) and (2,2) are not empty because they have lightbulbs, (1,1) - // because it is a black tile, and (1,3),(3,1),(3,3) because they are not lit. Confirm the rest - // are empty - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 0 && j == 0) - || (i == 2 && j == 2) - || (i == 1 && j == 1) - || (i == 1 && j == 3) - || (i == 3 && j == 1) - || (i == 3 && j == 3)) { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, c)); + private static final EmptyCellinLightDirectRule RULE = new EmptyCellinLightDirectRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + // tests a 3x3 board with with a 0 black tile in the center and lightbulbs in top left and + // bototm + // right + // confirms the rest of the tiles must be empty + public void EmptyCellinLightDirectRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/EmptyCellinLightDirectRule/EmptyCells", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); + + // change the board's cells considering the emptycellinlight rule + LightUpCell cell2 = board.getCell(1, 0); + cell2.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell2); + + LightUpCell cell3 = board.getCell(0, 1); + cell3.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell3); + + LightUpCell cell4 = board.getCell(2, 0); + cell4.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell4); + + LightUpCell cell5 = board.getCell(0, 2); + cell5.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell5); + + LightUpCell cell6 = board.getCell(1, 2); + cell6.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell6); + + LightUpCell cell7 = board.getCell(2, 1); + cell7.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell7); + + LightUpCell cell8 = board.getCell(3, 0); + cell8.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell8); + + LightUpCell cell9 = board.getCell(3, 2); + cell9.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell9); + + LightUpCell cell10 = board.getCell(2, 3); + cell10.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell10); + + LightUpCell cell11 = board.getCell(0, 3); + cell11.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell11); + + // confirm there is a logical following of the EmptyCellinLight rule + Assert.assertNull(RULE.checkRule(transition)); + + // cells (0,0) and (2,2) are not empty because they have lightbulbs, (1,1) + // because it is a black tile, and (1,3),(3,1),(3,3) because they are not lit. Confirm the + // rest + // are empty + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 0 && j == 0) + || (i == 2 && j == 2) + || (i == 1 && j == 1) + || (i == 1 && j == 3) + || (i == 3 && j == 1) + || (i == 3 && j == 3)) { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java index 0af76baeb..a4f958860 100644 --- a/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java @@ -14,65 +14,65 @@ import org.junit.Test; public class EmptyCornersDirectRuleTest { - private static final EmptyCornersDirectRule RULE = new EmptyCornersDirectRule(); - private static LightUp lightUp; + private static final EmptyCornersDirectRule RULE = new EmptyCornersDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void EmptyCornersTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/EmptyCornersDirectRule/EmptyCorners", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void EmptyCornersTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/EmptyCornersDirectRule/EmptyCorners", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the EmptyCorners rule to empty - LightUpCell cell1 = board.getCell(2, 2); - cell1.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell1); + // change the board's cells considering the EmptyCorners rule to empty + LightUpCell cell1 = board.getCell(2, 2); + cell1.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell1); - LightUpCell cell2 = board.getCell(0, 2); - cell2.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell2); + LightUpCell cell2 = board.getCell(0, 2); + cell2.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell2); - LightUpCell cell3 = board.getCell(4, 3); - cell3.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell3); + LightUpCell cell3 = board.getCell(4, 3); + cell3.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell3); - // confirm there is a logical following of the EmptyCorners rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the EmptyCorners rule + Assert.assertNull(RULE.checkRule(transition)); - // this should not be accepted, the cell should remain unknown - LightUpCell cell4 = board.getCell(4, 5); - cell4.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell4); + // this should not be accepted, the cell should remain unknown + LightUpCell cell4 = board.getCell(4, 5); + cell4.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell4); - // this should not be accepted, the cell should be empty but not because of this rule - LightUpCell cell5 = board.getCell(4, 1); - cell5.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell5); + // this should not be accepted, the cell should be empty but not because of this rule + LightUpCell cell5 = board.getCell(4, 1); + cell5.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell5); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - // confirm the two expected cells are emptied USING THE RULE - // and none of the rest are (others can be empty just not by the same rule) - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 2 && j == 0) || (i == 2 && j == 2) || (i == 3 && j == 4)) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + // confirm the two expected cells are emptied USING THE RULE + // and none of the rest are (others can be empty just not by the same rule) + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 2 && j == 0) || (i == 2 && j == 2) || (i == 3 && j == 4)) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java index d1b0422f9..59cbfdbf9 100644 --- a/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java @@ -14,91 +14,92 @@ import org.junit.Test; public class FinishWithBulbsDirectRuleTest { - private static final FinishWithBulbsDirectRule RULE = new FinishWithBulbsDirectRule(); - private static LightUp lightUp; + private static final FinishWithBulbsDirectRule RULE = new FinishWithBulbsDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void FinishBulbTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbs", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void FinishBulbTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbs", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the FinishWithBulbs rule to empty - LightUpCell cell1 = board.getCell(1, 0); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); + // change the board's cells considering the FinishWithBulbs rule to empty + LightUpCell cell1 = board.getCell(1, 0); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - // check every square except the top center (2,0) - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if (i == 0 && j == 1) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + // check every square except the top center (2,0) + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if (i == 0 && j == 1) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - // even though this test isnt a completely filled board because it is unsolveable, it tests - // FinishBulbs properly - @Test - public void FinishBulbTestWithThree() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbsWithThree", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // even though this test isnt a completely filled board because it is unsolveable, it tests + // FinishBulbs properly + @Test + public void FinishBulbTestWithThree() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbsWithThree", + lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the FinishWithBulbs rule to empty - LightUpCell cell1 = board.getCell(1, 2); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); + // change the board's cells considering the FinishWithBulbs rule to empty + LightUpCell cell1 = board.getCell(1, 2); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); - LightUpCell cell2 = board.getCell(0, 1); - cell2.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell2); + LightUpCell cell2 = board.getCell(0, 1); + cell2.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell2); - LightUpCell cell3 = board.getCell(2, 1); - cell3.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell3); + LightUpCell cell3 = board.getCell(2, 1); + cell3.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell3); - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - // check every square for logical following - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 1 && j == 2) || (i == 2 && j == 1) || (i == 1 && j == 0)) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + // check every square for logical following + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 1 && j == 2) || (i == 2 && j == 1) || (i == 1 && j == 0)) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java b/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java index 447e6af24..fa0698edb 100644 --- a/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java @@ -16,59 +16,60 @@ import org.junit.Test; public class LightOrEmptyCaseRuleTest { - private static final LightOrEmptyCaseRule RULE = new LightOrEmptyCaseRule(); - private static LightUp lightUp; + private static final LightOrEmptyCaseRule RULE = new LightOrEmptyCaseRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - // creates boards for what is expected output, and checks that the getcases function produces the - // correct boards - // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) - @Test - public void LightOrEmptyTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/LightOrEmptyCaseRule/LightOrEmpty", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // creates boards for what is expected output, and checks that the getcases function produces + // the + // correct boards + // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) + @Test + public void LightOrEmptyTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/LightOrEmptyCaseRule/LightOrEmpty", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(0, 0); // the focus cell - ArrayList cases = RULE.getCases(b, numbered_cell); + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(0, 0); // the focus cell + ArrayList cases = RULE.getCases(b, numbered_cell); - // assert correct number of cases - Assert.assertEquals(2, cases.size()); + // assert correct number of cases + Assert.assertEquals(2, cases.size()); - // make a list of boards that I expect - LightUpCell change_cell; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + // make a list of boards that I expect + LightUpCell change_cell; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - // change the cells of the first new case board - change_cell = case1.getCell(0, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); + // change the cells of the first new case board + change_cell = case1.getCell(0, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); - change_cell = case1.getCell(1, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); + change_cell = case1.getCell(1, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); - // change the cells of the second new case board - change_cell = case2.getCell(0, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); + // change the cells of the second new case board + change_cell = case2.getCell(0, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); - change_cell = case2.getCell(1, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); + change_cell = case2.getCell(1, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); - // check each board I expect and make sure it exists in returned board list - // currently cases is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - } + // check each board I expect and make sure it exists in returned board list + // currently cases is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + } } diff --git a/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java index 1602b8135..e0e1434c3 100644 --- a/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java @@ -14,45 +14,46 @@ import org.junit.Test; public class MustLightDirectRuleTest { - private static final MustLightDirectRule RULE = new MustLightDirectRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - @Test - public void MustLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/MustLightDirectRule/MustLight", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); - - // change the board's cells considering the MustLight rule - LightUpCell cell1 = board.getCell(1, 2); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); - - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if (i == 2 && j == 1) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + private static final MustLightDirectRule RULE = new MustLightDirectRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + public void MustLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/MustLightDirectRule/MustLight", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); + + // change the board's cells considering the MustLight rule + LightUpCell cell1 = board.getCell(1, 2); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); + + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if (i == 2 && j == 1) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java b/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java index b525b0266..a04f1c520 100644 --- a/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java @@ -16,145 +16,148 @@ import org.junit.Test; public class SatisfyNumberCaseRuleTest { - private static final SatisfyNumberCaseRule RULE = new SatisfyNumberCaseRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - // creates two boards for what is expected output, and checks that the getcases function produces - // the correct boards - // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) - @Test - public void SatisfyNumberTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumber", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(1, 0); // the tile cell - ArrayList cases = - RULE.getCases(b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE - - // assert correct number of cases - Assert.assertEquals(2, cases.size()); - - // make a list of boards that I expect - LightUpCell change_cell; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - - // change the cells of the first new case board - change_cell = case1.getCell(0, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); - - change_cell = case1.getCell(1, 1); - change_cell.setData(LightUpCellType.EMPTY.value); - // case1.addModifiedData(change_cell); - - // change the cells of the second new case board - change_cell = case2.getCell(0, 0); - change_cell.setData(LightUpCellType.EMPTY.value); - // case2.addModifiedData(change_cell); - - change_cell = case2.getCell(1, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); - - // check each board I expect and make sure it exists in returned board list - // currently cases is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - } - - @Test - public void SatisfyNumberTestTwo() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumberTwo", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(1, 1); // the tile cell - ArrayList cases = - RULE.getCases(b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE - - // assert correct number of cases - Assert.assertEquals(6, cases.size()); - - // make a list of boards that I expect - LightUpCell change_cell1; - LightUpCell change_cell2; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case3 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case4 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case5 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case6 = ((LightUpBoard) transition.getBoard()).copy(); - - // case 1: lights in (1,0) and (0,1) - change_cell1 = case1.getCell(1, 0); - change_cell2 = case1.getCell(0, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case1.addModifiedData(change_cell1); - case1.addModifiedData(change_cell2); - - // case 2: lights in (1,0) and (1,2) - change_cell1 = case2.getCell(1, 0); - change_cell2 = case2.getCell(1, 2); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case2.addModifiedData(change_cell1); - case2.addModifiedData(change_cell2); - - // case 3: lights in (1,0) and (2,1) - change_cell1 = case3.getCell(1, 0); - change_cell2 = case3.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case3.addModifiedData(change_cell1); - case3.addModifiedData(change_cell2); - - // case 4: lights in (0,1) and (2,1) - change_cell1 = case4.getCell(0, 1); - change_cell2 = case4.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case4.addModifiedData(change_cell1); - case4.addModifiedData(change_cell2); - - // case 5: lights in (0,1) and (1,2) - change_cell1 = case5.getCell(0, 1); - change_cell2 = case5.getCell(1, 2); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case5.addModifiedData(change_cell1); - case5.addModifiedData(change_cell2); - - // case 6: lights in (1,2) and (2,1) - change_cell1 = case6.getCell(1, 2); - change_cell2 = case6.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case6.addModifiedData(change_cell1); - case6.addModifiedData(change_cell2); - - // check each board I expect and make sure it exists in returned board list - // currently the cases list is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - // Assert.assertTrue(cases.contains((Board) case3)); - // Assert.assertTrue(cases.contains((Board) case4)); - // Assert.assertTrue(cases.contains((Board) case5)); - // Assert.assertTrue(cases.contains((Board) case6)); - } + private static final SatisfyNumberCaseRule RULE = new SatisfyNumberCaseRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + // creates two boards for what is expected output, and checks that the getcases function + // produces + // the correct boards + // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) + @Test + public void SatisfyNumberTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumber", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(1, 0); // the tile cell + ArrayList cases = + RULE.getCases( + b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE + + // assert correct number of cases + Assert.assertEquals(2, cases.size()); + + // make a list of boards that I expect + LightUpCell change_cell; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + + // change the cells of the first new case board + change_cell = case1.getCell(0, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); + + change_cell = case1.getCell(1, 1); + change_cell.setData(LightUpCellType.EMPTY.value); + // case1.addModifiedData(change_cell); + + // change the cells of the second new case board + change_cell = case2.getCell(0, 0); + change_cell.setData(LightUpCellType.EMPTY.value); + // case2.addModifiedData(change_cell); + + change_cell = case2.getCell(1, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); + + // check each board I expect and make sure it exists in returned board list + // currently cases is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + } + + @Test + public void SatisfyNumberTestTwo() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumberTwo", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(1, 1); // the tile cell + ArrayList cases = + RULE.getCases( + b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE + + // assert correct number of cases + Assert.assertEquals(6, cases.size()); + + // make a list of boards that I expect + LightUpCell change_cell1; + LightUpCell change_cell2; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case3 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case4 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case5 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case6 = ((LightUpBoard) transition.getBoard()).copy(); + + // case 1: lights in (1,0) and (0,1) + change_cell1 = case1.getCell(1, 0); + change_cell2 = case1.getCell(0, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case1.addModifiedData(change_cell1); + case1.addModifiedData(change_cell2); + + // case 2: lights in (1,0) and (1,2) + change_cell1 = case2.getCell(1, 0); + change_cell2 = case2.getCell(1, 2); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case2.addModifiedData(change_cell1); + case2.addModifiedData(change_cell2); + + // case 3: lights in (1,0) and (2,1) + change_cell1 = case3.getCell(1, 0); + change_cell2 = case3.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case3.addModifiedData(change_cell1); + case3.addModifiedData(change_cell2); + + // case 4: lights in (0,1) and (2,1) + change_cell1 = case4.getCell(0, 1); + change_cell2 = case4.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case4.addModifiedData(change_cell1); + case4.addModifiedData(change_cell2); + + // case 5: lights in (0,1) and (1,2) + change_cell1 = case5.getCell(0, 1); + change_cell2 = case5.getCell(1, 2); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case5.addModifiedData(change_cell1); + case5.addModifiedData(change_cell2); + + // case 6: lights in (1,2) and (2,1) + change_cell1 = case6.getCell(1, 2); + change_cell2 = case6.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case6.addModifiedData(change_cell1); + case6.addModifiedData(change_cell2); + + // check each board I expect and make sure it exists in returned board list + // currently the cases list is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + // Assert.assertTrue(cases.contains((Board) case3)); + // Assert.assertTrue(cases.contains((Board) case4)); + // Assert.assertTrue(cases.contains((Board) case5)); + // Assert.assertTrue(cases.contains((Board) case6)); + } } diff --git a/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java index 25389f299..fe994baa6 100644 --- a/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java @@ -12,57 +12,57 @@ import org.junit.Test; public class TooFewBulbsContradictionRuleTest { - private static final TooFewBulbsContradictionRule RULE = new TooFewBulbsContradictionRule(); - private static LightUp lightUp; + private static final TooFewBulbsContradictionRule RULE = new TooFewBulbsContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooFewBulbsContradictionRule/FullTooFewTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooFewBulbsContradictionRule/FullTooFewTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm that there arent enough bulbs around the black tiles - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(4, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); + // confirm that there arent enough bulbs around the black tiles + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(4, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); - // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(4, 4))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); - } + // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(4, 4))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); + } - @Test - public void TooFewSimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooFewBulbsContradictionRule/TooFew", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void TooFewSimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooFewBulbsContradictionRule/TooFew", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm it is impossible to satisfy up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to satisfy up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } } diff --git a/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java index 0ee6fdb5e..e27fa3323 100644 --- a/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java @@ -12,57 +12,57 @@ import org.junit.Test; public class TooManyBulbsContradictionRuleTest { - private static final TooManyBulbsContradictionRule RULE = new TooManyBulbsContradictionRule(); - private static LightUp lightUp; + private static final TooManyBulbsContradictionRule RULE = new TooManyBulbsContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - // complex extensive toofew test - public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooManyBulbsContradictionRule/FullTooManyTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // complex extensive toofew test + public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooManyBulbsContradictionRule/FullTooManyTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm that there are too many bulbs around the black tiles - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); + // confirm that there are too many bulbs around the black tiles + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); - // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); - } + // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); + } - @Test - // tests a 3x3 board with a 3 in the center and 4 surrounding lightbulbs - public void TooManySimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooManyBulbsContradictionRule/TooMany", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // tests a 3x3 board with a 3 in the center and 4 surrounding lightbulbs + public void TooManySimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooManyBulbsContradictionRule/TooMany", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm it is impossible to satisfy up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to satisfy up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java index 3fda4956d..d87398303 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java @@ -19,184 +19,186 @@ public class BlackBetweenRegionsDirectRuleTest { - private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other - * (diagonal going from top left to bottom right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(2, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(1, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Black Between Regions direct rule for regions that are diagonal to each other + * (diagonal going from top left to bottom right) + */ + @Test + public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell1 = board.getCell(2, 1); + cell1.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell2 = board.getCell(1, 2); + cell2.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other - * (diagonal going from bottom left to top right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(1, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(2, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Black Between Regions direct rule for regions that are diagonal to each other + * (diagonal going from bottom left to top right) + */ + @Test + public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell1 = board.getCell(1, 1); + cell1.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell2 = board.getCell(2, 2); + cell2.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Black Between Regions direct rule for regions that are horizontally opposite each - * other - */ - @Test - public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Black Between Regions direct rule for regions that are horizontally opposite each + * other + */ + @Test + public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Black Between Regions direct rule for regions that are vertically opposite each other - */ - @Test - public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Black Between Regions direct rule for regions that are vertically opposite each + * other + */ + @Test + public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Black Between Regions direct rule for a false application of the rule, where a black - * tile is enclosed by one region - */ - @Test - public void BlackBetweenRegionsDirectRule_FalseBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/FalseBlackBetweenRegions", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** + * Tests the Black Between Regions direct rule for a false application of the rule, where a + * black tile is enclosed by one region + */ + @Test + public void BlackBetweenRegionsDirectRule_FalseBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/FalseBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java index cddcd7871..262a4bdbd 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java @@ -17,94 +17,94 @@ public class BlackBottleNeckDirectRuleTest { - private static final BlackBottleNeckDirectRule RULE = new BlackBottleNeckDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** Tests the Black BottleNeck direct rule for a bottleneck in the center of the board */ - @Test - public void BlackBottleNeckDirectRule_TwoSurroundBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/SimpleBlackBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final BlackBottleNeckDirectRule RULE = new BlackBottleNeckDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** Tests the Black BottleNeck direct rule for a bottleneck in the center of the board */ + @Test + public void BlackBottleNeckDirectRule_TwoSurroundBlackTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/SimpleBlackBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the Black BottleNeck direct rule for a bottleneck in the corner of the board */ - @Test - public void BlackBottleNeckDirectRule_CornerBottleneck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/CornerBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** Tests the Black BottleNeck direct rule for a bottleneck in the corner of the board */ + @Test + public void BlackBottleNeckDirectRule_CornerBottleneck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/CornerBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Black BottleNeck direct rule for a false bottleneck */ - @Test - public void BlackBottleNeckDirectRule_FalseBottleneck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/FalseBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black BottleNeck direct rule for a false bottleneck */ + @Test + public void BlackBottleNeckDirectRule_FalseBottleneck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/FalseBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.BLACK.toValue()); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java index 65f42ac6e..d8f353393 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java @@ -19,56 +19,57 @@ public class BlackOrWhiteCaseRuleTest { - private static final BlackOrWhiteCaseRule RULE = new BlackOrWhiteCaseRule(); - private static Nurikabe nurikabe; + private static final BlackOrWhiteCaseRule RULE = new BlackOrWhiteCaseRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Black Or White case rule by ensuring that it results in two children, that contain a - * modified cell that is either black or white - */ - @Test - public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackOrWhiteCaseRule/SimpleBlackOrWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Black Or White case rule by ensuring that it results in two children, that contain + * a modified cell that is either black or white + */ + @Test + public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackOrWhiteCaseRule/SimpleBlackOrWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, cell); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, cell); - Assert.assertEquals(2, cases.size()); + Assert.assertEquals(2, cases.size()); - NurikabeBoard caseBoard = (NurikabeBoard) cases.get(0); - NurikabeBoard caseBoard2 = (NurikabeBoard) cases.get(1); + NurikabeBoard caseBoard = (NurikabeBoard) cases.get(0); + NurikabeBoard caseBoard2 = (NurikabeBoard) cases.get(1); - NurikabeType board1Type = caseBoard.getCell(0, 0).getType(); - NurikabeType board2Type = caseBoard2.getCell(0, 0).getType(); + NurikabeType board1Type = caseBoard.getCell(0, 0).getType(); + NurikabeType board2Type = caseBoard2.getCell(0, 0).getType(); - Assert.assertTrue( - (board1Type.equals(NurikabeType.BLACK) || board1Type.equals(NurikabeType.WHITE)) - && (board2Type.equals(NurikabeType.BLACK) || board2Type.equals(NurikabeType.WHITE))); - Assert.assertFalse(board1Type.equals(board2Type)); + Assert.assertTrue( + (board1Type.equals(NurikabeType.BLACK) || board1Type.equals(NurikabeType.WHITE)) + && (board2Type.equals(NurikabeType.BLACK) + || board2Type.equals(NurikabeType.WHITE))); + Assert.assertFalse(board1Type.equals(board2Type)); - Assert.assertEquals(caseBoard.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard.getWidth(), caseBoard2.getWidth(), board.getWidth()); + Assert.assertEquals(caseBoard.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard.getWidth(), caseBoard2.getWidth(), board.getWidth()); - for (int i = 0; i < caseBoard.getHeight(); i++) { - for (int k = 0; k < caseBoard.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(caseBoard.getCell(k, i).getLocation())) { - continue; + for (int i = 0; i < caseBoard.getHeight(); i++) { + for (int k = 0; k < caseBoard.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(caseBoard.getCell(k, i).getLocation())) { + continue; + } + Assert.assertTrue(caseBoard.getCell(k, i).equals(caseBoard2.getCell(k, i))); + } } - Assert.assertTrue(caseBoard.getCell(k, i).equals(caseBoard2.getCell(k, i))); - } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java index d317a7835..d27e546bc 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java @@ -15,97 +15,97 @@ import org.junit.Test; public class BlackSquareContradictionRuleTest { - private static final BlackSquareContradictionRule RULE = new BlackSquareContradictionRule(); - private static Nurikabe nurikabe; + private static final BlackSquareContradictionRule RULE = new BlackSquareContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Black Square contradiction rule for a black square in the middle of the board */ - @Test - public void BlackSquareContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/SimpleBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a black square in the middle of the board */ + @Test + public void BlackSquareContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/SimpleBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); - NurikabeCell cell2 = board.getCell(1, 2); - NurikabeCell cell3 = board.getCell(2, 1); - NurikabeCell cell4 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); + NurikabeCell cell2 = board.getCell(1, 2); + NurikabeCell cell3 = board.getCell(2, 1); + NurikabeCell cell4 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Black Square contradiction rule for a square in the corner of the board */ - @Test - public void BlackSquareContradictionRule_CornerSquareTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/CornerBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a square in the corner of the board */ + @Test + public void BlackSquareContradictionRule_CornerSquareTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/CornerBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 2); - NurikabeCell cell2 = board.getCell(2, 3); - NurikabeCell cell3 = board.getCell(3, 2); - NurikabeCell cell4 = board.getCell(3, 3); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(2, 2); + NurikabeCell cell2 = board.getCell(2, 3); + NurikabeCell cell3 = board.getCell(3, 2); + NurikabeCell cell4 = board.getCell(3, 3); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Black Square contradiction rule for a false contradiction */ - @Test - public void BlackSquareContradictionRule_FalseBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/FalseBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a false contradiction */ + @Test + public void BlackSquareContradictionRule_FalseBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/FalseBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java index deb93c43f..164e08e38 100644 --- a/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java @@ -17,75 +17,76 @@ public class CannotReachCellDirectRuleTest { - private static final CannotReachCellDirectRule RULE = new CannotReachCellDirectRule(); - private static Nurikabe nurikabe; + private static final CannotReachCellDirectRule RULE = new CannotReachCellDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Cannot Reach Cell direct rule for a simple unreachable cell */ - @Test - public void CannotReachCellDirectRule_SimpleUnreachableCell() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CannotReachCellDirectRule/SimpleUnreachableCell", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); + /** Tests the Cannot Reach Cell direct rule for a simple unreachable cell */ + @Test + public void CannotReachCellDirectRule_SimpleUnreachableCell() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CannotReachCellDirectRule/SimpleUnreachableCell", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Cannot Reach Cell direct rule for a more complex board with all cells reachable */ - @Test - public void CannotReachCellDirectRule_AllCellsReachable() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CannotReachCellDirectRule/AllCellsReachable", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); + /** Tests the Cannot Reach Cell direct rule for a more complex board with all cells reachable */ + @Test + public void CannotReachCellDirectRule_AllCellsReachable() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CannotReachCellDirectRule/AllCellsReachable", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 3); - NurikabeCell cell2 = board.getCell(0, 1); - NurikabeCell cell3 = board.getCell(4, 1); + NurikabeCell cell1 = board.getCell(2, 3); + NurikabeCell cell2 = board.getCell(0, 1); + NurikabeCell cell3 = board.getCell(4, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (!(point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()))) { - NurikabeCell newCell = board.getCell(k, i); - newCell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(newCell); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (!(point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()))) { + NurikabeCell newCell = board.getCell(k, i); + newCell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(newCell); + } + } } - } - } - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java index 567d663e8..196a1ac2f 100644 --- a/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java @@ -17,65 +17,65 @@ public class CornerBlackDirectRuleTest { - private static final CornerBlackDirectRule RULE = new CornerBlackDirectRule(); - private static Nurikabe nurikabe; + private static final CornerBlackDirectRule RULE = new CornerBlackDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Corner Black direct rule for a simple corner black tile */ - @Test - public void CornerBlackContradictionRule_SimpleCornerBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CornerBlackDirectRule/SimpleCornerBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); + /** Tests the Corner Black direct rule for a simple corner black tile */ + @Test + public void CornerBlackContradictionRule_SimpleCornerBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CornerBlackDirectRule/SimpleCornerBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); - NurikabeCell cell = board.getCell(2, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeCell cell = board.getCell(2, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Corner Black direct rule for a false application of the rule */ - @Test - public void CornerBlackContradictionRule_FalseCornerBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CornerBlackDirectRule/FalseCornerBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); + /** Tests the Corner Black direct rule for a false application of the rule */ + @Test + public void CornerBlackContradictionRule_FalseCornerBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CornerBlackDirectRule/FalseCornerBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); - NurikabeCell cell = board.getCell(2, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeCell cell = board.getCell(2, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java index c4ed751b0..5238411b2 100644 --- a/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java @@ -17,125 +17,126 @@ public class FillinBlackDirectRuleTest { - private static final FillinBlackDirectRule RULE = new FillinBlackDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the middle of the board - */ - @Test - public void FillinBlackDirectRule_UnknownSurroundBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/UnknownSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final FillinBlackDirectRule RULE = new FillinBlackDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the middle of the + * board + */ + @Test + public void FillinBlackDirectRule_UnknownSurroundBlackTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/UnknownSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the top left corner of - * the board - */ - @Test - public void FillinBlackDirectRule_CornerTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the top left corner of + * the board + */ + @Test + public void FillinBlackDirectRule_CornerTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the bottom right corner - * of the board - */ - @Test - public void FillinBlackDirectRule_CornerTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 2); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the bottom right + * corner of the board + */ + @Test + public void FillinBlackDirectRule_CornerTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 2); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the Fillin Black direct rule for a false application of the rule */ - @Test - public void FillinBlackDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/FalseFillinBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the Fillin Black direct rule for a false application of the rule */ + @Test + public void FillinBlackDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/FalseFillinBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java index 317f44521..e6aea12b9 100644 --- a/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java @@ -16,127 +16,128 @@ import org.junit.Test; public class FillinWhiteDirectRuleTest { - private static final FillinWhiteDirectRule RULE = new FillinWhiteDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the middle of the board - */ - @Test - public void FillinWhiteDirectRule_UnknownSurroundWhiteTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/UnknownSurroundWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final FillinWhiteDirectRule RULE = new FillinWhiteDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the middle of the + * board + */ + @Test + public void FillinWhiteDirectRule_UnknownSurroundWhiteTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/UnknownSurroundWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the top left corner of - * the board - */ - @Test - public void FillinWhiteDirectRule_CornerTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the top left corner of + * the board + */ + @Test + public void FillinWhiteDirectRule_CornerTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the bottom right corner - * of the board - */ - @Test - public void FillinWhiteDirectRule_CornerTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 2); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the bottom right + * corner of the board + */ + @Test + public void FillinWhiteDirectRule_CornerTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 2); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the Fillin White direct rule for a false application of the rule */ - @Test - public void FillinWhiteDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/FalseFillinWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the Fillin White direct rule for a false application of the rule */ + @Test + public void FillinWhiteDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/FalseFillinWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java index 1c6773e35..660542d79 100644 --- a/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java @@ -16,93 +16,96 @@ public class IsolateBlackContradictionRuleTest { - private static final IsolateBlackContradictionRule RULE = new IsolateBlackContradictionRule(); - private static Nurikabe nurikabe; + private static final IsolateBlackContradictionRule RULE = new IsolateBlackContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Isolate Black contradiction rule for a black square in the corner, separated by a - * diagonal of white squares - */ - @Test - public void IsolateBlackContradictionRule_SimpleIsolateBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/SimpleIsolateBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Isolate Black contradiction rule for a black square in the corner, separated by a + * diagonal of white squares + */ + @Test + public void IsolateBlackContradictionRule_SimpleIsolateBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/SimpleIsolateBlack", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Isolate Black contradiction rule for diagonally connected black squares */ - @Test - public void IsolateBlackContradictionRule_DiagonalBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/DiagonalIsolateBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Isolate Black contradiction rule for diagonally connected black squares */ + @Test + public void IsolateBlackContradictionRule_DiagonalBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/DiagonalIsolateBlack", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(1, 1); - NurikabeCell cell3 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(1, 1); + NurikabeCell cell3 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Isolate Black contradiction rule for a false contradiction */ - @Test - public void IsolateBlackContradictionRule_FalseIsolateBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/FalseIsolateBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Isolate Black contradiction rule for a false contradiction */ + @Test + public void IsolateBlackContradictionRule_FalseIsolateBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/FalseIsolateBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java index 4bc98a9ac..0ca30c136 100644 --- a/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java @@ -16,96 +16,99 @@ public class MultipleNumbersContradictionRuleTest { - private static final MultipleNumbersContradictionRule RULE = - new MultipleNumbersContradictionRule(); - private static Nurikabe nurikabe; + private static final MultipleNumbersContradictionRule RULE = + new MultipleNumbersContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Multiple Numbers contradiction rule for a single region with multiple numbers */ - @Test - public void MultipleNumbersContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/MultipleNumbers", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Multiple Numbers contradiction rule for a single region with multiple numbers */ + @Test + public void MultipleNumbersContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/MultipleNumbers", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(0, 0)) || point.equals(new Point(2, 0))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(0, 0)) || point.equals(new Point(2, 0))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** - * Tests the Multiple Numbers contradiction rule for a more complex regions with multiple numbers - */ - @Test - public void MultipleNumbersContradictionRule_ComplexRegion() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/ComplexRegion", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Multiple Numbers contradiction rule for a more complex regions with multiple + * numbers + */ + @Test + public void MultipleNumbersContradictionRule_ComplexRegion() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/ComplexRegion", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(2, 0); - NurikabeCell cell3 = board.getCell(4, 0); - NurikabeCell cell4 = board.getCell(2, 3); - NurikabeCell cell5 = board.getCell(4, 4); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(2, 0); + NurikabeCell cell3 = board.getCell(4, 0); + NurikabeCell cell4 = board.getCell(2, 3); + NurikabeCell cell5 = board.getCell(4, 4); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation()) - || point.equals(cell5.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation()) + || point.equals(cell5.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** - * Tests the Multiple Numbers contradiction rule for two regions with one number each, separated - * diagonally - */ - @Test - public void MultipleNumbersContradictionRule_FalseContradiction() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/FalseContradiction", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Multiple Numbers contradiction rule for two regions with one number each, separated + * diagonally + */ + @Test + public void MultipleNumbersContradictionRule_FalseContradiction() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/FalseContradiction", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java index 2b032e650..c5293880f 100644 --- a/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java @@ -15,72 +15,73 @@ public class NoNumbersContradictionRuleTest { - private static final NoNumberContradictionRule RULE = new NoNumberContradictionRule(); - private static Nurikabe nurikabe; + private static final NoNumberContradictionRule RULE = new NoNumberContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the No Number contradiction rule for a white region enclosed by black squares */ - @Test - public void NoNumberContradictionRule_NoNumberSurroundBlack() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/SimpleNoNumber", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the No Number contradiction rule for a white region enclosed by black squares */ + @Test + public void NoNumberContradictionRule_NoNumberSurroundBlack() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/SimpleNoNumber", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the No Number contradiction rule for a false contradiction */ - @Test - public void NoNumberContradictionRule_FalseNoNumber() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the No Number contradiction rule for a false contradiction */ + @Test + public void NoNumberContradictionRule_FalseNoNumber() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - @Test - public void NoNumberContradictionRule_FalseNoNumber2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void NoNumberContradictionRule_FalseNoNumber2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java index 67f87e751..c529c81cc 100644 --- a/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java @@ -17,157 +17,162 @@ public class PreventBlackSquareDirectRuleTest { - private static final PreventBlackSquareDirectRule RULE = new PreventBlackSquareDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the bottom left corner - * missing - */ - @Test - public void PreventBlackSquareDirectRule_BottomLeftWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomLeftWhiteBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final PreventBlackSquareDirectRule RULE = new PreventBlackSquareDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Prevent Black Square direct rule for a black square with the bottom left corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_BottomLeftWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomLeftWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the bottom right corner - * missing - */ - @Test - public void PreventBlackSquareDirectRule_BottomRightWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomRightWhiteBlackSquare", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Prevent Black Square direct rule for a black square with the bottom right corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_BottomRightWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomRightWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the top left corner missing - */ - @Test - public void PreventBlackSquareDirectRule_TopLeftWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopLeftWhiteBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Prevent Black Square direct rule for a black square with the top left corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_TopLeftWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopLeftWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the top right corner missing - */ - @Test - public void PreventBlackSquareDirectRule_TopRightWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopRightWhiteBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Prevent Black Square direct rule for a black square with the top right corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_TopRightWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopRightWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the Prevent Black Square direct rule for a false contradiction */ - @Test - public void PreventBlackSquareDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/FalseBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the Prevent Black Square direct rule for a false contradiction */ + @Test + public void PreventBlackSquareDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/FalseBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java index 6520e1221..a09475cff 100644 --- a/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java @@ -17,103 +17,105 @@ public class SurroundRegionDirectRuleTest { - private static final SurroundRegionDirectRule RULE = new SurroundRegionDirectRule(); - private static Nurikabe nurikabe; + private static final SurroundRegionDirectRule RULE = new SurroundRegionDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Surround Region direct rule for a white square in the middle of the board */ - @Test - public void SurroundRegionDirectRule_SurroundRegionBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a white square in the middle of the board */ + @Test + public void SurroundRegionDirectRule_SurroundRegionBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 0); - cell1.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell1); - NurikabeCell cell2 = board.getCell(0, 1); - cell2.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell2); - NurikabeCell cell3 = board.getCell(2, 1); - cell3.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell3); - NurikabeCell cell4 = board.getCell(1, 2); - cell4.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell4); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 0); + cell1.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell1); + NurikabeCell cell2 = board.getCell(0, 1); + cell2.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell2); + NurikabeCell cell3 = board.getCell(2, 1); + cell3.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell3); + NurikabeCell cell4 = board.getCell(1, 2); + cell4.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell4); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Surround Region direct rule for a white square in the corner of the board */ - @Test - public void SurroundRegionDirectRule_SurroundRegionBlackInCornerTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlackInCorner", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a white square in the corner of the board */ + @Test + public void SurroundRegionDirectRule_SurroundRegionBlackInCornerTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlackInCorner", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 0); - cell1.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell1); - NurikabeCell cell2 = board.getCell(0, 1); - cell2.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 0); + cell1.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell1); + NurikabeCell cell2 = board.getCell(0, 1); + cell2.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell2); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Surround Region direct rule for a false application of the rule */ - @Test - public void SurroundRegionDirectRule_FalseSurroundRegionBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/FalseSurroundRegion", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a false application of the rule */ + @Test + public void SurroundRegionDirectRule_FalseSurroundRegionBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/FalseSurroundRegion", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java index b5774e3dd..89b1a29a7 100644 --- a/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java @@ -16,84 +16,85 @@ public class TooFewSpacesContradictionRuleTest { - private static final TooFewSpacesContradictionRule RULE = new TooFewSpacesContradictionRule(); - private static Nurikabe nurikabe; + private static final TooFewSpacesContradictionRule RULE = new TooFewSpacesContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Too Few Spaces contradiction rule for an isolated completely enclosed number */ - @Test - public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for an isolated completely enclosed number */ + @Test + public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(1, 1))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(1, 1))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Too Few Spaces contradiction rule for a region with insufficient space */ - @Test - public void TooFewSpacesContradictionRule_InsufficientSpaceTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for a region with insufficient space */ + @Test + public void TooFewSpacesContradictionRule_InsufficientSpaceTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Too Few Spaces contradiction rule for a false contradiction */ - @Test - public void TooFewSpacesContradictionRule_FalseTooFewSpaces() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/FalseTooFewSpaces", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for a false contradiction */ + @Test + public void TooFewSpacesContradictionRule_FalseTooFewSpaces() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/FalseTooFewSpaces", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java index 1a3280653..31fb92f5d 100644 --- a/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java @@ -15,92 +15,94 @@ public class TooManySpacesContradictionRuleTest { - private static final TooManySpacesContradictionRule RULE = new TooManySpacesContradictionRule(); - private static Nurikabe nurikabe; + private static final TooManySpacesContradictionRule RULE = new TooManySpacesContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Too Many Spaces contradiction rule for a 2 in the center surrounded by 4 white - * squares - */ - @Test - public void TooManySpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/TwoSurroundWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Too Many Spaces contradiction rule for a 2 in the center surrounded by 4 white + * squares + */ + @Test + public void TooManySpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/TwoSurroundWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(1, 0)) - || point.equals(new Point(1, 1)) - || point.equals(new Point(2, 1)) - || point.equals(new Point(1, 2)) - || point.equals(new Point(0, 1))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(1, 0)) + || point.equals(new Point(1, 1)) + || point.equals(new Point(2, 1)) + || point.equals(new Point(1, 2)) + || point.equals(new Point(0, 1))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Too Many Spaces contradiction rule for an extra diagonal space */ - @Test - public void TooManySpacesContradictionRule_ExtraDiagonalSpace() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/ExtraDiagonalSpace", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Many Spaces contradiction rule for an extra diagonal space */ + @Test + public void TooManySpacesContradictionRule_ExtraDiagonalSpace() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/ExtraDiagonalSpace", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - /** - * Tests the Too Many Spaces contradiction rule for a contradiction.with multiple numbers, wherein - * one of the numbers is larger than the region - */ - @Test - public void TooManySpacesContradictionRule_MultipleNumberRegion() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/MultipleNumberRegion", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Too Many Spaces contradiction rule for a contradiction.with multiple numbers, + * wherein one of the numbers is larger than the region + */ + @Test + public void TooManySpacesContradictionRule_MultipleNumberRegion() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/MultipleNumberRegion", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(board.getCell(2, 1).getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + Assert.assertNull(RULE.checkContradiction(board)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(board.getCell(2, 1).getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java index 58470d6b0..da94d7598 100644 --- a/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java @@ -16,67 +16,69 @@ public class UnreachableWhiteCellContradictionRuleTest { - private static final UnreachableWhiteCellContradictionRule RULE = - new UnreachableWhiteCellContradictionRule(); - private static Nurikabe nurikabe; + private static final UnreachableWhiteCellContradictionRule RULE = + new UnreachableWhiteCellContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Unreachable White Cell contradiction rule for a simple case of an unreachable white - * cell - */ - @Test - public void UnreachableWhiteCellContradictionRule_SimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/SimpleUnreachableTest", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Unreachable White Cell contradiction rule for a simple case of an unreachable white + * cell + */ + @Test + public void UnreachableWhiteCellContradictionRule_SimpleTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/SimpleUnreachableTest", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(2, 2); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** - * Tests the Unreachable White Cell contradiction rule for a variety of white square that should - * all be reachable in some manner - */ - @Test - public void UnreachableWhiteCellContradictionRule_AllCellsReachable() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/AllCellsReachable", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Unreachable White Cell contradiction rule for a variety of white square that should + * all be reachable in some manner + */ + @Test + public void UnreachableWhiteCellContradictionRule_AllCellsReachable() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/AllCellsReachable", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java index 4ad9267bd..ce9144879 100644 --- a/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java @@ -17,87 +17,87 @@ public class WhiteBottleNeckDirectRuleTest { - private static final WhiteBottleNeckDirectRule RULE = new WhiteBottleNeckDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** Tests the White BottleNeck direct rule for a bottleneck in the middle of the board */ - @Test - public void WhiteBottleNeckDirectRule_SimpleWhiteBottleNeckTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/SimpleWhiteBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final WhiteBottleNeckDirectRule RULE = new WhiteBottleNeckDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** Tests the White BottleNeck direct rule for a bottleneck in the middle of the board */ + @Test + public void WhiteBottleNeckDirectRule_SimpleWhiteBottleNeckTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/SimpleWhiteBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the White BottleNeck direct rule for a more complex board */ - @Test - public void WhiteBottleNeckDirectRule_NurikabeBoard1Test() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/NurikabeBoard1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the White BottleNeck direct rule for a more complex board */ + @Test + public void WhiteBottleNeckDirectRule_NurikabeBoard1Test() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/NurikabeBoard1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - /** Tests the White BottleNeck direct rule for a more false bottle neck */ - @Test - public void WhiteBottleNeckDirectRule_FalseBottleNeck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/FalseBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the White BottleNeck direct rule for a more false bottle neck */ + @Test + public void WhiteBottleNeckDirectRule_FalseBottleNeck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/FalseBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java index 693acc682..58fc67824 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java @@ -18,142 +18,142 @@ public class AndCaseRuleTest { - private static final CaseRuleAnd RULE = new CaseRuleAnd(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - private void falseAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); - - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); - ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); - - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); - ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); - - // Assert that the corresponding cells for the different case rules do not - // match with each other - Assert.assertNotEquals(board1A, board2A); - Assert.assertNotEquals(board1B, board2B); - - // First assert the two cells are not equal, then verify that they are either - // unknown or false. - Assert.assertNotEquals(board1A, board1B); - Assert.assertTrue( - board1A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - board1B.equals(ShortTruthTableCellType.UNKNOWN) - || board1B.equals(ShortTruthTableCellType.FALSE)); - - Assert.assertNotEquals(board2A, board2B); - Assert.assertTrue( - board2A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - board2B.equals(ShortTruthTableCellType.UNKNOWN) - || board2B.equals(ShortTruthTableCellType.FALSE)); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the two cells that should be different - if (!((i == aX && j == aY) || (i == bX && j == bY))) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + private static final CaseRuleAnd RULE = new CaseRuleAnd(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + private void falseAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); + + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); + ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); + + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); + ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); + + // Assert that the corresponding cells for the different case rules do not + // match with each other + Assert.assertNotEquals(board1A, board2A); + Assert.assertNotEquals(board1B, board2B); + + // First assert the two cells are not equal, then verify that they are either + // unknown or false. + Assert.assertNotEquals(board1A, board1B); + Assert.assertTrue( + board1A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + board1B.equals(ShortTruthTableCellType.UNKNOWN) + || board1B.equals(ShortTruthTableCellType.FALSE)); + + Assert.assertNotEquals(board2A, board2B); + Assert.assertTrue( + board2A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + board2B.equals(ShortTruthTableCellType.UNKNOWN) + || board2B.equals(ShortTruthTableCellType.FALSE)); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the two cells that should be different + if (!((i == aX && j == aY) || (i == bX && j == bY))) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + } + } } - } } - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches - * are created: one where A is false and one where B is false. - */ - @Test - public void SimpleStatement1FalseTest() throws InvalidFileFormatException { - falseAndTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring - * that two branches are created: one where ~ is false and one where the second ^ is false. - */ - @Test - public void ComplexStatement1FalseTest() throws InvalidFileFormatException { - falseAndTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); - } - - private void trueAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // There should only be 1 branch - Assert.assertEquals(1, cases.size()); - - ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); - ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); - - // Both cells should be true - Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.TRUE); - Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.TRUE); - Assert.assertEquals(caseBoardAType, caseBoardBType); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is - * created where A and B are both true. - */ - @Test - public void SimpleStatement1AndTest() throws InvalidFileFormatException { - trueAndTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring that - * one branch is created where both ~ and the second ^ are true. - */ - @Test - public void ComplexStatement1TrueTest() throws InvalidFileFormatException { - trueAndTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); - } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches + * are created: one where A is false and one where B is false. + */ + @Test + public void SimpleStatement1FalseTest() throws InvalidFileFormatException { + falseAndTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring + * that two branches are created: one where ~ is false and one where the second ^ is false. + */ + @Test + public void ComplexStatement1FalseTest() throws InvalidFileFormatException { + falseAndTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); + } + + private void trueAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // There should only be 1 branch + Assert.assertEquals(1, cases.size()); + + ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); + ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); + + // Both cells should be true + Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.TRUE); + Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.TRUE); + Assert.assertEquals(caseBoardAType, caseBoardBType); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is + * created where A and B are both true. + */ + @Test + public void SimpleStatement1AndTest() throws InvalidFileFormatException { + trueAndTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring + * that one branch is created where both ~ and the second ^ are true. + */ + @Test + public void ComplexStatement1TrueTest() throws InvalidFileFormatException { + trueAndTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java index 94b99801b..61f29a669 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java @@ -15,198 +15,205 @@ import org.junit.Test; public class AndEliminationDirectRuleTest { - private static final DirectRuleAndElimination RULE = new DirectRuleAndElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: B^C where ^ is true - * - *

Checks all possible combinations of true, false, and unknown for B and C except for where - * both B and C are true and asserts that each one of them is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void trueAndTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.TRUE) { - continue; - } + private static final DirectRuleAndElimination RULE = new DirectRuleAndElimination(); + private static ShortTruthTable stt; - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); + /** + * Given one statement: B^C where ^ is true + * + *

Checks all possible combinations of true, false, and unknown for B and C except for where + * both B and C are true and asserts that each one of them is not a valid application of the + * rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void trueAndTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.TRUE) { + continue; + } + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); + + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } + + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); + /** + * Given one statement: B^C where ^ is true + * + *

Checks all possible combinations of true and unknown for B and C except for where both B + * and C are unknown and asserts that each one of them is a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void trueAndTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.UNKNOWN) { + continue; + } + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); + + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } + + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + + Assert.assertNull(RULE.checkRule(transition)); + } } - - Assert.assertNotNull(RULE.checkRule(transition)); - } } - } - - /** - * Given one statement: B^C where ^ is true - * - *

Checks all possible combinations of true and unknown for B and C except for where both B and - * C are unknown and asserts that each one of them is a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void trueAndTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.UNKNOWN) { - continue; - } - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); + /** + * Given one statement: B^C where ^ is false + * + *

Checks all possible combinations of true, false, and unknown for B and C and asserts that + * each one of them is not a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithUnknownsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); + + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } + + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } + /** + * Given one statement: B^C where both B and ^ are false + * + *

Asserts that this is not a valid application of the rule if C is set to either true or + * false. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithKnownFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownFalse", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } - } - } - - /** - * Given one statement: B^C where ^ is false - * - *

Checks all possible combinations of true, false, and unknown for B and C and asserts that - * each one of them is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithUnknownsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); + clyde.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); - } + clyde.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); + } - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } + /** + * Given one statement: B^C where B is true and ^ is false + * + *

Asserts that this is a valid application of the rule if and only if C is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithKnownTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownTrue", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell clyde = board.getCell(2, 0); + clyde.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(clyde); Assert.assertNotNull(RULE.checkRule(transition)); - } + + clyde.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(clyde); + Assert.assertNull(RULE.checkRule(transition)); } - } - - /** - * Given one statement: B^C where both B and ^ are false - * - *

Asserts that this is not a valid application of the rule if C is set to either true or - * false. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithKnownFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownFalse", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell clyde = board.getCell(2, 0); - clyde.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - - clyde.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: B^C where B is true and ^ is false - * - *

Asserts that this is a valid application of the rule if and only if C is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithKnownTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownTrue", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell clyde = board.getCell(2, 0); - clyde.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - - clyde.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(clyde); - Assert.assertNull(RULE.checkRule(transition)); - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java index d17ffd6cf..ec03919ae 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java @@ -15,91 +15,91 @@ import org.junit.Test; public class AndIntroductionDirectRuleTest { - private static final DirectRuleAndIntroduction RULE = new DirectRuleAndIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleAndIntroduction RULE = new DirectRuleAndIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A ^ B - * - *

Asserts that if at least 1 of A or B is false, then this is a valid application of the rule - * if and only if ^ is false. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseAndTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; - falseAndTestHelper(path + "FUF"); - falseAndTestHelper(path + "FUU"); - falseAndTestHelper(path + "UUF"); - falseAndTestHelper(path + "FUT"); - falseAndTestHelper(path + "TUF"); - } + /** + * Given a statement: A ^ B + * + *

Asserts that if at least 1 of A or B is false, then this is a valid application of the + * rule if and only if ^ is false. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseAndTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; + falseAndTestHelper(path + "FUF"); + falseAndTestHelper(path + "FUU"); + falseAndTestHelper(path + "UUF"); + falseAndTestHelper(path + "FUT"); + falseAndTestHelper(path + "TUF"); + } - private void falseAndTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseAndTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell and = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell and = board.getCell(1, 0); - and.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(and); - Assert.assertNotNull(RULE.checkRule(transition)); + and.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(and); + Assert.assertNotNull(RULE.checkRule(transition)); - and.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(and); - Assert.assertNull(RULE.checkRule(transition)); - } + and.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(and); + Assert.assertNull(RULE.checkRule(transition)); + } - /** - * Given a statement: A ^ B - * - *

Asserts that setting ^ to true is a valid application of the rule if and only if both A and - * B are true. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String first : letters) { - for (String second : letters) { - trueAndTestHelper(path + first + "U" + second); - } + /** + * Given a statement: A ^ B + * + *

Asserts that setting ^ to true is a valid application of the rule if and only if both A + * and B are true. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; + String[] letters = {"T", "F", "U"}; + for (String first : letters) { + for (String second : letters) { + trueAndTestHelper(path + first + "U" + second); + } + } } - } - private void trueAndTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueAndTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - ShortTruthTableCell and = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell and = board.getCell(1, 0); - and.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(and); + and.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(and); - if (a.getType() == ShortTruthTableCellType.TRUE - && b.getType() == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + if (a.getType() == ShortTruthTableCellType.TRUE + && b.getType() == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java index 2126fc60d..c631db613 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java @@ -15,156 +15,156 @@ import org.junit.Test; public class AtomicDirectRuleTest { - private static final DirectRuleAtomic RULE = new DirectRuleAtomic(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given two statements: A A where the first A is set to false. - * - *

This test sets the second A to false and then asserts that this is a valid application of - * the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MatchingFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: A A where the first A is set to false. - * - *

This test sets the second A to true and then asserts that this is not a valid application of - * the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MismatchingFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: B B where the first B is set to true. - * - *

This test sets the second B to true and then asserts that this is a valid application of the - * rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MatchingTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: B B where the first B is set to true. - * - *

This test sets the second B to false and then asserts that this is not a valid application - * of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MismatchingTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: C C where neither statement is set to anything. - * - *

This test sets the second C to false and then asserts that this is not a valid application - * of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void NothingPreviouslyMarkedTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: C C where neither statement is set to anything. - * - *

This test sets the second C to true and then asserts that this is not a valid application of - * the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void NothingPreviouslyMarkedTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } + private static final DirectRuleAtomic RULE = new DirectRuleAtomic(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given two statements: A A where the first A is set to false. + * + *

This test sets the second A to false and then asserts that this is a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MatchingFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: A A where the first A is set to false. + * + *

This test sets the second A to true and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MismatchingFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: B B where the first B is set to true. + * + *

This test sets the second B to true and then asserts that this is a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MatchingTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: B B where the first B is set to true. + * + *

This test sets the second B to false and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MismatchingTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: C C where neither statement is set to anything. + * + *

This test sets the second C to false and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void NothingPreviouslyMarkedTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: C C where neither statement is set to anything. + * + *

This test sets the second C to true and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void NothingPreviouslyMarkedTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java index 36824faee..987d194f9 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java @@ -15,380 +15,385 @@ import org.junit.Test; public class BiconditionalEliminationTest { - private static final DirectRuleBiconditionalElimination RULE = - new DirectRuleBiconditionalElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: A <-> B where both A and <-> are true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where both B and <-> are true - * - *

Asserts that this is a valid application of the rule if and only if A is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A is false and <-> is true - * - *

Asserts that this is a valid application of the rule if and only if B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B is false and <-> is true - * - *

Asserts that this is a valid application of the rule if and only if A is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A is true and <-> is false - * - *

Asserts that this is a valid application of the rule if and only if B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B is true and <-> is false - * - *

Asserts that this is a valid application of the rule if and only if A is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A and <-> are false - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B and <-> are false - * - *

Asserts that this is a valid application of the rule if and only if A is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where <-> is true - * - *

Asserts that setting any combination of A and B at the same time is not a valid application - * of this rule - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalSetBothAtOnceTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { + private static final DirectRuleBiconditionalElimination RULE = + new DirectRuleBiconditionalElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: A <-> B where both A and <-> are true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); ShortTruthTableCell morty = board.getCell(2, 0); - rick.setData(cellType1); - morty.setData(cellType2); + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where both B and <-> are true + * + *

Asserts that this is a valid application of the rule if and only if A is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + // Asserts that this is not a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A is false and <-> is true + * + *

Asserts that this is a valid application of the rule if and only if B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + // Asserts that this is not a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); Assert.assertNotNull(RULE.checkRule(transition)); - } + + // Asserts that this is a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); } - } - - /** - * Asserts that setting any combination of A and B at the same time is not a valid application of - * this rule. This is tested on multiple files. - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAandBAtOnceTest() throws InvalidFileFormatException { - String directory = "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/"; - setAandBBothAtOnceTest(directory + "FalseBiconditional"); - setAandBBothAtOnceTest(directory + "TrueBiconditional"); - setAandBBothAtOnceTest(directory + "FalseBiconditionalWithFalseA"); - setAandBBothAtOnceTest(directory + "TrueBiconditionalWithFalseA"); - setAandBBothAtOnceTest(directory + "FalseBiconditionalWithTrueA"); - setAandBBothAtOnceTest(directory + "TrueBiconditionalWithTrueA"); - } - - /** - * Helper function to test biconditional elimination rule with given file path. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - private void setAandBBothAtOnceTest(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { + + /** + * Given one statement: A <-> B where B is false and <-> is true + * + *

Asserts that this is a valid application of the rule if and only if A is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A is true and <-> is false + * + *

Asserts that this is a valid application of the rule if and only if B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell morty = board.getCell(2, 0); - rick.setData(cellType1); - morty.setData(cellType2); + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B is true and <-> is false + * + *

Asserts that this is a valid application of the rule if and only if A is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A and <-> are false + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B and <-> are false + * + *

Asserts that this is a valid application of the rule if and only if A is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); Assert.assertNotNull(RULE.checkRule(transition)); - } + + // Asserts that this is not a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where <-> is true + * + *

Asserts that setting any combination of A and B at the same time is not a valid + * application of this rule + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalSetBothAtOnceTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + ShortTruthTableCell morty = board.getCell(2, 0); + + rick.setData(cellType1); + morty.setData(cellType2); + + board.addModifiedData(rick); + board.addModifiedData(morty); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + + /** + * Asserts that setting any combination of A and B at the same time is not a valid application + * of this rule. This is tested on multiple files. + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAandBAtOnceTest() throws InvalidFileFormatException { + String directory = "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/"; + setAandBBothAtOnceTest(directory + "FalseBiconditional"); + setAandBBothAtOnceTest(directory + "TrueBiconditional"); + setAandBBothAtOnceTest(directory + "FalseBiconditionalWithFalseA"); + setAandBBothAtOnceTest(directory + "TrueBiconditionalWithFalseA"); + setAandBBothAtOnceTest(directory + "FalseBiconditionalWithTrueA"); + setAandBBothAtOnceTest(directory + "TrueBiconditionalWithTrueA"); + } + + /** + * Helper function to test biconditional elimination rule with given file path. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + private void setAandBBothAtOnceTest(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + ShortTruthTableCell morty = board.getCell(2, 0); + + rick.setData(cellType1); + morty.setData(cellType2); + + board.addModifiedData(rick); + board.addModifiedData(morty); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java index 99a86c6f1..e1c5cf957 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java @@ -15,103 +15,103 @@ import org.junit.Test; public class BiconditionalIntroductionTest { - private static final DirectRuleBiconditionalIntroduction RULE = - new DirectRuleBiconditionalIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleBiconditionalIntroduction RULE = + new DirectRuleBiconditionalIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A <-> B - * - *

Asserts that if setting <-> to false is a valid application of this rule if and only if A - * and B do not match. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; + /** + * Given a statement: A <-> B + * + *

Asserts that if setting <-> to false is a valid application of this rule if and only if A + * and B do not match. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - System.out.println(a + b); - falseConditionalHelper(path + a + "U" + b); - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + System.out.println(a + b); + falseConditionalHelper(path + a + "U" + b); + } + } } - } - private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() != b.getType()) { - // Not valid if they don't match but at least one of the values of A or B is unknown - if (a.getType() == ShortTruthTableCellType.UNKNOWN - || b.getType() == ShortTruthTableCellType.UNKNOWN) { - Assert.assertNotNull(RULE.checkRule(transition)); - } else { - Assert.assertNull(RULE.checkRule(transition)); - } - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() != b.getType()) { + // Not valid if they don't match but at least one of the values of A or B is unknown + if (a.getType() == ShortTruthTableCellType.UNKNOWN + || b.getType() == ShortTruthTableCellType.UNKNOWN) { + Assert.assertNotNull(RULE.checkRule(transition)); + } else { + Assert.assertNull(RULE.checkRule(transition)); + } + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } - /** - * Given a statement: A <-> B - * - *

Asserts that if setting <-> to true is a valid application of this rule if and only if A and - * B match. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; + /** + * Given a statement: A <-> B + * + *

Asserts that if setting <-> to true is a valid application of this rule if and only if A + * and B match. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - System.out.println(a + b); - trueConditionalHelper(path + a + "U" + b); - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + System.out.println(a + b); + trueConditionalHelper(path + a + "U" + b); + } + } } - } - private void trueConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == b.getType() && a.getType() != ShortTruthTableCellType.UNKNOWN) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == b.getType() && a.getType() != ShortTruthTableCellType.UNKNOWN) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java index 7574ce337..0f95906f2 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java @@ -15,229 +15,237 @@ import org.junit.Test; public class ConditionalEliminationTest { - private static final DirectRuleConditionalElimination RULE = - new DirectRuleConditionalElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that the only valid combination of A and B that is a valid application of this rule - * is when A is true and B is false - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { + private static final DirectRuleConditionalElimination RULE = + new DirectRuleConditionalElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that the only valid combination of A and B that is a valid application of this + * rule is when A is true and B is false + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); + ShortTruthTableCell boniato = board.getCell(2, 0); + + aubergine.setData(cellType1); + boniato.setData(cellType2); + + board.addModifiedData(aubergine); + board.addModifiedData(boniato); + + if (cellType1 == ShortTruthTableCellType.TRUE + && cellType2 == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that this is a valid application of the rule if and only if A is set to true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell aubergine = board.getCell(0, 0); - ShortTruthTableCell boniato = board.getCell(2, 0); - aubergine.setData(cellType1); - boniato.setData(cellType2); + aubergine.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(aubergine); + Assert.assertNull(RULE.checkRule(transition)); + aubergine.setData(ShortTruthTableCellType.FALSE); board.addModifiedData(aubergine); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that this is a valid application of the rule if and only if B is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } - if (cellType1 == ShortTruthTableCellType.TRUE - && cellType2 == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + /** + * Given one statement: A -> B where -> is true + * + *

Asserts that you cannot set any combination of both A and B at the same time. + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAandBTrueConditionalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); + ShortTruthTableCell boniato = board.getCell(2, 0); + + aubergine.setData(cellType1); + boniato.setData(cellType2); + + board.addModifiedData(aubergine); + board.addModifiedData(boniato); + + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that this is a valid application of the rule if and only if A is set to true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - - aubergine.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(aubergine); - Assert.assertNull(RULE.checkRule(transition)); - - aubergine.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(aubergine); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that this is a valid application of the rule if and only if B is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNull(RULE.checkRule(transition)); - - boniato.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where -> is true - * - *

Asserts that you cannot set any combination of both A and B at the same time. - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAandBTrueConditionalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { + + /** + * Given one statement: A -> B where A and -> are true + * + *

Asserts that this is a valid application of this rule if and only if B is set to true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueAMeansTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(boniato); + Assert.assertNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where B is false and -> is true + * + *

Asserts that this is a valid application of this rule if and only if A is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBMeansFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell aubergine = board.getCell(0, 0); - ShortTruthTableCell boniato = board.getCell(2, 0); - aubergine.setData(cellType1); - boniato.setData(cellType2); + aubergine.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(aubergine); + Assert.assertNull(RULE.checkRule(transition)); + aubergine.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(aubergine); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where B and -> are true + * + *

Asserts that this is not a valid application of this rule no matter what A is set to. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBCannotDetermineA() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); Assert.assertNotNull(RULE.checkRule(transition)); - } } - } - - /** - * Given one statement: A -> B where A and -> are true - * - *

Asserts that this is a valid application of this rule if and only if B is set to true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueAMeansTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(boniato); - Assert.assertNull(RULE.checkRule(transition)); - - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where B is false and -> is true - * - *

Asserts that this is a valid application of this rule if and only if A is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBMeansFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - - aubergine.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(aubergine); - Assert.assertNull(RULE.checkRule(transition)); - - aubergine.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(aubergine); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where B and -> are true - * - *

Asserts that this is not a valid application of this rule no matter what A is set to. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBCannotDetermineA() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java index 5eea810a7..1bc28373d 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java @@ -15,97 +15,97 @@ import org.junit.Test; public class ConditionalIntroductionTest { - private static final DirectRuleConditionalIntroduction RULE = - new DirectRuleConditionalIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleConditionalIntroduction RULE = + new DirectRuleConditionalIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A -> B - * - *

Asserts that if setting -> to false is a valid application of this rule if and only if A is - * true and B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; + /** + * Given a statement: A -> B + * + *

Asserts that if setting -> to false is a valid application of this rule if and only if A + * is true and B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - falseConditionalHelper(path + a + "U" + b); - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + falseConditionalHelper(path + a + "U" + b); + } + } } - } - private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == ShortTruthTableCellType.TRUE - && b.getType() == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == ShortTruthTableCellType.TRUE + && b.getType() == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } - /** - * Given a statement: A -> B - * - *

Asserts that if setting -> to true is a valid application of this rule if and only if A is - * false or B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; + /** + * Given a statement: A -> B + * + *

Asserts that if setting -> to true is a valid application of this rule if and only if A is + * false or B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - trueConditionalTestHelper(path + a + "U" + b); - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + trueConditionalTestHelper(path + a + "U" + b); + } + } } - } - private void trueConditionalTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueConditionalTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == ShortTruthTableCellType.FALSE - || b.getType() == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == ShortTruthTableCellType.FALSE + || b.getType() == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java index 9caf2414a..589e3cfb9 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java @@ -15,116 +15,120 @@ import org.junit.Test; public class NotEliminationTest { - private static final DirectRuleNotElimination RULE = new DirectRuleNotElimination(); - private static ShortTruthTable stt; + private static final DirectRuleNotElimination RULE = new DirectRuleNotElimination(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given one statement: ¬A where ¬ is false - * - *

Asserts that this is a valid application of this rule if and only if A is true - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotEliminationDirectRule/FalseNot", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Given one statement: ¬A where ¬ is false + * + *

Asserts that this is a valid application of this rule if and only if A is true + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotEliminationDirectRule/FalseNot", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(1, 0); - a.setData(cellType); - board.addModifiedData(a); + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(1, 0); + a.setData(cellType); + board.addModifiedData(a); - if (cellType == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } - /** - * Given one statement: ¬A where ¬ is true - * - *

Asserts that this is a valid application of this rule if and only if A is false - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotEliminationDirectRule/TrueNot", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Given one statement: ¬A where ¬ is true + * + *

Asserts that this is a valid application of this rule if and only if A is false + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotEliminationDirectRule/TrueNot", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(1, 0); - a.setData(cellType); - board.addModifiedData(a); + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(1, 0); + a.setData(cellType); + board.addModifiedData(a); - if (cellType == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } - // /** - // * Given one statement: ¬A - // * - // * Asserts that setting both ¬ and A to any values would not be a valid - // * application of this rule - // * - // * @throws InvalidFileFormatException - // */ - // @Test - // public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { - // - // TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/BlankNot", stt); - // TreeNode rootNode = stt.getTree().getRootNode(); - // TreeTransition transition = rootNode.getChildren().get(0); - // transition.setRule(RULE); - // - // ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, - // ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - // - // for (ShortTruthTableCellType cellType1 : cellTypes) { - // for (ShortTruthTableCellType cellType2 : cellTypes) { - // ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - // ShortTruthTableCell not = board.getCell(0, 0); - // ShortTruthTableCell a = board.getCell(1, 0); - // - // not.setData(cellType1); - // a.setData(cellType2); - // - // board.addModifiedData(not); - // board.addModifiedData(a); - // - // System.out.println("TYPE1:" + cellType1); - // System.out.println("TYPE2:" + cellType2); - // Assert.assertNotNull(RULE.checkRule(transition)); - // } - // } - // } + // /** + // * Given one statement: ¬A + // * + // * Asserts that setting both ¬ and A to any values would not be a valid + // * application of this rule + // * + // * @throws InvalidFileFormatException + // */ + // @Test + // public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { + // + // TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/BlankNot", stt); + // TreeNode rootNode = stt.getTree().getRootNode(); + // TreeTransition transition = rootNode.getChildren().get(0); + // transition.setRule(RULE); + // + // ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, + // ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; + // + // for (ShortTruthTableCellType cellType1 : cellTypes) { + // for (ShortTruthTableCellType cellType2 : cellTypes) { + // ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + // ShortTruthTableCell not = board.getCell(0, 0); + // ShortTruthTableCell a = board.getCell(1, 0); + // + // not.setData(cellType1); + // a.setData(cellType2); + // + // board.addModifiedData(not); + // board.addModifiedData(a); + // + // System.out.println("TYPE1:" + cellType1); + // System.out.println("TYPE2:" + cellType2); + // Assert.assertNotNull(RULE.checkRule(transition)); + // } + // } + // } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java index 9949651eb..e338fb9bd 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java @@ -15,115 +15,121 @@ import org.junit.Test; public class NotIntroductionTest { - private static final DirectRuleNotIntroduction RULE = new DirectRuleNotIntroduction(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: ¬A where A is false - * - *

Asserts that this is a valid application of this rule if and only if ¬ is true - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - not.setData(cellType); - board.addModifiedData(not); - - if (cellType == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + private static final DirectRuleNotIntroduction RULE = new DirectRuleNotIntroduction(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); } - } - - /** - * Given one statement: ¬A where A is true - * - *

Asserts that this is a valid application of this rule if and only if ¬ is false - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/TrueA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - not.setData(cellType); - board.addModifiedData(not); - - if (cellType == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + + /** + * Given one statement: ¬A where A is false + * + *

Asserts that this is a valid application of this rule if and only if ¬ is true + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + not.setData(cellType); + board.addModifiedData(not); + + if (cellType == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } - - /** - * Given one statement: ¬A - * - *

Asserts that setting both ¬ and A to any values would not be a valid application of this - * rule - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/BlankA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - ShortTruthTableCell a = board.getCell(1, 0); - - not.setData(cellType1); - a.setData(cellType2); - - board.addModifiedData(not); - board.addModifiedData(a); - - Assert.assertNotNull(RULE.checkRule(transition)); - } + + /** + * Given one statement: ¬A where A is true + * + *

Asserts that this is a valid application of this rule if and only if ¬ is false + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/TrueA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + not.setData(cellType); + board.addModifiedData(not); + + if (cellType == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + + /** + * Given one statement: ¬A + * + *

Asserts that setting both ¬ and A to any values would not be a valid application of this + * rule + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/BlankA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + ShortTruthTableCell a = board.getCell(1, 0); + + not.setData(cellType1); + a.setData(cellType2); + + board.addModifiedData(not); + board.addModifiedData(a); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java index a2cc2abc0..0bfa6fc6e 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java @@ -18,142 +18,142 @@ public class OrCaseRuleTest { - private static final CaseRuleOr RULE = new CaseRuleOr(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - private void trueOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); - - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); - ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); - - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); - ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); - - // Assert that the corresponding cells for the different case rules do not - // match with each other - Assert.assertNotEquals(board1A, board2A); - Assert.assertNotEquals(board1B, board2B); - - // First assert the two cells are not equal, then verify that they are either - // unknown or false. - Assert.assertNotEquals(board1A, board1B); - Assert.assertTrue( - board1A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.TRUE)); - Assert.assertTrue( - board1B.equals(ShortTruthTableCellType.UNKNOWN) - || board1B.equals(ShortTruthTableCellType.TRUE)); - - Assert.assertNotEquals(board2A, board2B); - Assert.assertTrue( - board2A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.TRUE)); - Assert.assertTrue( - board2B.equals(ShortTruthTableCellType.UNKNOWN) - || board2B.equals(ShortTruthTableCellType.TRUE)); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the two cells that should be different - if (!((i == aX && j == aY) || (i == bX && j == bY))) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + private static final CaseRuleOr RULE = new CaseRuleOr(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + private void trueOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); + + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); + ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); + + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); + ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); + + // Assert that the corresponding cells for the different case rules do not + // match with each other + Assert.assertNotEquals(board1A, board2A); + Assert.assertNotEquals(board1B, board2B); + + // First assert the two cells are not equal, then verify that they are either + // unknown or false. + Assert.assertNotEquals(board1A, board1B); + Assert.assertTrue( + board1A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.TRUE)); + Assert.assertTrue( + board1B.equals(ShortTruthTableCellType.UNKNOWN) + || board1B.equals(ShortTruthTableCellType.TRUE)); + + Assert.assertNotEquals(board2A, board2B); + Assert.assertTrue( + board2A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.TRUE)); + Assert.assertTrue( + board2B.equals(ShortTruthTableCellType.UNKNOWN) + || board2B.equals(ShortTruthTableCellType.TRUE)); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the two cells that should be different + if (!((i == aX && j == aY) || (i == bX && j == bY))) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + } + } } - } } - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches - * are created: one where A is false and one where B is false. - */ - @Test - public void SimpleStatement1TrueTest() throws InvalidFileFormatException { - trueOrTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring - * that two branches are created: one where ~ is false and one where the second ^ is false. - */ - @Test - public void ComplexStatement1TrueTest() throws InvalidFileFormatException { - trueOrTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); - } - - private void falseOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // There should only be 1 branch - Assert.assertEquals(1, cases.size()); - - ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); - ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); - - // Both cells should be true - Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.FALSE); - Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.FALSE); - Assert.assertEquals(caseBoardAType, caseBoardBType); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is - * created where A and B are both true. - */ - @Test - public void SimpleStatement1FalseTest() throws InvalidFileFormatException { - falseOrTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring that - * one branch is created where both ~ and the second ^ are true. - */ - @Test - public void ComplexStatement1FalseTest() throws InvalidFileFormatException { - falseOrTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); - } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches + * are created: one where A is false and one where B is false. + */ + @Test + public void SimpleStatement1TrueTest() throws InvalidFileFormatException { + trueOrTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring + * that two branches are created: one where ~ is false and one where the second ^ is false. + */ + @Test + public void ComplexStatement1TrueTest() throws InvalidFileFormatException { + trueOrTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); + } + + private void falseOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // There should only be 1 branch + Assert.assertEquals(1, cases.size()); + + ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); + ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); + + // Both cells should be true + Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.FALSE); + Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.FALSE); + Assert.assertEquals(caseBoardAType, caseBoardBType); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is + * created where A and B are both true. + */ + @Test + public void SimpleStatement1FalseTest() throws InvalidFileFormatException { + falseOrTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring + * that one branch is created where both ~ and the second ^ are true. + */ + @Test + public void ComplexStatement1FalseTest() throws InvalidFileFormatException { + falseOrTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java index b678b6610..e4efad465 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java @@ -15,139 +15,148 @@ import org.junit.Test; public class OrEliminationTest { - private static final DirectRuleOrElimination RULE = new DirectRuleOrElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given a statement: A V B, where A is false and V is true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FTUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/FTU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(2, 0); - - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); - - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given a statement: A V B, where B is false and V is true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void UTFTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTF", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(0, 0); - - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); - - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given a statement: A V B, where V is false - * - *

Asserts that this is a valid application of the rule if and only if both A and B are false. - * - * @throws InvalidFileFormatException - */ - @Test - public void UFUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UFU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); + private static final DirectRuleOrElimination RULE = new DirectRuleOrElimination(); + private static ShortTruthTable stt; - a.setData(cellType1); - b.setData(cellType2); + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - board.addModifiedData(a); - board.addModifiedData(b); + /** + * Given a statement: A V B, where A is false and V is true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FTUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/OrEliminationDirectRule/FTU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - if (cellType1 == ShortTruthTableCellType.FALSE - && cellType2 == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - } - - /** - * Given a statement: A V B, where V is true - * - *

Asserts that setting both A and B is not a valid application of this rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void UTUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell cell = board.getCell(2, 0); + + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + Assert.assertNull(RULE.checkRule(transition)); + + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + Assert.assertNotNull(RULE.checkRule(transition)); + } - a.setData(cellType1); - b.setData(cellType2); + /** + * Given a statement: A V B, where B is false and V is true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void UTFTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTF", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.addModifiedData(a); - board.addModifiedData(b); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(0, 0); + + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + Assert.assertNull(RULE.checkRule(transition)); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); Assert.assertNotNull(RULE.checkRule(transition)); - } } - } + + /** + * Given a statement: A V B, where V is false + * + *

Asserts that this is a valid application of the rule if and only if both A and B are + * false. + * + * @throws InvalidFileFormatException + */ + @Test + public void UFUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UFU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + + a.setData(cellType1); + b.setData(cellType2); + + board.addModifiedData(a); + board.addModifiedData(b); + + if (cellType1 == ShortTruthTableCellType.FALSE + && cellType2 == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + } + + /** + * Given a statement: A V B, where V is true + * + *

Asserts that setting both A and B is not a valid application of this rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void UTUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + + a.setData(cellType1); + b.setData(cellType2); + + board.addModifiedData(a); + board.addModifiedData(b); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java index 67a111da7..d5f9387eb 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java @@ -15,91 +15,91 @@ import org.junit.Test; public class OrIntroductionTest { - private static final DirectRuleOrIntroduction RULE = new DirectRuleOrIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleOrIntroduction RULE = new DirectRuleOrIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A V B - * - *

Asserts that if at least 1 of A or B is true, then this is a valid application of the rule - * if and only if V is true. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void TrueOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; - trueOrTestHelper(path + "TUT"); - trueOrTestHelper(path + "TUU"); - trueOrTestHelper(path + "UUT"); - trueOrTestHelper(path + "TUF"); - trueOrTestHelper(path + "FUT"); - } + /** + * Given a statement: A V B + * + *

Asserts that if at least 1 of A or B is true, then this is a valid application of the rule + * if and only if V is true. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void TrueOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; + trueOrTestHelper(path + "TUT"); + trueOrTestHelper(path + "TUU"); + trueOrTestHelper(path + "UUT"); + trueOrTestHelper(path + "TUF"); + trueOrTestHelper(path + "FUT"); + } - private void trueOrTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueOrTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell or = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell or = board.getCell(1, 0); - or.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(or); - Assert.assertNull(RULE.checkRule(transition)); + or.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(or); + Assert.assertNull(RULE.checkRule(transition)); - or.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(or); - Assert.assertNotNull(RULE.checkRule(transition)); - } + or.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(or); + Assert.assertNotNull(RULE.checkRule(transition)); + } - /** - * Given a statement: A V B - * - *

Asserts that setting V to false is a valid application of the rule if and only if both A and - * B are false. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String first : letters) { - for (String second : letters) { - falseOrTestHelper(path + first + "U" + second); - } + /** + * Given a statement: A V B + * + *

Asserts that setting V to false is a valid application of the rule if and only if both A + * and B are false. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; + String[] letters = {"T", "F", "U"}; + for (String first : letters) { + for (String second : letters) { + falseOrTestHelper(path + first + "U" + second); + } + } } - } - private void falseOrTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseOrTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - ShortTruthTableCell or = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell or = board.getCell(1, 0); - or.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(or); + or.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(or); - if (a.getType() == ShortTruthTableCellType.FALSE - && b.getType() == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + if (a.getType() == ShortTruthTableCellType.FALSE + && b.getType() == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java index 3a9c749e7..d0c390785 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java @@ -18,66 +18,66 @@ public class TrueOrFalseCaseRuleTest { - private static final CaseRuleAtomic RULE = new CaseRuleAtomic(); - private static ShortTruthTable stt; + private static final CaseRuleAtomic RULE = new CaseRuleAtomic(); + private static ShortTruthTable stt; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Tests the True or False case rule by ensuring that it results in two children, one that - * contains Statement as true and one that contains Statement as false. - */ - @Test - public void TwoBranchesTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/TrueOrFalseCaseRule/Statement", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the True or False case rule by ensuring that it results in two children, one that + * contains Statement as true and one that contains Statement as false. + */ + @Test + public void TwoBranchesTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/TrueOrFalseCaseRule/Statement", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, cell); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, cell); - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType cellType1 = caseBoard1.getCell(0, 0).getType(); - ShortTruthTableCellType cellType2 = caseBoard2.getCell(0, 0).getType(); + ShortTruthTableCellType cellType1 = caseBoard1.getCell(0, 0).getType(); + ShortTruthTableCellType cellType2 = caseBoard2.getCell(0, 0).getType(); - // First assert the two cells are not equal, then verify that they are true - // or false. - Assert.assertNotEquals(cellType1, cellType2); - Assert.assertTrue( - cellType1.equals(ShortTruthTableCellType.TRUE) - || cellType1.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - cellType2.equals(ShortTruthTableCellType.TRUE) - || cellType2.equals(ShortTruthTableCellType.FALSE)); + // First assert the two cells are not equal, then verify that they are true + // or false. + Assert.assertNotEquals(cellType1, cellType2); + Assert.assertTrue( + cellType1.equals(ShortTruthTableCellType.TRUE) + || cellType1.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + cellType2.equals(ShortTruthTableCellType.TRUE) + || cellType2.equals(ShortTruthTableCellType.FALSE)); - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the one cell that should be different - if (i != 0 && j != 0) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the one cell that should be different + if (i != 0 && j != 0) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java b/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java index 598e9fd9c..1fce24cf1 100644 --- a/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java @@ -17,238 +17,242 @@ public class CellForNumberCaseRuleTest { - private static final CellForNumberCaseRule RULE = new CellForNumberCaseRule(); - private static Skyscrapers skyscrapers; + private static final CellForNumberCaseRule RULE = new CellForNumberCaseRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - // basic, max cases - @Test - public void CellForNumberCaseRule_BasicEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // basic, max cases + @Test + public void CellForNumberCaseRule_BasicEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(false); + board.setDupeFlag(false); + board.setViewFlag(false); - ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); + ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); - Assert.assertEquals(board.getWidth(), cases.size()); + Assert.assertEquals(board.getWidth(), cases.size()); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, i); - changedCell.setData(1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, i); + changedCell.setData(1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // dupe, max cases - @Test - public void CellForNumberCaseRule_DupeEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // dupe, max cases + @Test + public void CellForNumberCaseRule_DupeEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); + ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); - Assert.assertEquals(board.getWidth(), cases.size()); + Assert.assertEquals(board.getWidth(), cases.size()); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, i); - changedCell.setData(1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, i); + changedCell.setData(1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // dupe, 1 case - @Test - public void CellForNumberCaseRule_DupeSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // dupe, 1 case + @Test + public void CellForNumberCaseRule_DupeSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + board.setDupeFlag(true); + board.setViewFlag(false); - board.setDupeFlag(true); - board.setViewFlag(false); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + Assert.assertEquals(1, cases.size()); - Assert.assertEquals(1, cases.size()); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + // dupe, no cases + @Test + public void CellForNumberCaseRule_DupeNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); - // dupe, no cases - @Test - public void CellForNumberCaseRule_DupeNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + board.setDupeFlag(true); + board.setViewFlag(false); - board.setDupeFlag(true); - board.setViewFlag(false); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + Assert.assertEquals(0, cases.size()); + } - Assert.assertEquals(0, cases.size()); - } + // visibility, max cases + @Test + public void CellForNumberCaseRule_ViewEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - // visibility, max cases - @Test - public void CellForNumberCaseRule_ViewEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + board.setDupeFlag(false); + board.setViewFlag(true); - board.setDupeFlag(false); - board.setViewFlag(true); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(1), 1); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(1), 1); + Assert.assertEquals(board.getWidth(), cases.size()); - Assert.assertEquals(board.getWidth(), cases.size()); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(i, 1); + changedCell.setData(1); + expected.addModifiedData(changedCell); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(i, 1); - changedCell.setData(1); - expected.addModifiedData(changedCell); + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; + Assert.assertTrue(exists); } - } - - Assert.assertTrue(exists); } - } - // visibility, 1 Case, direct - @Test - public void CellForNumberCaseRule_ViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // visibility, 1 Case, direct + @Test + public void CellForNumberCaseRule_ViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, 1 Case, implied - @Test - public void CellForNumberCaseRule_ImpliedViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // visibility, 1 Case, implied + @Test + public void CellForNumberCaseRule_ImpliedViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(0), 5); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(0), 5); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(4, 0); - changedCell.setData(5); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(4, 0); + changedCell.setData(5); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, no cases - @Test - public void CellForNumberCaseRule_ViewNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + // visibility, no cases + @Test + public void CellForNumberCaseRule_ViewNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - Assert.assertEquals(0, cases.size()); - } + Assert.assertEquals(0, cases.size()); + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java index cf74604f8..a7bb63a08 100644 --- a/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java @@ -14,143 +14,149 @@ public class DuplicateNumberContradictionTest { - private static final DuplicateNumberContradictionRule RULE = - new DuplicateNumberContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void DuplicateNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + private static final DuplicateNumberContradictionRule RULE = + new DuplicateNumberContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void DuplicateNumberContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void DuplicateNumberContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - // invalid board, no cont - @Test - public void DuplicateNumberContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + // correct board, no cont + @Test + public void DuplicateNumberContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - // on row - @Test - public void DuplicateNumberContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if ((k == 0 || k == 1) && i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // invalid board, no cont + @Test + public void DuplicateNumberContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - } } - } - - // on col - @Test - public void DuplicateNumberContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 0 && (i == 0 || i == 1)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // on row + @Test + public void DuplicateNumberContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if ((k == 0 || k == 1) && i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } + } + } + + // on col + @Test + public void DuplicateNumberContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/ColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 0 && (i == 0 || i == 1)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // multitudes - @Test - public void DuplicateNumberContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/AllContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + // multitudes + @Test + public void DuplicateNumberContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/AllContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java index 5fbadf555..a5a07f997 100644 --- a/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java @@ -14,133 +14,137 @@ public class ExceedingVisibilityContradictionTest { - private static final ExceedingVisibilityContradictionRule RULE = - new ExceedingVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void ExceedingVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + private static final ExceedingVisibilityContradictionRule RULE = + new ExceedingVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void ExceedingVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void ExceedingVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // invalid board, no cont - @Test - public void ExceedingVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); + // correct board, no cont + @Test + public void ExceedingVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on row - @Test - public void ExceedingVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // invalid board, no cont + @Test + public void ExceedingVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on col - @Test - public void ExceedingVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // on row + @Test + public void ExceedingVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } + } + + // on col + @Test + public void ExceedingVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - // multitudes - @Test - public void ExceedingVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void ExceedingVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java index a59fa3746..ee0f3349a 100644 --- a/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java @@ -14,133 +14,137 @@ public class InsufficientVisibilityContradictionTest { - private static final InsufficientVisibilityContradictionRule RULE = - new InsufficientVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void InsufficientVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + private static final InsufficientVisibilityContradictionRule RULE = + new InsufficientVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void InsufficientVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void InsufficientVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // invalid board, no cont - @Test - public void InsufficientVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); + // correct board, no cont + @Test + public void InsufficientVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on row - @Test - public void InsufficientVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // invalid board, no cont + @Test + public void InsufficientVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on col - @Test - public void InsufficientVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // on row + @Test + public void InsufficientVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } + } + + // on col + @Test + public void InsufficientVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - // multitudes - @Test - public void InsufficientVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void InsufficientVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java index 78ba581b9..76540f010 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java @@ -16,213 +16,215 @@ public class LastSingularCellDirectTest { - private static final LastSingularCellDirectRule RULE = new LastSingularCellDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastSingularCellDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastSingularCellDirectRule RULE = new LastSingularCellDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastSingularCellDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // full col - @Test - public void LastSingularCellDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // full col + @Test + public void LastSingularCellDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty row/col - @Test - public void LastSingularCellDirectRule_EmptyTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/0-3Opening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 1); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty row/col + @Test + public void LastSingularCellDirectRule_EmptyTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/0-3Opening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 1); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 row - @Test - public void LastSingularCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 row + @Test + public void LastSingularCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 col - @Test - public void LastSingularCellDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 col + @Test + public void LastSingularCellDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 row - @Test - public void LastSingularCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 row + @Test + public void LastSingularCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 col - @Test - public void LastSingularCellDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 0); - cell.setData(4); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 col + @Test + public void LastSingularCellDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 0); + cell.setData(4); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java index 5cecb9b4c..6b99994a2 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java @@ -16,126 +16,132 @@ public class LastSingularNumberDirectTest { - private static final LastSingularNumberDirectRule RULE = new LastSingularNumberDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row / empty col - @Test - public void LastSingularNumberDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastSingularNumberDirectRule RULE = new LastSingularNumberDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row / empty col + @Test + public void LastSingularNumberDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // full col / empty row - @Test - public void LastSingularNumberDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // full col / empty row + @Test + public void LastSingularNumberDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 row / 1-2 col - @Test - public void LastSingularNumberDirectRule_PartialRowColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 1); - cell.setData(4); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 row / 1-2 col + @Test + public void LastSingularNumberDirectRule_PartialRowColTest1() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1RowOpening", + skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 1); + cell.setData(4); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 col / 1-2 row - @Test - public void LastSingularNumberDirectRule_PartialRowColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 col / 1-2 row + @Test + public void LastSingularNumberDirectRule_PartialRowColTest2() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1ColOpening", + skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java index 3fe530a32..756ff7468 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java @@ -16,236 +16,238 @@ public class LastVisibleCellDirectTest { - private static final LastVisibleCellDirectRule RULE = new LastVisibleCellDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastVisibleCellDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastVisibleCellDirectRule RULE = new LastVisibleCellDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastVisibleCellDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // full col - @Test - public void LastVisibleCellDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // full col + @Test + public void LastVisibleCellDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty row - @Test - public void LastVisibleCellDirectRule_EmptyRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty row + @Test + public void LastVisibleCellDirectRule_EmptyRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty col - @Test - public void LastVisibleCellDirectRule_EmptyColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 4); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty col + @Test + public void LastVisibleCellDirectRule_EmptyColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 4); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 row - public void LastVisibleCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 row + public void LastVisibleCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 col - public void LastVisibleCellDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 2); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 col + public void LastVisibleCellDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 2); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 row - public void LastVisibleCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 row + public void LastVisibleCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 col - public void LastVisibleCellDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 col + public void LastVisibleCellDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java index 65311f2ca..c628b89da 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java @@ -16,236 +16,238 @@ public class LastVisibleNumberDirectTest { - private static final LastVisibleNumberDirectRule RULE = new LastVisibleNumberDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastVisibleNumberDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastVisibleNumberDirectRule RULE = new LastVisibleNumberDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastVisibleNumberDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // full col - @Test - public void LastVisibleNumberDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // full col + @Test + public void LastVisibleNumberDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty row - @Test - public void LastVisibleNumberDirectRule_EmptyRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty row + @Test + public void LastVisibleNumberDirectRule_EmptyRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty col - @Test - public void LastVisibleNumberDirectRule_EmptyColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 4); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty col + @Test + public void LastVisibleNumberDirectRule_EmptyColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 4); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 row - public void LastVisibleNumberDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 row + public void LastVisibleNumberDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 col - public void LastVisibleNumberDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 2); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 col + public void LastVisibleNumberDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 2); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 row - public void LastVisibleNumberDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 row + public void LastVisibleNumberDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 col - public void LastVisibleNumberDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 col + public void LastVisibleNumberDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java index 2ba6d7ad7..ed70fce40 100644 --- a/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java @@ -16,127 +16,127 @@ public class NEdgeDirectTest { - private static final NEdgeDirectRule RULE = new NEdgeDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // -> row, empty -> full - @Test - public void NEdgeDirectRule_RightRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < 5; i++) { - SkyscrapersCell cell = board.getCell(i, 0); - cell.setData(i + 1); - board.addModifiedData(cell); + private static final NEdgeDirectRule RULE = new NEdgeDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - Assert.assertNull(RULE.checkRule(transition)); + // -> row, empty -> full + @Test + public void NEdgeDirectRule_RightRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < 5; i++) { + SkyscrapersCell cell = board.getCell(i, 0); + cell.setData(i + 1); + board.addModifiedData(cell); + } + + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // <-row, partial -> partial - @Test - public void NEdgeDirectRule_LeftRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/LeftRowPartial", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 3); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // <-row, partial -> partial + @Test + public void NEdgeDirectRule_LeftRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/LeftRowPartial", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 3); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - } - } - - // up col, partial -> full - @Test - public void NEdgeDirectRule_UpColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/UpColPartial", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < 2; i++) { - SkyscrapersCell cell = board.getCell(1, i); - cell.setData(i + 1); - board.addModifiedData(cell); } - Assert.assertNull(RULE.checkRule(transition)); + // up col, partial -> full + @Test + public void NEdgeDirectRule_UpColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/UpColPartial", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < 2; i++) { + SkyscrapersCell cell = board.getCell(1, i); + cell.setData(i + 1); + board.addModifiedData(cell); + } + + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 1 && i < 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 1 && i < 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - } - } - - // down col, empty -> partial - @Test - public void NEdgeDirectRule_DownColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/DownColEmpty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 1; i < 5; i++) { - SkyscrapersCell cell = board.getCell(3, i); - cell.setData(5 - i); - board.addModifiedData(cell); } - Assert.assertNull(RULE.checkRule(transition)); + // down col, empty -> partial + @Test + public void NEdgeDirectRule_DownColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/DownColEmpty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 1; i < 5; i++) { + SkyscrapersCell cell = board.getCell(3, i); + cell.setData(5 - i); + board.addModifiedData(cell); + } + + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 3 && i > 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 3 && i > 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java b/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java index f4a298c7c..b417a5227 100644 --- a/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java @@ -17,212 +17,216 @@ public class NumberForCellCaseRuleTest { - private static final NumberForCellCaseRule RULE = new NumberForCellCaseRule(); - private static Skyscrapers skyscrapers; + private static final NumberForCellCaseRule RULE = new NumberForCellCaseRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - // basic, max cases - @Test - public void NumberForCellCaseRule_BasicEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // basic, max cases + @Test + public void NumberForCellCaseRule_BasicEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(false); + board.setDupeFlag(false); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); + ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); - Assert.assertEquals(board.getWidth(), cases.size()); + Assert.assertEquals(board.getWidth(), cases.size()); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, 0); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, 0); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // dupe, max cases - @Test - public void NumberForCellCaseRule_DupeEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // dupe, max cases + @Test + public void NumberForCellCaseRule_DupeEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); + ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); - Assert.assertEquals(board.getWidth(), cases.size()); + Assert.assertEquals(board.getWidth(), cases.size()); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, 0); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, 0); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // dupe, 1 case - @Test - public void NumberForCellCaseRule_DupeSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // dupe, 1 case + @Test + public void NumberForCellCaseRule_DupeSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // dupe, no cases - @Test - public void NumberForCellCaseRule_DupeNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + // dupe, no cases + @Test + public void NumberForCellCaseRule_DupeNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(0, cases.size()); - } + Assert.assertEquals(0, cases.size()); + } - // visibility, max cases - @Test - public void NumberForCellCaseRule_ViewEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // visibility, max cases + @Test + public void NumberForCellCaseRule_ViewEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board, board.getCell(1, 4)); + ArrayList cases = RULE.getCases(board, board.getCell(1, 4)); - Assert.assertEquals(4, cases.size()); + Assert.assertEquals(4, cases.size()); - for (int i = 0; i < board.getWidth() - 1; i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(1, 4); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth() - 1; i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(1, 4); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // visibility, 1 case - @Test - public void NumberForCellCaseRule_ViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // visibility, 1 case + @Test + public void NumberForCellCaseRule_ViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, no cases - @Test - public void NumberForCellCaseRule_ViewNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + // visibility, no cases + @Test + public void NumberForCellCaseRule_ViewNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(0, cases.size()); - } + Assert.assertEquals(0, cases.size()); + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java index b615ce7fb..ec49a8194 100644 --- a/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java @@ -14,155 +14,157 @@ public class PreemptiveVisibilityContradictionTest { - private static final PreemptiveVisibilityContradictionRule RULE = - new PreemptiveVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void PreemptiveVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + private static final PreemptiveVisibilityContradictionRule RULE = + new PreemptiveVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void PreemptiveVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void PreemptiveVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // invalid board, no cont - @Test - public void PreemptiveVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); + // correct board, no cont + @Test + public void PreemptiveVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on row - @Test - public void PreemptiveVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedRowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // invalid board, no cont + @Test + public void PreemptiveVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on col - @Test - public void PreemptiveVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedColContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // on row + @Test + public void PreemptiveVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } + } + + // on col + @Test + public void PreemptiveVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - // multitudes - @Test - public void PreemptiveVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void PreemptiveVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // multitudes - preemptive - @Test - public void PreemptiveVisibilityContradictionRule_ImpliedAllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); + // multitudes - preemptive + @Test + public void PreemptiveVisibilityContradictionRule_ImpliedAllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java index f9509990a..398bba6e5 100644 --- a/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java @@ -14,147 +14,152 @@ public class UnresolvedCellContradictionTest { - private static final UnresolvedCellContradictionRule RULE = new UnresolvedCellContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void UnresolvedCellContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + private static final UnresolvedCellContradictionRule RULE = + new UnresolvedCellContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void UnresolvedCellContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void UnresolvedCellContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } + } + + // correct board, no cont + @Test + public void UnresolvedCellContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - // invalid board, no cont - @Test - public void UnresolvedCellContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + // invalid board, no cont + @Test + public void UnresolvedCellContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - // 3 in a row, 1 in col creates contradiction - @Test - public void UnresolvedCellContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 2 && i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 3 in a row, 1 in col creates contradiction + @Test + public void UnresolvedCellContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 2 && i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 3 in a col, 1 in row creates contradiction - @Test - public void UnresolvedCellContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 1 && i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 3 in a col, 1 in row creates contradiction + @Test + public void UnresolvedCellContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 1 && i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2 in a col, 2 in row creates cell contradiction - @Test - public void UnresolvedCellContradictionRule_MixedContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 2 && i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2 in a col, 2 in row creates cell contradiction + @Test + public void UnresolvedCellContradictionRule_MixedContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 2 && i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java index eb6cf566c..17139fb60 100644 --- a/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java @@ -14,162 +14,165 @@ public class UnresolvedNumberContradictionTest { - private static final UnresolvedNumberContradictionRule RULE = - new UnresolvedNumberContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void UnresolvedNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + private static final UnresolvedNumberContradictionRule RULE = + new UnresolvedNumberContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void UnresolvedNumberContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void UnresolvedNumberContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // invalid board, no cont - @Test - public void UnresolvedNumberContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); + // correct board, no cont + @Test + public void UnresolvedNumberContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // 3 in a row, 1 in col creates contradiction - @Test - public void UnresolvedNumberContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // invalid board, no cont + @Test + public void UnresolvedNumberContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // 3 in a col, 1 in row creates contradiction - @Test - public void UnresolvedNumberContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // 3 in a row, 1 in col creates contradiction + @Test + public void UnresolvedNumberContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - - // 2 in a row/col, 2 in other row/cols creates number contradiction - @Test - public void UnresolvedNumberContradictionRule_TwoContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2NumberContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // 3 in a col, 1 in row creates contradiction + @Test + public void UnresolvedNumberContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } + } + + // 2 in a row/col, 2 in other row/cols creates number contradiction + @Test + public void UnresolvedNumberContradictionRule_TwoContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2NumberContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - - // 1 in a row/col, 3 in other row/cols creates number contradiction - @Test - public void UnresolvedNumberContradictionRule_ThreeContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/1-3NumberContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // 1 in a row/col, 3 in other row/cols creates number contradiction + @Test + public void UnresolvedNumberContradictionRule_ThreeContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/1-3NumberContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java index df343b6b9..38284c410 100644 --- a/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java @@ -17,259 +17,259 @@ public class EmptyFieldDirectRuleTest { - private static final EmptyFieldDirectRule RULE = new EmptyFieldDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - // creates a 3x3 puzzle with no trees - // make the (1,1) tile GRASS - // checks if tiles logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyField", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + private static final EmptyFieldDirectRule RULE = new EmptyFieldDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + // creates a 3x3 puzzle with no trees + // make the (1,1) tile GRASS + // checks if tiles logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyField", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - // creates a 3x3 puzzle with 4 trees - // trees are at (0,0), (2,0), (0,2), and (2,2) - // make the (1,1) tile GRASS. - // checks if tiles logically follow the EmptyFieldDirectRule - @Test - public void DiagonalTreeTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/DiagonalTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + // creates a 3x3 puzzle with 4 trees + // trees are at (0,0), (2,0), (0,2), and (2,2) + // make the (1,1) tile GRASS. + // checks if tiles logically follow the EmptyFieldDirectRule + @Test + public void DiagonalTreeTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/DiagonalTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - // creates a 3x3 puzzle with 4 trees - // trees are at (0,1), (1,0), (1,2), and (2,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFail() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 4 trees + // trees are at (0,1), (1,0), (1,2), and (2,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFail() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - - // creates a 3x3 puzzle with 1 tree - // tree is at (1,0) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailTop() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailTop", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 1 tree + // tree is at (1,0) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailTop() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailTop", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - - // creates a 3x3 puzzle with 1 tree - // tree is at (1,2) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailTopBottom() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailBottom", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 1 tree + // tree is at (1,2) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailTopBottom() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailBottom", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - - // creates a 3x3 puzzle with 1 tree - // tree is at (0,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 1 tree + // tree is at (0,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - - // creates a 3x3 puzzle with 1 tree - // tree is at (2,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 1 tree + // tree is at (2,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java index 45a1add86..0783ab8b8 100644 --- a/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java @@ -19,350 +19,350 @@ public class FinishWithGrassDirectRuleTest { - private static final FinishWithGrassDirectRule RULE = new FinishWithGrassDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles - * horizontal of the tent at (1,0) and (2,0) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassHorizontalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final FinishWithGrassDirectRule RULE = new FinishWithGrassDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); } - } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles - * vertical of the tent at (0,1) and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassVerticalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles + * horizontal of the tent at (1,0) and (2,0) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassHorizontalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles at - * (1,0), (2,0), (0,1), and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.GRASS); - TreeTentCell cell3 = board.getCell(0, 1); - cell3.setData(TreeTentType.GRASS); - TreeTentCell cell4 = board.getCell(0, 2); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles + * vertical of the tent at (0,1) and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassVerticalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - } - } - - /** - * 3x3 TreeTent puzzle with no tents Tests FinishWithGrassDirectRule on GRASS tiles GRASS tiles - * fill entire board - * - * @throws InvalidFileFormatException - */ - @Test - public void NoTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/NoTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - List cells = new ArrayList(); - for (int i = 0; i < board.getWidth(); i++) { - for (int k = 0; k < board.getHeight(); k++) { - TreeTentCell c = board.getCell(i, k); - c.setData(TreeTentType.GRASS); - cells.add(c); - } } - for (TreeTentCell c : cells) { - board.addModifiedData(c); + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles at + * (1,0), (2,0), (0,1), and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.GRASS); + TreeTentCell cell3 = board.getCell(0, 1); + cell3.setData(TreeTentType.GRASS); + TreeTentCell cell4 = board.getCell(0, 2); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } + } } - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); + /** + * 3x3 TreeTent puzzle with no tents Tests FinishWithGrassDirectRule on GRASS tiles GRASS tiles + * fill entire board + * + * @throws InvalidFileFormatException + */ + @Test + public void NoTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/NoTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + List cells = new ArrayList(); + for (int i = 0; i < board.getWidth(); i++) { + for (int k = 0; k < board.getHeight(); k++) { + TreeTentCell c = board.getCell(i, k); + c.setData(TreeTentType.GRASS); + cells.add(c); + } + } - // all cells should change following the rule - for (TreeTentCell c : cells) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - } - - /** - * 3x3 TreeTent puzzle with a tent at (1,1) Tests FinishWithGrassDirectRule on GRASS tiles - * surrounding the tent at (1,0), (0,1), (2,1), and (1,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void MiddleTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/MiddleTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(0, 1); - TreeTentCell cell3 = board.getCell(2, 1); - TreeTentCell cell4 = board.getCell(1, 2); - - cell1.setData(TreeTentType.GRASS); - cell2.setData(TreeTentType.GRASS); - cell3.setData(TreeTentType.GRASS); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + for (TreeTentCell c : cells) { + board.addModifiedData(c); + } + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // all cells should change following the rule + for (TreeTentCell c : cells) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); } - } - } - } - - /** - * 3x3 TreeTent puzzle with missing tents Tests FinishWithGrassDirectRule on GRASS tiles filling - * the puzzle all GRASS tiles should fail the FinishWithGrassDirectRule - * - * @throws InvalidFileFormatException - */ - @Test - public void FailTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/FailTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells not following the FinishWithGrass rule - List cells = new ArrayList(); - for (int i = 0; i < board.getWidth(); i++) { - for (int k = 0; k < board.getHeight(); k++) { - TreeTentCell c = board.getCell(i, k); - c.setData(TreeTentType.GRASS); - cells.add(c); - } } - for (TreeTentCell c : cells) { - board.addModifiedData(c); + /** + * 3x3 TreeTent puzzle with a tent at (1,1) Tests FinishWithGrassDirectRule on GRASS tiles + * surrounding the tent at (1,0), (0,1), (2,1), and (1,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void MiddleTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/MiddleTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(0, 1); + TreeTentCell cell3 = board.getCell(2, 1); + TreeTentCell cell4 = board.getCell(1, 2); + + cell1.setData(TreeTentType.GRASS); + cell2.setData(TreeTentType.GRASS); + cell3.setData(TreeTentType.GRASS); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } + } } - // confirm there is a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); + /** + * 3x3 TreeTent puzzle with missing tents Tests FinishWithGrassDirectRule on GRASS tiles filling + * the puzzle all GRASS tiles should fail the FinishWithGrassDirectRule + * + * @throws InvalidFileFormatException + */ + @Test + public void FailTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/FailTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells not following the FinishWithGrass rule + List cells = new ArrayList(); + for (int i = 0; i < board.getWidth(); i++) { + for (int k = 0; k < board.getHeight(); k++) { + TreeTentCell c = board.getCell(i, k); + c.setData(TreeTentType.GRASS); + cells.add(c); + } + } - // all cells should fail the rule test - for (TreeTentCell c : cells) { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + for (TreeTentCell c : cells) { + board.addModifiedData(c); + } + + // confirm there is a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // all cells should fail the rule test + for (TreeTentCell c : cells) { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - } - - /** - * 7x7 TreeTent puzzle with multiple tents spaced out Tests FinishWithGrassDirectRule on GRASS - * tiles between the tents at (0,3), (2,3), (4,3), and (6,3) - * - * @throws InvalidFileFormatException - */ - @Test - public void SpacedOutTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/SpacedOutTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(0, 3); - TreeTentCell cell2 = board.getCell(2, 3); - TreeTentCell cell3 = board.getCell(4, 3); - TreeTentCell cell4 = board.getCell(6, 3); - - cell1.setData(TreeTentType.GRASS); - cell2.setData(TreeTentType.GRASS); - cell3.setData(TreeTentType.GRASS); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 7x7 TreeTent puzzle with multiple tents spaced out Tests FinishWithGrassDirectRule on GRASS + * tiles between the tents at (0,3), (2,3), (4,3), and (6,3) + * + * @throws InvalidFileFormatException + */ + @Test + public void SpacedOutTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/SpacedOutTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(0, 3); + TreeTentCell cell2 = board.getCell(2, 3); + TreeTentCell cell3 = board.getCell(4, 3); + TreeTentCell cell4 = board.getCell(6, 3); + + cell1.setData(TreeTentType.GRASS); + cell2.setData(TreeTentType.GRASS); + cell3.setData(TreeTentType.GRASS); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java index 9903a9685..652af615f 100644 --- a/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java @@ -18,335 +18,337 @@ public class FinishWithTentsDirectRuleTest { - private static final FinishWithTentsDirectRule RULE = new FinishWithTentsDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles - * horizontal of the GRASS tile at (1,0) and (2,0) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithHorizontalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithHorizontalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.TENT); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final FinishWithTentsDirectRule RULE = new FinishWithTentsDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); } - } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles - * vertical of the GRASS tile at (0,1) and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithVerticalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithVerticalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.TENT); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles + * horizontal of the GRASS tile at (1,0) and (2,0) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithHorizontalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithHorizontalTents", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.TENT); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the GRASS tile at (1,0), (1,2), (0,1), and (2,1) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 2); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(2, 1); - - cell1.setData(TreeTentType.TENT); - cell2.setData(TreeTentType.TENT); - cell3.setData(TreeTentType.TENT); - cell4.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation()) - || (c.getLocation()).equals(cell3.getLocation()) - || (c.getLocation()).equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles + * vertical of the GRASS tile at (0,1) and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithVerticalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithVerticalTents", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.TENT); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) - * - * @throws InvalidFileFormatException - */ - @Test - public void AdditionalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/AdditionalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 2); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(2, 1); - - cell1.setData(TreeTentType.TENT); - cell2.setData(TreeTentType.TENT); - cell3.setData(TreeTentType.TENT); - cell4.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation()) - || (c.getLocation()).equals(cell3.getLocation()) - || (c.getLocation()).equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the GRASS tile at (1,0), (1,2), (0,1), and (2,1) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 2); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(2, 1); + + cell1.setData(TreeTentType.TENT); + cell2.setData(TreeTentType.TENT); + cell3.setData(TreeTentType.TENT); + cell4.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation()) + || (c.getLocation()).equals(cell3.getLocation()) + || (c.getLocation()).equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - /** - * Empty 3x3 TreeTent puzzle Tests FinishWithTentsDirectRule on TENT tiles of entire puzzle all - * TENT tiles should fail FinishWithTentsDirectRule as no TENT tiles should be there - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithTentsFailTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTentsFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - ArrayList cells = new ArrayList(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - c.setData(TreeTentType.TENT); - board.addModifiedData(c); - cells.add(c); - } + + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) + * + * @throws InvalidFileFormatException + */ + @Test + public void AdditionalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/AdditionalTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 2); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(2, 1); + + cell1.setData(TreeTentType.TENT); + cell2.setData(TreeTentType.TENT); + cell3.setData(TreeTentType.TENT); + cell4.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation()) + || (c.getLocation()).equals(cell3.getLocation()) + || (c.getLocation()).equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } + } } - Assert.assertNotNull(RULE.checkRule(transition)); + /** + * Empty 3x3 TreeTent puzzle Tests FinishWithTentsDirectRule on TENT tiles of entire puzzle all + * TENT tiles should fail FinishWithTentsDirectRule as no TENT tiles should be there + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithTentsFailTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTentsFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + ArrayList cells = new ArrayList(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + c.setData(TreeTentType.TENT); + board.addModifiedData(c); + cells.add(c); + } + } - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail - * FinishWithTentsDirectRule as there were already sufficient number of TENT tiles - * - * @throws InvalidFileFormatException - */ - @Test - public void TooManyTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/TooManyTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - ArrayList cells = new ArrayList(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if ((k == 1) && (i == 1)) { - continue; + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - TreeTentCell c = board.getCell(k, i); - c.setData(TreeTentType.TENT); - board.addModifiedData(c); - cells.add(c); - } } - Assert.assertNotNull(RULE.checkRule(transition)); + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail + * FinishWithTentsDirectRule as there were already sufficient number of TENT tiles + * + * @throws InvalidFileFormatException + */ + @Test + public void TooManyTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/TooManyTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + ArrayList cells = new ArrayList(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if ((k == 1) && (i == 1)) { + continue; + } + TreeTentCell c = board.getCell(k, i); + c.setData(TreeTentType.TENT); + board.addModifiedData(c); + cells.add(c); + } + } - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail - * FinishWithTentsDirectRule as there are multiple configurations of the placement of the TENT - * tiles - * - * @throws InvalidFileFormatException - */ - @Test - public void AmbiguousTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/AmbiguousTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell = board.getCell(0, 1); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(1, 0); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail + * FinishWithTentsDirectRule as there are multiple configurations of the placement of the TENT + * tiles + * + * @throws InvalidFileFormatException + */ + @Test + public void AmbiguousTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/AmbiguousTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell = board.getCell(0, 1); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(1, 0); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(2, 1); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(2, 1); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(1, 2); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(1, 2); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java index b3a1de6d5..92d6e4a59 100644 --- a/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java @@ -17,148 +17,148 @@ public class LastCampingSpotDirectRuleTest { - private static final LastCampingSpotDirectRule RULE = new LastCampingSpotDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square above a tree which is surrounded on all other - * sides. - */ - @Test - public void EmptyFieldTest_Up() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotUp", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastCampingSpotDirectRule RULE = new LastCampingSpotDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square above a tree which is surrounded on all + * other sides. + */ + @Test + public void EmptyFieldTest_Up() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotUp", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square below a tree which is surrounded on all other - * sides. - */ - @Test - public void EmptyFieldTest_Down() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotDown", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 2); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square below a tree which is surrounded on all + * other sides. + */ + @Test + public void EmptyFieldTest_Down() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotDown", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 2); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square to the left of a tree which is surrounded on - * all other sides. - */ - @Test - public void EmptyFieldTest_Left() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square to the left of a tree which is surrounded + * on all other sides. + */ + @Test + public void EmptyFieldTest_Left() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square to the right of a tree which is surrounded on - * all other sides. - */ - @Test - public void EmptyFieldTest_Right() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(2, 1); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square to the right of a tree which is surrounded + * on all other sides. + */ + @Test + public void EmptyFieldTest_Right() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(2, 1); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java index 8d099f283..b17c92486 100644 --- a/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java @@ -15,96 +15,99 @@ public class NoTentForTreeContradictionRuleTest { - private static final NoTentForTreeContradictionRule RULE = new NoTentForTreeContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Tests if a tree is next to only grass in a 2x2 grid triggers - * the contradiction - */ - @Test - public void NoTentForTreeContradictionRule_Basic() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally - * next to the tree, which should still contradict - */ - @Test - public void NoTentForTreeContradictionRule_Diagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeDiagonal", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests that adjacent trees do not allow a pass - */ - @Test - public void NoTentForTreeContradictionRule_TwoTrees() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTrees", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally - * next to two trees, which should still contradict on one. - */ - @Test - public void NoTentForTreeContradictionRule_TwoTreesDiagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTreesDiagonal", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } + private static final NoTentForTreeContradictionRule RULE = new NoTentForTreeContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Tests if a tree is next to only grass in a 2x2 grid + * triggers the contradiction + */ + @Test + public void NoTentForTreeContradictionRule_Basic() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally + * next to the tree, which should still contradict + */ + @Test + public void NoTentForTreeContradictionRule_Diagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests that adjacent trees do not allow a pass + */ + @Test + public void NoTentForTreeContradictionRule_TwoTrees() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTrees", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally + * next to two trees, which should still contradict on one. + */ + @Test + public void NoTentForTreeContradictionRule_TwoTreesDiagonal() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTreesDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } } diff --git a/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java index c639b2a25..fd6be92de 100644 --- a/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java @@ -14,201 +14,204 @@ public class NoTreeForTentContradictionRuleTest { - private static final NoTreeForTentContradictionRule RULE = new NoTreeForTentContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_NW() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNW", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NE corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_NE() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNE", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_SW() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSW", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the SE corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_SE() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSE", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with no trees, a Tent in the center - * cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_3x3() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTent3x3", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with diagonal trees, a Tent in the - * center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_3x3WithDiagonalTrees() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentDiagonals", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with an adjacent tree, test does not - * assert null. - */ - @Test - public void NoTreeForTentContradictionRule_YesTree() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentYesTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with touching tents, a Tent in the - * center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_JustTent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentJustTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } + private static final NoTreeForTentContradictionRule RULE = new NoTreeForTentContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_NW() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNW", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NE corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_NE() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNE", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_SW() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSW", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the SE corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_SE() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSE", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with no trees, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_3x3() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTent3x3", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with diagonal trees, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_3x3WithDiagonalTrees() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentDiagonals", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with an adjacent tree, test does + * not assert null. + */ + @Test + public void NoTreeForTentContradictionRule_YesTree() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentYesTree", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with touching tents, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_JustTent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentJustTent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } } diff --git a/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java index e48fd0979..7ff57a052 100644 --- a/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java @@ -17,138 +17,140 @@ public class SurroundTentWithGrassDirectRuleTest { - private static final SurroundTentWithGrassDirectRule RULE = new SurroundTentWithGrassDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Test to check if all adjacent and diagonals not filled with - * a tree are filled with grass - */ - @Test - public void SurroundTentWithGrassBasicRuleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrass", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final SurroundTentWithGrassDirectRule RULE = + new SurroundTentWithGrassDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Test to check if all adjacent and diagonals not filled + * with a tree are filled with grass + */ + @Test + public void SurroundTentWithGrassBasicRuleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrass", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Test with a 3x3 board with an absolutely empty area aside from a tent in the middle - * While such a situation is an illegal treetent setup, this direct rule doesn't consider that - * aspect, so its ok in this context - */ - @Test - public void SurroundTentWithGrassBasicRuleTest_BadBoard() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassBad", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(1, 0); - cell2.setData(TreeTentType.GRASS); - TreeTentCell cell3 = board.getCell(2, 0); - cell3.setData(TreeTentType.GRASS); - TreeTentCell cell4 = board.getCell(0, 1); - cell4.setData(TreeTentType.GRASS); - // Skip (1,1) due to being the Tent - TreeTentCell cell5 = board.getCell(2, 1); - cell5.setData(TreeTentType.GRASS); - TreeTentCell cell6 = board.getCell(0, 2); - cell6.setData(TreeTentType.GRASS); - TreeTentCell cell7 = board.getCell(1, 2); - cell7.setData(TreeTentType.GRASS); - TreeTentCell cell8 = board.getCell(2, 2); - cell8.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - // board.addModifiedData(cell4); - board.addModifiedData(cell5); - board.addModifiedData(cell6); - board.addModifiedData(cell7); - board.addModifiedData(cell8); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || // point.equals(cell4.getLocation()) || - point.equals(cell5.getLocation()) - || point.equals(cell6.getLocation()) - || point.equals(cell7.getLocation()) - || point.equals(cell8.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException + *

Test with a 3x3 board with an absolutely empty area aside from a tent in the middle + * While such a situation is an illegal treetent setup, this direct rule doesn't consider + * that aspect, so its ok in this context + */ + @Test + public void SurroundTentWithGrassBasicRuleTest_BadBoard() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassBad", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(1, 0); + cell2.setData(TreeTentType.GRASS); + TreeTentCell cell3 = board.getCell(2, 0); + cell3.setData(TreeTentType.GRASS); + TreeTentCell cell4 = board.getCell(0, 1); + cell4.setData(TreeTentType.GRASS); + // Skip (1,1) due to being the Tent + TreeTentCell cell5 = board.getCell(2, 1); + cell5.setData(TreeTentType.GRASS); + TreeTentCell cell6 = board.getCell(0, 2); + cell6.setData(TreeTentType.GRASS); + TreeTentCell cell7 = board.getCell(1, 2); + cell7.setData(TreeTentType.GRASS); + TreeTentCell cell8 = board.getCell(2, 2); + cell8.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + // board.addModifiedData(cell4); + board.addModifiedData(cell5); + board.addModifiedData(cell6); + board.addModifiedData(cell7); + board.addModifiedData(cell8); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || // point.equals(cell4.getLocation()) || + point.equals(cell5.getLocation()) + || point.equals(cell6.getLocation()) + || point.equals(cell7.getLocation()) + || point.equals(cell8.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Test to see if the rule passes even if no grass was able to be placed due to the - * presence of trees. - */ - @Test - public void SurroundTentWithGrassBasicRuleTest_FullBoard() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassTrees", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** + * @throws InvalidFileFormatException + *

Test to see if the rule passes even if no grass was able to be placed due to the + * presence of trees. + */ + @Test + public void SurroundTentWithGrassBasicRuleTest_FullBoard() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassTrees", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java index 237013212..68dbeaf48 100644 --- a/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java @@ -3,12 +3,12 @@ // This feature is no longer supported public class TentForTreeDirectRuleTest { - // private static final TentForTreeBasicRule RULE = new TentForTreeBasicRule(); - // private static TreeTent treetent; - // - // @BeforeClass - // public static void setUp() { - // MockGameBoardFacade.getInstance(); - // treetent = new TreeTent(); - // } + // private static final TentForTreeBasicRule RULE = new TentForTreeBasicRule(); + // private static TreeTent treetent; + // + // @BeforeClass + // public static void setUp() { + // MockGameBoardFacade.getInstance(); + // treetent = new TreeTent(); + // } } diff --git a/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java b/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java index 1f08fa597..1fe7e4bd0 100644 --- a/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java @@ -18,62 +18,62 @@ import org.junit.Test; public class TentOrGrassCaseRuleTest { - private static final TentOrGrassCaseRule RULE = new TentOrGrassCaseRule(); - private static TreeTent treetent; + private static final TentOrGrassCaseRule RULE = new TentOrGrassCaseRule(); + private static TreeTent treetent; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } - /** - * empty 3x3 TreeTent puzzle Tests TentOrGrassCaseRule on UNKOWN tile at (0,0) - * - *

checks 2 cases are created checks first case is TENT tile checks second case is GRASS tile - * checks other cells have not been modified - * - * @throws InvalidFileFormatException - */ - @Test - public void TentOrTreeTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TentOrGrassCaseRule/TestPuzzle", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * empty 3x3 TreeTent puzzle Tests TentOrGrassCaseRule on UNKOWN tile at (0,0) + * + *

checks 2 cases are created checks first case is TENT tile checks second case is GRASS tile + * checks other cells have not been modified + * + * @throws InvalidFileFormatException + */ + @Test + public void TentOrTreeTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TentOrGrassCaseRule/TestPuzzle", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentCell testing_cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, testing_cell); + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentCell testing_cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, testing_cell); - // assert correct number of cases created - Assert.assertEquals(2, cases.size()); + // assert correct number of cases created + Assert.assertEquals(2, cases.size()); - // TENT case - TreeTentBoard tentCase = (TreeTentBoard) cases.get(0); - Assert.assertEquals(tentCase.getCell(0, 0).getType(), TreeTentType.TENT); + // TENT case + TreeTentBoard tentCase = (TreeTentBoard) cases.get(0); + Assert.assertEquals(tentCase.getCell(0, 0).getType(), TreeTentType.TENT); - // GRASS case - TreeTentBoard grassCase = (TreeTentBoard) cases.get(1); - Assert.assertEquals(grassCase.getCell(0, 0).getType(), TreeTentType.GRASS); + // GRASS case + TreeTentBoard grassCase = (TreeTentBoard) cases.get(1); + Assert.assertEquals(grassCase.getCell(0, 0).getType(), TreeTentType.GRASS); - // checks other cells have not been modified - TreeTentCell original_cell; - TreeTentCell case_cell; + // checks other cells have not been modified + TreeTentCell original_cell; + TreeTentCell case_cell; - for (int w = 0; w < board.getWidth(); w++) { - for (int h = 0; h < board.getHeight(); h++) { - if (w == 0 && h == 0) { - continue; - } - original_cell = board.getCell(w, h); - case_cell = tentCase.getCell(w, h); - Assert.assertEquals(original_cell.getType(), case_cell.getType()); + for (int w = 0; w < board.getWidth(); w++) { + for (int h = 0; h < board.getHeight(); h++) { + if (w == 0 && h == 0) { + continue; + } + original_cell = board.getCell(w, h); + case_cell = tentCase.getCell(w, h); + Assert.assertEquals(original_cell.getType(), case_cell.getType()); - case_cell = grassCase.getCell(w, h); - Assert.assertEquals(original_cell.getType(), case_cell.getType()); - } + case_cell = grassCase.getCell(w, h); + Assert.assertEquals(original_cell.getType(), case_cell.getType()); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java index f08d87a3b..e1773827d 100644 --- a/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java @@ -16,225 +16,231 @@ public class TooFewTentsContradictionRuleTest { - private static final TooFewTentsContradictionRule RULE = new TooFewTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if the - * fact it expects a tent on the y-axis is caught. - */ - @Test - public void TooFewTentsContradictionRule_JustY() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsJustY", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just a tent, checks if the - * fact it expects 2 tents on the y-axis is caught. (This is an impossible situation given the - * constraints, but for the purposes of the test it is fine) - */ - @Test - public void TooFewTentsContradictionRule_WithTent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsWithTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if the - * fact it expects a tent on both x and y is caught. - */ - @Test - public void TooFewTentsContradictionRule_DoubleBad() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsDoubleBad", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: [] Tr [] Gr Column 2 is - * checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_2x2ColumnOnly() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Column", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 1); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final TooFewTentsContradictionRule RULE = new TooFewTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if + * the fact it expects a tent on the y-axis is caught. + */ + @Test + public void TooFewTentsContradictionRule_JustY() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsJustY", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just a tent, checks if + * the fact it expects 2 tents on the y-axis is caught. (This is an impossible situation + * given the constraints, but for the purposes of the test it is fine) + */ + @Test + public void TooFewTentsContradictionRule_WithTent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsWithTent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if + * the fact it expects a tent on both x and y is caught. + */ + @Test + public void TooFewTentsContradictionRule_DoubleBad() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsDoubleBad", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: [] Tr [] Gr Column 2 + * is checked to have 1 Tent (which is not present, thus producing a contradiction) + */ + @Test + public void TooFewTentsContradictionRule_2x2ColumnOnly() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Column", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 1); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tr Gr [] [] Row 1 is - * checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_2x2RowOnly() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Row", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(1, 0); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tr Gr [] [] Row 1 is + * checked to have 1 Tent (which is not present, thus producing a contradiction) + */ + @Test + public void TooFewTentsContradictionRule_2x2RowOnly() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Row", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(1, 0); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: [] Tr [] [] Gr [] [] Gr - * [] Column 2 is checked to have 1 Tent (which is not present, thus producing a - * contradiction) - */ - @Test - public void TooFewTentsContradictionRule_3x3OneColumn() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3Column", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 1); - TreeTentCell cell3 = board.getCell(1, 2); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: [] Tr [] [] Gr [] [] + * Gr [] Column 2 is checked to have 1 Tent (which is not present, thus producing a + * contradiction) + */ + @Test + public void TooFewTentsContradictionRule_3x3OneColumn() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3Column", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 1); + TreeTentCell cell3 = board.getCell(1, 2); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: Gr Tr Gr Gr [] Gr Gr Tr - * Gr Column 1 and 3 are checked to have 1 Tent (which is not present, thus producing a - * contradiction) - */ - @Test - public void TooFewTentsContradictionRule_3x3TwoColumn() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3DoubleColumn", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(0, 1); - TreeTentCell cell3 = board.getCell(0, 2); - TreeTentCell cell4 = board.getCell(2, 0); - TreeTentCell cell5 = board.getCell(2, 1); - TreeTentCell cell6 = board.getCell(2, 2); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation()) - || point.equals(cell5.getLocation()) - || point.equals(cell6.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: Gr Tr Gr Gr [] Gr Gr + * Tr Gr Column 1 and 3 are checked to have 1 Tent (which is not present, thus producing a + * contradiction) + */ + @Test + public void TooFewTentsContradictionRule_3x3TwoColumn() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3DoubleColumn", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(0, 1); + TreeTentCell cell3 = board.getCell(0, 2); + TreeTentCell cell4 = board.getCell(2, 0); + TreeTentCell cell5 = board.getCell(2, 1); + TreeTentCell cell6 = board.getCell(2, 2); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation()) + || point.equals(cell5.getLocation()) + || point.equals(cell6.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tn [] Tr [] This should - * fail the contradiction as it is a legal board. - */ - @Test - public void TooFewTentsContradictionRule_NoContradiction() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsNoContradiction", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tn [] Tr [] This + * should fail the contradiction as it is a legal board. + */ + @Test + public void TooFewTentsContradictionRule_NoContradiction() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsNoContradiction", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java index fb94aa006..2e542b3d2 100644 --- a/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java @@ -16,246 +16,253 @@ public class TooManyTentsContradictionRuleTest { - private static final TooManyTentsContradictionRule RULE = new TooManyTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /* - TESTING BASIS: - All test in this Rule use a 3x3 table. - There is a Tree at (1,1) - There are tents at (0,1) and (2,2) - All Tent Counts are listed left to right or top to bottom - */ - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_TotalFail() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTotalFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final TooManyTentsContradictionRule RULE = new TooManyTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /* + TESTING BASIS: + All test in this Rule use a 3x3 table. + There is a Tree at (1,1) + There are tents at (0,1) and (2,2) + All Tent Counts are listed left to right or top to bottom + */ + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_TotalFail() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTotalFail", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 1,0,0 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_TopRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(0, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 1,0,0 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_TopRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(0, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTests if: Row Tent Counts: 0,0,1 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_BottomRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(0, 2); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTests if: Row Tent Counts: 0,0,1 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_BottomRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(0, 2); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,1,0 - */ - @Test - public void TooManyTentsContradictionRule_TopDown() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopDown", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(1, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,1,0 + */ + @Test + public void TooManyTentsContradictionRule_TopDown() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopDown", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(1, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,0,1 - */ - @Test - public void TooManyTentsContradictionRule_BottomDown() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomDown", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(2, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,0,1 + */ + @Test + public void TooManyTentsContradictionRule_BottomDown() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomDown", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(2, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if the Top Tent is completely - * accounted for, but not the bottom Row Tent Counts: 1,0,0 Column Tent Counts: 0,1,0 - */ - @Test - public void TooManyTentsContradictionRule_TopAccount() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopAccount", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(1, 0); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(1, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if the Top Tent is completely + * accounted for, but not the bottom Row Tent Counts: 1,0,0 Column Tent Counts: 0,1,0 + */ + @Test + public void TooManyTentsContradictionRule_TopAccount() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopAccount", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(1, 0); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(1, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if the Bottom Tent is completely - * accounted for, but not the Top Row Tent Counts: 0,0,1 Column Tent Counts: 0,0,1 - */ - @Test - public void TooManyTentsContradictionRule_BottomAccount() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomAccount", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(2, 1); - TreeTentCell cell3 = board.getCell(0, 2); - TreeTentCell cell4 = board.getCell(2, 2); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if the Bottom Tent is completely + * accounted for, but not the Top Row Tent Counts: 0,0,1 Column Tent Counts: 0,0,1 + */ + @Test + public void TooManyTentsContradictionRule_BottomAccount() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomAccount", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(2, 1); + TreeTentCell cell3 = board.getCell(0, 2); + TreeTentCell cell4 = board.getCell(2, 2); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java index 6018b6853..9f5455a92 100644 --- a/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java @@ -14,239 +14,246 @@ public class TouchingTentsContradictionRuleTest { - private static final TouchingTentsContradictionRule RULE = new TouchingTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - // DIAGONAL TESTS - /** - * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_DiagonalUpLeftToDownRight() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonal", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - - /** - * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_DiagonalDownLeftToUpRight() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonalAlt", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - // ADJACENT TESTS - /** - * @throws InvalidFileFormatException Tests a tent adjacent of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_AdjacentVertical() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent adjacent of orientation TT - */ - @Test - public void TouchingTentsContradictionRule_AdjacentHorizontal() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacentAlt", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - // MIXED TESTS - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT TT - */ - @Test - public void TouchingTentsContradictionRule_2By2Square() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsFull2By2", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT T - */ - @Test - public void TouchingTentsContradictionRule_UpLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT T - */ - @Test - public void TouchingTentsContradictionRule_UpRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpRight", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation T TT - */ - @Test - public void TouchingTentsContradictionRule_DownLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownLeft", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation T TT - */ - @Test - public void TouchingTentsContradictionRule_DownRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownRight", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Tests if tree adjacent triggers a null - */ - @Test - public void TouchingTentsContradictionRule_TreeAdjacent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeAdjacent", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if tree diagonal triggers a null - */ - @Test - public void TouchingTentsContradictionRule_TreeDiagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeDiagonal", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } + private static final TouchingTentsContradictionRule RULE = new TouchingTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + // DIAGONAL TESTS + /** + * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_DiagonalUpLeftToDownRight() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } + + /** + * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_DiagonalDownLeftToUpRight() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonalAlt", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + // ADJACENT TESTS + /** + * @throws InvalidFileFormatException Tests a tent adjacent of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_AdjacentVertical() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent adjacent of orientation TT + */ + @Test + public void TouchingTentsContradictionRule_AdjacentHorizontal() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacentAlt", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + // MIXED TESTS + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT TT + */ + @Test + public void TouchingTentsContradictionRule_2By2Square() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsFull2By2", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT T + */ + @Test + public void TouchingTentsContradictionRule_UpLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpLeft", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT T + */ + @Test + public void TouchingTentsContradictionRule_UpRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation T TT + */ + @Test + public void TouchingTentsContradictionRule_DownLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownLeft", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation T TT + */ + @Test + public void TouchingTentsContradictionRule_DownRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Tests if tree adjacent triggers a null + */ + @Test + public void TouchingTentsContradictionRule_TreeAdjacent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeAdjacent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if tree diagonal triggers a null + */ + @Test + public void TouchingTentsContradictionRule_TreeDiagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } } diff --git a/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java index 2aecd0f0a..f4ea6703b 100644 --- a/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java @@ -3,12 +3,12 @@ // This feature is no longer supported public class TreeForTentDirectRuleTest { - // private static final TreeForTentBasicRule RULE = new TreeForTentBasicRule(); - // private static TreeTent treetent; + // private static final TreeForTentBasicRule RULE = new TreeForTentBasicRule(); + // private static TreeTent treetent; - // @BeforeClass - // public static void setUp() { - // MockGameBoardFacade.getInstance(); - // treetent = new TreeTent(); - // } + // @BeforeClass + // public static void setUp() { + // MockGameBoardFacade.getInstance(); + // treetent = new TreeTent(); + // } } From a62e03f7773ecc26d5a359e138aa300f06949156 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 18:32:27 -0500 Subject: [PATCH 41/54] Default google formatting style --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index ae16e26c8..ac8abd443 100644 --- a/build.gradle +++ b/build.gradle @@ -33,7 +33,7 @@ spotless{ formatAnnotations() - googleJavaFormat('1.19.2').aosp().reflowLongStrings() + googleJavaFormat('1.19.2') } } From 96da739b464978dd58da376c3588c70a7ee907a0 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln Date: Tue, 13 Feb 2024 23:34:07 +0000 Subject: [PATCH 42/54] Automated Java code formatting changes --- src/main/java/edu/rpi/legup/Legup.java | 20 +- src/main/java/edu/rpi/legup/app/Config.java | 253 ++- .../edu/rpi/legup/app/GameBoardFacade.java | 912 ++++---- .../rpi/legup/app/InvalidConfigException.java | 6 +- .../edu/rpi/legup/app/LegupPreferences.java | 229 +- .../rpi/legup/app/PuzzleKeyAccelerator.java | 140 +- .../rpi/legup/controller/BoardController.java | 150 +- .../edu/rpi/legup/controller/Controller.java | 196 +- .../legup/controller/CursorController.java | 80 +- .../controller/EditorElementController.java | 66 +- .../legup/controller/ElementController.java | 571 +++-- .../rpi/legup/controller/RuleController.java | 181 +- .../legup/controller/ToolbarController.java | 34 +- .../rpi/legup/controller/TreeController.java | 267 ++- .../legup/history/AddTreeElementCommand.java | 167 +- .../ApplyDefaultDirectRuleCommand.java | 206 +- .../legup/history/AutoCaseRuleCommand.java | 235 +- .../edu/rpi/legup/history/CommandError.java | 44 +- .../edu/rpi/legup/history/CommandState.java | 24 +- .../history/DeleteTreeElementCommand.java | 153 +- .../rpi/legup/history/EditDataCommand.java | 272 +-- .../java/edu/rpi/legup/history/History.java | 154 +- .../java/edu/rpi/legup/history/ICommand.java | 38 +- .../rpi/legup/history/IHistoryListener.java | 44 +- .../rpi/legup/history/IHistorySubject.java | 36 +- .../InvalidCommandStateTransition.java | 20 +- .../edu/rpi/legup/history/MergeCommand.java | 224 +- .../edu/rpi/legup/history/PuzzleCommand.java | 144 +- .../history/ValidateCaseRuleCommand.java | 212 +- .../ValidateContradictionRuleCommand.java | 279 ++- .../history/ValidateDirectRuleCommand.java | 222 +- src/main/java/edu/rpi/legup/model/Puzzle.java | 1209 +++++----- .../edu/rpi/legup/model/PuzzleExporter.java | 233 +- .../edu/rpi/legup/model/PuzzleImporter.java | 717 +++--- .../edu/rpi/legup/model/elements/Element.java | 109 +- .../rpi/legup/model/elements/ElementType.java | 4 +- .../model/elements/NonPlaceableElement.java | 10 +- .../model/elements/PlaceableElement.java | 10 +- .../edu/rpi/legup/model/gameboard/Board.java | 410 ++-- .../rpi/legup/model/gameboard/CaseBoard.java | 90 +- .../legup/model/gameboard/ElementFactory.java | 38 +- .../rpi/legup/model/gameboard/GridBoard.java | 281 ++- .../rpi/legup/model/gameboard/GridCell.java | 100 +- .../legup/model/gameboard/PuzzleElement.java | 354 +-- .../legup/model/observer/IBoardListener.java | 36 +- .../legup/model/observer/IBoardSubject.java | 36 +- .../legup/model/observer/ITreeListener.java | 40 +- .../legup/model/observer/ITreeSubject.java | 36 +- .../edu/rpi/legup/model/rules/CaseRule.java | 246 +- .../legup/model/rules/ContradictionRule.java | 178 +- .../edu/rpi/legup/model/rules/DirectRule.java | 169 +- .../edu/rpi/legup/model/rules/MergeRule.java | 152 +- .../java/edu/rpi/legup/model/rules/Rule.java | 300 ++- .../edu/rpi/legup/model/rules/RuleType.java | 8 +- .../java/edu/rpi/legup/model/tree/Tree.java | 345 ++- .../edu/rpi/legup/model/tree/TreeElement.java | 114 +- .../rpi/legup/model/tree/TreeElementType.java | 4 +- .../edu/rpi/legup/model/tree/TreeNode.java | 606 ++--- .../rpi/legup/model/tree/TreeTransition.java | 781 +++---- .../legup/puzzle/battleship/Battleship.java | 294 +-- .../puzzle/battleship/BattleshipBoard.java | 256 +-- .../puzzle/battleship/BattleshipCell.java | 58 +- .../battleship/BattleshipCellController.java | 64 +- .../battleship/BattleshipCellFactory.java | 112 +- .../puzzle/battleship/BattleshipClue.java | 124 +- .../puzzle/battleship/BattleshipClueView.java | 98 +- .../battleship/BattleshipElementView.java | 179 +- .../puzzle/battleship/BattleshipExporter.java | 100 +- .../puzzle/battleship/BattleshipImporter.java | 341 ++- .../puzzle/battleship/BattleshipType.java | 86 +- .../puzzle/battleship/BattleshipView.java | 31 +- .../rules/AdjacentShipsContradictionRule.java | 126 +- .../rules/ContinueShipDirectRule.java | 63 +- .../rules/FinishWithShipsDirectRule.java | 159 +- .../rules/FinishWithWaterDirectRule.java | 63 +- .../IncompleteShipContradictionRule.java | 40 +- .../battleship/rules/SegmentTypeCaseRule.java | 110 +- .../rules/SegmentTypeDirectRule.java | 63 +- .../rules/ShipLocationCaseRule.java | 110 +- .../battleship/rules/ShipOrWaterCaseRule.java | 110 +- .../rules/SurroundShipDirectRule.java | 63 +- .../rules/TooFewInFleetContradictionRule.java | 40 +- .../rules/TooFewRowColContradictionRule.java | 40 +- .../TooManyInFleetContradictionRule.java | 40 +- .../rules/TooManyRowColContradiction.java | 40 +- .../rpi/legup/puzzle/fillapix/Fillapix.java | 94 +- .../legup/puzzle/fillapix/FillapixBoard.java | 98 +- .../legup/puzzle/fillapix/FillapixCell.java | 162 +- .../fillapix/FillapixCellController.java | 70 +- .../puzzle/fillapix/FillapixCellFactory.java | 107 +- .../puzzle/fillapix/FillapixCellType.java | 20 +- .../puzzle/fillapix/FillapixElementView.java | 97 +- .../puzzle/fillapix/FillapixExporter.java | 52 +- .../puzzle/fillapix/FillapixImporter.java | 190 +- .../puzzle/fillapix/FillapixUtilities.java | 415 ++-- .../legup/puzzle/fillapix/FillapixView.java | 23 +- .../puzzle/fillapix/elements/BlackTile.java | 14 +- .../puzzle/fillapix/elements/NumberTile.java | 42 +- .../puzzle/fillapix/elements/UnknownTile.java | 14 +- .../puzzle/fillapix/elements/WhiteTile.java | 14 +- .../fillapix/rules/BlackOrWhiteCaseRule.java | 130 +- .../rules/FinishWithBlackDirectRule.java | 91 +- .../rules/FinishWithWhiteDirectRule.java | 91 +- .../fillapix/rules/MirrorDirectRule.java | 156 +- .../rules/NonTouchingSharedDirectRule.java | 149 +- .../fillapix/rules/SatisfyClueCaseRule.java | 383 ++-- .../TooFewBlackCellsContradictionRule.java | 78 +- .../TooManyBlackCellsContradictionRule.java | 72 +- .../rules/TouchingCornersDirectRule.java | 165 +- .../rules/TouchingSidesDirectRule.java | 189 +- .../rpi/legup/puzzle/heyawake/Heyawake.java | 102 +- .../legup/puzzle/heyawake/HeyawakeBoard.java | 80 +- .../legup/puzzle/heyawake/HeyawakeCell.java | 32 +- .../puzzle/heyawake/HeyawakeElementView.java | 73 +- .../puzzle/heyawake/HeyawakeExporter.java | 52 +- .../puzzle/heyawake/HeyawakeFactory.java | 113 +- .../puzzle/heyawake/HeyawakeImporter.java | 170 +- .../legup/puzzle/heyawake/HeyawakeView.java | 69 +- .../AdjacentBlacksContradictionRule.java | 40 +- .../heyawake/rules/BlackOrWhiteCaseRule.java | 110 +- .../heyawake/rules/BlackPathDirectRule.java | 6 +- .../heyawake/rules/BottleNeckDirectRule.java | 6 +- .../rules/FillRoomBlackDirectRule.java | 63 +- .../rules/FillRoomWhiteDirectRule.java | 63 +- .../heyawake/rules/OneRowDirectRule.java | 6 +- .../rules/PreventWhiteLineDirectRule.java | 6 +- .../rules/RoomTooEmptyContradictionRule.java | 40 +- .../rules/RoomTooFullContradictionRule.java | 40 +- .../rules/ThreeByThreeDirectRule.java | 6 +- .../heyawake/rules/TwoInCornerDirectRule.java | 6 +- .../rules/WhiteAreaContradictionRule.java | 40 +- .../rules/WhiteAroundBlackDirectRule.java | 63 +- .../heyawake/rules/WhiteEscapeDirectRule.java | 6 +- .../rules/WhiteLineContradictionRule.java | 40 +- .../puzzle/heyawake/rules/ZigZagCaseRule.java | 6 +- .../heyawake/rules/ZigZagWhiteDirectRule.java | 6 +- .../edu/rpi/legup/puzzle/lightup/LightUp.java | 133 +- .../legup/puzzle/lightup/LightUpBoard.java | 292 ++- .../rpi/legup/puzzle/lightup/LightUpCell.java | 128 +- .../puzzle/lightup/LightUpCellController.java | 66 +- .../puzzle/lightup/LightUpCellFactory.java | 106 +- .../legup/puzzle/lightup/LightUpCellType.java | 18 +- .../puzzle/lightup/LightUpElementView.java | 145 +- .../legup/puzzle/lightup/LightUpExporter.java | 52 +- .../legup/puzzle/lightup/LightUpImporter.java | 192 +- .../rpi/legup/puzzle/lightup/LightUpView.java | 144 +- .../puzzle/lightup/elements/BlackTile.java | 11 +- .../puzzle/lightup/elements/BulbTile.java | 10 +- .../puzzle/lightup/elements/NumberTile.java | 32 +- .../puzzle/lightup/elements/UnknownTile.java | 14 +- .../rules/BulbsInPathContradictionRule.java | 122 +- .../CannotLightACellContradictionRule.java | 140 +- .../rules/EmptyCellinLightDirectRule.java | 99 +- .../lightup/rules/EmptyCornersDirectRule.java | 182 +- .../rules/FinishWithBulbsDirectRule.java | 170 +- .../rules/FinishWithEmptyDirectRule.java | 193 +- .../lightup/rules/LightOrEmptyCaseRule.java | 171 +- .../lightup/rules/MustLightDirectRule.java | 249 +- .../lightup/rules/SatisfyNumberCaseRule.java | 598 +++-- .../rules/TooFewBulbsContradictionRule.java | 58 +- .../rules/TooManyBulbsContradictionRule.java | 90 +- .../legup/puzzle/masyu/EditLineCommand.java | 271 ++- .../edu/rpi/legup/puzzle/masyu/Masyu.java | 102 +- .../rpi/legup/puzzle/masyu/MasyuBoard.java | 90 +- .../edu/rpi/legup/puzzle/masyu/MasyuCell.java | 28 +- .../legup/puzzle/masyu/MasyuCellFactory.java | 104 +- .../legup/puzzle/masyu/MasyuController.java | 154 +- .../legup/puzzle/masyu/MasyuElementView.java | 80 +- .../rpi/legup/puzzle/masyu/MasyuExporter.java | 47 +- .../rpi/legup/puzzle/masyu/MasyuImporter.java | 168 +- .../edu/rpi/legup/puzzle/masyu/MasyuLine.java | 72 +- .../rpi/legup/puzzle/masyu/MasyuLineView.java | 36 +- .../edu/rpi/legup/puzzle/masyu/MasyuType.java | 30 +- .../edu/rpi/legup/puzzle/masyu/MasyuView.java | 76 +- .../rules/BadLoopingContradictionRule.java | 40 +- .../masyu/rules/BlackContradictionRule.java | 32 +- .../masyu/rules/BlackEdgeDirectRule.java | 55 +- .../masyu/rules/BlackSplitCaseRule.java | 102 +- .../masyu/rules/BlockedBlackDirectRule.java | 59 +- .../masyu/rules/ConnectedCellsDirectRule.java | 63 +- .../masyu/rules/FinishPathDirectRule.java | 59 +- .../masyu/rules/NearWhiteDirectRule.java | 55 +- .../rules/NoOptionsContradictionRule.java | 40 +- .../masyu/rules/NormalSplitCaseRule.java | 106 +- .../masyu/rules/OnlyOneChoiceDirectRule.java | 63 +- .../masyu/rules/OnlyTwoContradictionRule.java | 36 +- .../masyu/rules/WhiteContradictionRule.java | 32 +- .../masyu/rules/WhiteEdgeDirectRule.java | 55 +- .../masyu/rules/WhiteSplitCaseRule.java | 102 +- .../rpi/legup/puzzle/nurikabe/Nurikabe.java | 126 +- .../legup/puzzle/nurikabe/NurikabeBoard.java | 84 +- .../legup/puzzle/nurikabe/NurikabeCell.java | 150 +- .../puzzle/nurikabe/NurikabeCellFactory.java | 107 +- .../puzzle/nurikabe/NurikabeController.java | 66 +- .../puzzle/nurikabe/NurikabeElementView.java | 103 +- .../puzzle/nurikabe/NurikabeExporter.java | 52 +- .../puzzle/nurikabe/NurikabeImporter.java | 192 +- .../legup/puzzle/nurikabe/NurikabeType.java | 14 +- .../puzzle/nurikabe/NurikabeUtilities.java | 522 +++-- .../legup/puzzle/nurikabe/NurikabeView.java | 23 +- .../puzzle/nurikabe/elements/BlackTile.java | 14 +- .../puzzle/nurikabe/elements/NumberTile.java | 42 +- .../puzzle/nurikabe/elements/UnknownTile.java | 14 +- .../puzzle/nurikabe/elements/WhiteTile.java | 14 +- .../rules/BlackBetweenRegionsDirectRule.java | 177 +- .../rules/BlackBottleNeckDirectRule.java | 90 +- .../nurikabe/rules/BlackOrWhiteCaseRule.java | 173 +- .../rules/BlackSquareContradictionRule.java | 88 +- .../rules/CannotReachCellDirectRule.java | 86 +- .../nurikabe/rules/CornerBlackDirectRule.java | 210 +- .../nurikabe/rules/FillinBlackDirectRule.java | 83 +- .../nurikabe/rules/FillinWhiteDirectRule.java | 83 +- .../rules/IsolateBlackContradictionRule.java | 82 +- .../MultipleNumbersContradictionRule.java | 67 +- .../rules/NoNumberContradictionRule.java | 101 +- .../rules/PreventBlackSquareDirectRule.java | 87 +- .../rules/SurroundRegionDirectRule.java | 139 +- .../rules/TooFewSpacesContradictionRule.java | 88 +- .../rules/TooManySpacesContradictionRule.java | 85 +- ...UnreachableWhiteCellContradictionRule.java | 159 +- .../rules/WhiteBottleNeckDirectRule.java | 93 +- .../shorttruthtable/ShortTruthTable.java | 186 +- .../shorttruthtable/ShortTruthTableBoard.java | 196 +- .../shorttruthtable/ShortTruthTableCell.java | 391 ++-- .../ShortTruthTableCellFactory.java | 95 +- .../ShortTruthTableCellType.java | 100 +- .../ShortTruthTableController.java | 42 +- .../ShortTruthTableElementView.java | 119 +- .../ShortTruthTableExporter.java | 67 +- .../ShortTruthTableImporter.java | 630 +++--- .../ShortTruthTableOperation.java | 74 +- .../ShortTruthTableStatement.java | 516 ++--- .../shorttruthtable/ShortTruthTableView.java | 25 +- .../elements/ArgumentElement.java | 14 +- .../elements/GreenElement.java | 14 +- .../elements/LogicSymbolElement.java | 14 +- .../shorttruthtable/elements/RedElement.java | 14 +- .../elements/UnknownElement.java | 14 +- .../rules/basic/DirectRuleAtomic.java | 18 +- .../rules/basic/DirectRule_Generic.java | 129 +- .../elimination/DirectRuleAndElimination.java | 6 +- .../DirectRuleBiconditionalElimination.java | 6 +- .../DirectRuleConditionalElimination.java | 6 +- .../elimination/DirectRuleNotElimination.java | 6 +- .../elimination/DirectRuleOrElimination.java | 6 +- .../DirectRule_GenericElimination.java | 20 +- .../DirectRuleAndIntroduction.java | 6 +- .../DirectRuleBiconditionalIntroduction.java | 6 +- .../DirectRuleConditionalIntroduction.java | 6 +- .../DirectRuleNotIntroduction.java | 6 +- .../DirectRuleOrIntroduction.java | 6 +- .../DirectRule_GenericIntroduction.java | 20 +- .../rules/caserule/CaseRuleAnd.java | 16 +- .../rules/caserule/CaseRuleAtomic.java | 92 +- .../rules/caserule/CaseRuleBiconditional.java | 32 +- .../rules/caserule/CaseRuleConditional.java | 30 +- .../rules/caserule/CaseRuleOr.java | 20 +- .../rules/caserule/CaseRule_Generic.java | 100 +- .../caserule/CaseRule_GenericStatement.java | 259 ++- .../contradiction/ContradictionRuleAnd.java | 28 +- .../ContradictionRuleAtomic.java | 84 +- .../ContradictionRuleBiconditional.java | 28 +- .../ContradictionRuleConditional.java | 26 +- .../contradiction/ContradictionRuleNot.java | 24 +- .../contradiction/ContradictionRuleOr.java | 26 +- .../ContradictionRule_GenericStatement.java | 131 +- .../legup/puzzle/skyscrapers/Skyscrapers.java | 128 +- .../puzzle/skyscrapers/SkyscrapersBoard.java | 448 ++-- .../puzzle/skyscrapers/SkyscrapersCell.java | 94 +- .../skyscrapers/SkyscrapersCellFactory.java | 106 +- .../puzzle/skyscrapers/SkyscrapersClue.java | 94 +- .../skyscrapers/SkyscrapersClueView.java | 96 +- .../skyscrapers/SkyscrapersController.java | 42 +- .../skyscrapers/SkyscrapersElementView.java | 51 +- .../skyscrapers/SkyscrapersExporter.java | 104 +- .../skyscrapers/SkyscrapersImporter.java | 390 ++-- .../puzzle/skyscrapers/SkyscrapersType.java | 62 +- .../puzzle/skyscrapers/SkyscrapersView.java | 333 ++- .../puzzle/skyscrapers/elements/ClueTile.java | 14 +- .../skyscrapers/elements/NumberTile.java | 14 +- .../skyscrapers/elements/UnknownTile.java | 14 +- .../rules/CellForNumberCaseRule.java | 343 ++- .../DuplicateNumberContradictionRule.java | 96 +- .../ExceedingVisibilityContradictionRule.java | 221 +- ...sufficientVisibilityContradictionRule.java | 223 +- .../rules/LastSingularCellDirectRule.java | 201 +- .../rules/LastSingularNumberDirectRule.java | 157 +- .../rules/LastVisibleCellDirectRule.java | 207 +- .../rules/LastVisibleNumberDirectRule.java | 159 +- .../skyscrapers/rules/NEdgeDirectRule.java | 162 +- .../rules/NumberForCellCaseRule.java | 298 ++- ...PreemptiveVisibilityContradictionRule.java | 346 ++- .../UnresolvedCellContradictionRule.java | 50 +- .../UnresolvedNumberContradictionRule.java | 160 +- .../rpi/legup/puzzle/sudoku/GroupType.java | 6 +- .../sudoku/PossibleNumberCaseBoard.java | 118 +- .../edu/rpi/legup/puzzle/sudoku/Sudoku.java | 178 +- .../rpi/legup/puzzle/sudoku/SudokuBoard.java | 306 +-- .../rpi/legup/puzzle/sudoku/SudokuCell.java | 106 +- .../puzzle/sudoku/SudokuCellController.java | 52 +- .../puzzle/sudoku/SudokuCellFactory.java | 106 +- .../puzzle/sudoku/SudokuElementView.java | 114 +- .../legup/puzzle/sudoku/SudokuExporter.java | 50 +- .../legup/puzzle/sudoku/SudokuImporter.java | 214 +- .../rpi/legup/puzzle/sudoku/SudokuView.java | 286 ++- .../puzzle/sudoku/elements/NumberTile.java | 34 +- .../rules/AdvancedDeductionDirectRule.java | 153 +- .../rules/LastCellForNumberDirectRule.java | 143 +- .../rules/LastNumberForCellDirectRule.java | 124 +- .../rules/NoSolutionContradictionRule.java | 90 +- .../sudoku/rules/PossibleCellCaseRule.java | 166 +- .../sudoku/rules/PossibleNumberCaseRule.java | 200 +- .../RepeatedNumberContradictionRule.java | 98 +- .../legup/puzzle/treetent/ClueCommand.java | 317 ++- .../puzzle/treetent/EditLineCommand.java | 378 ++-- .../rpi/legup/puzzle/treetent/TreeTent.java | 136 +- .../legup/puzzle/treetent/TreeTentBoard.java | 430 ++-- .../legup/puzzle/treetent/TreeTentCell.java | 80 +- .../puzzle/treetent/TreeTentCellFactory.java | 152 +- .../legup/puzzle/treetent/TreeTentClue.java | 98 +- .../puzzle/treetent/TreeTentClueView.java | 88 +- .../puzzle/treetent/TreeTentController.java | 199 +- .../puzzle/treetent/TreeTentElementView.java | 104 +- .../puzzle/treetent/TreeTentExporter.java | 114 +- .../puzzle/treetent/TreeTentImporter.java | 379 ++-- .../legup/puzzle/treetent/TreeTentLine.java | 72 +- .../puzzle/treetent/TreeTentLineView.java | 38 +- .../legup/puzzle/treetent/TreeTentType.java | 38 +- .../legup/puzzle/treetent/TreeTentView.java | 403 ++-- .../puzzle/treetent/elements/GrassTile.java | 14 +- .../puzzle/treetent/elements/TentTile.java | 10 +- .../puzzle/treetent/elements/TreeTile.java | 10 +- .../puzzle/treetent/elements/UnknownTile.java | 14 +- .../treetent/rules/EmptyFieldDirectRule.java | 135 +- .../treetent/rules/FillinRowCaseRule.java | 358 ++- .../rules/FinishWithGrassDirectRule.java | 125 +- .../rules/FinishWithTentsDirectRule.java | 130 +- .../rules/LastCampingSpotDirectRule.java | 155 +- .../treetent/rules/LinkTentCaseRule.java | 292 ++- .../treetent/rules/LinkTreeCaseRule.java | 307 ++- .../rules/NoTentForTreeContradictionRule.java | 98 +- .../rules/NoTreeForTentContradictionRule.java | 86 +- .../SurroundTentWithGrassDirectRule.java | 127 +- .../treetent/rules/TentForTreeDirectRule.java | 194 +- .../treetent/rules/TentOrGrassCaseRule.java | 172 +- .../rules/TooFewTentsContradictionRule.java | 62 +- .../rules/TooManyTentsContradictionRule.java | 58 +- .../rules/TouchingTentsContradictionRule.java | 60 +- .../treetent/rules/TreeForTentDirectRule.java | 194 +- .../rpi/legup/save/ExportFileException.java | 6 +- .../save/InvalidFileFormatException.java | 6 +- .../java/edu/rpi/legup/save/SavableBoard.java | 14 +- .../edu/rpi/legup/ui/CreatePuzzleDialog.java | 378 ++-- .../java/edu/rpi/legup/ui/DynamicView.java | 397 ++-- .../edu/rpi/legup/ui/DynamicViewType.java | 4 +- src/main/java/edu/rpi/legup/ui/HomePanel.java | 1218 +++++----- .../java/edu/rpi/legup/ui/LegupPanel.java | 6 +- src/main/java/edu/rpi/legup/ui/LegupUI.java | 372 ++- .../legup/ui/ManualPuzzleCreatorDialog.java | 2 +- .../java/edu/rpi/legup/ui/PickGameDialog.java | 260 +-- .../edu/rpi/legup/ui/PreferencesDialog.java | 803 ++++--- .../edu/rpi/legup/ui/ProofEditorPanel.java | 2002 ++++++++--------- .../edu/rpi/legup/ui/PuzzleEditorPanel.java | 988 ++++---- .../java/edu/rpi/legup/ui/ScrollView.java | 559 +++-- .../java/edu/rpi/legup/ui/ToolbarName.java | 48 +- .../java/edu/rpi/legup/ui/WrapLayout.java | 294 +-- .../java/edu/rpi/legup/ui/ZoomWidget.java | 78 +- .../java/edu/rpi/legup/ui/ZoomablePane.java | 56 +- .../edu/rpi/legup/ui/boardview/BoardView.java | 386 ++-- .../legup/ui/boardview/DataSelectionView.java | 8 +- .../legup/ui/boardview/ElementSelection.java | 104 +- .../rpi/legup/ui/boardview/ElementView.java | 661 +++--- .../rpi/legup/ui/boardview/GridBoardView.java | 134 +- .../legup/ui/boardview/GridElementView.java | 6 +- .../legup/ui/boardview/SelectionItemView.java | 38 +- .../ui/lookandfeel/LegupLookAndFeel.java | 664 +++--- .../animation/MaterialUIMovement.java | 14 +- .../animation/MaterialUITimer.java | 184 +- .../components/MaterialButtonUI.java | 50 +- .../MaterialCheckBoxMenuItemUI.java | 80 +- .../components/MaterialCheckBoxUI.java | 34 +- .../components/MaterialComboBoxRenderer.java | 29 +- .../components/MaterialComboBoxUI.java | 74 +- .../components/MaterialEditorPaneUI.java | 14 +- .../components/MaterialFileChooserUI.java | 88 +- .../components/MaterialLabelUI.java | 34 +- .../components/MaterialMenuBarUI.java | 32 +- .../components/MaterialMenuItemUI.java | 36 +- .../components/MaterialMenuUI.java | 34 +- .../components/MaterialPanelUI.java | 32 +- .../components/MaterialPasswordFieldUI.java | 343 ++- .../components/MaterialPopupMenuUI.java | 30 +- .../components/MaterialProgressBarUI.java | 30 +- .../MaterialRadioButtonMenuItemUI.java | 86 +- .../components/MaterialRadioButtonUI.java | 34 +- .../components/MaterialScrollBarUI.java | 72 +- .../components/MaterialSeparatorUI.java | 22 +- .../components/MaterialSliderUI.java | 236 +- .../components/MaterialSpinnerUI.java | 108 +- .../components/MaterialSplitPaneDivider.java | 32 +- .../components/MaterialSplitPaneUI.java | 36 +- .../components/MaterialTabbedPaneUI.java | 134 +- .../components/MaterialTableCellEditor.java | 35 +- .../components/MaterialTableCellRenderer.java | 25 +- .../MaterialTableHeaderCellRenderer.java | 27 +- .../components/MaterialTableHeaderUI.java | 26 +- .../components/MaterialTableUI.java | 60 +- .../components/MaterialTextFieldUI.java | 351 ++- .../components/MaterialTextPaneUI.java | 14 +- .../components/MaterialToggleButtonUI.java | 38 +- .../components/MaterialToolBarUI.java | 40 +- .../components/MaterialToolTipUI.java | 22 +- .../components/MaterialTreeCellEditor.java | 78 +- .../components/MaterialTreeCellRenderer.java | 66 +- .../components/MaterialTreeUI.java | 58 +- .../materialdesign/DropShadowBorder.java | 745 +++--- .../materialdesign/MaterialBorders.java | 18 +- .../materialdesign/MaterialColors.java | 528 ++--- .../materialdesign/MaterialDrawingUtils.java | 40 +- .../materialdesign/MaterialFonts.java | 89 +- .../materialdesign/MaterialImages.java | 70 +- .../rulesview/CaseRulePanel.java | 28 +- .../rulesview/CaseRuleSelectionView.java | 20 +- .../rulesview/ContradictionRulePanel.java | 28 +- .../rulesview/DirectRulePanel.java | 30 +- .../proofeditorui/rulesview/RuleButton.java | 58 +- .../ui/proofeditorui/rulesview/RuleFrame.java | 325 ++- .../ui/proofeditorui/rulesview/RulePanel.java | 633 +++--- .../rulesview/SearchBarPanel.java | 30 +- .../treeview/TreeElementView.java | 330 +-- .../proofeditorui/treeview/TreeNodeView.java | 578 +++-- .../ui/proofeditorui/treeview/TreePanel.java | 188 +- .../treeview/TreeToolBarButton.java | 24 +- .../treeview/TreeToolBarName.java | 8 +- .../treeview/TreeToolbarPanel.java | 100 +- .../treeview/TreeTransitionView.java | 650 +++--- .../ui/proofeditorui/treeview/TreeView.java | 1612 +++++++------ .../treeview/TreeViewSelection.java | 303 ++- .../elementsview/ElementButton.java | 54 +- .../elementsview/ElementFrame.java | 175 +- .../elementsview/ElementPanel.java | 113 +- .../NonPlaceableElementPanel.java | 18 +- .../elementsview/PlaceableElementPanel.java | 18 +- .../java/edu/rpi/legup/user/Submission.java | 4 +- .../edu/rpi/legup/user/UsageStatistics.java | 66 +- .../rpi/legup/utility/ConnectedRegions.java | 112 +- .../edu/rpi/legup/utility/DisjointSets.java | 286 +-- .../java/edu/rpi/legup/utility/Entry.java | 88 +- .../edu/rpi/legup/utility/LegupUtils.java | 148 +- .../java/edu/rpi/legup/utility/Logger.java | 56 +- src/test/java/legup/MockGameBoardFacade.java | 54 +- src/test/java/legup/TestRunner.java | 174 +- src/test/java/legup/TestUtilities.java | 18 +- .../AdjacentShipsContradictionRuleTest.java | 87 +- .../rules/FinishWithShipsDirectRuleTests.java | 95 +- .../BulbsInPathContradictionRuleTest.java | 128 +- ...CannotLightACellContradictionRuleTest.java | 134 +- .../rules/EmptyCellinLightDirectRuleTest.java | 172 +- .../rules/EmptyCornersDirectRuleTest.java | 96 +- .../rules/FinishWithBulbsDirectRuleTest.java | 141 +- .../rules/LightOrEmptyCaseRuleTest.java | 92 +- .../rules/MustLightDirectRuleTest.java | 79 +- .../rules/SatisfyNumberCaseRuleTest.java | 286 ++- .../TooFewBulbsContradictionRuleTest.java | 88 +- .../TooManyBulbsContradictionRuleTest.java | 88 +- .../BlackBetweenRegionsDirectRuleTest.java | 344 ++- .../rules/BlackBottleNeckDirectRuleTest.java | 160 +- .../rules/BlackOrWhiteCaseRuleTest.java | 83 +- .../BlackSquareContradictionRuleTest.java | 152 +- .../rules/CannotReachCellDirectRuleTest.java | 113 +- .../rules/CornerBlackDirectRuleTest.java | 98 +- .../rules/FillinBlackDirectRuleTest.java | 229 +- .../rules/FillinWhiteDirectRuleTest.java | 233 +- .../IsolateBlackContradictionRuleTest.java | 147 +- .../MultipleNumbersContradictionRuleTest.java | 157 +- .../rules/NoNumbersContradictionRuleTest.java | 113 +- .../PreventBlackSquareDirectRuleTest.java | 293 ++- .../rules/SurroundRegionDirectRuleTest.java | 166 +- .../TooFewSpacesContradictionRuleTest.java | 129 +- .../TooManySpacesContradictionRuleTest.java | 144 +- ...achableWhiteCellContradictionRuleTest.java | 104 +- .../rules/WhiteBottleNeckDirectRuleTest.java | 158 +- .../rules/AndCaseRuleTest.java | 272 +-- .../rules/AndEliminationDirectRuleTest.java | 361 ++- .../rules/AndIntroductionDirectRuleTest.java | 148 +- .../rules/AtomicDirectRuleTest.java | 304 +-- .../rules/BiconditionalEliminationTest.java | 719 +++--- .../rules/BiconditionalIntroductionTest.java | 164 +- .../rules/ConditionalEliminationTest.java | 422 ++-- .../rules/ConditionalIntroductionTest.java | 152 +- .../rules/NotEliminationTest.java | 204 +- .../rules/NotIntroductionTest.java | 222 +- .../shorttruthtable/rules/OrCaseRuleTest.java | 272 +-- .../rules/OrEliminationTest.java | 261 ++- .../rules/OrIntroductionTest.java | 148 +- .../rules/TrueOrFalseCaseRuleTest.java | 100 +- .../rules/CellForNumberCaseRuleTest.java | 338 ++- .../DuplicateNumberContradictionTest.java | 260 ++- .../ExceedingVisibilityContradictionTest.java | 226 +- ...sufficientVisibilityContradictionTest.java | 226 +- .../rules/LastSingularCellDirectTest.java | 392 ++-- .../rules/LastSingularNumberDirectTest.java | 234 +- .../rules/LastVisibleCellDirectTest.java | 434 ++-- .../rules/LastVisibleNumberDirectTest.java | 434 ++-- .../skyscrapers/rules/NEdgeDirectTest.java | 216 +- .../rules/NumberForCellCaseRuleTest.java | 302 ++- ...PreemptiveVisibilityContradictionTest.java | 258 ++- .../UnresolvedCellContradictionTest.java | 265 ++- .../UnresolvedNumberContradictionTest.java | 289 ++- .../rules/EmptyFieldDirectRuleTest.java | 492 ++-- .../rules/FinishWithGrassDirectRuleTest.java | 656 +++--- .../rules/FinishWithTentsDirectRuleTest.java | 614 +++-- .../rules/LastCampingSpotDirectRuleTest.java | 272 +-- .../NoTentForTreeContradictionRuleTest.java | 187 +- .../NoTreeForTentContradictionRuleTest.java | 397 ++-- .../SurroundTentWithGrassDirectRuleTest.java | 260 ++- .../rules/TentForTreeDirectRuleTest.java | 16 +- .../rules/TentOrGrassCaseRuleTest.java | 96 +- .../TooFewTentsContradictionRuleTest.java | 430 ++-- .../TooManyTentsContradictionRuleTest.java | 463 ++-- .../TouchingTentsContradictionRuleTest.java | 477 ++-- .../rules/TreeForTentDirectRuleTest.java | 14 +- 522 files changed, 40056 insertions(+), 40888 deletions(-) diff --git a/src/main/java/edu/rpi/legup/Legup.java b/src/main/java/edu/rpi/legup/Legup.java index 79471286b..0ea5b638a 100644 --- a/src/main/java/edu/rpi/legup/Legup.java +++ b/src/main/java/edu/rpi/legup/Legup.java @@ -5,14 +5,14 @@ public class Legup { - /** - * Starts the Legup Program - * - * @param args arguments to Legup - */ - public static void main(String[] args) { - Logger.initLogger(); - GameBoardFacade.getInstance(); - GameBoardFacade.setupConfig(); - } + /** + * Starts the Legup Program + * + * @param args arguments to Legup + */ + public static void main(String[] args) { + Logger.initLogger(); + GameBoardFacade.getInstance(); + GameBoardFacade.setupConfig(); + } } diff --git a/src/main/java/edu/rpi/legup/app/Config.java b/src/main/java/edu/rpi/legup/app/Config.java index 8a8e9665d..baaeb1dbd 100644 --- a/src/main/java/edu/rpi/legup/app/Config.java +++ b/src/main/java/edu/rpi/legup/app/Config.java @@ -13,140 +13,139 @@ import org.xml.sax.SAXException; public class Config { - private static final Logger Logger = LogManager.getLogger(Config.class.getName()); - - private Map puzzles; - private Map fileCreationDisabledStatuses; - private static final String CONFIG_LOCATION = "edu/rpi/legup/legup/config"; - - /** - * Config Constructor for logic puzzles - * - * @throws InvalidConfigException if configuration is invalid - */ - public Config() throws InvalidConfigException { - this.puzzles = new Hashtable<>(); - this.fileCreationDisabledStatuses = new Hashtable<>(); - loadConfig(this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION)); + private static final Logger Logger = LogManager.getLogger(Config.class.getName()); + + private Map puzzles; + private Map fileCreationDisabledStatuses; + private static final String CONFIG_LOCATION = "edu/rpi/legup/legup/config"; + + /** + * Config Constructor for logic puzzles + * + * @throws InvalidConfigException if configuration is invalid + */ + public Config() throws InvalidConfigException { + this.puzzles = new Hashtable<>(); + this.fileCreationDisabledStatuses = new Hashtable<>(); + loadConfig(this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION)); + } + + /** + * Gets a list of all available Puzzle names + * + * @return Vector of Puzzle names which are Strings + */ + public List getPuzzleClassNames() { + return new LinkedList<>(puzzles.keySet()); + } + + /** + * Returns a list of the names of the puzzles which can have puzzles created and edited within the + * proof editor. + * + * @return the aforementioned list of Strings + */ + public List getFileCreationEnabledPuzzles() { + LinkedList puzzles = new LinkedList(); + for (String puzzle : this.getPuzzleClassNames()) { + if (!this.fileCreationDisabledStatuses.get(puzzle)) { + puzzles.add(puzzle); + } } - - /** - * Gets a list of all available Puzzle names - * - * @return Vector of Puzzle names which are Strings - */ - public List getPuzzleClassNames() { - return new LinkedList<>(puzzles.keySet()); - } - - /** - * Returns a list of the names of the puzzles which can have puzzles created and edited within - * the proof editor. - * - * @return the aforementioned list of Strings - */ - public List getFileCreationEnabledPuzzles() { - LinkedList puzzles = new LinkedList(); - for (String puzzle : this.getPuzzleClassNames()) { - if (!this.fileCreationDisabledStatuses.get(puzzle)) { - puzzles.add(puzzle); - } - } - return puzzles; - } - - /** - * Converts the class name of the puzzles to their display names. Some examples of the - * conversion: convertClassNameToDisplayName("TreeTent") will return "Tree Tent" - * convertClassNameToDisplayName("Nurikabe") will return "Nurikabe" - * - * @param className the name of the class - * @return displayName the name of the puzzle - */ - public static String convertClassNameToDisplayName(String className) { - String displayName = ""; - for (int i = 0; i < className.length(); i++) { - if (Character.isUpperCase(className.charAt(i)) && i != 0) { - displayName += " "; - } - displayName += className.charAt(i); - } - return displayName; + return puzzles; + } + + /** + * Converts the class name of the puzzles to their display names. Some examples of the conversion: + * convertClassNameToDisplayName("TreeTent") will return "Tree Tent" + * convertClassNameToDisplayName("Nurikabe") will return "Nurikabe" + * + * @param className the name of the class + * @return displayName the name of the puzzle + */ + public static String convertClassNameToDisplayName(String className) { + String displayName = ""; + for (int i = 0; i < className.length(); i++) { + if (Character.isUpperCase(className.charAt(i)) && i != 0) { + displayName += " "; + } + displayName += className.charAt(i); } - - public static String convertDisplayNameToClassName(String displayName) { - String className = ""; - for (int i = 0; i < displayName.length(); i++) { - if (displayName.charAt(i) != ' ') { - className += displayName.charAt(i); - } - } - return className; + return displayName; + } + + public static String convertDisplayNameToClassName(String displayName) { + String className = ""; + for (int i = 0; i < displayName.length(); i++) { + if (displayName.charAt(i) != ' ') { + className += displayName.charAt(i); + } } + return className; + } - public List getPuzzleNames() { - List names = new LinkedList(); - for (String puzzle : this.getPuzzleClassNames()) { - names.add(Config.convertClassNameToDisplayName(puzzle)); - } - return names; + public List getPuzzleNames() { + List names = new LinkedList(); + for (String puzzle : this.getPuzzleClassNames()) { + names.add(Config.convertClassNameToDisplayName(puzzle)); } + return names; + } - public List getFileCreationEnabledPuzzleNames() { - List names = new LinkedList(); - for (String puzzle : this.getFileCreationEnabledPuzzles()) { - names.add(Config.convertClassNameToDisplayName(puzzle)); - } - return names; + public List getFileCreationEnabledPuzzleNames() { + List names = new LinkedList(); + for (String puzzle : this.getFileCreationEnabledPuzzles()) { + names.add(Config.convertClassNameToDisplayName(puzzle)); } - - /** - * Gets a {@link edu.rpi.legup.model.Puzzle} class for a puzzle name - * - * @param puzzleName puzzle name of the class - * @return class name for the puzzle name - */ - public String getPuzzleClassForName(String puzzleName) { - if (puzzles.containsKey(puzzleName)) { - return puzzles.get(puzzleName); - } - return null; + return names; + } + + /** + * Gets a {@link edu.rpi.legup.model.Puzzle} class for a puzzle name + * + * @param puzzleName puzzle name of the class + * @return class name for the puzzle name + */ + public String getPuzzleClassForName(String puzzleName) { + if (puzzles.containsKey(puzzleName)) { + return puzzles.get(puzzleName); } - - /** - * Loads the config object from the config xml file - * - * @param stream file stream for the config xml file - */ - private void loadConfig(InputStream stream) throws InvalidConfigException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.parse(stream); - Element configNode = document.getDocumentElement(); - - if (!configNode.getNodeName().equalsIgnoreCase("Legup")) { - throw new InvalidConfigException("Config is not formatted correctly"); - } - - Element puzzleList = (Element) configNode.getElementsByTagName("puzzles").item(0); - Logger.debug(puzzleList); - NodeList puzzleNodes = puzzleList.getElementsByTagName("puzzle"); - - for (int i = 0; i < puzzleNodes.getLength(); i++) { - Element puzzle = (Element) puzzleNodes.item(i); - String name = puzzle.getAttribute("name"); - String className = puzzle.getAttribute("qualifiedClassName"); - boolean status = - Boolean.parseBoolean( - puzzle.getAttribute("fileCreationDisabled").toLowerCase()); - Logger.debug("Class Name: " + className); - this.puzzles.put(name, className); - this.fileCreationDisabledStatuses.put(name, Boolean.valueOf(status)); - } - - } catch (ParserConfigurationException | SAXException | IOException e) { - throw new InvalidConfigException(e.getMessage()); - } + return null; + } + + /** + * Loads the config object from the config xml file + * + * @param stream file stream for the config xml file + */ + private void loadConfig(InputStream stream) throws InvalidConfigException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(stream); + Element configNode = document.getDocumentElement(); + + if (!configNode.getNodeName().equalsIgnoreCase("Legup")) { + throw new InvalidConfigException("Config is not formatted correctly"); + } + + Element puzzleList = (Element) configNode.getElementsByTagName("puzzles").item(0); + Logger.debug(puzzleList); + NodeList puzzleNodes = puzzleList.getElementsByTagName("puzzle"); + + for (int i = 0; i < puzzleNodes.getLength(); i++) { + Element puzzle = (Element) puzzleNodes.item(i); + String name = puzzle.getAttribute("name"); + String className = puzzle.getAttribute("qualifiedClassName"); + boolean status = + Boolean.parseBoolean(puzzle.getAttribute("fileCreationDisabled").toLowerCase()); + Logger.debug("Class Name: " + className); + this.puzzles.put(name, className); + this.fileCreationDisabledStatuses.put(name, Boolean.valueOf(status)); + } + + } catch (ParserConfigurationException | SAXException | IOException e) { + throw new InvalidConfigException(e.getMessage()); } + } } diff --git a/src/main/java/edu/rpi/legup/app/GameBoardFacade.java b/src/main/java/edu/rpi/legup/app/GameBoardFacade.java index c928c1209..8babbbfa3 100644 --- a/src/main/java/edu/rpi/legup/app/GameBoardFacade.java +++ b/src/main/java/edu/rpi/legup/app/GameBoardFacade.java @@ -32,495 +32,491 @@ import org.xml.sax.SAXException; public class GameBoardFacade implements IHistorySubject { - private static final Logger LOGGER = LogManager.getLogger(GameBoardFacade.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(GameBoardFacade.class.getName()); - protected static volatile GameBoardFacade instance; + protected static volatile GameBoardFacade instance; - private Config config; + private Config config; - protected Puzzle puzzle; + protected Puzzle puzzle; - private LegupUI legupUI; + private LegupUI legupUI; - private ProofEditorPanel puzzleSolver; + private ProofEditorPanel puzzleSolver; - private PuzzleEditorPanel puzzleEditor; + private PuzzleEditorPanel puzzleEditor; - private String curFileName; + private String curFileName; - private History history; - private List historyListeners; + private History history; + private List historyListeners; - /** Private GameBoardFacade Constructor creates a game board facade */ - protected GameBoardFacade() { - history = new History(); - historyListeners = new ArrayList<>(); - curFileName = null; - LegupPreferences.getInstance(); - initializeUI(); - } + /** Private GameBoardFacade Constructor creates a game board facade */ + protected GameBoardFacade() { + history = new History(); + historyListeners = new ArrayList<>(); + curFileName = null; + LegupPreferences.getInstance(); + initializeUI(); + } - /** - * Gets the singleton instance of GameBoardFacade - * - * @return single instance of GameBoardFacade - */ - public static synchronized GameBoardFacade getInstance() { - if (instance == null) { - instance = new GameBoardFacade(); - } - return instance; + /** + * Gets the singleton instance of GameBoardFacade + * + * @return single instance of GameBoardFacade + */ + public static synchronized GameBoardFacade getInstance() { + if (instance == null) { + instance = new GameBoardFacade(); } - - public void initializeUI() { - EventQueue.invokeLater( - () -> { - legupUI = new LegupUI(); - puzzleSolver = legupUI.getProofEditor(); - puzzleEditor = legupUI.getPuzzleEditor(); - addHistoryListener(legupUI.getProofEditor()); - addHistoryListener(legupUI.getPuzzleEditor()); - }); + return instance; + } + + public void initializeUI() { + EventQueue.invokeLater( + () -> { + legupUI = new LegupUI(); + puzzleSolver = legupUI.getProofEditor(); + puzzleEditor = legupUI.getPuzzleEditor(); + addHistoryListener(legupUI.getProofEditor()); + addHistoryListener(legupUI.getPuzzleEditor()); + }); + } + + public void setPuzzle(Puzzle puzzle) { + this.puzzle = puzzle; + this.puzzleSolver.setPuzzleView(puzzle); + this.history.clear(); + } + + public void clearPuzzle() { + this.puzzle = null; + this.curFileName = null; + this.history.clear(); + } + + public static void setupConfig() { + Config config = null; + try { + config = new Config(); + } catch (InvalidConfigException e) { + System.exit(1); } - - public void setPuzzle(Puzzle puzzle) { - this.puzzle = puzzle; - this.puzzleSolver.setPuzzleView(puzzle); - this.history.clear(); + GameBoardFacade.getInstance().setConfig(config); + } + + public void setPuzzleEditor(Puzzle puzzle) { + this.puzzle = puzzle; + this.puzzleEditor.setPuzzleView(puzzle); + } + + public void setConfig(Config config) { + this.config = config; + } + + /** + * Validates the given dimensions for the given puzzle + * + * @param game name of the puzzle + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @return true if it is possible to create a board for the given game with the given number of + * rows and columns, false otherwise + * @throws RuntimeException if any of the given input is invalid + */ + public boolean validateDimensions(String game, int rows, int columns) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + try { + Class c = Class.forName(qualifiedClassName); + Constructor constructor = c.getConstructor(); + Puzzle puzzle = (Puzzle) constructor.newInstance(); + return puzzle.isValidDimensions(rows, columns); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Error validating puzzle dimensions"); } - - public void clearPuzzle() { - this.puzzle = null; - this.curFileName = null; - this.history.clear(); + } + + /** + * Validates the given text input for the given puzzle + * + * @param game the name of the puzzle + * @param statements an array of statements + * @return true if it is possible to create a board for the given game with the given statements, + * false otherwise + * @throws RuntimeException if any of the input is invalid + */ + public boolean validateTextInput(String game, String[] statements) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + try { + Class c = Class.forName(qualifiedClassName); + Constructor constructor = c.getConstructor(); + Puzzle puzzle = (Puzzle) constructor.newInstance(); + return puzzle.isValidTextInput(statements); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Error validating puzzle text input"); } - - public static void setupConfig() { - Config config = null; - try { - config = new Config(); - } catch (InvalidConfigException e) { - System.exit(1); - } - GameBoardFacade.getInstance().setConfig(config); + } + + /** + * Loads an empty puzzle + * + * @param game name of the puzzle + * @param rows the number of rows on the board + * @param columns the number of columns on the board + */ + public void loadPuzzle(String game, int rows, int columns) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + LOGGER.debug("Loading " + qualifiedClassName); + + try { + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new RuntimeException("Puzzle importer null"); + } + + // Theoretically, this exception should never be thrown, since LEGUP should not be + // allowing the user to give row/column input for a puzzle that doesn't support it + if (!importer.acceptsRowsAndColumnsInput()) { + throw new IllegalArgumentException( + puzzle.getName() + " does not accept rows and columns input"); + } + + setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); + importer.initializePuzzle(rows, columns); + + puzzle.initializeView(); + // + // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Puzzle creation error"); } - - public void setPuzzleEditor(Puzzle puzzle) { - this.puzzle = puzzle; - this.puzzleEditor.setPuzzleView(puzzle); + } + + public void loadPuzzle(String game, String[] statements) { + String qualifiedClassName = config.getPuzzleClassForName(game); + LOGGER.debug("Loading " + qualifiedClassName); + + try { + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new RuntimeException("Puzzle importer null"); + } + + // Theoretically, this exception should never be thrown, since LEGUP should not be + // allowing the user to give text input for a puzzle that doesn't support it + if (!importer.acceptsTextInput()) { + throw new IllegalArgumentException(puzzle.getName() + " does not accept text input"); + } + + setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); + importer.initializePuzzle(statements); + + puzzle.initializeView(); + // + // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Puzzle creation error"); } - - public void setConfig(Config config) { - this.config = config; + } + + /** + * Loads a puzzle file + * + * @param fileName file name of the board file + * @throws InvalidFileFormatException if input is invalid + */ + public void loadPuzzle(String fileName) throws InvalidFileFormatException { + try { + loadPuzzle(new FileInputStream(fileName)); + curFileName = fileName; + setWindowTitle(puzzle.getName(), fileName); + } catch (IOException e) { + LOGGER.error("Invalid file " + fileName, e); + throw new InvalidFileFormatException("Could not find file"); } - - /** - * Validates the given dimensions for the given puzzle - * - * @param game name of the puzzle - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @return true if it is possible to create a board for the given game with the given number of - * rows and columns, false otherwise - * @throws RuntimeException if any of the given input is invalid - */ - public boolean validateDimensions(String game, int rows, int columns) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - try { - Class c = Class.forName(qualifiedClassName); - Constructor constructor = c.getConstructor(); - Puzzle puzzle = (Puzzle) constructor.newInstance(); - return puzzle.isValidDimensions(rows, columns); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Error validating puzzle dimensions"); - } + } + + public void loadPuzzleEditor(String fileName) throws InvalidFileFormatException { + try { + loadPuzzleEditor(new FileInputStream(fileName)); + curFileName = fileName; + setWindowTitle(puzzle.getName(), fileName); + } catch (IOException e) { + LOGGER.error("Invalid file " + fileName, e); + throw new InvalidFileFormatException("Could not find file"); } - - /** - * Validates the given text input for the given puzzle - * - * @param game the name of the puzzle - * @param statements an array of statements - * @return true if it is possible to create a board for the given game with the given - * statements, false otherwise - * @throws RuntimeException if any of the input is invalid - */ - public boolean validateTextInput(String game, String[] statements) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - try { - Class c = Class.forName(qualifiedClassName); - Constructor constructor = c.getConstructor(); - Puzzle puzzle = (Puzzle) constructor.newInstance(); - return puzzle.isValidTextInput(statements); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Error validating puzzle text input"); - } + } + + public void loadPuzzleEditor(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Invalid file", e); + throw new InvalidFileFormatException("Could not find file"); } - /** - * Loads an empty puzzle - * - * @param game name of the puzzle - * @param rows the number of rows on the board - * @param columns the number of columns on the board - */ - public void loadPuzzle(String game, int rows, int columns) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - LOGGER.debug("Loading " + qualifiedClassName); - - try { - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new RuntimeException("Puzzle importer null"); - } - - // Theoretically, this exception should never be thrown, since LEGUP should not be - // allowing the user to give row/column input for a puzzle that doesn't support it - if (!importer.acceptsRowsAndColumnsInput()) { - throw new IllegalArgumentException( - puzzle.getName() + " does not accept rows and columns input"); - } - - setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); - importer.initializePuzzle(rows, columns); - - puzzle.initializeView(); - // - // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Puzzle creation error"); + Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + try { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + String qualifiedClassName = + config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); + if (qualifiedClassName == null) { + throw new InvalidFileFormatException( + "Puzzle creation error: cannot find puzzle with that name"); } - } - - public void loadPuzzle(String game, String[] statements) { - String qualifiedClassName = config.getPuzzleClassForName(game); + // Check if puzzle is a "FileCreationEnabled" puzzle (meaning it is editable). + String[] editablePuzzles = config.getFileCreationEnabledPuzzles().toArray(new String[0]); + boolean isEditablePuzzle = false; + for (int i = 0; i < editablePuzzles.length; i++) { + if (qualifiedClassName.contains(editablePuzzles[i])) { + isEditablePuzzle = true; + break; + } + } + if (!isEditablePuzzle) { + LOGGER.error("Puzzle is not editable"); + throw new InvalidFileFormatException("Puzzle is not editable"); + } + // If it is editable, start loading it LOGGER.debug("Loading " + qualifiedClassName); - try { - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new RuntimeException("Puzzle importer null"); - } - - // Theoretically, this exception should never be thrown, since LEGUP should not be - // allowing the user to give text input for a puzzle that doesn't support it - if (!importer.acceptsTextInput()) { - throw new IllegalArgumentException( - puzzle.getName() + " does not accept text input"); - } - - setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); - importer.initializePuzzle(statements); - - puzzle.initializeView(); - // - // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Puzzle creation error"); - } - } + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); - /** - * Loads a puzzle file - * - * @param fileName file name of the board file - * @throws InvalidFileFormatException if input is invalid - */ - public void loadPuzzle(String fileName) throws InvalidFileFormatException { - try { - loadPuzzle(new FileInputStream(fileName)); - curFileName = fileName; - setWindowTitle(puzzle.getName(), fileName); - } catch (IOException e) { - LOGGER.error("Invalid file " + fileName, e); - throw new InvalidFileFormatException("Could not find file"); + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new InvalidFileFormatException("Puzzle importer null"); } + importer.initializePuzzle(node); + puzzle.initializeView(); + puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new InvalidFileFormatException("Puzzle creation error"); + } + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - - public void loadPuzzleEditor(String fileName) throws InvalidFileFormatException { - try { - loadPuzzleEditor(new FileInputStream(fileName)); - curFileName = fileName; - setWindowTitle(puzzle.getName(), fileName); - } catch (IOException e) { - LOGGER.error("Invalid file " + fileName, e); - throw new InvalidFileFormatException("Could not find file"); - } + } + + /** + * Loads a puzzle file from the input stream + * + * @throws InvalidFileFormatException if input is invalid + * @param inputStream input stream for the puzzle file + */ + public void loadPuzzle(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Invalid file", e); + throw new InvalidFileFormatException("Could not find file"); } - public void loadPuzzleEditor(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Invalid file", e); - throw new InvalidFileFormatException("Could not find file"); - } - - Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - try { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - String qualifiedClassName = - config.getPuzzleClassForName( - node.getAttributes().getNamedItem("name").getNodeValue()); - if (qualifiedClassName == null) { - throw new InvalidFileFormatException( - "Puzzle creation error: cannot find puzzle with that name"); - } - // Check if puzzle is a "FileCreationEnabled" puzzle (meaning it is editable). - String[] editablePuzzles = - config.getFileCreationEnabledPuzzles().toArray(new String[0]); - boolean isEditablePuzzle = false; - for (int i = 0; i < editablePuzzles.length; i++) { - if (qualifiedClassName.contains(editablePuzzles[i])) { - isEditablePuzzle = true; - break; - } - } - if (!isEditablePuzzle) { - LOGGER.error("Puzzle is not editable"); - throw new InvalidFileFormatException("Puzzle is not editable"); - } - // If it is editable, start loading it - LOGGER.debug("Loading " + qualifiedClassName); - - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new InvalidFileFormatException("Puzzle importer null"); - } - importer.initializePuzzle(node); - puzzle.initializeView(); - puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new InvalidFileFormatException("Puzzle creation error"); - } - } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); + Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + try { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + String qualifiedClassName = + config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); + if (qualifiedClassName == null) { + throw new InvalidFileFormatException( + "Puzzle creation error: cannot find puzzle with that name"); } - } + LOGGER.debug("Loading " + qualifiedClassName); - /** - * Loads a puzzle file from the input stream - * - * @throws InvalidFileFormatException if input is invalid - * @param inputStream input stream for the puzzle file - */ - public void loadPuzzle(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Invalid file", e); - throw new InvalidFileFormatException("Could not find file"); - } + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); - Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - try { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - String qualifiedClassName = - config.getPuzzleClassForName( - node.getAttributes().getNamedItem("name").getNodeValue()); - if (qualifiedClassName == null) { - throw new InvalidFileFormatException( - "Puzzle creation error: cannot find puzzle with that name"); - } - LOGGER.debug("Loading " + qualifiedClassName); - - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new InvalidFileFormatException("Puzzle importer null"); - } - importer.initializePuzzle(node); - puzzle.initializeView(); - puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzle(puzzle); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new InvalidFileFormatException("Puzzle creation error"); - } - } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new InvalidFileFormatException("Puzzle importer null"); } + importer.initializePuzzle(node); + puzzle.initializeView(); + puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzle(puzzle); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new InvalidFileFormatException("Puzzle creation error"); + } + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - - /** - * Sets the window title to 'PuzzleName - FileName' Removes the extension - * - * @param puzzleName puzzle name for the file - * @param fileName file name of the edu.rpi.legup.puzzle - */ - public void setWindowTitle(String puzzleName, String fileName) { - File file = new File(fileName); - legupUI.setTitle(puzzleName + " - " + file.getName()); - } - - /** - * Gets the Config info - * - * @return Config object - */ - public Config getConfig() { - return config; - } - - /** - * Gets the LegupUI - * - * @return LegupUI - */ - public LegupUI getLegupUI() { - return legupUI; - } - - /** - * Gets the initial board state - * - * @return the initial board state - */ - public Board getBoard() { - return puzzle == null ? null : puzzle.getCurrentBoard(); - } - - /** - * Sets the initial board state and the tree - * - * @param board initial board - */ - public void setBoard(Board board) { - puzzle.setCurrentBoard(board); - } - - /** - * Gets the rules tree - * - * @return rules tree - */ - public Tree getTree() { - return puzzle == null ? null : puzzle.getTree(); - } - - /** - * Gets the Puzzle for the board - * - * @return the Puzzle for the board - */ - public Puzzle getPuzzleModule() { - return puzzle; - } - - /** - * Sets the Puzzle for the board - * - * @param puzzle the PuzzleModule for the board - */ - public void setPuzzleModule(Puzzle puzzle) { - this.puzzle = puzzle; - } - - public String getCurFileName() { - return this.curFileName; - } - - /** - * Adds a {@link IHistoryListener} - * - * @param listener listener to add - */ - @Override - public void addHistoryListener(IHistoryListener listener) { - historyListeners.add(listener); - } - - /** - * Adds a {@link IHistoryListener} - * - * @param listener listener to remove - */ - @Override - public void removeHistoryListener(IHistoryListener listener) { - historyListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyHistoryListeners(Consumer algorithm) { - historyListeners.forEach(algorithm); - } - - /** - * Gets the History object for storing changes to the board states - * - * @return History object - */ - public History getHistory() { - return history; - } + } + + /** + * Sets the window title to 'PuzzleName - FileName' Removes the extension + * + * @param puzzleName puzzle name for the file + * @param fileName file name of the edu.rpi.legup.puzzle + */ + public void setWindowTitle(String puzzleName, String fileName) { + File file = new File(fileName); + legupUI.setTitle(puzzleName + " - " + file.getName()); + } + + /** + * Gets the Config info + * + * @return Config object + */ + public Config getConfig() { + return config; + } + + /** + * Gets the LegupUI + * + * @return LegupUI + */ + public LegupUI getLegupUI() { + return legupUI; + } + + /** + * Gets the initial board state + * + * @return the initial board state + */ + public Board getBoard() { + return puzzle == null ? null : puzzle.getCurrentBoard(); + } + + /** + * Sets the initial board state and the tree + * + * @param board initial board + */ + public void setBoard(Board board) { + puzzle.setCurrentBoard(board); + } + + /** + * Gets the rules tree + * + * @return rules tree + */ + public Tree getTree() { + return puzzle == null ? null : puzzle.getTree(); + } + + /** + * Gets the Puzzle for the board + * + * @return the Puzzle for the board + */ + public Puzzle getPuzzleModule() { + return puzzle; + } + + /** + * Sets the Puzzle for the board + * + * @param puzzle the PuzzleModule for the board + */ + public void setPuzzleModule(Puzzle puzzle) { + this.puzzle = puzzle; + } + + public String getCurFileName() { + return this.curFileName; + } + + /** + * Adds a {@link IHistoryListener} + * + * @param listener listener to add + */ + @Override + public void addHistoryListener(IHistoryListener listener) { + historyListeners.add(listener); + } + + /** + * Adds a {@link IHistoryListener} + * + * @param listener listener to remove + */ + @Override + public void removeHistoryListener(IHistoryListener listener) { + historyListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyHistoryListeners(Consumer algorithm) { + historyListeners.forEach(algorithm); + } + + /** + * Gets the History object for storing changes to the board states + * + * @return History object + */ + public History getHistory() { + return history; + } } diff --git a/src/main/java/edu/rpi/legup/app/InvalidConfigException.java b/src/main/java/edu/rpi/legup/app/InvalidConfigException.java index a570e7d44..03120dffe 100644 --- a/src/main/java/edu/rpi/legup/app/InvalidConfigException.java +++ b/src/main/java/edu/rpi/legup/app/InvalidConfigException.java @@ -1,7 +1,7 @@ package edu.rpi.legup.app; public class InvalidConfigException extends Exception { - public InvalidConfigException(String message) { - super(message); - } + public InvalidConfigException(String message) { + super(message); + } } diff --git a/src/main/java/edu/rpi/legup/app/LegupPreferences.java b/src/main/java/edu/rpi/legup/app/LegupPreferences.java index 12433d7e4..eb5ea5981 100644 --- a/src/main/java/edu/rpi/legup/app/LegupPreferences.java +++ b/src/main/java/edu/rpi/legup/app/LegupPreferences.java @@ -6,125 +6,120 @@ public class LegupPreferences { - private static LegupPreferences instance; - - private static String SAVED_PATH = ""; - - private static final Preferences preferences = - Preferences.userNodeForPackage(LegupPreferences.class); - - private static final Map preferencesMap = new HashMap<>(); - private static final Map defaultPreferencesMap = new HashMap<>(); - - public static final String WORK_DIRECTORY = "work-directory"; - public static final String START_FULL_SCREEN = "start-full-screen"; - public static final String AUTO_UPDATE = "auto-update"; - public static final String DARK_MODE = "night-mode"; - public static final String SHOW_MISTAKES = "show-mistakes"; - public static final String SHOW_ANNOTATIONS = "show-annotations"; - public static final String ALLOW_DEFAULT_RULES = "allow-default-rules"; - public static final String AUTO_GENERATE_CASES = "auto-generate-cases"; - public static final String IMMEDIATE_FEEDBACK = "immediate-feedback"; - public static final String COLOR_BLIND = "color-blind"; - - static { - defaultPreferencesMap.put(WORK_DIRECTORY, System.getProperty("user.home")); - defaultPreferencesMap.put(START_FULL_SCREEN, Boolean.toString(false)); - defaultPreferencesMap.put(AUTO_UPDATE, Boolean.toString(true)); - defaultPreferencesMap.put(DARK_MODE, Boolean.toString(false)); - defaultPreferencesMap.put(SHOW_MISTAKES, Boolean.toString(true)); - defaultPreferencesMap.put(SHOW_ANNOTATIONS, Boolean.toString(false)); - defaultPreferencesMap.put(ALLOW_DEFAULT_RULES, Boolean.toString(false)); - defaultPreferencesMap.put(AUTO_GENERATE_CASES, Boolean.toString(true)); - defaultPreferencesMap.put(IMMEDIATE_FEEDBACK, Boolean.toString(true)); - defaultPreferencesMap.put(COLOR_BLIND, Boolean.toString(false)); + private static LegupPreferences instance; + + private static String SAVED_PATH = ""; + + private static final Preferences preferences = + Preferences.userNodeForPackage(LegupPreferences.class); + + private static final Map preferencesMap = new HashMap<>(); + private static final Map defaultPreferencesMap = new HashMap<>(); + + public static final String WORK_DIRECTORY = "work-directory"; + public static final String START_FULL_SCREEN = "start-full-screen"; + public static final String AUTO_UPDATE = "auto-update"; + public static final String DARK_MODE = "night-mode"; + public static final String SHOW_MISTAKES = "show-mistakes"; + public static final String SHOW_ANNOTATIONS = "show-annotations"; + public static final String ALLOW_DEFAULT_RULES = "allow-default-rules"; + public static final String AUTO_GENERATE_CASES = "auto-generate-cases"; + public static final String IMMEDIATE_FEEDBACK = "immediate-feedback"; + public static final String COLOR_BLIND = "color-blind"; + + static { + defaultPreferencesMap.put(WORK_DIRECTORY, System.getProperty("user.home")); + defaultPreferencesMap.put(START_FULL_SCREEN, Boolean.toString(false)); + defaultPreferencesMap.put(AUTO_UPDATE, Boolean.toString(true)); + defaultPreferencesMap.put(DARK_MODE, Boolean.toString(false)); + defaultPreferencesMap.put(SHOW_MISTAKES, Boolean.toString(true)); + defaultPreferencesMap.put(SHOW_ANNOTATIONS, Boolean.toString(false)); + defaultPreferencesMap.put(ALLOW_DEFAULT_RULES, Boolean.toString(false)); + defaultPreferencesMap.put(AUTO_GENERATE_CASES, Boolean.toString(true)); + defaultPreferencesMap.put(IMMEDIATE_FEEDBACK, Boolean.toString(true)); + defaultPreferencesMap.put(COLOR_BLIND, Boolean.toString(false)); + } + + static { + preferencesMap.put( + WORK_DIRECTORY, preferences.get(WORK_DIRECTORY, defaultPreferencesMap.get(WORK_DIRECTORY))); + preferencesMap.put( + START_FULL_SCREEN, + preferences.get(START_FULL_SCREEN, defaultPreferencesMap.get(START_FULL_SCREEN))); + preferencesMap.put( + AUTO_UPDATE, preferences.get(AUTO_UPDATE, defaultPreferencesMap.get(AUTO_UPDATE))); + preferencesMap.put(DARK_MODE, preferences.get(DARK_MODE, defaultPreferencesMap.get(DARK_MODE))); + preferencesMap.put( + SHOW_MISTAKES, preferences.get(SHOW_MISTAKES, defaultPreferencesMap.get(SHOW_MISTAKES))); + preferencesMap.put( + SHOW_ANNOTATIONS, + preferences.get(SHOW_ANNOTATIONS, defaultPreferencesMap.get(SHOW_ANNOTATIONS))); + preferencesMap.put( + ALLOW_DEFAULT_RULES, + preferences.get(ALLOW_DEFAULT_RULES, defaultPreferencesMap.get(ALLOW_DEFAULT_RULES))); + preferencesMap.put( + AUTO_GENERATE_CASES, + preferences.get(AUTO_GENERATE_CASES, defaultPreferencesMap.get(AUTO_GENERATE_CASES))); + preferencesMap.put( + IMMEDIATE_FEEDBACK, + preferences.get(IMMEDIATE_FEEDBACK, defaultPreferencesMap.get(IMMEDIATE_FEEDBACK))); + preferencesMap.put( + COLOR_BLIND, preferences.get(COLOR_BLIND, defaultPreferencesMap.get(COLOR_BLIND))); + } + + /** + * Gets the legup preferences singleton instance. + * + * @return legup preferences + */ + public static LegupPreferences getInstance() { + if (instance == null) { + instance = new LegupPreferences(); } - - static { - preferencesMap.put( - WORK_DIRECTORY, - preferences.get(WORK_DIRECTORY, defaultPreferencesMap.get(WORK_DIRECTORY))); - preferencesMap.put( - START_FULL_SCREEN, - preferences.get(START_FULL_SCREEN, defaultPreferencesMap.get(START_FULL_SCREEN))); - preferencesMap.put( - AUTO_UPDATE, preferences.get(AUTO_UPDATE, defaultPreferencesMap.get(AUTO_UPDATE))); - preferencesMap.put( - DARK_MODE, preferences.get(DARK_MODE, defaultPreferencesMap.get(DARK_MODE))); - preferencesMap.put( - SHOW_MISTAKES, - preferences.get(SHOW_MISTAKES, defaultPreferencesMap.get(SHOW_MISTAKES))); - preferencesMap.put( - SHOW_ANNOTATIONS, - preferences.get(SHOW_ANNOTATIONS, defaultPreferencesMap.get(SHOW_ANNOTATIONS))); - preferencesMap.put( - ALLOW_DEFAULT_RULES, - preferences.get( - ALLOW_DEFAULT_RULES, defaultPreferencesMap.get(ALLOW_DEFAULT_RULES))); - preferencesMap.put( - AUTO_GENERATE_CASES, - preferences.get( - AUTO_GENERATE_CASES, defaultPreferencesMap.get(AUTO_GENERATE_CASES))); - preferencesMap.put( - IMMEDIATE_FEEDBACK, - preferences.get(IMMEDIATE_FEEDBACK, defaultPreferencesMap.get(IMMEDIATE_FEEDBACK))); - preferencesMap.put( - COLOR_BLIND, preferences.get(COLOR_BLIND, defaultPreferencesMap.get(COLOR_BLIND))); - } - - /** - * Gets the legup preferences singleton instance. - * - * @return legup preferences - */ - public static LegupPreferences getInstance() { - if (instance == null) { - instance = new LegupPreferences(); - } - return instance; + return instance; + } + + /** Private LegupPreferences Singleton Constructor */ + private LegupPreferences() {} + + /** + * Gets the user preference by the string key + * + * @param key key name of the preference + * @return value of the preference + */ + public String getUserPref(String key) { + return preferencesMap.get(key); + } + + /** + * Gets the user preference by the string key, value pair + * + * @param key key name of the preference + * @param value value of the preference + */ + public void setUserPref(String key, String value) { + preferences.put(key, value); + preferencesMap.put(key, value); + } + + public boolean getUserPrefAsBool(String key) { + if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(true))) { + return true; + } else { + if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(false))) { + return false; + } else { + throw new RuntimeException("Cannot get user preference - " + key); + } } + } - /** Private LegupPreferences Singleton Constructor */ - private LegupPreferences() {} - - /** - * Gets the user preference by the string key - * - * @param key key name of the preference - * @return value of the preference - */ - public String getUserPref(String key) { - return preferencesMap.get(key); - } - - /** - * Gets the user preference by the string key, value pair - * - * @param key key name of the preference - * @param value value of the preference - */ - public void setUserPref(String key, String value) { - preferences.put(key, value); - preferencesMap.put(key, value); - } + public String getSavedPath() { + return SAVED_PATH; + } - public boolean getUserPrefAsBool(String key) { - if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(true))) { - return true; - } else { - if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(false))) { - return false; - } else { - throw new RuntimeException("Cannot get user preference - " + key); - } - } - } - - public String getSavedPath() { - return SAVED_PATH; - } - - public void setSavedPath(String path) { - SAVED_PATH = path; - } + public void setSavedPath(String path) { + SAVED_PATH = path; + } } diff --git a/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java b/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java index f3945be22..4a055ab3a 100644 --- a/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java +++ b/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java @@ -19,87 +19,85 @@ public class PuzzleKeyAccelerator implements KeyListener { - private Map keyStrokeMap; + private Map keyStrokeMap; - public PuzzleKeyAccelerator() { - this.keyStrokeMap = new HashMap<>(); - } + public PuzzleKeyAccelerator() { + this.keyStrokeMap = new HashMap<>(); + } - public void addKeyAccelerator(KeyStroke keyStroke, Rule rule) { - keyStrokeMap.put(keyStroke, rule); - } + public void addKeyAccelerator(KeyStroke keyStroke, Rule rule) { + keyStrokeMap.put(keyStroke, rule); + } - public Map getKeyStrokeMap() { - return this.keyStrokeMap; - } + public Map getKeyStrokeMap() { + return this.keyStrokeMap; + } - public void clearKeyMap() { - this.keyStrokeMap.clear(); - } + public void clearKeyMap() { + this.keyStrokeMap.clear(); + } - /** - * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a - * definition of a key typed event. - * - * @param e the event to be processed - */ - @Override - public void keyTyped(KeyEvent e) {} + /** + * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a + * definition of a key typed event. + * + * @param e the event to be processed + */ + @Override + public void keyTyped(KeyEvent e) {} - /** - * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a - * definition of a key pressed event. - * - * @param e the event to be processed - */ - @Override - public void keyPressed(KeyEvent e) { - KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); - Rule rule = keyStrokeMap.get(keyStroke); - if (rule != null) { - TreeView treeView = - GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + /** + * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a + * definition of a key pressed event. + * + * @param e the event to be processed + */ + @Override + public void keyPressed(KeyEvent e) { + KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); + Rule rule = keyStrokeMap.get(keyStroke); + if (rule != null) { + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - String update = ""; - if (rule.getRuleType() == RuleType.CASE) { - // TODO: review this line of code and figure out what it's supposed to do (remove if - // necessary) - // handleCaseRule((CaseRule)rule); - } else { - if (rule.getRuleType() == RuleType.CONTRADICTION) { - TreeViewSelection selection = treeView.getSelection(); + String update = ""; + if (rule.getRuleType() == RuleType.CASE) { + // TODO: review this line of code and figure out what it's supposed to do (remove if + // necessary) + // handleCaseRule((CaseRule)rule); + } else { + if (rule.getRuleType() == RuleType.CONTRADICTION) { + TreeViewSelection selection = treeView.getSelection(); - ICommand validate = - new ValidateContradictionRuleCommand( - selection, (ContradictionRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - update = validate.getError(); - } - } else { - TreeViewSelection selection = treeView.getSelection(); + ICommand validate = + new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + update = validate.getError(); + } + } else { + TreeViewSelection selection = treeView.getSelection(); - ICommand validate = new ValidateDirectRuleCommand(selection, (DirectRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - update = validate.getError(); - } - } - } - GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(update); + ICommand validate = new ValidateDirectRuleCommand(selection, (DirectRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + update = validate.getError(); + } } + } + GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(update); } + } - /** - * Invoked when a key has been released. See the class description for {@link KeyEvent} for a - * definition of a key released event. - * - * @param e the event to be processed - */ - @Override - public void keyReleased(KeyEvent e) {} + /** + * Invoked when a key has been released. See the class description for {@link KeyEvent} for a + * definition of a key released event. + * + * @param e the event to be processed + */ + @Override + public void keyReleased(KeyEvent e) {} } diff --git a/src/main/java/edu/rpi/legup/controller/BoardController.java b/src/main/java/edu/rpi/legup/controller/BoardController.java index eaae3851d..f672961d2 100644 --- a/src/main/java/edu/rpi/legup/controller/BoardController.java +++ b/src/main/java/edu/rpi/legup/controller/BoardController.java @@ -4,88 +4,88 @@ import java.awt.event.*; public class BoardController extends Controller { - protected Point lastLeftMousePoint; - protected Point lastRightMousePoint; + protected Point lastLeftMousePoint; + protected Point lastRightMousePoint; - /** - * BoardController Constructor creates a controller object to listen to ui events from a - * ScrollView - */ - public BoardController() { - super(); - lastLeftMousePoint = null; - lastRightMousePoint = null; - } + /** + * BoardController Constructor creates a controller object to listen to ui events from a + * ScrollView + */ + public BoardController() { + super(); + lastLeftMousePoint = null; + lastRightMousePoint = null; + } - /** - * Mouse Clicked event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event - sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); - } + /** + * Mouse Pressed event - sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); + } - /** - * Mouse Released event - sets the cursor back to the default cursor and reset info for panning - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - } + /** + * Mouse Released event - sets the cursor back to the default cursor and reset info for panning + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + } - /** - * Mouse Entered event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) {} + /** + * Mouse Entered event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) {} - /** - * Mouse Exited event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) {} + /** + * Mouse Exited event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) {} - /** - * Mouse Dragged event - adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - super.mouseDragged(e); - } + /** + * Mouse Dragged event - adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + super.mouseDragged(e); + } - /** - * Mouse Moved event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) {} + /** + * Mouse Moved event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) {} - /** - * Mouse Wheel Moved event - zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - super.mouseWheelMoved(e); - } + /** + * Mouse Wheel Moved event - zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + super.mouseWheelMoved(e); + } } diff --git a/src/main/java/edu/rpi/legup/controller/Controller.java b/src/main/java/edu/rpi/legup/controller/Controller.java index 57ce107ac..cd281fc21 100644 --- a/src/main/java/edu/rpi/legup/controller/Controller.java +++ b/src/main/java/edu/rpi/legup/controller/Controller.java @@ -6,116 +6,116 @@ import javax.swing.*; public abstract class Controller implements MouseMotionListener, MouseListener, MouseWheelListener { - protected ScrollView viewer; - private int x, y; - private boolean pan; + protected ScrollView viewer; + private int x, y; + private boolean pan; - /** - * Controller Constructor creates a controller object to listen to ui events from a {@link - * ScrollView} - */ - public Controller() { - x = y = -1; - pan = false; - } + /** + * Controller Constructor creates a controller object to listen to ui events from a {@link + * ScrollView} + */ + public Controller() { + x = y = -1; + pan = false; + } - public void setViewer(ScrollView viewer) { - this.viewer = viewer; - } + public void setViewer(ScrollView viewer) { + this.viewer = viewer; + } - /** - * Mouse Clicked event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON2) { - pan = true; - x = e.getX(); - y = e.getY(); - viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); - } + /** + * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON2) { + pan = true; + x = e.getX(); + y = e.getY(); + viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } + } - /** - * Mouse Released event sets the cursor back to the default cursor and reset info for panning - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON2) { - pan = false; - viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } + /** + * Mouse Released event sets the cursor back to the default cursor and reset info for panning + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON2) { + pan = false; + viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } + } - /** - * Mouse Entered event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) {} + /** + * Mouse Entered event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) {} - /** - * Mouse Exited event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) {} + /** + * Mouse Exited event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) {} - /** - * Mouse Dragged event adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - if (pan) { - JViewport viewport = viewer.getViewport(); - Point position = viewer.getViewport().getViewPosition(); - position.x += (x - e.getX()); - position.y += (y - e.getY()); - viewport.setViewPosition(position); - viewer.revalidate(); - } + /** + * Mouse Dragged event adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + if (pan) { + JViewport viewport = viewer.getViewport(); + Point position = viewer.getViewport().getViewPosition(); + position.x += (x - e.getX()); + position.y += (y - e.getY()); + viewport.setViewPosition(position); + viewer.revalidate(); } + } - /** - * Mouse Moved event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) {} + /** + * Mouse Moved event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) {} - /** - * Mouse Wheel Moved event zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - // System.out.println(e.getWheelRotation()); - if (e.isControlDown()) { - if (e.getWheelRotation() != 0) { - viewer.zoom(e.getWheelRotation() * 2, e.getPoint()); - } - } else { - if (e.getWheelRotation() != 0) { - viewer.zoom(e.getWheelRotation(), e.getPoint()); - } - } + /** + * Mouse Wheel Moved event zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + // System.out.println(e.getWheelRotation()); + if (e.isControlDown()) { + if (e.getWheelRotation() != 0) { + viewer.zoom(e.getWheelRotation() * 2, e.getPoint()); + } + } else { + if (e.getWheelRotation() != 0) { + viewer.zoom(e.getWheelRotation(), e.getPoint()); + } } + } } diff --git a/src/main/java/edu/rpi/legup/controller/CursorController.java b/src/main/java/edu/rpi/legup/controller/CursorController.java index 2706bd522..a97f147b8 100644 --- a/src/main/java/edu/rpi/legup/controller/CursorController.java +++ b/src/main/java/edu/rpi/legup/controller/CursorController.java @@ -7,48 +7,48 @@ import java.util.TimerTask; public class CursorController { - public static final Cursor BUSY_CURSOR = new Cursor(Cursor.WAIT_CURSOR); - public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); - public static final int DELAY = 200; // in milliseconds + public static final Cursor BUSY_CURSOR = new Cursor(Cursor.WAIT_CURSOR); + public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); + public static final int DELAY = 200; // in milliseconds - private CursorController() { - // Intentionally left empty - } + private CursorController() { + // Intentionally left empty + } - /** - * Creates an ActionListener that will still do the same action processing as the given - * ActionListener while also displaying a loading cursor if the time it takes to execute the - * given process exceeds the time (in milliseconds) specified in this.DELAY - * - *

Sources consulted: http://www.catalysoft.com/articles/busycursor.html - * - * @param component The component you want to set the cursor for - * @param mainActionListener The ActionListener that does the intended action processing - * @return An ActionListener object that does the same action processing as mainActionListener - * while also modifying the cursor if needed - */ - public static ActionListener createListener( - final Component component, final ActionListener mainActionListener) { - ActionListener actionListener = - e -> { - TimerTask timerTask = - new TimerTask() { - @Override - public void run() { - component.setCursor(BUSY_CURSOR); - } - }; + /** + * Creates an ActionListener that will still do the same action processing as the given + * ActionListener while also displaying a loading cursor if the time it takes to execute the given + * process exceeds the time (in milliseconds) specified in this.DELAY + * + *

Sources consulted: http://www.catalysoft.com/articles/busycursor.html + * + * @param component The component you want to set the cursor for + * @param mainActionListener The ActionListener that does the intended action processing + * @return An ActionListener object that does the same action processing as mainActionListener + * while also modifying the cursor if needed + */ + public static ActionListener createListener( + final Component component, final ActionListener mainActionListener) { + ActionListener actionListener = + e -> { + TimerTask timerTask = + new TimerTask() { + @Override + public void run() { + component.setCursor(BUSY_CURSOR); + } + }; - Timer timer = new Timer(); - try { - timer.schedule(timerTask, DELAY); - mainActionListener.actionPerformed(e); - } finally { - timer.cancel(); - component.setCursor(DEFAULT_CURSOR); - } - }; + Timer timer = new Timer(); + try { + timer.schedule(timerTask, DELAY); + mainActionListener.actionPerformed(e); + } finally { + timer.cancel(); + component.setCursor(DEFAULT_CURSOR); + } + }; - return actionListener; - } + return actionListener; + } } diff --git a/src/main/java/edu/rpi/legup/controller/EditorElementController.java b/src/main/java/edu/rpi/legup/controller/EditorElementController.java index 5a23885af..7aa1fe06c 100644 --- a/src/main/java/edu/rpi/legup/controller/EditorElementController.java +++ b/src/main/java/edu/rpi/legup/controller/EditorElementController.java @@ -10,43 +10,43 @@ import javax.swing.*; public class EditorElementController implements ActionListener { - protected Object lastSource; - protected ElementController elementController; - protected ElementButton prevButton; - - public EditorElementController() { - super(); - elementController = null; - prevButton = null; + protected Object lastSource; + protected ElementController elementController; + protected ElementButton prevButton; + + public EditorElementController() { + super(); + elementController = null; + prevButton = null; + } + + public void setElementController(ElementController elementController) { + this.elementController = elementController; + } + + public void buttonPressed(Element element) { + // TODO: implement what happens when element is pressed + + System.out.printf("%s button pressed!\n", element.getElementName()); + if (elementController != null) { + elementController.setSelectedElement(element); } + } - public void setElementController(ElementController elementController) { - this.elementController = elementController; - } - - public void buttonPressed(Element element) { - // TODO: implement what happens when element is pressed + @Override + public void actionPerformed(ActionEvent e) { + lastSource = e.getSource(); + ElementButton button = (ElementButton) lastSource; + buttonPressed(button.getElement()); - System.out.printf("%s button pressed!\n", element.getElementName()); - if (elementController != null) { - elementController.setSelectedElement(element); - } + // reset border in previous selected button + if (this.prevButton != null) { + this.prevButton.resetBorder(); } - @Override - public void actionPerformed(ActionEvent e) { - lastSource = e.getSource(); - ElementButton button = (ElementButton) lastSource; - buttonPressed(button.getElement()); - - // reset border in previous selected button - if (this.prevButton != null) { - this.prevButton.resetBorder(); - } + // change border color when select a button + button.setBorderToSelected(); - // change border color when select a button - button.setBorderToSelected(); - - this.prevButton = button; - } + this.prevButton = button; + } } diff --git a/src/main/java/edu/rpi/legup/controller/ElementController.java b/src/main/java/edu/rpi/legup/controller/ElementController.java index 5840650e1..6b6707c32 100644 --- a/src/main/java/edu/rpi/legup/controller/ElementController.java +++ b/src/main/java/edu/rpi/legup/controller/ElementController.java @@ -27,325 +27,324 @@ import java.awt.event.*; public class ElementController - implements MouseListener, MouseMotionListener, ActionListener, KeyListener { - protected BoardView boardView; - private Element selectedElement; + implements MouseListener, MouseMotionListener, ActionListener, KeyListener { + protected BoardView boardView; + private Element selectedElement; - /** - * ElementController Constructor controller to handles ui events associated interacting with a - * {@link BoardView} - */ - public ElementController() { - this.boardView = null; - this.selectedElement = null; - } + /** + * ElementController Constructor controller to handles ui events associated interacting with a + * {@link BoardView} + */ + public ElementController() { + this.boardView = null; + this.selectedElement = null; + } - public void setSelectedElement(Element selectedElement) { - this.selectedElement = selectedElement; - } + public void setSelectedElement(Element selectedElement) { + this.selectedElement = selectedElement; + } - /** - * Sets the {@link BoardView} - * - * @param boardView board view - */ - public void setBoardView(BoardView boardView) { - this.boardView = boardView; - } + /** + * Sets the {@link BoardView} + * + * @param boardView board view + */ + public void setBoardView(BoardView boardView) { + this.boardView = boardView; + } - /** - * Invoked when the mouse button has been clicked (pressed and released) on a component. - * - * @param e the event to be processed - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Invoked when the mouse button has been clicked (pressed and released) on a component. + * + * @param e the event to be processed + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e the event to be processed - */ - @Override - public void mousePressed(MouseEvent e) {} + /** + * Invoked when a mouse button has been pressed on a component. + * + * @param e the event to be processed + */ + @Override + public void mousePressed(MouseEvent e) {} - /** - * Invoked when a mouse button has been released on a component. - * - * @param e the event to be processed - */ - @Override - public void mouseReleased(MouseEvent e) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = null; - if (treePanel != null) { - treeView = treePanel.getTreeView(); - } + /** + * Invoked when a mouse button has been released on a component. + * + * @param e the event to be processed + */ + @Override + public void mouseReleased(MouseEvent e) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = null; + if (treePanel != null) { + treeView = treePanel.getTreeView(); + } - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - ElementView elementView = boardView.getElement(e.getPoint()); - TreeViewSelection selection = null; - if (treeView != null) { - selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + Board board = boardView.getBoard(); + ElementView elementView = boardView.getElement(e.getPoint()); + TreeViewSelection selection = null; + if (treeView != null) { + selection = treeView.getSelection(); + } + // funny + if (elementView != null) { + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + AutoCaseRuleCommand autoCaseRuleCommand = + new AutoCaseRuleCommand(elementView, selection, caseBoard.getCaseRule(), caseBoard, e); + if (autoCaseRuleCommand.canExecute()) { + autoCaseRuleCommand.execute(); + getInstance().getHistory().pushChange(autoCaseRuleCommand); + if (treePanel != null) { + treePanel.updateError(""); + } + } else { + if (treePanel != null) { + treePanel.updateError(autoCaseRuleCommand.getError()); + } } - // funny - if (elementView != null) { - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - AutoCaseRuleCommand autoCaseRuleCommand = - new AutoCaseRuleCommand( - elementView, selection, caseBoard.getCaseRule(), caseBoard, e); - if (autoCaseRuleCommand.canExecute()) { - autoCaseRuleCommand.execute(); - getInstance().getHistory().pushChange(autoCaseRuleCommand); - if (treePanel != null) { - treePanel.updateError(""); - } - } else { - if (treePanel != null) { - treePanel.updateError(autoCaseRuleCommand.getError()); - } - } - } else { - if (selection != null) { - ICommand edit = new EditDataCommand(elementView, selection, e); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - if (treePanel != null) { - treePanel.updateError(""); - } - } else { - if (treePanel != null) { - treePanel.updateError(edit.getError()); - } - } - } + } else { + if (selection != null) { + ICommand edit = new EditDataCommand(elementView, selection, e); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + if (treePanel != null) { + treePanel.updateError(""); } + } else { + if (treePanel != null) { + treePanel.updateError(edit.getError()); + } + } } - // if (selectedElement != null) { - GridBoard b = (GridBoard) this.boardView.getBoard(); - Point point = e.getPoint(); - Point scaledPoint = - new Point( - (int) Math.floor(point.x / (30 * this.boardView.getScale())), - (int) Math.floor(point.y / (30 * this.boardView.getScale()))); - if (this.boardView.getBoard() instanceof TreeTentBoard) { - scaledPoint.setLocation(scaledPoint.getX() - 1, scaledPoint.getY() - 1); - } - System.out.printf( - "selected Element is NOT null, attempting to change board at (%d, %d)\n", - scaledPoint.x, scaledPoint.y); - // System.out.println("Before: " + b.getCell(scaledPoint.x, - // scaledPoint.y).getData()); - b.setCell(scaledPoint.x, scaledPoint.y, this.selectedElement, e); - // System.out.println("After: " + b.getCell(scaledPoint.x, - // scaledPoint.y).getData()); - // } else { - // System.out.println("selected Element is null!"); - // } - boardView.repaint(); + } + } + // if (selectedElement != null) { + GridBoard b = (GridBoard) this.boardView.getBoard(); + Point point = e.getPoint(); + Point scaledPoint = + new Point( + (int) Math.floor(point.x / (30 * this.boardView.getScale())), + (int) Math.floor(point.y / (30 * this.boardView.getScale()))); + if (this.boardView.getBoard() instanceof TreeTentBoard) { + scaledPoint.setLocation(scaledPoint.getX() - 1, scaledPoint.getY() - 1); } + System.out.printf( + "selected Element is NOT null, attempting to change board at (%d, %d)\n", + scaledPoint.x, scaledPoint.y); + // System.out.println("Before: " + b.getCell(scaledPoint.x, + // scaledPoint.y).getData()); + b.setCell(scaledPoint.x, scaledPoint.y, this.selectedElement, e); + // System.out.println("After: " + b.getCell(scaledPoint.x, + // scaledPoint.y).getData()); + // } else { + // System.out.println("selected Element is null!"); + // } + boardView.repaint(); + } - /** - * Invoked when the mouse enters a component. - * - * @param e the event to be processed - */ - @Override - public void mouseEntered(MouseEvent e) { - boardView.setFocusable(true); - boardView.requestFocusInWindow(); - TreeElement treeElement = boardView.getTreeElement(); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + /** + * Invoked when the mouse enters a component. + * + * @param e the event to be processed + */ + @Override + public void mouseEntered(MouseEvent e) { + boardView.setFocusable(true); + boardView.requestFocusInWindow(); + TreeElement treeElement = boardView.getTreeElement(); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + Board board = boardView.getBoard(); + ElementView elementView = boardView.getElement(e.getPoint()); + ElementSelection selection = boardView.getSelection(); + String error = null; + if (elementView != null) { + selection.newHover(elementView); + if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { + PuzzleElement element = elementView.getPuzzleElement(); + if (treeElement != null + && treeElement.getType() == TreeElementType.TRANSITION + && board.getModifiedData().contains(element)) { + TreeTransition transition = (TreeTransition) treeElement; + if (transition.isJustified() && !transition.isCorrect()) { + error = transition.getRule().checkRuleAt(transition, element); + } } - Board board = boardView.getBoard(); - ElementView elementView = boardView.getElement(e.getPoint()); - ElementSelection selection = boardView.getSelection(); - String error = null; - if (elementView != null) { - selection.newHover(elementView); - if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { - PuzzleElement element = elementView.getPuzzleElement(); - if (treeElement != null - && treeElement.getType() == TreeElementType.TRANSITION - && board.getModifiedData().contains(element)) { - TreeTransition transition = (TreeTransition) treeElement; - if (transition.isJustified() && !transition.isCorrect()) { - error = transition.getRule().checkRuleAt(transition, element); - } - } - if (error != null) { - dynamicView.updateError(error); - } else { - dynamicView.resetStatus(); - } - } - boardView.repaint(); + if (error != null) { + dynamicView.updateError(error); + } else { + dynamicView.resetStatus(); } + } + boardView.repaint(); } + } - /** - * Invoked when the mouse exits a component. - * - * @param e the event to be processed - */ - @Override - public void mouseExited(MouseEvent e) { - boardView.setFocusable(false); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); - } - ElementView element = boardView.getElement(e.getPoint()); - if (element != null) { - boardView.getSelection().clearHover(); - dynamicView.resetStatus(); - boardView.repaint(); - } + /** + * Invoked when the mouse exits a component. + * + * @param e the event to be processed + */ + @Override + public void mouseExited(MouseEvent e) { + boardView.setFocusable(false); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + ElementView element = boardView.getElement(e.getPoint()); + if (element != null) { + boardView.getSelection().clearHover(); + dynamicView.resetStatus(); + boardView.repaint(); } + } - /** - * Invoked when the mouse dragged - * - * @param e the event to be processed - */ - @Override - public void mouseDragged(MouseEvent e) {} + /** + * Invoked when the mouse dragged + * + * @param e the event to be processed + */ + @Override + public void mouseDragged(MouseEvent e) {} - /** - * Invoked when the mouse moved - * - * @param e the event to be processed - */ - @Override - public void mouseMoved(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - TreeElement treeElement = boardView.getTreeElement(); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + /** + * Invoked when the mouse moved + * + * @param e the event to be processed + */ + @Override + public void mouseMoved(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + Board board = boardView.getBoard(); + TreeElement treeElement = boardView.getTreeElement(); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + ElementView elementView = boardView.getElement(e.getPoint()); + ElementSelection selection = boardView.getSelection(); + String error = null; + if (elementView != null && elementView != selection.getHover()) { + selection.newHover(elementView); + if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { + PuzzleElement element = elementView.getPuzzleElement(); + if (treeElement != null + && treeElement.getType() == TreeElementType.TRANSITION + && board.getModifiedData().contains(element)) { + TreeTransition transition = (TreeTransition) treeElement; + if (transition.isJustified() && !transition.isCorrect()) { + error = transition.getRule().checkRuleAt(transition, element); + } } - ElementView elementView = boardView.getElement(e.getPoint()); - ElementSelection selection = boardView.getSelection(); - String error = null; - if (elementView != null && elementView != selection.getHover()) { - selection.newHover(elementView); - if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { - PuzzleElement element = elementView.getPuzzleElement(); - if (treeElement != null - && treeElement.getType() == TreeElementType.TRANSITION - && board.getModifiedData().contains(element)) { - TreeTransition transition = (TreeTransition) treeElement; - if (transition.isJustified() && !transition.isCorrect()) { - error = transition.getRule().checkRuleAt(transition, element); - } - } - if (error != null) { - dynamicView.updateError(error); - } else { - dynamicView.resetStatus(); - } - } - boardView.repaint(); + if (error != null) { + dynamicView.updateError(error); + } else { + dynamicView.resetStatus(); } + } + boardView.repaint(); } + } - public void changeCell(MouseEvent e, PuzzleElement data) {} + public void changeCell(MouseEvent e, PuzzleElement data) {} - /** - * Invoked when an action occurs. - * - * @param e the event to be processed - */ - @SuppressWarnings("Unchecked") - @Override - public void actionPerformed(ActionEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - ElementView selectedElement = boardView.getSelection().getFirstSelection(); - PuzzleElement puzzleElement = selectedElement.getPuzzleElement(); + /** + * Invoked when an action occurs. + * + * @param e the event to be processed + */ + @SuppressWarnings("Unchecked") + @Override + public void actionPerformed(ActionEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + ElementView selectedElement = boardView.getSelection().getFirstSelection(); + PuzzleElement puzzleElement = selectedElement.getPuzzleElement(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeTransitionView transitionView = (TreeTransitionView) selectedView; + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeTransitionView transitionView = (TreeTransitionView) selectedView; - Board prevBord = transitionView.getTreeElement().getParents().get(0).getBoard(); + Board prevBord = transitionView.getTreeElement().getParents().get(0).getBoard(); - int value = (Integer) ((SelectionItemView) e.getSource()).getData().getData(); + int value = (Integer) ((SelectionItemView) e.getSource()).getData().getData(); - puzzleElement.setData(value); + puzzleElement.setData(value); - if (puzzleElement.equalsData(prevBord.getPuzzleElement(puzzleElement))) { - puzzleElement.setModified(false); - } else { - puzzleElement.setModified(true); - } + if (puzzleElement.equalsData(prevBord.getPuzzleElement(puzzleElement))) { + puzzleElement.setModified(false); + } else { + puzzleElement.setModified(true); + } - transitionView.getTreeElement().propagateChange(puzzleElement); + transitionView.getTreeElement().propagateChange(puzzleElement); - boardView.repaint(); - boardView.getSelection().clearSelection(); - } + boardView.repaint(); + boardView.getSelection().clearSelection(); + } - /** - * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a - * definition of a key typed event. - * - * @param e the event to be processed - */ - @Override - public void keyTyped(KeyEvent e) {} + /** + * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a + * definition of a key typed event. + * + * @param e the event to be processed + */ + @Override + public void keyTyped(KeyEvent e) {} - /** - * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a - * definition of a key pressed event. - * - * @param e the event to be processed - */ - @Override - public void keyPressed(KeyEvent e) {} + /** + * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a + * definition of a key pressed event. + * + * @param e the event to be processed + */ + @Override + public void keyPressed(KeyEvent e) {} - /** - * Invoked when a key has been released. See the class description for {@link KeyEvent} for a - * definition of a key released event. - * - * @param e the event to be processed - */ - @Override - public void keyReleased(KeyEvent e) { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { - puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); - } - } + /** + * Invoked when a key has been released. See the class description for {@link KeyEvent} for a + * definition of a key released event. + * + * @param e the event to be processed + */ + @Override + public void keyReleased(KeyEvent e) { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + Board board = boardView.getBoard(); + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); + } } + } } diff --git a/src/main/java/edu/rpi/legup/controller/RuleController.java b/src/main/java/edu/rpi/legup/controller/RuleController.java index 6e88dc4be..f72dddbde 100644 --- a/src/main/java/edu/rpi/legup/controller/RuleController.java +++ b/src/main/java/edu/rpi/legup/controller/RuleController.java @@ -17,105 +17,102 @@ import java.util.List; public class RuleController implements ActionListener { - protected Object lastSource; + protected Object lastSource; - /** - * RuleController Constructor creates a controller object to listen to ui events from a {@link - * RulePanel} - */ - public RuleController() { - super(); - } + /** + * RuleController Constructor creates a controller object to listen to ui events from a {@link + * RulePanel} + */ + public RuleController() { + super(); + } - /** - * Button Pressed event occurs a when a rule button has been pressed - * - * @param rule rule of the button that was pressed - */ - public void buttonPressed(Rule rule) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = treePanel.getTreeView(); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - List selectedViews = selection.getSelectedViews(); + /** + * Button Pressed event occurs a when a rule button has been pressed + * + * @param rule rule of the button that was pressed + */ + public void buttonPressed(Rule rule) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = treePanel.getTreeView(); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + List selectedViews = selection.getSelectedViews(); - String updateErrorString = ""; - if (rule.getRuleType() == RuleType.CASE) { - CaseRule caseRule = (CaseRule) rule; - if (selectedViews.size() == 1) { - TreeElementView elementView = selection.getFirstSelection(); - TreeElement element = elementView.getTreeElement(); - if (element.getType() == TreeElementType.TRANSITION) { - ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); - if (caseRuleCommand.canExecute()) { - caseRuleCommand.execute(); - getInstance().getHistory().pushChange(caseRuleCommand); - } else { - updateErrorString = caseRuleCommand.getError(); - } - } else { - if (LegupPreferences.getInstance() - .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) - .equalsIgnoreCase(Boolean.toString(true))) { - CaseBoard caseBoard = caseRule.getCaseBoard(element.getBoard()); - if (caseBoard != null && caseBoard.getCount() > 0) { - puzzle.notifyBoardListeners( - listener -> listener.onCaseBoardAdded(caseBoard)); - } else { - updateErrorString = "This board cannot be applied with this case rule."; - } - } else { - updateErrorString = - "Auto generated case rules are turned off in preferences."; - } - } - } else { - ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); - if (caseRuleCommand.canExecute()) { - caseRuleCommand.execute(); - getInstance().getHistory().pushChange(caseRuleCommand); - } else { - updateErrorString = caseRuleCommand.getError(); - } - } + String updateErrorString = ""; + if (rule.getRuleType() == RuleType.CASE) { + CaseRule caseRule = (CaseRule) rule; + if (selectedViews.size() == 1) { + TreeElementView elementView = selection.getFirstSelection(); + TreeElement element = elementView.getTreeElement(); + if (element.getType() == TreeElementType.TRANSITION) { + ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); + if (caseRuleCommand.canExecute()) { + caseRuleCommand.execute(); + getInstance().getHistory().pushChange(caseRuleCommand); + } else { + updateErrorString = caseRuleCommand.getError(); + } } else { - if (rule.getRuleType() == RuleType.CONTRADICTION) { - ICommand validate = - new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - updateErrorString = validate.getError(); - } + if (LegupPreferences.getInstance() + .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) + .equalsIgnoreCase(Boolean.toString(true))) { + CaseBoard caseBoard = caseRule.getCaseBoard(element.getBoard()); + if (caseBoard != null && caseBoard.getCount() > 0) { + puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); } else { - boolean def = - LegupPreferences.getInstance() - .getUserPrefAsBool(LegupPreferences.ALLOW_DEFAULT_RULES); - ICommand validate = - def - ? new ApplyDefaultDirectRuleCommand(selection, (DirectRule) rule) - : new ValidateDirectRuleCommand(selection, (DirectRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - updateErrorString = validate.getError(); - } + updateErrorString = "This board cannot be applied with this case rule."; } + } else { + updateErrorString = "Auto generated case rules are turned off in preferences."; + } + } + } else { + ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); + if (caseRuleCommand.canExecute()) { + caseRuleCommand.execute(); + getInstance().getHistory().pushChange(caseRuleCommand); + } else { + updateErrorString = caseRuleCommand.getError(); } - GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(updateErrorString); + } + } else { + if (rule.getRuleType() == RuleType.CONTRADICTION) { + ICommand validate = + new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + updateErrorString = validate.getError(); + } + } else { + boolean def = + LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.ALLOW_DEFAULT_RULES); + ICommand validate = + def + ? new ApplyDefaultDirectRuleCommand(selection, (DirectRule) rule) + : new ValidateDirectRuleCommand(selection, (DirectRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + updateErrorString = validate.getError(); + } + } } + GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(updateErrorString); + } - /** - * ICommand Performed event occurs when a rule button has been pressed - * - * @param e action event object - */ - @Override - public void actionPerformed(ActionEvent e) { - lastSource = e.getSource(); - RuleButton button = (RuleButton) lastSource; - buttonPressed(button.getRule()); - } + /** + * ICommand Performed event occurs when a rule button has been pressed + * + * @param e action event object + */ + @Override + public void actionPerformed(ActionEvent e) { + lastSource = e.getSource(); + RuleButton button = (RuleButton) lastSource; + buttonPressed(button.getRule()); + } } diff --git a/src/main/java/edu/rpi/legup/controller/ToolbarController.java b/src/main/java/edu/rpi/legup/controller/ToolbarController.java index 6cbb5ee60..489e6b69f 100644 --- a/src/main/java/edu/rpi/legup/controller/ToolbarController.java +++ b/src/main/java/edu/rpi/legup/controller/ToolbarController.java @@ -5,23 +5,23 @@ import java.awt.event.ActionListener; public class ToolbarController implements ActionListener { - private LegupUI legupUI; + private LegupUI legupUI; - /** - * ToolbarController Constructor - creates a new {@link ToolbarController} to listen for button - * pressed from the tool mBar - * - * @param legupUI legupUI - */ - public ToolbarController(LegupUI legupUI) { - this.legupUI = legupUI; - } + /** + * ToolbarController Constructor - creates a new {@link ToolbarController} to listen for button + * pressed from the tool mBar + * + * @param legupUI legupUI + */ + public ToolbarController(LegupUI legupUI) { + this.legupUI = legupUI; + } - /** - * ICommand Performed event - - * - * @param e action event - */ - @Override - public void actionPerformed(ActionEvent e) {} + /** + * ICommand Performed event - + * + * @param e action event + */ + @Override + public void actionPerformed(ActionEvent e) {} } diff --git a/src/main/java/edu/rpi/legup/controller/TreeController.java b/src/main/java/edu/rpi/legup/controller/TreeController.java index 80fdee1af..f19b40cb1 100644 --- a/src/main/java/edu/rpi/legup/controller/TreeController.java +++ b/src/main/java/edu/rpi/legup/controller/TreeController.java @@ -12,155 +12,152 @@ import javax.swing.*; public class TreeController extends Controller { - /** - * TreeController Constructor creates a controller object to listen to ui events from a {@link - * TreePanel} - */ - public TreeController() {} + /** + * TreeController Constructor creates a controller object to listen to ui events from a {@link + * TreePanel} + */ + public TreeController() {} - /** - * Mouse Clicked event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); - } + /** + * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); + } - /** - * Mouse Released event sets the cursor back to the default cursor and reset info for panning - * Set board modifiability - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); + /** + * Mouse Released event sets the cursor back to the default cursor and reset info for panning Set + * board modifiability + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - if (treeElementView != null) { - if (e.isShiftDown()) { - selection.addToSelection(treeElementView); - } else { - if (e.isControlDown()) { - if (!(selection.getSelectedViews().size() == 1 - && treeElementView == selection.getFirstSelection())) { - selection.toggleSelection(treeElementView); - } - } else { - selection.newSelection(treeElementView); - } - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + if (treeElementView != null) { + if (e.isShiftDown()) { + selection.addToSelection(treeElementView); + } else { + if (e.isControlDown()) { + if (!(selection.getSelectedViews().size() == 1 + && treeElementView == selection.getFirstSelection())) { + selection.toggleSelection(treeElementView); + } + } else { + selection.newSelection(treeElementView); } + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); } + } - /** - * Mouse Entered event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - Tree tree = getInstance().getTree(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - if (treeElementView != null) { - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); - } + /** + * Mouse Entered event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + Tree tree = getInstance().getTree(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + if (treeElementView != null) { + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); } + } - /** - * Mouse Exited event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView elementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); + /** + * Mouse Exited event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView elementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); - selection.setMousePoint(null); - if (elementView != null) { - TreeElementView selectedView = selection.getFirstSelection(); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(selectedView.getTreeElement())); - } + selection.setMousePoint(null); + if (elementView != null) { + TreeElementView selectedView = selection.getFirstSelection(); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(selectedView.getTreeElement())); } + } - /** - * Mouse Dragged event adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - super.mouseDragged(e); - } + /** + * Mouse Dragged event adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + super.mouseDragged(e); + } - /** - * Mouse Moved event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - if (puzzle != null) { - TreeViewSelection selection = treeView.getSelection(); - selection.setMousePoint(treeView.getActualPoint(e.getPoint())); - if (treeElementView != null && treeElementView != selection.getHover()) { - puzzle.notifyBoardListeners( - listener -> - listener.onTreeElementChanged(treeElementView.getTreeElement())); - selection.newHover(treeElementView); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } else { - if (treeElementView == null && selection.getHover() != null) { - puzzle.notifyBoardListeners( - listener -> - listener.onTreeElementChanged( - selection.getFirstSelection().getTreeElement())); - selection.clearHover(); - puzzle.notifyTreeListeners( - listener -> listener.onTreeSelectionChanged(selection)); - } - } + /** + * Mouse Moved event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + if (puzzle != null) { + TreeViewSelection selection = treeView.getSelection(); + selection.setMousePoint(treeView.getActualPoint(e.getPoint())); + if (treeElementView != null && treeElementView != selection.getHover()) { + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); + selection.newHover(treeElementView); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } else { + if (treeElementView == null && selection.getHover() != null) { + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); + selection.clearHover(); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } + } } + } - /** - * Mouse Wheel Moved event zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - super.viewer.scroll(e.getWheelRotation()); - } + /** + * Mouse Wheel Moved event zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + super.viewer.scroll(e.getWheelRotation()); + } } diff --git a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java index b413bebb7..2f9c3e553 100644 --- a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java @@ -12,103 +12,102 @@ public class AddTreeElementCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - private Map addChild; + private Map addChild; - /** - * AddTreeElementCommand Constructor creates a command for adding a tree element to the proof - * tree - * - * @param selection selection of tree elements views - */ - public AddTreeElementCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - this.addChild = new HashMap<>(); - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement treeElement = view.getTreeElement(); - TreeElement child = addChild.get(treeElement); - if (child == null) { - child = tree.addTreeElement(treeElement); - } else { - if (treeElement.getType() == TreeElementType.NODE) { - child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); - } else { - child = tree.addTreeElement((TreeTransition) treeElement, (TreeNode) child); - } - } - addChild.put(treeElement, child); + /** + * AddTreeElementCommand Constructor creates a command for adding a tree element to the proof tree + * + * @param selection selection of tree elements views + */ + public AddTreeElementCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + this.addChild = new HashMap<>(); + } - final TreeElement finalChild = child; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalChild)); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - newSelection.addToSelection(treeView.getElementView(child)); + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement treeElement = view.getTreeElement(); + TreeElement child = addChild.get(treeElement); + if (child == null) { + child = tree.addTreeElement(treeElement); + } else { + if (treeElement.getType() == TreeElementType.NODE) { + child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); + } else { + child = tree.addTreeElement((TreeTransition) treeElement, (TreeNode) child); } + } + addChild.put(treeElement, child); + + final TreeElement finalChild = child; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalChild)); - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + newSelection.addToSelection(treeView.getElementView(child)); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } else { + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) element; + if (transition.getChildNode() != null) { + return CommandError.ADD_WITH_CHILD.toString(); + } } else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) element; - if (transition.getChildNode() != null) { - return CommandError.ADD_WITH_CHILD.toString(); - } - } else { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - TreeTransition transition = node.getChildren().get(0); - if (transition.getParents().size() > 1) { - return CommandError.ADD_TO_MERGE.toString(); - } - } - } + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + TreeTransition transition = node.getChildren().get(0); + if (transition.getParents().size() > 1) { + return CommandError.ADD_TO_MERGE.toString(); } + } } - return null; + } } + return null; + } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - for (TreeElementView view : selection.getSelectedViews()) { - TreeElement element = view.getTreeElement(); - TreeElement child = addChild.get(element); - tree.removeTreeElement(child); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(child)); - newSelection.addToSelection(treeView.getElementView(element)); - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + for (TreeElementView view : selection.getSelectedViews()) { + TreeElement element = view.getTreeElement(); + TreeElement child = addChild.get(element); + tree.removeTreeElement(child); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(child)); + newSelection.addToSelection(treeView.getElementView(element)); } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java index 02dffae44..a2c68112c 100644 --- a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java @@ -12,118 +12,114 @@ public class ApplyDefaultDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - private DirectRule rule; - private Map addMap; - - /** - * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a - * basic rule - * - * @param selection selection of tree element views - * @param rule basic rule for the command - */ - public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.rule = rule; - this.addMap = new HashMap<>(); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.DEFAULT_APPLICATION - + " - " - + CommandError.NO_SELECTED_VIEWS.toString(); - } else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - - return CommandError.DEFAULT_APPLICATION - + " - " - + CommandError.NO_CHILDREN.toString(); - } else { - if (rule.getDefaultBoard(node) == null) { - return CommandError.DEFAULT_APPLICATION - + " - This selection contains a tree element that this rule" - + " cannot be applied to."; - } - } - } else { - return CommandError.DEFAULT_APPLICATION - + " - " - + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } + private TreeViewSelection selection; + private DirectRule rule; + private Map addMap; + + /** + * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a basic + * rule + * + * @param selection selection of tree element views + * @param rule basic rule for the command + */ + public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.rule = rule; + this.addMap = new HashMap<>(); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_SELECTED_VIEWS.toString(); + } else { + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + + return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); + } else { + if (rule.getDefaultBoard(node) == null) { + return CommandError.DEFAULT_APPLICATION + + " - This selection contains a tree element that this rule" + + " cannot be applied to."; } + } + } else { + return CommandError.DEFAULT_APPLICATION + + " - " + + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); } - return null; + } } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - TreeTransition transition = addMap.get(node); - TreeNode childNode; - if (transition == null) { - transition = (TreeTransition) tree.addTreeElement(node); - childNode = (TreeNode) tree.addTreeElement(transition); - addMap.put(node, transition); - } else { - tree.addTreeElement(node, transition); - childNode = transition.getChildNode(); - } - - transition.setRule(rule); - Board defaultBoard = rule.getDefaultBoard(node); - transition.setBoard(defaultBoard); - Board copyBoard = defaultBoard.copy(); - copyBoard.setModifiable(false); - childNode.setBoard(copyBoard); - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(childNode)); - } - - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + return null; + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + TreeTransition transition = addMap.get(node); + TreeNode childNode; + if (transition == null) { + transition = (TreeTransition) tree.addTreeElement(node); + childNode = (TreeNode) tree.addTreeElement(transition); + addMap.put(node, transition); + } else { + tree.addTreeElement(node, transition); + childNode = transition.getChildNode(); + } + + transition.setRule(rule); + Board defaultBoard = rule.getDefaultBoard(node); + transition.setBoard(defaultBoard); + Board copyBoard = defaultBoard.copy(); + copyBoard.setModifiable(false); + childNode.setBoard(copyBoard); + + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(childNode)); } - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - final TreeTransition transition = addMap.get(node); + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - } + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + final TreeTransition transition = addMap.get(node); - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java b/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java index 54e33756a..501f1d0a5 100644 --- a/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java @@ -15,132 +15,131 @@ public class AutoCaseRuleCommand extends PuzzleCommand { - private ElementView elementView; - private TreeViewSelection selection; - private CaseRule caseRule; - private CaseBoard caseBoard; - private MouseEvent mouseEvent; - - private List caseTrans; - - private static final int MAX_CASES = 10; - - /** - * AutoCaseRuleCommand Constructor creates a command for validating a case rule - * - * @param elementView currently selected puzzle puzzleElement view that is being edited - * @param selection currently selected tree puzzleElement views that is being edited - * @param caseRule currently selected caseRule puzzleElement view that is being edited - * @param caseBoard currently selected caseBoard puzzleElement view that is being edited - * @param mouseEvent currently selected mouseEvent puzzleElement view that is being edited - */ - public AutoCaseRuleCommand( - ElementView elementView, - TreeViewSelection selection, - CaseRule caseRule, - CaseBoard caseBoard, - MouseEvent mouseEvent) { - this.elementView = elementView; - this.selection = selection.copy(); - this.caseRule = caseRule; - this.caseBoard = caseBoard; - this.mouseEvent = mouseEvent; - this.caseTrans = new ArrayList<>(); + private ElementView elementView; + private TreeViewSelection selection; + private CaseRule caseRule; + private CaseBoard caseBoard; + private MouseEvent mouseEvent; + + private List caseTrans; + + private static final int MAX_CASES = 10; + + /** + * AutoCaseRuleCommand Constructor creates a command for validating a case rule + * + * @param elementView currently selected puzzle puzzleElement view that is being edited + * @param selection currently selected tree puzzleElement views that is being edited + * @param caseRule currently selected caseRule puzzleElement view that is being edited + * @param caseBoard currently selected caseBoard puzzleElement view that is being edited + * @param mouseEvent currently selected mouseEvent puzzleElement view that is being edited + */ + public AutoCaseRuleCommand( + ElementView elementView, + TreeViewSelection selection, + CaseRule caseRule, + CaseBoard caseBoard, + MouseEvent mouseEvent) { + this.elementView = elementView; + this.selection = selection.copy(); + this.caseRule = caseRule; + this.caseBoard = caseBoard; + this.mouseEvent = mouseEvent; + this.caseTrans = new ArrayList<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); + if (caseTrans.isEmpty()) { + List cases = + caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()); + for (Board board : cases) { + final TreeTransition transition = (TreeTransition) tree.addTreeElement(node); + board.setModifiable(false); + transition.setBoard(board); + transition.setRule(caseRule); + transition.setSelection(elementView.getPuzzleElement().copy()); + caseTrans.add(transition); + + TreeNode childNode = (TreeNode) tree.addTreeElement(transition); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + } else { + for (final TreeTransition transition : caseTrans) { + tree.addTreeElement(node, transition); + TreeNode childNode = transition.getChildNode(); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } } - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); - if (caseTrans.isEmpty()) { - List cases = - caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()); - for (Board board : cases) { - final TreeTransition transition = (TreeTransition) tree.addTreeElement(node); - board.setModifiable(false); - transition.setBoard(board); - transition.setRule(caseRule); - transition.setSelection(elementView.getPuzzleElement().copy()); - caseTrans.add(transition); - - TreeNode childNode = (TreeNode) tree.addTreeElement(transition); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - newSelection.addToSelection(treeView.getElementView(childNode)); - } - } else { - for (final TreeTransition transition : caseTrans) { - tree.addTreeElement(node, transition); - TreeNode childNode = transition.getChildNode(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - newSelection.addToSelection(treeView.getElementView(childNode)); - } - } - - final TreeElement finalTreeElement = node.getChildren().get(0).getChildNode(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + final TreeElement finalTreeElement = node.getChildren().get(0).getChildNode(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + if (selection.getSelectedViews().size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - if (selection.getSelectedViews().size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); - } - - TreeElementView treeElementView = selection.getFirstSelection(); - if (treeElementView.getType() != TreeElementType.NODE) { - return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } - - TreeNodeView nodeView = (TreeNodeView) treeElementView; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.NO_CHILDREN.toString(); - } - - if (!caseBoard.isPickable(elementView.getPuzzleElement(), mouseEvent)) { - return "The selected data element is not pickable with this case rule."; - } - - if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() - == 0) { - return "The selection must produce at least one case"; - } - - if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() - > MAX_CASES) { - return "The selection can produce a max of " + MAX_CASES + " cases"; - } - - return null; + TreeElementView treeElementView = selection.getFirstSelection(); + if (treeElementView.getType() != TreeElementType.NODE) { + return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); } - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + TreeNodeView nodeView = (TreeNodeView) treeElementView; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.NO_CHILDREN.toString(); + } - TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); + if (!caseBoard.isPickable(elementView.getPuzzleElement(), mouseEvent)) { + return "The selected data element is not pickable with this case rule."; + } - for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { - final TreeTransition finalTran = it.next(); - it.remove(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); - } + if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() == 0) { + return "The selection must produce at least one case"; + } - final TreeElement finalTreeElement = node; - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() + > MAX_CASES) { + return "The selection can produce a max of " + MAX_CASES + " cases"; } + + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); + + for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { + final TreeTransition finalTran = it.next(); + it.remove(); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); + } + + final TreeElement finalTreeElement = node; + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/CommandError.java b/src/main/java/edu/rpi/legup/history/CommandError.java index 35b7bb15b..7b2bc41ed 100644 --- a/src/main/java/edu/rpi/legup/history/CommandError.java +++ b/src/main/java/edu/rpi/legup/history/CommandError.java @@ -1,29 +1,29 @@ package edu.rpi.legup.history; public enum CommandError { - NO_SELECTED_VIEWS("The selection does not have any tree elements."), - ONE_SELECTED_VIEW("The selection must have exactly one tree element."), - UNMODIFIABLE_BOARD("The selection contains a board which is not modifiable."), - UNMODIFIABLE_DATA("The selection contains a board where the data element is not modifiable."), - CONTAINS_ROOT("The selection contains the root tree node."), - ONE_CHILD("The selection contains a tree node that does not have exactly one child."), - ADD_WITH_CHILD("The selection contains a tree transition that already has a child tree node."), - TWO_TO_MERGE("The selection must have at least two tree nodes to merge."), - CONTAINS_MERGE("The selection contains a merging transition."), - ADD_TO_MERGE("The selection contains a tree node that merges."), - NO_CHILDREN("The selection contains a tree node that has children."), - SELECTION_CONTAINS_NODE("The selection contains a tree node."), - SELECTION_CONTAINS_TRANSITION("The selection contains a tree transition."), - DEFAULT_APPLICATION("[Apply Default Rule Application]"); + NO_SELECTED_VIEWS("The selection does not have any tree elements."), + ONE_SELECTED_VIEW("The selection must have exactly one tree element."), + UNMODIFIABLE_BOARD("The selection contains a board which is not modifiable."), + UNMODIFIABLE_DATA("The selection contains a board where the data element is not modifiable."), + CONTAINS_ROOT("The selection contains the root tree node."), + ONE_CHILD("The selection contains a tree node that does not have exactly one child."), + ADD_WITH_CHILD("The selection contains a tree transition that already has a child tree node."), + TWO_TO_MERGE("The selection must have at least two tree nodes to merge."), + CONTAINS_MERGE("The selection contains a merging transition."), + ADD_TO_MERGE("The selection contains a tree node that merges."), + NO_CHILDREN("The selection contains a tree node that has children."), + SELECTION_CONTAINS_NODE("The selection contains a tree node."), + SELECTION_CONTAINS_TRANSITION("The selection contains a tree transition."), + DEFAULT_APPLICATION("[Apply Default Rule Application]"); - private String value; + private String value; - CommandError(String value) { - this.value = value; - } + CommandError(String value) { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/main/java/edu/rpi/legup/history/CommandState.java b/src/main/java/edu/rpi/legup/history/CommandState.java index f47c0405d..36e4def4f 100644 --- a/src/main/java/edu/rpi/legup/history/CommandState.java +++ b/src/main/java/edu/rpi/legup/history/CommandState.java @@ -1,19 +1,19 @@ package edu.rpi.legup.history; public enum CommandState { - CREATED("Created"), - EXECUTED("Executed"), - UNDOED("Undoed"), - REDOED("Redoed"); + CREATED("Created"), + EXECUTED("Executed"), + UNDOED("Undoed"), + REDOED("Redoed"); - private String value; + private String value; - CommandState(String value) { - this.value = value; - } + CommandState(String value) { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java index 0469685c1..e301175fe 100644 --- a/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java @@ -8,97 +8,94 @@ import java.util.List; public class DeleteTreeElementCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - /** - * DeleteTreeElementCommand Constructor creates a PuzzleCommand for deleting a tree - * puzzleElement - * - * @param selection the currently selected tree elements before the command is executed - */ - public DeleteTreeElementCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + /** + * DeleteTreeElementCommand Constructor creates a PuzzleCommand for deleting a tree puzzleElement + * + * @param selection the currently selected tree elements before the command is executed + */ + public DeleteTreeElementCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + } - List selectedViews = selection.getSelectedViews(); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - TreeElementView firstSelectedView = selectedViews.get(0); - TreeElementView newSelectedView; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - newSelectedView = nodeView.getParentView(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - newSelectedView = transitionView.getParentViews().get(0); - } + List selectedViews = selection.getSelectedViews(); - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - tree.removeTreeElement(element); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(element)); - } + TreeElementView firstSelectedView = selectedViews.get(0); + TreeElementView newSelectedView; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + newSelectedView = nodeView.getParentView(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + newSelectedView = transitionView.getParentViews().get(0); + } - final TreeViewSelection newSelection = new TreeViewSelection(newSelectedView); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(newSelectedView.getTreeElement())); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeSelectionChanged(newSelection)); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + tree.removeTreeElement(element); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(element)); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } + final TreeViewSelection newSelection = new TreeViewSelection(newSelectedView); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(newSelectedView.getTreeElement())); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeSelectionChanged(newSelection)); + } - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE && ((TreeNode) element).isRoot()) { - return CommandError.CONTAINS_ROOT.toString(); - } - } - return null; + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE && ((TreeNode) element).isRoot()) { + return CommandError.CONTAINS_ROOT.toString(); + } + } + return null; + } - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getParent().setChildNode(node); + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + List selectedViews = selection.getSelectedViews(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(node)); - } else { - TreeTransition transition = (TreeTransition) element; - transition.getParents().forEach(node -> node.addChild(transition)); - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getParent().setChildNode(node); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - } - } + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(node)); + } else { + TreeTransition transition = (TreeTransition) element; + transition.getParents().forEach(node -> node.addChild(transition)); + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - puzzle.notifyBoardListeners( - listener -> - listener.onTreeElementChanged( - selection.getFirstSelection().getTreeElement())); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + } } + + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/EditDataCommand.java b/src/main/java/edu/rpi/legup/history/EditDataCommand.java index d65f03d66..6b5f4062f 100644 --- a/src/main/java/edu/rpi/legup/history/EditDataCommand.java +++ b/src/main/java/edu/rpi/legup/history/EditDataCommand.java @@ -14,155 +14,155 @@ import java.util.List; public class EditDataCommand extends PuzzleCommand { - private TreeTransition transition; - private PuzzleElement savePuzzleElement; - private PuzzleElement puzzleElement; - - private ElementView elementView; - private TreeViewSelection selection; - private MouseEvent event; - - /** - * EditDataCommand Constructor create a puzzle command for editing a board - * - * @param elementView currently selected puzzle puzzleElement view that is being edited - * @param selection currently selected tree puzzleElement views that is being edited - * @param event mouse event - */ - public EditDataCommand(ElementView elementView, TreeViewSelection selection, MouseEvent event) { - this.elementView = elementView; - this.selection = selection.copy(); - this.event = event; - this.puzzleElement = null; - this.savePuzzleElement = null; - this.transition = null; - } - - /** Executes a command */ - @SuppressWarnings("unchecked") - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - Board board = treeElement.getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - if (treeNode.getChildren().isEmpty()) { - if (transition == null) { - transition = tree.addNewTransition(treeNode); - } - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - } - - board = transition.getBoard(); - - puzzleElement = board.getPuzzleElement(selectedPuzzleElement); - savePuzzleElement = puzzleElement.copy(); - } else { - transition = (TreeTransition) treeElement; - puzzleElement = board.getPuzzleElement(selectedPuzzleElement); - savePuzzleElement = puzzleElement.copy(); + private TreeTransition transition; + private PuzzleElement savePuzzleElement; + private PuzzleElement puzzleElement; + + private ElementView elementView; + private TreeViewSelection selection; + private MouseEvent event; + + /** + * EditDataCommand Constructor create a puzzle command for editing a board + * + * @param elementView currently selected puzzle puzzleElement view that is being edited + * @param selection currently selected tree puzzleElement views that is being edited + * @param event mouse event + */ + public EditDataCommand(ElementView elementView, TreeViewSelection selection, MouseEvent event) { + this.elementView = elementView; + this.selection = selection.copy(); + this.event = event; + this.puzzleElement = null; + this.savePuzzleElement = null; + this.transition = null; + } + + /** Executes a command */ + @SuppressWarnings("unchecked") + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + Board board = treeElement.getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + if (treeNode.getChildren().isEmpty()) { + if (transition == null) { + transition = tree.addNewTransition(treeNode); } + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + } - Board prevBoard = transition.getParents().get(0).getBoard(); + board = transition.getBoard(); - boardView.getElementController().changeCell(event, puzzleElement); + puzzleElement = board.getPuzzleElement(selectedPuzzleElement); + savePuzzleElement = puzzleElement.copy(); + } else { + transition = (TreeTransition) treeElement; + puzzleElement = board.getPuzzleElement(selectedPuzzleElement); + savePuzzleElement = puzzleElement.copy(); + } - if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { - board.removeModifiedData(puzzleElement); - } else { - board.addModifiedData(puzzleElement); - } - transition.propagateChange(puzzleElement); + Board prevBoard = transition.getParents().get(0).getBoard(); - final TreeElement finalTreeElement = transition; - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); + boardView.getElementController().changeCell(event, puzzleElement); - final TreeViewSelection newSelection = - new TreeViewSelection(treeView.getElementView(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { + board.removeModifiedData(puzzleElement); + } else { + board.addModifiedData(puzzleElement); } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); + transition.propagateChange(puzzleElement); + + final TreeElement finalTreeElement = transition; + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); + + final TreeViewSelection newSelection = + new TreeViewSelection(treeView.getElementView(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); + } + TreeElementView selectedView = selection.getFirstSelection(); + Board board = selectedView.getTreeElement().getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + if (selectedView.getType() == TreeElementType.NODE) { + + TreeNodeView nodeView = (TreeNodeView) selectedView; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } else { + if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); } - TreeElementView selectedView = selection.getFirstSelection(); - Board board = selectedView.getTreeElement().getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - if (selectedView.getType() == TreeElementType.NODE) { - - TreeNodeView nodeView = (TreeNodeView) selectedView; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } else { - if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); - } - } - } else { - TreeTransitionView transitionView = (TreeTransitionView) selectedView; - if (!transitionView.getTreeElement().getBoard().isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } else { - if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); - } - } + } + } else { + TreeTransitionView transitionView = (TreeTransitionView) selectedView; + if (!transitionView.getTreeElement().getBoard().isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } else { + if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); } - return null; + } + } + return null; + } + + /** Undoes an command */ + @SuppressWarnings("unchecked") + @Override + public void undoCommand() { + TreeElementView selectedView = selection.getFirstSelection(); + Tree tree = getInstance().getTree(); + Puzzle puzzle = getInstance().getPuzzleModule(); + + Board board = transition.getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + + if (selectedView.getType() == TreeElementType.NODE) { + tree.removeTreeElement(transition); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeElementRemoved(transition)); } - /** Undoes an command */ - @SuppressWarnings("unchecked") - @Override - public void undoCommand() { - TreeElementView selectedView = selection.getFirstSelection(); - Tree tree = getInstance().getTree(); - Puzzle puzzle = getInstance().getPuzzleModule(); - - Board board = transition.getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - - if (selectedView.getType() == TreeElementType.NODE) { - tree.removeTreeElement(transition); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeElementRemoved(transition)); - } - - Board prevBoard = transition.getParents().get(0).getBoard(); + Board prevBoard = transition.getParents().get(0).getBoard(); - puzzleElement.setData(savePuzzleElement.getData()); - board.notifyChange(puzzleElement); + puzzleElement.setData(savePuzzleElement.getData()); + board.notifyChange(puzzleElement); - if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { - board.removeModifiedData(puzzleElement); - } else { - board.addModifiedData(puzzleElement); - } - transition.propagateChange(puzzleElement); + if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { + board.removeModifiedData(puzzleElement); + } else { + board.addModifiedData(puzzleElement); + } + transition.propagateChange(puzzleElement); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/History.java b/src/main/java/edu/rpi/legup/history/History.java index 371284f8c..8221449e6 100644 --- a/src/main/java/edu/rpi/legup/history/History.java +++ b/src/main/java/edu/rpi/legup/history/History.java @@ -7,94 +7,92 @@ import org.apache.logging.log4j.Logger; public class History { - private static final Logger LOGGER = LogManager.getLogger(History.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(History.class.getName()); - private final Object lock = new Object(); - private List history; - private int curIndex; + private final Object lock = new Object(); + private List history; + private int curIndex; - /** - * History Constructor this holds information about changes to the board and Tree structure for - * undoing and redoing operations. Though history is an List, it is implemented like a stack. - * The curIndex points to the top of the stack (where the last change was made). - */ - public History() { - history = new ArrayList<>(); - curIndex = -1; - } + /** + * History Constructor this holds information about changes to the board and Tree structure for + * undoing and redoing operations. Though history is an List, it is implemented like a stack. The + * curIndex points to the top of the stack (where the last change was made). + */ + public History() { + history = new ArrayList<>(); + curIndex = -1; + } - /** - * Pushes a change to the history list and increments the current index. If the current index - * does not point to the top of the stack, then at least 1 undo operation was called and that - * information will be lost by the next change - * - * @param command command to be pushed onto the stack - */ - public void pushChange(ICommand command) { - synchronized (lock) { - if (curIndex < history.size() - 1) { - for (int i = history.size() - 1; i > curIndex; i--) { - history.remove(i); - } - } - history.add(command); - curIndex++; - LOGGER.info("Pushed " + command.getClass().getSimpleName() + " to stack."); - GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onPushChange(command)); + /** + * Pushes a change to the history list and increments the current index. If the current index does + * not point to the top of the stack, then at least 1 undo operation was called and that + * information will be lost by the next change + * + * @param command command to be pushed onto the stack + */ + public void pushChange(ICommand command) { + synchronized (lock) { + if (curIndex < history.size() - 1) { + for (int i = history.size() - 1; i > curIndex; i--) { + history.remove(i); } + } + history.add(command); + curIndex++; + LOGGER.info("Pushed " + command.getClass().getSimpleName() + " to stack."); + GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onPushChange(command)); } + } - /** Undoes an action */ - public void undo() { - synchronized (lock) { - if (curIndex > -1) { - ICommand command = history.get(curIndex--); - command.undo(); - LOGGER.info("Undoed " + command.getClass().getSimpleName()); - GameBoardFacade.getInstance() - .notifyHistoryListeners( - l -> l.onUndo(curIndex < 0, curIndex == history.size() - 1)); - } - } + /** Undoes an action */ + public void undo() { + synchronized (lock) { + if (curIndex > -1) { + ICommand command = history.get(curIndex--); + command.undo(); + LOGGER.info("Undoed " + command.getClass().getSimpleName()); + GameBoardFacade.getInstance() + .notifyHistoryListeners(l -> l.onUndo(curIndex < 0, curIndex == history.size() - 1)); + } } + } - /** Redoes an action */ - public void redo() { - synchronized (lock) { - if (curIndex < history.size() - 1) { - ICommand command = history.get(++curIndex); - command.redo(); - LOGGER.info("Redoed " + command.getClass().getSimpleName()); - GameBoardFacade.getInstance() - .notifyHistoryListeners( - l -> l.onRedo(curIndex < 0, curIndex == history.size() - 1)); - } - } + /** Redoes an action */ + public void redo() { + synchronized (lock) { + if (curIndex < history.size() - 1) { + ICommand command = history.get(++curIndex); + command.redo(); + LOGGER.info("Redoed " + command.getClass().getSimpleName()); + GameBoardFacade.getInstance() + .notifyHistoryListeners(l -> l.onRedo(curIndex < 0, curIndex == history.size() - 1)); + } } + } - /** Clears all actions from the history stack */ - public void clear() { - history.clear(); - curIndex = -1; - LOGGER.debug("History Cleared"); - GameBoardFacade.getInstance().notifyHistoryListeners(IHistoryListener::onClearHistory); - } + /** Clears all actions from the history stack */ + public void clear() { + history.clear(); + curIndex = -1; + LOGGER.debug("History Cleared"); + GameBoardFacade.getInstance().notifyHistoryListeners(IHistoryListener::onClearHistory); + } - /** - * Gets the current index that points to the action at the top of stack - * - * @return index of the action on top of the stack - */ - public int getIndex() { - return curIndex; - } + /** + * Gets the current index that points to the action at the top of stack + * + * @return index of the action on top of the stack + */ + public int getIndex() { + return curIndex; + } - /** - * Gets the amount of actions that have been pushed onto the stack - * - * @return size of the history stack - */ - public int size() { - return history.size(); - } + /** + * Gets the amount of actions that have been pushed onto the stack + * + * @return size of the history stack + */ + public int size() { + return history.size(); + } } diff --git a/src/main/java/edu/rpi/legup/history/ICommand.java b/src/main/java/edu/rpi/legup/history/ICommand.java index 913d9daaf..b10cdc861 100644 --- a/src/main/java/edu/rpi/legup/history/ICommand.java +++ b/src/main/java/edu/rpi/legup/history/ICommand.java @@ -1,27 +1,27 @@ package edu.rpi.legup.history; public interface ICommand { - /** Executes a command */ - void execute(); + /** Executes a command */ + void execute(); - /** - * Determines whether this command can be executed - * - * @return true if can execute, false otherwise - */ - boolean canExecute(); + /** + * Determines whether this command can be executed + * + * @return true if can execute, false otherwise + */ + boolean canExecute(); - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - String getError(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + String getError(); - /** Undoes a command */ - void undo(); + /** Undoes a command */ + void undo(); - /** Redoes a command */ - void redo(); + /** Redoes a command */ + void redo(); } diff --git a/src/main/java/edu/rpi/legup/history/IHistoryListener.java b/src/main/java/edu/rpi/legup/history/IHistoryListener.java index f464941d6..1b3253b9f 100644 --- a/src/main/java/edu/rpi/legup/history/IHistoryListener.java +++ b/src/main/java/edu/rpi/legup/history/IHistoryListener.java @@ -1,29 +1,29 @@ package edu.rpi.legup.history; public interface IHistoryListener { - /** - * Called when a action is pushed onto the edu.rpi.legup.history stack - * - * @param command action to push onto the stack - */ - void onPushChange(ICommand command); + /** + * Called when a action is pushed onto the edu.rpi.legup.history stack + * + * @param command action to push onto the stack + */ + void onPushChange(ICommand command); - /** - * Called when an action is undone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - void onUndo(boolean isBottom, boolean isTop); + /** + * Called when an action is undone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + void onUndo(boolean isBottom, boolean isTop); - /** - * Called when an action is redone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - void onRedo(boolean isBottom, boolean isTop); + /** + * Called when an action is redone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + void onRedo(boolean isBottom, boolean isTop); - /** Called when the edu.rpi.legup.history is cleared */ - void onClearHistory(); + /** Called when the edu.rpi.legup.history is cleared */ + void onClearHistory(); } diff --git a/src/main/java/edu/rpi/legup/history/IHistorySubject.java b/src/main/java/edu/rpi/legup/history/IHistorySubject.java index 78fefff00..63acfa4c6 100644 --- a/src/main/java/edu/rpi/legup/history/IHistorySubject.java +++ b/src/main/java/edu/rpi/legup/history/IHistorySubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface IHistorySubject { - /** - * Adds a history listener - * - * @param listener listener to add - */ - void addHistoryListener(IHistoryListener listener); + /** + * Adds a history listener + * + * @param listener listener to add + */ + void addHistoryListener(IHistoryListener listener); - /** - * Removes a history listener - * - * @param listener listener to remove - */ - void removeHistoryListener(IHistoryListener listener); + /** + * Removes a history listener + * + * @param listener listener to remove + */ + void removeHistoryListener(IHistoryListener listener); - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - void notifyHistoryListeners(Consumer algorithm); + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + void notifyHistoryListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java b/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java index 71d072328..42a547e84 100644 --- a/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java +++ b/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java @@ -2,14 +2,14 @@ public class InvalidCommandStateTransition extends RuntimeException { - public InvalidCommandStateTransition( - PuzzleCommand puzzleCommand, CommandState from, CommandState to) { - super( - "PuzzleCommand - " - + puzzleCommand.getClass().getSimpleName() - + " - Attempted invalid command state transition from " - + from - + " to " - + to); - } + public InvalidCommandStateTransition( + PuzzleCommand puzzleCommand, CommandState from, CommandState to) { + super( + "PuzzleCommand - " + + puzzleCommand.getClass().getSimpleName() + + " - Attempted invalid command state transition from " + + from + + " to " + + to); + } } diff --git a/src/main/java/edu/rpi/legup/history/MergeCommand.java b/src/main/java/edu/rpi/legup/history/MergeCommand.java index f234a0884..e170e9856 100644 --- a/src/main/java/edu/rpi/legup/history/MergeCommand.java +++ b/src/main/java/edu/rpi/legup/history/MergeCommand.java @@ -11,128 +11,128 @@ import java.util.Set; public class MergeCommand extends PuzzleCommand { - private TreeViewSelection selection; - private TreeTransition transition; - - /** - * Merge Command Constructor create a command for merging tree nodes. - * - * @param selection selection of tree elements - */ - public MergeCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - this.transition = null; + private TreeViewSelection selection; + private TreeTransition transition; + + /** + * Merge Command Constructor create a command for merging tree nodes. + * + * @param selection selection of tree elements + */ + public MergeCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + this.transition = null; + } + + /** Executes an command */ + @Override + public void executeCommand() { + List selectedViews = selection.getSelectedViews(); + + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeNode mergedNode; + if (transition == null) { + List mergingNodes = new ArrayList<>(); + List mergingBoards = new ArrayList<>(); + for (TreeElementView view : selectedViews) { + TreeNode node = ((TreeNodeView) view).getTreeElement(); + mergingNodes.add(node); + mergingBoards.add(node.getBoard()); + } + + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + Board lcaBoard = lca.getBoard(); + + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + mergedNode = new TreeNode(mergedBoard.copy()); + transition = new TreeTransition(mergedBoard); + transition.setRule(new MergeRule()); + transition.setChildNode(mergedNode); + mergedNode.setParent(transition); + } else { + mergedNode = transition.getChildNode(); } - /** Executes an command */ - @Override - public void executeCommand() { - List selectedViews = selection.getSelectedViews(); - - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeNode mergedNode; - if (transition == null) { - List mergingNodes = new ArrayList<>(); - List mergingBoards = new ArrayList<>(); - for (TreeElementView view : selectedViews) { - TreeNode node = ((TreeNodeView) view).getTreeElement(); - mergingNodes.add(node); - mergingBoards.add(node.getBoard()); - } - - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - Board lcaBoard = lca.getBoard(); - - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); - - mergedNode = new TreeNode(mergedBoard.copy()); - transition = new TreeTransition(mergedBoard); - transition.setRule(new MergeRule()); - transition.setChildNode(mergedNode); - mergedNode.setParent(transition); - } else { - mergedNode = transition.getChildNode(); - } - - transition.getParents().clear(); - for (TreeElementView elementView : selectedViews) { - TreeNode node = (TreeNode) elementView.getTreeElement(); - - node.addChild(transition); - transition.addParent(node); - } - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + transition.getParents().clear(); + for (TreeElementView elementView : selectedViews) { + TreeNode node = (TreeNode) elementView.getTreeElement(); - final TreeViewSelection newSelection = new TreeViewSelection(); - newSelection.addToSelection(treeView.getElementView(mergedNode)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + node.addChild(transition); + transition.addParent(node); } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeTransition transition = - ((TreeNode) selection.getFirstSelection().getTreeElement()).getChildren().get(0); - tree.removeTreeElement(transition); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + + final TreeViewSelection newSelection = new TreeViewSelection(); + newSelection.addToSelection(treeView.getElementView(mergedNode)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeTransition transition = + ((TreeNode) selection.getFirstSelection().getTreeElement()).getChildren().get(0); + tree.removeTreeElement(transition); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + Tree tree = GameBoardFacade.getInstance().getTree(); + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() < 2) { + return CommandError.TWO_TO_MERGE.toString(); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - Tree tree = GameBoardFacade.getInstance().getTree(); - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() < 2) { - return CommandError.TWO_TO_MERGE.toString(); - } - - List nodeList = new ArrayList<>(); - for (TreeElementView view : selection.getSelectedViews()) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.NO_CHILDREN.toString(); - } - nodeList.add(nodeView.getTreeElement()); - } else { - return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } - } - - List mergingNodes = new ArrayList<>(); - for (TreeElementView view : selectedViews) { - TreeNode node = ((TreeNodeView) view).getTreeElement(); - mergingNodes.add(node); + List nodeList = new ArrayList<>(); + for (TreeElementView view : selection.getSelectedViews()) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.NO_CHILDREN.toString(); } + nodeList.add(nodeView.getTreeElement()); + } else { + return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + } - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - return "Unable to merge tree elements."; - } - Set leafNodes = tree.getLeafTreeElements(lca); - if (leafNodes.size() != mergingNodes.size()) { - // return "Unable to merge tree elements."; - } + List mergingNodes = new ArrayList<>(); + for (TreeElementView view : selectedViews) { + TreeNode node = ((TreeNodeView) view).getTreeElement(); + mergingNodes.add(node); + } - for (TreeNode node : mergingNodes) { - if (!leafNodes.contains(node)) { - // return "Unable to merge tree elements."; - } - } + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + return "Unable to merge tree elements."; + } + Set leafNodes = tree.getLeafTreeElements(lca); + if (leafNodes.size() != mergingNodes.size()) { + // return "Unable to merge tree elements."; + } - return null; + for (TreeNode node : mergingNodes) { + if (!leafNodes.contains(node)) { + // return "Unable to merge tree elements."; + } } + + return null; + } } diff --git a/src/main/java/edu/rpi/legup/history/PuzzleCommand.java b/src/main/java/edu/rpi/legup/history/PuzzleCommand.java index 3768e3cbd..482c11cc7 100644 --- a/src/main/java/edu/rpi/legup/history/PuzzleCommand.java +++ b/src/main/java/edu/rpi/legup/history/PuzzleCommand.java @@ -1,91 +1,91 @@ package edu.rpi.legup.history; public abstract class PuzzleCommand implements ICommand { - private CommandState state; - private boolean isCached; - private String cachedError; + private CommandState state; + private boolean isCached; + private String cachedError; - /** Puzzle Command Constructor for creating an undoable and redoable change to the model. */ - protected PuzzleCommand() { - this.state = CommandState.CREATED; - this.isCached = false; - this.cachedError = null; - } + /** Puzzle Command Constructor for creating an undoable and redoable change to the model. */ + protected PuzzleCommand() { + this.state = CommandState.CREATED; + this.isCached = false; + this.cachedError = null; + } - /** Executes an command */ - @Override - public final void execute() { - if (canExecute()) { - executeCommand(); - state = CommandState.EXECUTED; - } + /** Executes an command */ + @Override + public final void execute() { + if (canExecute()) { + executeCommand(); + state = CommandState.EXECUTED; } + } - /** Determines whether this command can be executed */ - @Override - public final boolean canExecute() { - cachedError = getError(); - isCached = true; - return cachedError == null; - } + /** Determines whether this command can be executed */ + @Override + public final boolean canExecute() { + cachedError = getError(); + isCached = true; + return cachedError == null; + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public final String getError() { - if (isCached) { - return cachedError; - } else { - return getErrorString(); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public final String getError() { + if (isCached) { + return cachedError; + } else { + return getErrorString(); } + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - public abstract String getErrorString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + public abstract String getErrorString(); - /** Executes an command */ - public abstract void executeCommand(); + /** Executes an command */ + public abstract void executeCommand(); - /** Undoes an command */ - public abstract void undoCommand(); + /** Undoes an command */ + public abstract void undoCommand(); - /** Redoes an command */ - public void redoCommand() { - if (state == CommandState.UNDOED) { - executeCommand(); - state = CommandState.REDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); - } + /** Redoes an command */ + public void redoCommand() { + if (state == CommandState.UNDOED) { + executeCommand(); + state = CommandState.REDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); } + } - /** Undoes an command */ - @Override - public final void undo() { - if (state == CommandState.EXECUTED || state == CommandState.REDOED) { - undoCommand(); - state = CommandState.UNDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.UNDOED); - } + /** Undoes an command */ + @Override + public final void undo() { + if (state == CommandState.EXECUTED || state == CommandState.REDOED) { + undoCommand(); + state = CommandState.UNDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.UNDOED); } + } - /** Redoes an command */ - public final void redo() { - if (state == CommandState.UNDOED) { - redoCommand(); - state = CommandState.REDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); - } + /** Redoes an command */ + public final void redo() { + if (state == CommandState.UNDOED) { + redoCommand(); + state = CommandState.REDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); } + } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java index 7737ecfd3..4718a56c8 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java @@ -14,118 +14,118 @@ public class ValidateCaseRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - private CaseRule caseRule; - - private Map oldRule; - private Map addNode; - - /** - * AutoCaseRuleCommand Constructor creates a command for verifying a case rule - * - * @param selection currently selected tree puzzleElement views that is being edited - * @param caseRule currently selected caseRule puzzleElement view that is being edited - */ - public ValidateCaseRuleCommand(TreeViewSelection selection, CaseRule caseRule) { - this.selection = selection.copy(); - this.caseRule = caseRule; - this.oldRule = new HashMap<>(); - this.addNode = new HashMap<>(); - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeTransition transition = (TreeTransition) element; - oldRule.put(transition, transition.getRule()); - - transition.setRule(caseRule); - - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); - } else { - childNode = (TreeNode) tree.addTreeElement(transition, childNode); - } - - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - newSelection.addToSelection(treeView.getElementView(childNode)); - } - - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + private TreeViewSelection selection; + private CaseRule caseRule; + + private Map oldRule; + private Map addNode; + + /** + * AutoCaseRuleCommand Constructor creates a command for verifying a case rule + * + * @param selection currently selected tree puzzleElement views that is being edited + * @param caseRule currently selected caseRule puzzleElement view that is being edited + */ + public ValidateCaseRuleCommand(TreeViewSelection selection, CaseRule caseRule) { + this.selection = selection.copy(); + this.caseRule = caseRule; + this.oldRule = new HashMap<>(); + this.addNode = new HashMap<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeTransition transition = (TreeTransition) element; + oldRule.put(transition, transition.getRule()); + + transition.setRule(caseRule); + + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); - } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + childNode = (TreeNode) tree.addTreeElement(transition, childNode); } - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - return CommandError.SELECTION_CONTAINS_NODE.toString(); - } else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); - } - } - } - return null; + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + newSelection.addToSelection(treeView.getElementView(childNode)); } - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeTransition transition = (TreeTransition) element; - - transition.setRule(oldRule.get(transition)); + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); + } + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } - final TreeNode childNode = transition.getChildNode(); - if (addNode.get(transition) != null) { - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + return CommandError.SELECTION_CONTAINS_NODE.toString(); + } else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); } - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } + } + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeTransition transition = (TreeTransition) element; + + transition.setRule(oldRule.get(transition)); + + final TreeNode childNode = transition.getChildNode(); + if (addNode.get(transition) != null) { + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java index 8737b4008..cc60029bf 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java @@ -11,156 +11,147 @@ import java.util.Map; public class ValidateContradictionRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - - private Map> saveElements; - private ContradictionRule newRule; - private Map addTran; - - /** - * ValidateContradictionRuleCommand Constructor creates a puzzle command for verifying a - * contradiction rule - * - * @param selection currently selected tree puzzleElement views - * @param rule contradiction rule to be set to all the tree elements - */ - public ValidateContradictionRuleCommand(TreeViewSelection selection, ContradictionRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.saveElements = new HashMap<>(); - this.addTran = new HashMap<>(); + private TreeViewSelection selection; + + private Map> saveElements; + private ContradictionRule newRule; + private Map addTran; + + /** + * ValidateContradictionRuleCommand Constructor creates a puzzle command for verifying a + * contradiction rule + * + * @param selection currently selected tree puzzleElement views + * @param rule contradiction rule to be set to all the tree elements + */ + public ValidateContradictionRuleCommand(TreeViewSelection selection, ContradictionRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.saveElements = new HashMap<>(); + this.addTran = new HashMap<>(); + } + + /** Executes a command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement treeElement = view.getTreeElement(); + TreeNode treeNode; + if (treeElement.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) treeElement; + treeNode = transition.getParents().get(0); + } else { + treeNode = (TreeNode) treeElement; + } + + if (!treeNode.getChildren().isEmpty()) { + ArrayList save = new ArrayList<>(treeNode.getChildren()); + saveElements.put(treeNode, save); + } + + treeNode + .getChildren() + .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); + + treeNode.getChildren().clear(); + + TreeTransition transition = addTran.get(treeElement); + if (transition == null) { + transition = tree.addNewTransition(treeNode); + transition.setRule(newRule); + transition.getBoard().setModifiable(false); + tree.addTreeElement(transition); + } else { + transition.getBoard().setModifiable(false); + tree.addTreeElement(treeNode, transition); + } + + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(transition)); } - /** Executes a command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement treeElement = view.getTreeElement(); - TreeNode treeNode; - if (treeElement.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) treeElement; - treeNode = transition.getParents().get(0); - } else { - treeNode = (TreeNode) treeElement; - } - - if (!treeNode.getChildren().isEmpty()) { - ArrayList save = new ArrayList<>(treeNode.getChildren()); - saveElements.put(treeNode, save); - } - - treeNode.getChildren() - .forEach( - n -> - puzzle.notifyTreeListeners( - listener -> listener.onTreeElementRemoved(n))); - - treeNode.getChildren().clear(); - - TreeTransition transition = addTran.get(treeElement); - if (transition == null) { - transition = tree.addNewTransition(treeNode); - transition.setRule(newRule); - transition.getBoard().setModifiable(false); - tree.addTreeElement(transition); - } else { - transition.getBoard().setModifiable(false); - tree.addTreeElement(treeNode, transition); - } - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(transition)); - } - - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - if (transitionView.getChildView() != null) { - finalTreeElement = transitionView.getChildView().getTreeElement(); - } else { - finalTreeElement = null; - } - } - - if (finalTreeElement != null) { - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(finalTreeElement)); - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + if (transitionView.getChildView() != null) { + finalTreeElement = transitionView.getChildView().getTreeElement(); + } else { + finalTreeElement = null; + } } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } - - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.TRANSITION) { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); - } - } - } - return null; + if (finalTreeElement != null) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - /** Undoes a command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeNode node; - if (element.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) element; - node = transition.getParents().get(0); - } else { - node = (TreeNode) element; - } - node.getChildren() - .forEach( - n -> - puzzle.notifyTreeListeners( - listener -> listener.onTreeElementRemoved(n))); - node.getChildren().clear(); - - ArrayList save = saveElements.get(node); - - if (save != null) { - node.getChildren().addAll(save); - node.getChildren() - .forEach( - n -> - puzzle.notifyTreeListeners( - listener -> listener.onTreeElementAdded(n))); - } + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.TRANSITION) { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); } - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } + } + return null; + } + + /** Undoes a command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeNode node; + if (element.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) element; + node = transition.getParents().get(0); + } else { + node = (TreeNode) element; + } + node.getChildren() + .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); + node.getChildren().clear(); + + ArrayList save = saveElements.get(node); + + if (save != null) { + node.getChildren().addAll(save); + node.getChildren() + .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(n))); + } } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java index d9c063464..0fe35218f 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java @@ -11,132 +11,132 @@ import java.util.Map; public class ValidateDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - private Map oldRules; - private Map addNode; - private DirectRule newRule; + private Map oldRules; + private Map addNode; + private DirectRule newRule; - /** - * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule - * - * @param selection selection of tree elements - * @param rule basic rule - */ - public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.oldRules = new HashMap<>(); - this.addNode = new HashMap<>(); - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + /** + * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule + * + * @param selection selection of tree elements + * @param rule basic rule + */ + public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.oldRules = new HashMap<>(); + this.addNode = new HashMap<>(); + } - List selectedViews = selection.getSelectedViews(); - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - oldRules.put(transition, transition.getRule()); - transition.setRule(newRule); + List selectedViews = selection.getSelectedViews(); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); - } else { - tree.addTreeElement(transition, childNode); - } + oldRules.put(transition, transition.getRule()); + transition.setRule(newRule); - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - newSelection.addToSelection(treeView.getElementView(childNode)); - } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); + tree.addTreeElement(transition, childNode); } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + newSelection.addToSelection(treeView.getElementView(childNode)); + } + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); } + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (nodeView.getChildrenViews().size() != 1) { - return CommandError.ONE_CHILD.toString(); - } - } else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); - } - } + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (nodeView.getChildrenViews().size() != 1) { + return CommandError.ONE_CHILD.toString(); + } + } else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); } - return null; + } } + return null; + } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); - transition.setRule(oldRules.get(transition)); + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); + transition.setRule(oldRules.get(transition)); - if (addNode.get(transition) != null) { - final TreeNode childNode = transition.getChildNode(); - tree.removeTreeElement(childNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - } - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + if (addNode.get(transition) != null) { + final TreeNode childNode = transition.getChildNode(); + tree.removeTreeElement(childNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/model/Puzzle.java b/src/main/java/edu/rpi/legup/model/Puzzle.java index 7971c95af..6e5e681b2 100644 --- a/src/main/java/edu/rpi/legup/model/Puzzle.java +++ b/src/main/java/edu/rpi/legup/model/Puzzle.java @@ -36,615 +36,614 @@ import org.xml.sax.SAXException; public abstract class Puzzle implements IBoardSubject, ITreeSubject { - private static final Logger LOGGER = LogManager.getLogger(Puzzle.class.getName()); - - protected String name; - protected Board currentBoard; - protected Tree tree; - protected BoardView boardView; - protected PuzzleImporter importer; - protected PuzzleExporter exporter; - protected ElementFactory factory; - - private List boardListeners; - private List treeListeners; - - protected List directRules; - protected List contradictionRules; - protected List caseRules; - protected List placeableElements; - protected List nonPlaceableElements; - - /** Puzzle Constructor - creates a new Puzzle */ - public Puzzle() { - this.boardListeners = new ArrayList<>(); - this.treeListeners = new ArrayList<>(); - - this.directRules = new ArrayList<>(); - this.contradictionRules = new ArrayList<>(); - this.caseRules = new ArrayList<>(); - - this.placeableElements = new ArrayList<>(); - this.nonPlaceableElements = new ArrayList<>(); - - registerRules(); - registerPuzzleElements(); - } - - private void registerPuzzleElements() { - String packageName = this.getClass().getPackage().toString().replace("package ", ""); - - try { - Class[] possElements = LegupUtils.getClasses(packageName); - - for (Class c : possElements) { - - System.out.println("possible element: " + c.getName()); - - // check that the element is not abstract - if (Modifier.isAbstract(c.getModifiers())) continue; - - for (Annotation a : c.getAnnotations()) { - if (a.annotationType() == RegisterElement.class) { - RegisterElement registerElement = (RegisterElement) a; - Constructor cons = c.getConstructor(); - try { - Element element = (Element) cons.newInstance(); - - switch (element.getElementType()) { - case PLACEABLE: - this.addPlaceableElement((PlaceableElement) element); - break; - case NONPLACEABLE: - this.addNonPlaceableElement((NonPlaceableElement) element); - break; - default: - break; - } - } catch (InvocationTargetException e) { - System.out.println(" Failed "); - e.getTargetException().printStackTrace(); - } - } - } - } - - // } catch (IOException | ClassNotFoundException | NoSuchMethodException | - // InstantiationException | IllegalAccessException | - // InvocationTargetException - // e) { - // LOGGER.error("Unable to find rules for " + - // this.getClass().getSimpleName(), e); - // } - } catch (Exception e) { - LOGGER.error("Unable to find elements for " + this.getClass().getSimpleName(), e); - } - } - - private void registerRules() { - String packageName = this.getClass().getPackage().toString().replace("package ", ""); - - try { - Class[] possRules = LegupUtils.getClasses(packageName); - - for (Class c : possRules) { - - System.out.println("possible rule: " + c.getName()); - - // check that the rule is not abstract - if (Modifier.isAbstract(c.getModifiers())) continue; - - for (Annotation a : c.getAnnotations()) { - if (a.annotationType() == RegisterRule.class) { - RegisterRule registerRule = (RegisterRule) a; - Constructor cons = c.getConstructor(); - try { - Rule rule = (Rule) cons.newInstance(); - - switch (rule.getRuleType()) { - case BASIC: - this.addDirectRule((DirectRule) rule); - break; - case CASE: - this.addCaseRule((CaseRule) rule); - break; - case CONTRADICTION: - this.addContradictionRule((ContradictionRule) rule); - break; - case MERGE: - break; - default: - break; - } - } catch (InvocationTargetException e) { - System.out.println(" Failed "); - e.getTargetException().printStackTrace(); - } - } - } + private static final Logger LOGGER = LogManager.getLogger(Puzzle.class.getName()); + + protected String name; + protected Board currentBoard; + protected Tree tree; + protected BoardView boardView; + protected PuzzleImporter importer; + protected PuzzleExporter exporter; + protected ElementFactory factory; + + private List boardListeners; + private List treeListeners; + + protected List directRules; + protected List contradictionRules; + protected List caseRules; + protected List placeableElements; + protected List nonPlaceableElements; + + /** Puzzle Constructor - creates a new Puzzle */ + public Puzzle() { + this.boardListeners = new ArrayList<>(); + this.treeListeners = new ArrayList<>(); + + this.directRules = new ArrayList<>(); + this.contradictionRules = new ArrayList<>(); + this.caseRules = new ArrayList<>(); + + this.placeableElements = new ArrayList<>(); + this.nonPlaceableElements = new ArrayList<>(); + + registerRules(); + registerPuzzleElements(); + } + + private void registerPuzzleElements() { + String packageName = this.getClass().getPackage().toString().replace("package ", ""); + + try { + Class[] possElements = LegupUtils.getClasses(packageName); + + for (Class c : possElements) { + + System.out.println("possible element: " + c.getName()); + + // check that the element is not abstract + if (Modifier.isAbstract(c.getModifiers())) continue; + + for (Annotation a : c.getAnnotations()) { + if (a.annotationType() == RegisterElement.class) { + RegisterElement registerElement = (RegisterElement) a; + Constructor cons = c.getConstructor(); + try { + Element element = (Element) cons.newInstance(); + + switch (element.getElementType()) { + case PLACEABLE: + this.addPlaceableElement((PlaceableElement) element); + break; + case NONPLACEABLE: + this.addNonPlaceableElement((NonPlaceableElement) element); + break; + default: + break; + } + } catch (InvocationTargetException e) { + System.out.println(" Failed "); + e.getTargetException().printStackTrace(); } - - // } catch (IOException | ClassNotFoundException | NoSuchMethodException | - // InstantiationException | IllegalAccessException | - // InvocationTargetException - // e) { - // LOGGER.error("Unable to find rules for " + - // this.getClass().getSimpleName(), e); - // } - } catch (Exception e) { - LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); - } - } - - /** Initializes the view. Called by the invoker of the class */ - public abstract void initializeView(); - - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - public abstract Board generatePuzzle(int difficulty); - - /** - * Checks if the given height and width are valid board dimensions for the given puzzle - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @return true if the given dimensions are valid for the given puzzle, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows > 0 && columns > 0; - } - - /** - * Checks if the given array of statements is valid text input for the given puzzle - * - * @param statements - * @return - */ - public boolean isValidTextInput(String[] statements) { - return statements.length > 0; - } - - /** - * Determines if the edu.rpi.legup.puzzle was solves correctly - * - * @return true if the board was solved correctly, false otherwise - */ - public boolean isPuzzleComplete() { - if (tree == null) { - return false; + } } - - boolean isComplete = tree.isValid(); - if (isComplete) { - for (TreeElement leaf : tree.getLeafTreeElements()) { - if (leaf.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) leaf; - if (!node.isRoot()) { - isComplete &= - node.getParent().isContradictoryBranch() - || isBoardComplete(node.getBoard()); - } else { - isComplete &= isBoardComplete(node.getBoard()); - } - } else { - isComplete = false; - } + } + + // } catch (IOException | ClassNotFoundException | NoSuchMethodException | + // InstantiationException | IllegalAccessException | + // InvocationTargetException + // e) { + // LOGGER.error("Unable to find rules for " + + // this.getClass().getSimpleName(), e); + // } + } catch (Exception e) { + LOGGER.error("Unable to find elements for " + this.getClass().getSimpleName(), e); + } + } + + private void registerRules() { + String packageName = this.getClass().getPackage().toString().replace("package ", ""); + + try { + Class[] possRules = LegupUtils.getClasses(packageName); + + for (Class c : possRules) { + + System.out.println("possible rule: " + c.getName()); + + // check that the rule is not abstract + if (Modifier.isAbstract(c.getModifiers())) continue; + + for (Annotation a : c.getAnnotations()) { + if (a.annotationType() == RegisterRule.class) { + RegisterRule registerRule = (RegisterRule) a; + Constructor cons = c.getConstructor(); + try { + Rule rule = (Rule) cons.newInstance(); + + switch (rule.getRuleType()) { + case BASIC: + this.addDirectRule((DirectRule) rule); + break; + case CASE: + this.addCaseRule((CaseRule) rule); + break; + case CONTRADICTION: + this.addContradictionRule((ContradictionRule) rule); + break; + case MERGE: + break; + default: + break; + } + } catch (InvocationTargetException e) { + System.out.println(" Failed "); + e.getTargetException().printStackTrace(); } + } } - return isComplete; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - public abstract boolean isBoardComplete(Board board); - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - public abstract void onBoardChange(Board board); - - /** - * Imports the board using the file stream - * - * @param fileName the file that is imported - * @throws InvalidFileFormatException if file is invalid - */ - public void importPuzzle(String fileName) throws InvalidFileFormatException { - try { - importPuzzle(new FileInputStream(fileName)); - } catch (IOException e) { - LOGGER.error("Importing puzzle error", e); - throw new InvalidFileFormatException("Could not find file"); - } - } - - /** - * Imports the board using the file stream - * - * @param inputStream the file stream that is imported - * @throws InvalidFileFormatException if file stream is invalid - */ - public void importPuzzle(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Importing puzzle error", e); - throw new InvalidFileFormatException("Could not find file"); - } - - org.w3c.dom.Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - if (importer == null) { - throw new InvalidFileFormatException("Puzzle importer null"); - } - importer.initializePuzzle(node); + } + + // } catch (IOException | ClassNotFoundException | NoSuchMethodException | + // InstantiationException | IllegalAccessException | + // InvocationTargetException + // e) { + // LOGGER.error("Unable to find rules for " + + // this.getClass().getSimpleName(), e); + // } + } catch (Exception e) { + LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); + } + } + + /** Initializes the view. Called by the invoker of the class */ + public abstract void initializeView(); + + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + public abstract Board generatePuzzle(int difficulty); + + /** + * Checks if the given height and width are valid board dimensions for the given puzzle + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @return true if the given dimensions are valid for the given puzzle, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows > 0 && columns > 0; + } + + /** + * Checks if the given array of statements is valid text input for the given puzzle + * + * @param statements + * @return + */ + public boolean isValidTextInput(String[] statements) { + return statements.length > 0; + } + + /** + * Determines if the edu.rpi.legup.puzzle was solves correctly + * + * @return true if the board was solved correctly, false otherwise + */ + public boolean isPuzzleComplete() { + if (tree == null) { + return false; + } + + boolean isComplete = tree.isValid(); + if (isComplete) { + for (TreeElement leaf : tree.getLeafTreeElements()) { + if (leaf.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) leaf; + if (!node.isRoot()) { + isComplete &= + node.getParent().isContradictoryBranch() || isBoardComplete(node.getBoard()); + } else { + isComplete &= isBoardComplete(node.getBoard()); + } } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); + isComplete = false; } - } - - /** - * Gets the edu.rpi.legup.puzzle importer for importing edu.rpi.legup.puzzle files - * - * @return edu.rpi.legup.puzzle importer - */ - public PuzzleImporter getImporter() { - return importer; - } - - /** - * Gets the edu.rpi.legup.puzzle exporter for exporting edu.rpi.legup.puzzle files - * - * @return edu.rpi.legup.puzzle exporter - */ - public PuzzleExporter getExporter() { - return exporter; - } - - /** - * Gets the name of the edu.rpi.legup.puzzle - * - * @return name of the edu.rpi.legup.puzzle - */ - public String getName() { - return name; - } - - /** - * Gets the list of direct rules - * - * @return list of basic rules - */ - public List getDirectRules() { - return directRules; - } - - public List getPlaceableElements() { - return placeableElements; - } - - public List getNonPlaceableElements() { - return nonPlaceableElements; - } - - /** - * Sets the list of direct rules - * - * @param directRules list of basic rules - */ - public void setDirectRules(List directRules) { - this.directRules = directRules; - } - - /** - * Adds a basic rule to this Puzzle - * - * @param rule basic rule to add - */ - public void addDirectRule(DirectRule rule) { - directRules.add(rule); - } - - public void addPlaceableElement(PlaceableElement element) { - placeableElements.add(element); - } - - public void addNonPlaceableElement(NonPlaceableElement element) { - nonPlaceableElements.add(element); - } - - /** - * Remove a basic rule from this Puzzle - * - * @param rule basic rule to remove - */ - public void removeDirectRule(DirectRule rule) { - directRules.remove(rule); - } - - /** - * Gets the list of contradiction rules - * - * @return list of contradiction rules - */ - public List getContradictionRules() { - return contradictionRules; - } - - /** - * Sets the list of contradiction rules - * - * @param contradictionRules list of contradiction rules - */ - public void setContradictionRules(List contradictionRules) { - this.contradictionRules = contradictionRules; - } - - /** - * Adds a contradiction rule to this Puzzle - * - * @param rule contradiction rule to add - */ - public void addContradictionRule(ContradictionRule rule) { - contradictionRules.add(rule); - } - - /** - * Remove a contradiction rule from this Puzzle - * - * @param rule contradiction rule to remove - */ - public void removeContradictionRule(ContradictionRule rule) { - contradictionRules.remove(rule); - } - - /** - * Gets the list of case rules - * - * @return list of case rules - */ - public List getCaseRules() { - return caseRules; - } - - /** - * Sets the list of case rules - * - * @param caseRules list of case rules - */ - public void setCaseRules(List caseRules) { - this.caseRules = caseRules; - } - - /** - * Adds a case rule to this Puzzle - * - * @param rule case rule to add - */ - public void addCaseRule(CaseRule rule) { - caseRules.add(rule); - } - - /** - * Removes a case rule from this Puzzle - * - * @param rule case rule to remove - */ - public void removeCaseRule(CaseRule rule) { - caseRules.remove(rule); - } - - /** - * Gets the rule using the specified name - * - * @param name name of the rule - * @return Rule - */ - public Rule getRuleByName(String name) { - for (Rule rule : directRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - for (Rule rule : contradictionRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - for (Rule rule : caseRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - Rule mergeRule = new MergeRule(); - if (mergeRule.getRuleName().equals(name)) { - return mergeRule; - } - return null; - } - - /** - * Gets the rule using the specified name - * - * @param id name of the rule - * @return Rule - */ - public Rule getRuleByID(String id) { - for (Rule rule : directRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - for (Rule rule : contradictionRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - for (Rule rule : caseRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - Rule mergeRule = new MergeRule(); - if (mergeRule.getRuleID().equals(id)) { - return mergeRule; - } - return null; - } - - /** - * Gets the current board - * - * @return current board - */ - public Board getCurrentBoard() { - return currentBoard; - } - - /** - * Sets the current board - * - * @param currentBoard the current board - */ - public void setCurrentBoard(Board currentBoard) { - this.currentBoard = currentBoard; - } - - /** - * Gets the Tree for keeping the board states - * - * @return Tree - */ - public Tree getTree() { - return tree; - } - - /** - * Sets the Tree for keeping the board states - * - * @param tree tree of board states - */ - public void setTree(Tree tree) { - this.tree = tree; - } - - /** - * Gets the board view that displays the board - * - * @return board view - */ - public BoardView getBoardView() { - return boardView; - } - - /** - * Sets the board view that displays the board - * - * @param boardView board view - */ - public void setBoardView(BoardView boardView) { - this.boardView = boardView; - } - - /** - * Gets the ElementFactory associated with this edu.rpi.legup.puzzle - * - * @return ElementFactory associated with this edu.rpi.legup.puzzle - */ - public ElementFactory getFactory() { - return factory; - } - - /** - * Sets the ElementFactory associated with this edu.rpi.legup.puzzle - * - * @param factory ElementFactory associated with this edu.rpi.legup.puzzle - */ - public void setFactory(ElementFactory factory) { - this.factory = factory; - } - - /** - * Adds a board listener - * - * @param listener listener to add - */ - @Override - public void addBoardListener(IBoardListener listener) { - boardListeners.add(listener); - } - - /** - * Removes a board listener - * - * @param listener listener to remove - */ - @Override - public void removeBoardListener(IBoardListener listener) { - boardListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyBoardListeners(Consumer algorithm) { - boardListeners.forEach(algorithm); - } - - /** - * Adds a board listener - * - * @param listener listener to add - */ - @Override - public void addTreeListener(ITreeListener listener) { - treeListeners.add(listener); - } - - /** - * Removes a tree listener - * - * @param listener listener to remove - */ - @Override - public void removeTreeListener(ITreeListener listener) { - treeListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyTreeListeners(Consumer algorithm) { - treeListeners.forEach(algorithm); - } - - /** - * Check if the puzzle is valid - * - * @return if the puzzle is valid - */ - public boolean checkValidity() { - return true; - } + } + } + return isComplete; + } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + public abstract boolean isBoardComplete(Board board); + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + public abstract void onBoardChange(Board board); + + /** + * Imports the board using the file stream + * + * @param fileName the file that is imported + * @throws InvalidFileFormatException if file is invalid + */ + public void importPuzzle(String fileName) throws InvalidFileFormatException { + try { + importPuzzle(new FileInputStream(fileName)); + } catch (IOException e) { + LOGGER.error("Importing puzzle error", e); + throw new InvalidFileFormatException("Could not find file"); + } + } + + /** + * Imports the board using the file stream + * + * @param inputStream the file stream that is imported + * @throws InvalidFileFormatException if file stream is invalid + */ + public void importPuzzle(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Importing puzzle error", e); + throw new InvalidFileFormatException("Could not find file"); + } + + org.w3c.dom.Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + if (importer == null) { + throw new InvalidFileFormatException("Puzzle importer null"); + } + importer.initializePuzzle(node); + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); + } + } + + /** + * Gets the edu.rpi.legup.puzzle importer for importing edu.rpi.legup.puzzle files + * + * @return edu.rpi.legup.puzzle importer + */ + public PuzzleImporter getImporter() { + return importer; + } + + /** + * Gets the edu.rpi.legup.puzzle exporter for exporting edu.rpi.legup.puzzle files + * + * @return edu.rpi.legup.puzzle exporter + */ + public PuzzleExporter getExporter() { + return exporter; + } + + /** + * Gets the name of the edu.rpi.legup.puzzle + * + * @return name of the edu.rpi.legup.puzzle + */ + public String getName() { + return name; + } + + /** + * Gets the list of direct rules + * + * @return list of basic rules + */ + public List getDirectRules() { + return directRules; + } + + public List getPlaceableElements() { + return placeableElements; + } + + public List getNonPlaceableElements() { + return nonPlaceableElements; + } + + /** + * Sets the list of direct rules + * + * @param directRules list of basic rules + */ + public void setDirectRules(List directRules) { + this.directRules = directRules; + } + + /** + * Adds a basic rule to this Puzzle + * + * @param rule basic rule to add + */ + public void addDirectRule(DirectRule rule) { + directRules.add(rule); + } + + public void addPlaceableElement(PlaceableElement element) { + placeableElements.add(element); + } + + public void addNonPlaceableElement(NonPlaceableElement element) { + nonPlaceableElements.add(element); + } + + /** + * Remove a basic rule from this Puzzle + * + * @param rule basic rule to remove + */ + public void removeDirectRule(DirectRule rule) { + directRules.remove(rule); + } + + /** + * Gets the list of contradiction rules + * + * @return list of contradiction rules + */ + public List getContradictionRules() { + return contradictionRules; + } + + /** + * Sets the list of contradiction rules + * + * @param contradictionRules list of contradiction rules + */ + public void setContradictionRules(List contradictionRules) { + this.contradictionRules = contradictionRules; + } + + /** + * Adds a contradiction rule to this Puzzle + * + * @param rule contradiction rule to add + */ + public void addContradictionRule(ContradictionRule rule) { + contradictionRules.add(rule); + } + + /** + * Remove a contradiction rule from this Puzzle + * + * @param rule contradiction rule to remove + */ + public void removeContradictionRule(ContradictionRule rule) { + contradictionRules.remove(rule); + } + + /** + * Gets the list of case rules + * + * @return list of case rules + */ + public List getCaseRules() { + return caseRules; + } + + /** + * Sets the list of case rules + * + * @param caseRules list of case rules + */ + public void setCaseRules(List caseRules) { + this.caseRules = caseRules; + } + + /** + * Adds a case rule to this Puzzle + * + * @param rule case rule to add + */ + public void addCaseRule(CaseRule rule) { + caseRules.add(rule); + } + + /** + * Removes a case rule from this Puzzle + * + * @param rule case rule to remove + */ + public void removeCaseRule(CaseRule rule) { + caseRules.remove(rule); + } + + /** + * Gets the rule using the specified name + * + * @param name name of the rule + * @return Rule + */ + public Rule getRuleByName(String name) { + for (Rule rule : directRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + for (Rule rule : contradictionRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + for (Rule rule : caseRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + Rule mergeRule = new MergeRule(); + if (mergeRule.getRuleName().equals(name)) { + return mergeRule; + } + return null; + } + + /** + * Gets the rule using the specified name + * + * @param id name of the rule + * @return Rule + */ + public Rule getRuleByID(String id) { + for (Rule rule : directRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + for (Rule rule : contradictionRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + for (Rule rule : caseRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + Rule mergeRule = new MergeRule(); + if (mergeRule.getRuleID().equals(id)) { + return mergeRule; + } + return null; + } + + /** + * Gets the current board + * + * @return current board + */ + public Board getCurrentBoard() { + return currentBoard; + } + + /** + * Sets the current board + * + * @param currentBoard the current board + */ + public void setCurrentBoard(Board currentBoard) { + this.currentBoard = currentBoard; + } + + /** + * Gets the Tree for keeping the board states + * + * @return Tree + */ + public Tree getTree() { + return tree; + } + + /** + * Sets the Tree for keeping the board states + * + * @param tree tree of board states + */ + public void setTree(Tree tree) { + this.tree = tree; + } + + /** + * Gets the board view that displays the board + * + * @return board view + */ + public BoardView getBoardView() { + return boardView; + } + + /** + * Sets the board view that displays the board + * + * @param boardView board view + */ + public void setBoardView(BoardView boardView) { + this.boardView = boardView; + } + + /** + * Gets the ElementFactory associated with this edu.rpi.legup.puzzle + * + * @return ElementFactory associated with this edu.rpi.legup.puzzle + */ + public ElementFactory getFactory() { + return factory; + } + + /** + * Sets the ElementFactory associated with this edu.rpi.legup.puzzle + * + * @param factory ElementFactory associated with this edu.rpi.legup.puzzle + */ + public void setFactory(ElementFactory factory) { + this.factory = factory; + } + + /** + * Adds a board listener + * + * @param listener listener to add + */ + @Override + public void addBoardListener(IBoardListener listener) { + boardListeners.add(listener); + } + + /** + * Removes a board listener + * + * @param listener listener to remove + */ + @Override + public void removeBoardListener(IBoardListener listener) { + boardListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyBoardListeners(Consumer algorithm) { + boardListeners.forEach(algorithm); + } + + /** + * Adds a board listener + * + * @param listener listener to add + */ + @Override + public void addTreeListener(ITreeListener listener) { + treeListeners.add(listener); + } + + /** + * Removes a tree listener + * + * @param listener listener to remove + */ + @Override + public void removeTreeListener(ITreeListener listener) { + treeListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyTreeListeners(Consumer algorithm) { + treeListeners.forEach(algorithm); + } + + /** + * Check if the puzzle is valid + * + * @return if the puzzle is valid + */ + public boolean checkValidity() { + return true; + } } diff --git a/src/main/java/edu/rpi/legup/model/PuzzleExporter.java b/src/main/java/edu/rpi/legup/model/PuzzleExporter.java index a052a736a..cccf0155c 100644 --- a/src/main/java/edu/rpi/legup/model/PuzzleExporter.java +++ b/src/main/java/edu/rpi/legup/model/PuzzleExporter.java @@ -21,126 +21,125 @@ import org.w3c.dom.Element; public abstract class PuzzleExporter { - private static final Logger LOGGER = LogManager.getLogger(PuzzleExporter.class.getName()); - - protected Puzzle puzzle; - - /** - * PuzzleExporter Constructor exports the puzzle object to a file - * - * @param puzzle puzzle that is to be exported - */ - public PuzzleExporter(Puzzle puzzle) { - this.puzzle = puzzle; + private static final Logger LOGGER = LogManager.getLogger(PuzzleExporter.class.getName()); + + protected Puzzle puzzle; + + /** + * PuzzleExporter Constructor exports the puzzle object to a file + * + * @param puzzle puzzle that is to be exported + */ + public PuzzleExporter(Puzzle puzzle) { + this.puzzle = puzzle; + } + + /** + * Exports the puzzle to an xml formatted file + * + * @param fileName name of file to be exported + * @throws ExportFileException if puzzle can not be exported + */ + public void exportPuzzle(String fileName) throws ExportFileException { + try { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + Document newDocument = docBuilder.newDocument(); + + org.w3c.dom.Element legupElement = newDocument.createElement("Legup"); + legupElement.setAttribute("version", "3.0.0"); + newDocument.appendChild(legupElement); + + org.w3c.dom.Element timeSavedElement = newDocument.createElement("saved"); + legupElement.appendChild(timeSavedElement); + + org.w3c.dom.Element puzzleElement = newDocument.createElement("puzzle"); + puzzleElement.setAttribute("name", puzzle.getName()); + legupElement.appendChild(puzzleElement); + + puzzleElement.appendChild(createBoardElement(newDocument)); + if (puzzle.getTree() != null && !puzzle.getTree().getRootNode().getChildren().isEmpty()) { + puzzleElement.appendChild(createProofElement(newDocument)); + } + + org.w3c.dom.Element statusElement = newDocument.createElement("solved"); + String isSolved = "false"; + if (puzzle.isPuzzleComplete()) { + isSolved = "true"; + } + statusElement.setAttribute("isSolved", isSolved); + LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/New_York")); + String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + statusElement.setAttribute("lastSaved", time); + legupElement.appendChild(statusElement); + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + + DOMSource source = new DOMSource(newDocument); + StreamResult result = new StreamResult(new File(fileName)); + + transformer.transform(source, result); + } catch (ParserConfigurationException | TransformerException e) { + throw new ExportFileException("Puzzle Exporter: parser configuration exception"); + } catch (Exception e) { + throw e; + // throw new ExportFileException(e.getMessage()); } - - /** - * Exports the puzzle to an xml formatted file - * - * @param fileName name of file to be exported - * @throws ExportFileException if puzzle can not be exported - */ - public void exportPuzzle(String fileName) throws ExportFileException { - try { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document newDocument = docBuilder.newDocument(); - - org.w3c.dom.Element legupElement = newDocument.createElement("Legup"); - legupElement.setAttribute("version", "3.0.0"); - newDocument.appendChild(legupElement); - - org.w3c.dom.Element timeSavedElement = newDocument.createElement("saved"); - legupElement.appendChild(timeSavedElement); - - org.w3c.dom.Element puzzleElement = newDocument.createElement("puzzle"); - puzzleElement.setAttribute("name", puzzle.getName()); - legupElement.appendChild(puzzleElement); - - puzzleElement.appendChild(createBoardElement(newDocument)); - if (puzzle.getTree() != null - && !puzzle.getTree().getRootNode().getChildren().isEmpty()) { - puzzleElement.appendChild(createProofElement(newDocument)); - } - - org.w3c.dom.Element statusElement = newDocument.createElement("solved"); - String isSolved = "false"; - if (puzzle.isPuzzleComplete()) { - isSolved = "true"; - } - statusElement.setAttribute("isSolved", isSolved); - LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/New_York")); - String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - statusElement.setAttribute("lastSaved", time); - legupElement.appendChild(statusElement); - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - DOMSource source = new DOMSource(newDocument); - StreamResult result = new StreamResult(new File(fileName)); - - transformer.transform(source, result); - } catch (ParserConfigurationException | TransformerException e) { - throw new ExportFileException("Puzzle Exporter: parser configuration exception"); - } catch (Exception e) { - throw e; - // throw new ExportFileException(e.getMessage()); + } + + protected abstract Element createBoardElement(Document newDocument); + + protected Element createProofElement(Document newDocument) { + org.w3c.dom.Element proofElement = newDocument.createElement("proof"); + org.w3c.dom.Element treeElement = createTreeElement(newDocument); + proofElement.appendChild(treeElement); + return proofElement; + } + + protected Element createTreeElement(Document newDocument) { + org.w3c.dom.Element treeElement = newDocument.createElement("tree"); + + Set visited = new HashSet<>(); + List nodes = new ArrayList<>(); + nodes.add(puzzle.getTree().getRootNode()); + while (!nodes.isEmpty()) { + TreeNode treeNode = nodes.get(nodes.size() - 1); + nodes.remove(treeNode); + if (!visited.contains(treeNode)) { + visited.add(treeNode); + + org.w3c.dom.Element nodeElement = newDocument.createElement("node"); + nodeElement.setAttribute("id", String.valueOf(treeNode.hashCode())); + if (treeNode.isRoot()) { + nodeElement.setAttribute("root", "true"); } - } - - protected abstract Element createBoardElement(Document newDocument); - - protected Element createProofElement(Document newDocument) { - org.w3c.dom.Element proofElement = newDocument.createElement("proof"); - org.w3c.dom.Element treeElement = createTreeElement(newDocument); - proofElement.appendChild(treeElement); - return proofElement; - } - protected Element createTreeElement(Document newDocument) { - org.w3c.dom.Element treeElement = newDocument.createElement("tree"); - - Set visited = new HashSet<>(); - List nodes = new ArrayList<>(); - nodes.add(puzzle.getTree().getRootNode()); - while (!nodes.isEmpty()) { - TreeNode treeNode = nodes.get(nodes.size() - 1); - nodes.remove(treeNode); - if (!visited.contains(treeNode)) { - visited.add(treeNode); - - org.w3c.dom.Element nodeElement = newDocument.createElement("node"); - nodeElement.setAttribute("id", String.valueOf(treeNode.hashCode())); - if (treeNode.isRoot()) { - nodeElement.setAttribute("root", "true"); - } - - for (TreeTransition transition : treeNode.getChildren()) { - org.w3c.dom.Element transElement = newDocument.createElement("transition"); - transElement.setAttribute("id", String.valueOf(transition.hashCode())); - - TreeNode child = transition.getChildNode(); - if (child != null) { - transElement.setAttribute("child", String.valueOf(child.hashCode())); - nodes.add(child); - } - - if (transition.isJustified()) { - transElement.setAttribute("rule", transition.getRule().getRuleName()); - transElement.setAttribute("rule_id", transition.getRule().getRuleID()); - } - - for (PuzzleElement data : transition.getBoard().getModifiedData()) { - transElement.appendChild(puzzle.getFactory().exportCell(newDocument, data)); - } - nodeElement.appendChild(transElement); - } - treeElement.appendChild(nodeElement); - } + for (TreeTransition transition : treeNode.getChildren()) { + org.w3c.dom.Element transElement = newDocument.createElement("transition"); + transElement.setAttribute("id", String.valueOf(transition.hashCode())); + + TreeNode child = transition.getChildNode(); + if (child != null) { + transElement.setAttribute("child", String.valueOf(child.hashCode())); + nodes.add(child); + } + + if (transition.isJustified()) { + transElement.setAttribute("rule", transition.getRule().getRuleName()); + transElement.setAttribute("rule_id", transition.getRule().getRuleID()); + } + + for (PuzzleElement data : transition.getBoard().getModifiedData()) { + transElement.appendChild(puzzle.getFactory().exportCell(newDocument, data)); + } + nodeElement.appendChild(transElement); } - return treeElement; + treeElement.appendChild(nodeElement); + } } + return treeElement; + } } diff --git a/src/main/java/edu/rpi/legup/model/PuzzleImporter.java b/src/main/java/edu/rpi/legup/model/PuzzleImporter.java index 0cc163200..77332278b 100644 --- a/src/main/java/edu/rpi/legup/model/PuzzleImporter.java +++ b/src/main/java/edu/rpi/legup/model/PuzzleImporter.java @@ -14,402 +14,399 @@ import org.w3c.dom.NodeList; public abstract class PuzzleImporter { - private static final Logger LOGGER = LogManager.getLogger(PuzzleImporter.class.getName()); - - protected Puzzle puzzle; - - /** - * PuzzleImporter Constructor creates the puzzle object - * - * @param puzzle puzzle that is imported - */ - public PuzzleImporter(Puzzle puzzle) { - this.puzzle = puzzle; + private static final Logger LOGGER = LogManager.getLogger(PuzzleImporter.class.getName()); + + protected Puzzle puzzle; + + /** + * PuzzleImporter Constructor creates the puzzle object + * + * @param puzzle puzzle that is imported + */ + public PuzzleImporter(Puzzle puzzle) { + this.puzzle = puzzle; + } + + public abstract boolean acceptsRowsAndColumnsInput(); + + public abstract boolean acceptsTextInput(); + + /** + * Initializes an empty puzzle + * + * @param rows number of rows on the puzzle + * @param columns number of columns on the puzzle + * @throws RuntimeException if puzzle can not be made + */ + public void initializePuzzle(int rows, int columns) throws RuntimeException { + if (this.puzzle.isValidDimensions(rows, columns)) { + initializeBoard(rows, columns); + } else { + throw new IllegalArgumentException("Invalid dimensions provided"); } - - public abstract boolean acceptsRowsAndColumnsInput(); - - public abstract boolean acceptsTextInput(); - - /** - * Initializes an empty puzzle - * - * @param rows number of rows on the puzzle - * @param columns number of columns on the puzzle - * @throws RuntimeException if puzzle can not be made - */ - public void initializePuzzle(int rows, int columns) throws RuntimeException { - if (this.puzzle.isValidDimensions(rows, columns)) { - initializeBoard(rows, columns); + } + + public void initializePuzzle(String[] statements) + throws InputMismatchException, IllegalArgumentException { + // Note: Error checking for the statements will be left up to the puzzles that support + // text input. For example, some puzzles may be okay with "blank" statements (Strings with + // length = 0) while others may not. + initializeBoard(statements); + } + + /** + * Initializes the puzzle attributes + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public void initializePuzzle(Node node) throws InvalidFileFormatException { + if (node.getNodeName().equalsIgnoreCase("puzzle")) { + org.w3c.dom.Element puzzleElement = (org.w3c.dom.Element) node; + + boolean initBoard = false; + boolean initProof = false; + NodeList childNodes = puzzleElement.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node n = childNodes.item(i); + if (n.getNodeName().equalsIgnoreCase("board")) { + if (initBoard) { + throw new InvalidFileFormatException( + "Puzzle creation error: duplicate board puzzleElement found"); + } + initializeBoard(n); + initBoard = true; } else { - throw new IllegalArgumentException("Invalid dimensions provided"); - } - } - - public void initializePuzzle(String[] statements) - throws InputMismatchException, IllegalArgumentException { - // Note: Error checking for the statements will be left up to the puzzles that support - // text input. For example, some puzzles may be okay with "blank" statements (Strings with - // length = 0) while others may not. - initializeBoard(statements); - } - - /** - * Initializes the puzzle attributes - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public void initializePuzzle(Node node) throws InvalidFileFormatException { - if (node.getNodeName().equalsIgnoreCase("puzzle")) { - org.w3c.dom.Element puzzleElement = (org.w3c.dom.Element) node; - - boolean initBoard = false; - boolean initProof = false; - NodeList childNodes = puzzleElement.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - Node n = childNodes.item(i); - if (n.getNodeName().equalsIgnoreCase("board")) { - if (initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: duplicate board puzzleElement found"); - } - initializeBoard(n); - initBoard = true; - } else { - if (n.getNodeName().equalsIgnoreCase("proof")) { - if (initProof) { - throw new InvalidFileFormatException( - "Puzzle creation error: duplicate proof puzzleElement found"); - } - if (!initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: could not find board puzzleElement"); - } - initializeProof(n); - initProof = true; - } else { - if (!n.getNodeName().equalsIgnoreCase("#text")) { - throw new InvalidFileFormatException( - "Puzzle creation error: unknown node found in file"); - } - } - } + if (n.getNodeName().equalsIgnoreCase("proof")) { + if (initProof) { + throw new InvalidFileFormatException( + "Puzzle creation error: duplicate proof puzzleElement found"); } - if (!initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: could not find board puzzleElement"); + throw new InvalidFileFormatException( + "Puzzle creation error: could not find board puzzleElement"); } - if (!initProof) { - createDefaultTree(); + initializeProof(n); + initProof = true; + } else { + if (!n.getNodeName().equalsIgnoreCase("#text")) { + throw new InvalidFileFormatException( + "Puzzle creation error: unknown node found in file"); } - } else { - throw new InvalidFileFormatException( - "Invalid file format; does not contain \"puzzle\" node"); + } } + } + + if (!initBoard) { + throw new InvalidFileFormatException( + "Puzzle creation error: could not find board puzzleElement"); + } + if (!initProof) { + createDefaultTree(); + } + } else { + throw new InvalidFileFormatException("Invalid file format; does not contain \"puzzle\" node"); } - - /** - * Creates the board for building - * - * @param rows number of rows on the puzzle - * @param columns number of columns on the puzzle - * @throws RuntimeException if board can not be created - */ - public abstract void initializeBoard(int rows, int columns); - - /** - * Creates an empty board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public abstract void initializeBoard(Node node) throws InvalidFileFormatException; - - public abstract void initializeBoard(String[] statements) - throws UnsupportedOperationException, IllegalArgumentException; - - /** - * Creates the proof for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public void initializeProof(Node node) throws InvalidFileFormatException { - if (node.getNodeName().equalsIgnoreCase("proof")) { - org.w3c.dom.Element proofElement = (org.w3c.dom.Element) node; - NodeList treeList = proofElement.getElementsByTagName("tree"); - - boolean initTree = false; - for (int i = 0; i < treeList.getLength(); i++) { - Node n = treeList.item(i); - if (n.getNodeName().equalsIgnoreCase("tree")) { - if (initTree) { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate tree puzzleElement"); - } - createTree(n); - initTree = true; - } else { - throw new InvalidFileFormatException( - "Proof Tree construction error: unknown puzzleElement found"); - } - } - if (!initTree) { - createDefaultTree(); - } - } else { + } + + /** + * Creates the board for building + * + * @param rows number of rows on the puzzle + * @param columns number of columns on the puzzle + * @throws RuntimeException if board can not be created + */ + public abstract void initializeBoard(int rows, int columns); + + /** + * Creates an empty board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public abstract void initializeBoard(Node node) throws InvalidFileFormatException; + + public abstract void initializeBoard(String[] statements) + throws UnsupportedOperationException, IllegalArgumentException; + + /** + * Creates the proof for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public void initializeProof(Node node) throws InvalidFileFormatException { + if (node.getNodeName().equalsIgnoreCase("proof")) { + org.w3c.dom.Element proofElement = (org.w3c.dom.Element) node; + NodeList treeList = proofElement.getElementsByTagName("tree"); + + boolean initTree = false; + for (int i = 0; i < treeList.getLength(); i++) { + Node n = treeList.item(i); + if (n.getNodeName().equalsIgnoreCase("tree")) { + if (initTree) { throw new InvalidFileFormatException( - "Invalid file format; does not contain \"proof\" node"); + "Proof Tree construction error: duplicate tree puzzleElement"); + } + createTree(n); + initTree = true; + } else { + throw new InvalidFileFormatException( + "Proof Tree construction error: unknown puzzleElement found"); } + } + if (!initTree) { + createDefaultTree(); + } + } else { + throw new InvalidFileFormatException("Invalid file format; does not contain \"proof\" node"); } - - /** - * Sets the puzzleElement from the xml document node - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - protected void setCells(Node node) throws InvalidFileFormatException { - NodeList dataList = ((org.w3c.dom.Element) node).getElementsByTagName("cell"); - Board board = puzzle.getCurrentBoard(); - for (int i = 0; i < dataList.getLength(); i++) { - PuzzleElement data = - puzzle.getFactory().importCell(dataList.item(i), puzzle.getCurrentBoard()); - board.setPuzzleElement(data.getIndex(), data); + } + + /** + * Sets the puzzleElement from the xml document node + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + protected void setCells(Node node) throws InvalidFileFormatException { + NodeList dataList = ((org.w3c.dom.Element) node).getElementsByTagName("cell"); + Board board = puzzle.getCurrentBoard(); + for (int i = 0; i < dataList.getLength(); i++) { + PuzzleElement data = + puzzle.getFactory().importCell(dataList.item(i), puzzle.getCurrentBoard()); + board.setPuzzleElement(data.getIndex(), data); + } + } + + /** + * Creates the tree for the edu.rpi.legup.puzzle + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + protected void createTree(Node node) throws InvalidFileFormatException { + Element treeElement = (org.w3c.dom.Element) node; + + Tree tree = new Tree(); + puzzle.setTree(tree); + + NodeList nodeList = ((org.w3c.dom.Element) node).getElementsByTagName("node"); + + HashMap treeNodes = new HashMap<>(); + HashMap treeTransitions = new HashMap<>(); + HashMap nodeChanges = new HashMap<>(); + + for (int i = 0; i < nodeList.getLength(); i++) { + org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); + String nodeId = treeNodeElement.getAttribute("id"); + String isRoot = treeNodeElement.getAttribute("root"); + if (nodeId.isEmpty()) { + throw new InvalidFileFormatException("Proof Tree construction error: cannot find node ID"); + } + if (treeNodes.containsKey(nodeId)) { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate tree node ID found"); + } + TreeNode treeNode = new TreeNode(puzzle.getCurrentBoard().copy()); + if (isRoot.equalsIgnoreCase("true")) { + if (tree.getRootNode() != null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: multiple root nodes declared"); } + treeNode.setRoot(true); + tree.setRootNode(treeNode); + } + treeNodes.put(nodeId, treeNode); } - /** - * Creates the tree for the edu.rpi.legup.puzzle - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - protected void createTree(Node node) throws InvalidFileFormatException { - Element treeElement = (org.w3c.dom.Element) node; - - Tree tree = new Tree(); - puzzle.setTree(tree); - - NodeList nodeList = ((org.w3c.dom.Element) node).getElementsByTagName("node"); - - HashMap treeNodes = new HashMap<>(); - HashMap treeTransitions = new HashMap<>(); - HashMap nodeChanges = new HashMap<>(); - - for (int i = 0; i < nodeList.getLength(); i++) { - org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); - String nodeId = treeNodeElement.getAttribute("id"); - String isRoot = treeNodeElement.getAttribute("root"); - if (nodeId.isEmpty()) { - throw new InvalidFileFormatException( - "Proof Tree construction error: cannot find node ID"); - } - if (treeNodes.containsKey(nodeId)) { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate tree node ID found"); - } - TreeNode treeNode = new TreeNode(puzzle.getCurrentBoard().copy()); - if (isRoot.equalsIgnoreCase("true")) { - if (tree.getRootNode() != null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: multiple root nodes declared"); - } - treeNode.setRoot(true); - tree.setRootNode(treeNode); - } - treeNodes.put(nodeId, treeNode); + for (int i = 0; i < nodeList.getLength(); i++) { + org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); + String nodeId = treeNodeElement.getAttribute("id"); + TreeNode treeNode = treeNodes.get(nodeId); + + NodeList transList = treeNodeElement.getElementsByTagName("transition"); + for (int k = 0; k < transList.getLength(); k++) { + org.w3c.dom.Element trans = (org.w3c.dom.Element) transList.item(k); + String transId = trans.getAttribute("id"); + TreeTransition transition = treeTransitions.get(transId); + if (transition != null) { + if (transition.getRule() instanceof MergeRule) { + transition.addParent(treeNode); + treeNode.addChild(transition); + continue; + } else { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate transition ID found"); + } } - for (int i = 0; i < nodeList.getLength(); i++) { - org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); - String nodeId = treeNodeElement.getAttribute("id"); - TreeNode treeNode = treeNodes.get(nodeId); - - NodeList transList = treeNodeElement.getElementsByTagName("transition"); - for (int k = 0; k < transList.getLength(); k++) { - org.w3c.dom.Element trans = (org.w3c.dom.Element) transList.item(k); - String transId = trans.getAttribute("id"); - TreeTransition transition = treeTransitions.get(transId); - if (transition != null) { - if (transition.getRule() instanceof MergeRule) { - transition.addParent(treeNode); - treeNode.addChild(transition); - continue; - } else { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate transition ID found"); - } - } - - String childId = trans.getAttribute("child"); - String ruleName = trans.getAttribute("rule"); - String ruleId = trans.getAttribute("rule_id"); - - TreeNode child = treeNodes.get(childId); - - transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - - Rule rule; - if (!ruleName.isEmpty()) { - rule = puzzle.getRuleByID(ruleId); - if (rule == null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: could not find rule by ID"); - } - transition.setRule(rule); - } - - treeNode.addChild(transition); - if (child != null) { - child.setParent(transition); - transition.setChildNode(child); - } - - nodeChanges.put(transition, trans); - treeTransitions.put(transId, transition); - } + String childId = trans.getAttribute("child"); + String ruleName = trans.getAttribute("rule"); + String ruleId = trans.getAttribute("rule_id"); + + TreeNode child = treeNodes.get(childId); + + transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + + Rule rule; + if (!ruleName.isEmpty()) { + rule = puzzle.getRuleByID(ruleId); + if (rule == null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: could not find rule by ID"); + } + transition.setRule(rule); } - // validateTreeStructure(treeNodes, treeTransitions); - System.err.println("Tree Size: " + treeTransitions.size()); - for (Map.Entry entry : nodeChanges.entrySet()) { - makeTransitionChanges(entry.getKey(), entry.getValue()); + treeNode.addChild(transition); + if (child != null) { + child.setParent(transition); + transition.setChildNode(child); } + + nodeChanges.put(transition, trans); + treeTransitions.put(transId, transition); + } } - protected void validateTreeStructure( - HashMap nodes, HashMap transitions) - throws InvalidFileFormatException { - Tree tree = puzzle.getTree(); + // validateTreeStructure(treeNodes, treeTransitions); + System.err.println("Tree Size: " + treeTransitions.size()); + for (Map.Entry entry : nodeChanges.entrySet()) { + makeTransitionChanges(entry.getKey(), entry.getValue()); + } + } - if (tree == null) { - throw new InvalidFileFormatException("Proof Tree construction error: invalid tree"); - } + protected void validateTreeStructure( + HashMap nodes, HashMap transitions) + throws InvalidFileFormatException { + Tree tree = puzzle.getTree(); - HashMap connectedNodes = new HashMap<>(); - HashMap connectedTransitions = new HashMap<>(); + if (tree == null) { + throw new InvalidFileFormatException("Proof Tree construction error: invalid tree"); + } - for (TreeNode node : nodes.values()) { - connectedNodes.put(node, false); - } + HashMap connectedNodes = new HashMap<>(); + HashMap connectedTransitions = new HashMap<>(); - for (TreeTransition trans : transitions.values()) { - connectedTransitions.put(trans, false); - } + for (TreeNode node : nodes.values()) { + connectedNodes.put(node, false); + } - ArrayList treeElements = new ArrayList<>(); - treeElements.add(tree.getRootNode()); - while (!treeElements.isEmpty()) { - TreeElement element = treeElements.get(treeElements.size() - 1); - treeElements.remove(element); - if (element.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) element; - - if (connectedNodes.get(treeNode)) { - // for(TreeTransition trans : treeNode.getParents()) - // { - // if(!(trans.getRule() instanceof MergeRule)) - // { - // throw new InvalidFileFormatException("Proof Tree - // structure - // validation error: cyclic tree detected"); - // } - // } - } - connectedNodes.replace(treeNode, true); - - for (TreeTransition trans : treeNode.getChildren()) { - treeElements.add(trans); - } - } else { - TreeTransition treeTransition = (TreeTransition) element; - - if (connectedTransitions.get(treeTransition)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: cyclic tree detected"); - } - connectedTransitions.replace(treeTransition, true); - - if (treeTransition.getChildNode() != null) { - treeElements.add(treeTransition.getChildNode()); - } - } - } + for (TreeTransition trans : transitions.values()) { + connectedTransitions.put(trans, false); + } - for (TreeNode node : nodes.values()) { - if (!connectedNodes.get(node)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: disjoint node detected"); - } + ArrayList treeElements = new ArrayList<>(); + treeElements.add(tree.getRootNode()); + while (!treeElements.isEmpty()) { + TreeElement element = treeElements.get(treeElements.size() - 1); + treeElements.remove(element); + if (element.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) element; + + if (connectedNodes.get(treeNode)) { + // for(TreeTransition trans : treeNode.getParents()) + // { + // if(!(trans.getRule() instanceof MergeRule)) + // { + // throw new InvalidFileFormatException("Proof Tree + // structure + // validation error: cyclic tree detected"); + // } + // } } + connectedNodes.replace(treeNode, true); - for (TreeTransition trans : transitions.values()) { - if (!connectedTransitions.get(trans)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: disjoint transition detected"); - } + for (TreeTransition trans : treeNode.getChildren()) { + treeElements.add(trans); } - } + } else { + TreeTransition treeTransition = (TreeTransition) element; - protected void makeTransitionChanges(TreeTransition transition, Node transElement) - throws InvalidFileFormatException { - if (transition.getRule() instanceof MergeRule) { - List mergingNodes = transition.getParents(); - List mergingBoards = new ArrayList<>(); - mergingNodes.forEach(n -> mergingBoards.add(n.getBoard())); - - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: unable to find merge node"); - } - Board lcaBoard = lca.getBoard(); - - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + if (connectedTransitions.get(treeTransition)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: cyclic tree detected"); + } + connectedTransitions.replace(treeTransition, true); - transition.setBoard(mergedBoard); - TreeNode childNode = transition.getChildNode(); - if (childNode != null) { - childNode.setBoard(mergedBoard.copy()); - } - } else { - NodeList cellList = transElement.getChildNodes(); - for (int i = 0; i < cellList.getLength(); i++) { - Node node = cellList.item(i); - if (node.getNodeName().equalsIgnoreCase("cell")) { - Board board = transition.getBoard(); - PuzzleElement cell = puzzle.getFactory().importCell(node, board); - - board.setPuzzleElement(cell.getIndex(), cell); - board.addModifiedData(cell); - transition.propagateChange(cell); - } else { - if (!node.getNodeName().equalsIgnoreCase("#text")) { - throw new InvalidFileFormatException( - "Proof Tree construction error: unknown node in transition"); - } - } - } + if (treeTransition.getChildNode() != null) { + treeElements.add(treeTransition.getChildNode()); } + } } - protected void createDefaultTree() { - TreeNode root = new TreeNode(puzzle.getCurrentBoard()); - root.setRoot(true); - Tree tree = new Tree(); - tree.setRootNode(root); - puzzle.setTree(tree); + for (TreeNode node : nodes.values()) { + if (!connectedNodes.get(node)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: disjoint node detected"); + } } - /** - * Gets the result of building the Puzzle - * - * @return puzzle - */ - public Puzzle getPuzzle() { - return puzzle; + for (TreeTransition trans : transitions.values()) { + if (!connectedTransitions.get(trans)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: disjoint transition detected"); + } + } + } + + protected void makeTransitionChanges(TreeTransition transition, Node transElement) + throws InvalidFileFormatException { + if (transition.getRule() instanceof MergeRule) { + List mergingNodes = transition.getParents(); + List mergingBoards = new ArrayList<>(); + mergingNodes.forEach(n -> mergingBoards.add(n.getBoard())); + + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: unable to find merge node"); + } + Board lcaBoard = lca.getBoard(); + + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + transition.setBoard(mergedBoard); + TreeNode childNode = transition.getChildNode(); + if (childNode != null) { + childNode.setBoard(mergedBoard.copy()); + } + } else { + NodeList cellList = transElement.getChildNodes(); + for (int i = 0; i < cellList.getLength(); i++) { + Node node = cellList.item(i); + if (node.getNodeName().equalsIgnoreCase("cell")) { + Board board = transition.getBoard(); + PuzzleElement cell = puzzle.getFactory().importCell(node, board); + + board.setPuzzleElement(cell.getIndex(), cell); + board.addModifiedData(cell); + transition.propagateChange(cell); + } else { + if (!node.getNodeName().equalsIgnoreCase("#text")) { + throw new InvalidFileFormatException( + "Proof Tree construction error: unknown node in transition"); + } + } + } } + } + + protected void createDefaultTree() { + TreeNode root = new TreeNode(puzzle.getCurrentBoard()); + root.setRoot(true); + Tree tree = new Tree(); + tree.setRootNode(root); + puzzle.setTree(tree); + } + + /** + * Gets the result of building the Puzzle + * + * @return puzzle + */ + public Puzzle getPuzzle() { + return puzzle; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/Element.java b/src/main/java/edu/rpi/legup/model/elements/Element.java index 8b75d075d..5ad31782a 100644 --- a/src/main/java/edu/rpi/legup/model/elements/Element.java +++ b/src/main/java/edu/rpi/legup/model/elements/Element.java @@ -6,72 +6,71 @@ @RegisterElement public abstract class Element { - protected String elementID; - protected String elementName; - protected String description; + protected String elementID; + protected String elementName; + protected String description; - protected String imageName; - protected ImageIcon image; + protected String imageName; + protected ImageIcon image; - protected ElementType elementType; + protected ElementType elementType; - private final String INVALID_USE_MESSAGE; + private final String INVALID_USE_MESSAGE; - public Element(String elementID, String elementName, String description, String imageName) { - this.elementID = elementID; - this.elementName = elementName; - this.description = description; - this.imageName = imageName; - this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.elementName; - loadImage(); - } + public Element(String elementID, String elementName, String description, String imageName) { + this.elementID = elementID; + this.elementName = elementName; + this.description = description; + this.imageName = imageName; + this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.elementName; + loadImage(); + } - private void loadImage() { - if (imageName != null) { - this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(imageName)); - // Resize images to be 100px wide - Image image = this.image.getImage(); - if (this.image.getIconWidth() < 120) return; - int height = - (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); - if (height == 0) { - System.out.println("height is 0 error"); - System.out.println("height: " + this.image.getIconHeight()); - System.out.println("width: " + this.image.getIconWidth()); - return; - } - BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = bimage.createGraphics(); - g.drawImage(image, 0, 0, 100, height, null); - this.image = new ImageIcon(bimage); - } + private void loadImage() { + if (imageName != null) { + this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(imageName)); + // Resize images to be 100px wide + Image image = this.image.getImage(); + if (this.image.getIconWidth() < 120) return; + int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); + if (height == 0) { + System.out.println("height is 0 error"); + System.out.println("height: " + this.image.getIconHeight()); + System.out.println("width: " + this.image.getIconWidth()); + return; + } + BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = bimage.createGraphics(); + g.drawImage(image, 0, 0, 100, height, null); + this.image = new ImageIcon(bimage); } + } - public String getElementName() { - return elementName; - } + public String getElementName() { + return elementName; + } - public void setElementName(String elementName) { - this.elementName = elementName; - } + public void setElementName(String elementName) { + this.elementName = elementName; + } - public String getElementID() { - return elementID; - } + public String getElementID() { + return elementID; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public ImageIcon getImageIcon() { - return image; - } + public ImageIcon getImageIcon() { + return image; + } - public ElementType getElementType() { - return elementType; - } + public ElementType getElementType() { + return elementType; + } - public String getInvalidUseOfRuleMessage() { - return this.INVALID_USE_MESSAGE; - } + public String getInvalidUseOfRuleMessage() { + return this.INVALID_USE_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/ElementType.java b/src/main/java/edu/rpi/legup/model/elements/ElementType.java index dff4fe04f..1e32e6adf 100644 --- a/src/main/java/edu/rpi/legup/model/elements/ElementType.java +++ b/src/main/java/edu/rpi/legup/model/elements/ElementType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.model.elements; public enum ElementType { - PLACEABLE, - NONPLACEABLE + PLACEABLE, + NONPLACEABLE } diff --git a/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java b/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java index 4ab0ab509..94d14c4b5 100644 --- a/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java @@ -1,9 +1,9 @@ package edu.rpi.legup.model.elements; public abstract class NonPlaceableElement extends Element { - public NonPlaceableElement( - String elementID, String elementName, String description, String imageName) { - super(elementID, elementName, description, imageName); - this.elementType = ElementType.NONPLACEABLE; - } + public NonPlaceableElement( + String elementID, String elementName, String description, String imageName) { + super(elementID, elementName, description, imageName); + this.elementType = ElementType.NONPLACEABLE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java b/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java index 133658700..b79fbf407 100644 --- a/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java @@ -1,9 +1,9 @@ package edu.rpi.legup.model.elements; public abstract class PlaceableElement extends Element { - public PlaceableElement( - String elementID, String elementName, String description, String imageName) { - super(elementID, elementName, description, imageName); - this.elementType = ElementType.PLACEABLE; - } + public PlaceableElement( + String elementID, String elementName, String description, String imageName) { + super(elementID, elementName, description, imageName); + this.elementType = ElementType.PLACEABLE; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/Board.java b/src/main/java/edu/rpi/legup/model/gameboard/Board.java index d8bdf5199..453f698b4 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/Board.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/Board.java @@ -7,209 +7,209 @@ public abstract class Board { - protected List puzzleElements; - protected Set modifiedData; - protected boolean isModifiable; - - /** Board Constructor creates an empty board. */ - public Board() { - this.puzzleElements = new ArrayList<>(); - this.modifiedData = new HashSet<>(); - this.isModifiable = true; - } - - /** - * Board Constructor creates a board with null elements. - * - * @param size number of elements for the board - */ - public Board(int size) { - this(); - for (int i = 0; i < size; i++) { - puzzleElements.add(null); - } - } - - /** - * Gets a specific {@link PuzzleElement} on this board. - * - * @param puzzleElement equivalent puzzleElement - * @return equivalent puzzleElement on this board - */ - public PuzzleElement getPuzzleElement(PuzzleElement puzzleElement) { - int index = puzzleElement.getIndex(); - return index < puzzleElements.size() ? puzzleElements.get(index) : null; - } - - /** - * Sets a specific {@link PuzzleElement} on the board. - * - * @param index index of the puzzleElement - * @param puzzleElement new puzzleElement at the index - */ - public void setPuzzleElement(int index, PuzzleElement puzzleElement) { - if (index < puzzleElements.size()) { - puzzleElements.set(index, puzzleElement); - } - } - - /** - * Gets the number of elements on the board. - * - * @return number of elements on the board - */ - public int getElementCount() { - return puzzleElements.size(); - } - - /** - * Gets the {@link PuzzleElement} on the board. - * - * @return puzzle elements on the board - */ - public List getPuzzleElements() { - return puzzleElements; - } - - /** - * Sets the {@link PuzzleElement} on the board. - * - * @param puzzleElements elements on the board - */ - public void setPuzzleElements(List puzzleElements) { - this.puzzleElements = puzzleElements; - } - - /** - * Gets the modifiable attribute for the board. - * - * @return true if the board is modifiable, false otherwise - */ - public boolean isModifiable() { - return isModifiable; - } - - /** - * Sets the modifiable attribute for the board. - * - * @param isModifiable true if the board is modifiable, false otherwise - */ - public void setModifiable(boolean isModifiable) { - this.isModifiable = isModifiable; - } - - /** - * Gets whether any of {@link PuzzleElement} of this board has been modified by the user. - * - * @return true if the board has been modified, false otherwise - */ - public boolean isModified() { - return !modifiedData.isEmpty(); - } - - /** - * Gets the set of modified {@link PuzzleElement} of the board. - * - * @return set of modified puzzle element of the board - */ - public Set getModifiedData() { - return modifiedData; - } - - /** - * Adds a {@link PuzzleElement} that has been modified to the list. - * - * @param puzzleElement puzzleElement that has been modified - */ - public void addModifiedData(PuzzleElement puzzleElement) { - modifiedData.add(puzzleElement); - puzzleElement.setModified(true); - } - - /** - * Removes a {@link PuzzleElement} that is no longer modified. - * - * @param data puzzleElement that is no longer modified - */ - public void removeModifiedData(PuzzleElement data) { - modifiedData.remove(data); - data.setModified(false); - } - - /** - * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent - * puzzle element with the new data. - * - * @param puzzleElement equivalent puzzle element with the new data. - */ - @SuppressWarnings("unchecked") - public void notifyChange(PuzzleElement puzzleElement) { - puzzleElements.set(puzzleElement.getIndex(), puzzleElement); - } - - /** - * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle - * element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - public void notifyAddition(PuzzleElement puzzleElement) {} - - /** - * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle - * element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - public void notifyDeletion(PuzzleElement puzzleElement) {} - - @SuppressWarnings("unchecked") - public Board mergedBoard(Board lca, List boards) { - if (lca == null || boards.isEmpty()) { - return null; - } - - Board mergedBoard = lca.copy(); - - Board firstBoard = boards.get(0); - for (PuzzleElement lcaData : lca.getPuzzleElements()) { - PuzzleElement mData = firstBoard.getPuzzleElement(lcaData); - - boolean isSame = true; - for (Board board : boards) { - isSame &= mData.equalsData(board.getPuzzleElement(lcaData)); - } - - if (isSame && !lcaData.equalsData(mData)) { - PuzzleElement mergedData = mergedBoard.getPuzzleElement(lcaData); - mergedData.setData(mData.getData()); - mergedBoard.addModifiedData(mergedData); - } - } - - return mergedBoard; - } - - /** - * Determines if this board contains the equivalent puzzle elements as the one specified - * - * @param board board to check equivalence - * @return true if the boards are equivalent, false otherwise - */ - @SuppressWarnings("unchecked") - public boolean equalsBoard(Board board) { - for (PuzzleElement element : puzzleElements) { - if (!element.equalsData(board.getPuzzleElement(element))) { - return false; - } - } - return true; - } - - /** - * Performs a deep copy of this board. - * - * @return a new copy of the board that is independent of this one - */ - public abstract Board copy(); + protected List puzzleElements; + protected Set modifiedData; + protected boolean isModifiable; + + /** Board Constructor creates an empty board. */ + public Board() { + this.puzzleElements = new ArrayList<>(); + this.modifiedData = new HashSet<>(); + this.isModifiable = true; + } + + /** + * Board Constructor creates a board with null elements. + * + * @param size number of elements for the board + */ + public Board(int size) { + this(); + for (int i = 0; i < size; i++) { + puzzleElements.add(null); + } + } + + /** + * Gets a specific {@link PuzzleElement} on this board. + * + * @param puzzleElement equivalent puzzleElement + * @return equivalent puzzleElement on this board + */ + public PuzzleElement getPuzzleElement(PuzzleElement puzzleElement) { + int index = puzzleElement.getIndex(); + return index < puzzleElements.size() ? puzzleElements.get(index) : null; + } + + /** + * Sets a specific {@link PuzzleElement} on the board. + * + * @param index index of the puzzleElement + * @param puzzleElement new puzzleElement at the index + */ + public void setPuzzleElement(int index, PuzzleElement puzzleElement) { + if (index < puzzleElements.size()) { + puzzleElements.set(index, puzzleElement); + } + } + + /** + * Gets the number of elements on the board. + * + * @return number of elements on the board + */ + public int getElementCount() { + return puzzleElements.size(); + } + + /** + * Gets the {@link PuzzleElement} on the board. + * + * @return puzzle elements on the board + */ + public List getPuzzleElements() { + return puzzleElements; + } + + /** + * Sets the {@link PuzzleElement} on the board. + * + * @param puzzleElements elements on the board + */ + public void setPuzzleElements(List puzzleElements) { + this.puzzleElements = puzzleElements; + } + + /** + * Gets the modifiable attribute for the board. + * + * @return true if the board is modifiable, false otherwise + */ + public boolean isModifiable() { + return isModifiable; + } + + /** + * Sets the modifiable attribute for the board. + * + * @param isModifiable true if the board is modifiable, false otherwise + */ + public void setModifiable(boolean isModifiable) { + this.isModifiable = isModifiable; + } + + /** + * Gets whether any of {@link PuzzleElement} of this board has been modified by the user. + * + * @return true if the board has been modified, false otherwise + */ + public boolean isModified() { + return !modifiedData.isEmpty(); + } + + /** + * Gets the set of modified {@link PuzzleElement} of the board. + * + * @return set of modified puzzle element of the board + */ + public Set getModifiedData() { + return modifiedData; + } + + /** + * Adds a {@link PuzzleElement} that has been modified to the list. + * + * @param puzzleElement puzzleElement that has been modified + */ + public void addModifiedData(PuzzleElement puzzleElement) { + modifiedData.add(puzzleElement); + puzzleElement.setModified(true); + } + + /** + * Removes a {@link PuzzleElement} that is no longer modified. + * + * @param data puzzleElement that is no longer modified + */ + public void removeModifiedData(PuzzleElement data) { + modifiedData.remove(data); + data.setModified(false); + } + + /** + * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent + * puzzle element with the new data. + * + * @param puzzleElement equivalent puzzle element with the new data. + */ + @SuppressWarnings("unchecked") + public void notifyChange(PuzzleElement puzzleElement) { + puzzleElements.set(puzzleElement.getIndex(), puzzleElement); + } + + /** + * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element + * with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + public void notifyAddition(PuzzleElement puzzleElement) {} + + /** + * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + public void notifyDeletion(PuzzleElement puzzleElement) {} + + @SuppressWarnings("unchecked") + public Board mergedBoard(Board lca, List boards) { + if (lca == null || boards.isEmpty()) { + return null; + } + + Board mergedBoard = lca.copy(); + + Board firstBoard = boards.get(0); + for (PuzzleElement lcaData : lca.getPuzzleElements()) { + PuzzleElement mData = firstBoard.getPuzzleElement(lcaData); + + boolean isSame = true; + for (Board board : boards) { + isSame &= mData.equalsData(board.getPuzzleElement(lcaData)); + } + + if (isSame && !lcaData.equalsData(mData)) { + PuzzleElement mergedData = mergedBoard.getPuzzleElement(lcaData); + mergedData.setData(mData.getData()); + mergedBoard.addModifiedData(mergedData); + } + } + + return mergedBoard; + } + + /** + * Determines if this board contains the equivalent puzzle elements as the one specified + * + * @param board board to check equivalence + * @return true if the boards are equivalent, false otherwise + */ + @SuppressWarnings("unchecked") + public boolean equalsBoard(Board board) { + for (PuzzleElement element : puzzleElements) { + if (!element.equalsData(board.getPuzzleElement(element))) { + return false; + } + } + return true; + } + + /** + * Performs a deep copy of this board. + * + * @return a new copy of the board that is independent of this one + */ + public abstract Board copy(); } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java b/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java index fa3625a43..93176b941 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java @@ -6,49 +6,49 @@ import java.util.Set; public class CaseBoard extends Board { - protected Board baseBoard; - protected CaseRule caseRule; - protected Set pickablePuzzleElements; - - public CaseBoard(Board baseBoard, CaseRule caseRule) { - this.baseBoard = baseBoard; - this.caseRule = caseRule; - this.pickablePuzzleElements = new HashSet<>(); - } - - public void addPickableElement(PuzzleElement puzzleElement) { - pickablePuzzleElements.add(puzzleElement); - } - - public void removePickableElement(PuzzleElement puzzleElement) { - pickablePuzzleElements.remove(puzzleElement); - } - - public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { - return pickablePuzzleElements.contains(baseBoard.getPuzzleElement(puzzleElement)); - } - - public Board getBaseBoard() { - return baseBoard; - } - - public void setBaseBoard(Board baseBoard) { - this.baseBoard = baseBoard; - } - - public CaseRule getCaseRule() { - return caseRule; - } - - public void setCaseRule(CaseRule caseRule) { - this.caseRule = caseRule; - } - - public int getCount() { - return pickablePuzzleElements.size(); - } - - public CaseBoard copy() { - return null; - } + protected Board baseBoard; + protected CaseRule caseRule; + protected Set pickablePuzzleElements; + + public CaseBoard(Board baseBoard, CaseRule caseRule) { + this.baseBoard = baseBoard; + this.caseRule = caseRule; + this.pickablePuzzleElements = new HashSet<>(); + } + + public void addPickableElement(PuzzleElement puzzleElement) { + pickablePuzzleElements.add(puzzleElement); + } + + public void removePickableElement(PuzzleElement puzzleElement) { + pickablePuzzleElements.remove(puzzleElement); + } + + public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { + return pickablePuzzleElements.contains(baseBoard.getPuzzleElement(puzzleElement)); + } + + public Board getBaseBoard() { + return baseBoard; + } + + public void setBaseBoard(Board baseBoard) { + this.baseBoard = baseBoard; + } + + public CaseRule getCaseRule() { + return caseRule; + } + + public void setCaseRule(CaseRule caseRule) { + this.caseRule = caseRule; + } + + public int getCount() { + return pickablePuzzleElements.size(); + } + + public CaseBoard copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java b/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java index bfc785bdd..f0ea22dbe 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java @@ -7,24 +7,24 @@ public abstract class ElementFactory { - /** - * Creates a {@link PuzzleElement} based on the xml document Node and adds it to the board. - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException thrown if the xml node is invalid for the specific puzzle - * element - */ - public abstract PuzzleElement importCell(Node node, Board board) - throws InvalidFileFormatException; + /** + * Creates a {@link PuzzleElement} based on the xml document Node and adds it to the board. + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException thrown if the xml node is invalid for the specific puzzle + * element + */ + public abstract PuzzleElement importCell(Node node, Board board) + throws InvalidFileFormatException; - /** - * Creates a xml document {@link PuzzleElement} from a cell for exporting. - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public abstract Element exportCell(Document document, PuzzleElement puzzleElement); + /** + * Creates a xml document {@link PuzzleElement} from a cell for exporting. + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public abstract Element exportCell(Document document, PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java b/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java index 9593690ce..1cb7e564a 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java @@ -8,162 +8,161 @@ public class GridBoard extends Board { - protected Dimension dimension; + protected Dimension dimension; - /** - * GridBoard Constructor creates a board for grid using puzzles from a width and height. - * - * @param width width of the board - * @param height height of the board - */ - public GridBoard(int width, int height) { - this.dimension = new Dimension(width, height); + /** + * GridBoard Constructor creates a board for grid using puzzles from a width and height. + * + * @param width width of the board + * @param height height of the board + */ + public GridBoard(int width, int height) { + this.dimension = new Dimension(width, height); - for (int i = 0; i < width * height; i++) { - puzzleElements.add(null); - } + for (int i = 0; i < width * height; i++) { + puzzleElements.add(null); } + } - /** - * GridBoard Constructor creates a board for grid using puzzles from a size. - * - * @param size width and height of the GridBoard - */ - public GridBoard(int size) { - this(size, size); - } + /** + * GridBoard Constructor creates a board for grid using puzzles from a size. + * + * @param size width and height of the GridBoard + */ + public GridBoard(int size) { + this(size, size); + } - /** - * Gets a {@link GridCell} from the board. - * - * @param x x location of the cell - * @param y y location of the cell - * @return grid cell at location (x, y) - */ - public GridCell getCell(int x, int y) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - System.err.printf( - "not in bounds, bounds are %dx%d\n", dimension.width, dimension.height); - return null; - } - return (GridCell) puzzleElements.get(y * dimension.width + x); + /** + * Gets a {@link GridCell} from the board. + * + * @param x x location of the cell + * @param y y location of the cell + * @return grid cell at location (x, y) + */ + public GridCell getCell(int x, int y) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + System.err.printf("not in bounds, bounds are %dx%d\n", dimension.width, dimension.height); + return null; } + return (GridCell) puzzleElements.get(y * dimension.width + x); + } - /** - * Sets the {@link GridCell} at the location (x,y). This method does not set the cell if the - * location specified is out of bounds. - * - * @param x x location of the cell - * @param y y location of the cell - * @param cell grid cell to set at location (x,y) - */ - public void setCell(int x, int y, GridCell cell) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return; - } - puzzleElements.set(y * dimension.width + x, cell); + /** + * Sets the {@link GridCell} at the location (x,y). This method does not set the cell if the + * location specified is out of bounds. + * + * @param x x location of the cell + * @param y y location of the cell + * @param cell grid cell to set at location (x,y) + */ + public void setCell(int x, int y, GridCell cell) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return; } + puzzleElements.set(y * dimension.width + x, cell); + } - public void setCell(int x, int y, Element e, MouseEvent m) { - if (this instanceof TreeTentBoard - && ((y == dimension.height && 0 <= x && x < dimension.width) - || (x == dimension.width && 0 <= y && y < dimension.height))) { - TreeTentBoard treeTentBoard = ((TreeTentBoard) this); - TreeTentClue clue = treeTentBoard.getClue(x, y); - if (y == dimension.height) { - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.height) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } - } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } else { - clue.setData(dimension.height); - } - } - } else { // x == dimension.width - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.width) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } - } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } else { - clue.setData(dimension.width); - } - } - } + public void setCell(int x, int y, Element e, MouseEvent m) { + if (this instanceof TreeTentBoard + && ((y == dimension.height && 0 <= x && x < dimension.width) + || (x == dimension.width && 0 <= y && y < dimension.height))) { + TreeTentBoard treeTentBoard = ((TreeTentBoard) this); + TreeTentClue clue = treeTentBoard.getClue(x, y); + if (y == dimension.height) { + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.height) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.height); + } + } + } else { // x == dimension.width + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.width) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } } else { - if (e != null && y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return; - } else { - if (e != null) { - puzzleElements.get(y * dimension.width + x).setType(e, m); - } - } + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.width); + } } - // puzzleElements.set(y * dimension.width + x, puzzleElements.get(y * dimension.width - // + - // x)); + } + } else { + if (e != null && y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return; + } else { + if (e != null) { + puzzleElements.get(y * dimension.width + x).setType(e, m); + } + } } + // puzzleElements.set(y * dimension.width + x, puzzleElements.get(y * dimension.width + // + + // x)); + } - /** - * Gets the width of the board. - * - * @return width of the board - */ - public int getWidth() { - return dimension.width; - } + /** + * Gets the width of the board. + * + * @return width of the board + */ + public int getWidth() { + return dimension.width; + } - /** - * Gets the height of the board. - * - * @return height of the board - */ - public int getHeight() { - return dimension.height; - } + /** + * Gets the height of the board. + * + * @return height of the board + */ + public int getHeight() { + return dimension.height; + } - /** - * Gets the dimension of the grid board - * - * @return the dimension of the grid board - */ - public Dimension getDimension() { - return dimension; - } + /** + * Gets the dimension of the grid board + * + * @return the dimension of the grid board + */ + public Dimension getDimension() { + return dimension; + } - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - public GridBoard copy() { - GridBoard newGridBoard = new GridBoard(this.dimension.width, this.dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - newGridBoard.setCell(x, y, getCell(x, y).copy()); - } - } - return newGridBoard; + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + public GridBoard copy() { + GridBoard newGridBoard = new GridBoard(this.dimension.width, this.dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + newGridBoard.setCell(x, y, getCell(x, y).copy()); + } } + return newGridBoard; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java b/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java index a33c3ec80..9cc3d0768 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java @@ -3,59 +3,59 @@ import java.awt.*; public class GridCell extends PuzzleElement { - protected Point location; + protected Point location; - /** - * GridCell Constructor creates a grid cell at the specified location given as a {@link Point} - * - * @param value data value that represents the grid cell - * @param location location on the board - */ - public GridCell(T value, Point location) { - super(value); - this.location = location; - } + /** + * GridCell Constructor creates a grid cell at the specified location given as a {@link Point} + * + * @param value data value that represents the grid cell + * @param location location on the board + */ + public GridCell(T value, Point location) { + super(value); + this.location = location; + } - /** - * GridCell Constructor creates a grid cell at the specified location given as x,y pair - * - * @param value data value that represents the grid cell - * @param x x location - * @param y y location - */ - public GridCell(T value, int x, int y) { - this(value, new Point(x, y)); - } + /** + * GridCell Constructor creates a grid cell at the specified location given as x,y pair + * + * @param value data value that represents the grid cell + * @param x x location + * @param y y location + */ + public GridCell(T value, int x, int y) { + this(value, new Point(x, y)); + } - /** - * Gets the location of the grid cell on the board - * - * @return location of the grid cell - */ - public Point getLocation() { - return location; - } + /** + * Gets the location of the grid cell on the board + * + * @return location of the grid cell + */ + public Point getLocation() { + return location; + } - /** - * Sets the location of the grid cell on the board - * - * @param location location of the grid cell - */ - public void setLocation(Point location) { - this.location = location; - } + /** + * Sets the location of the grid cell on the board + * + * @param location location of the grid cell + */ + public void setLocation(Point location) { + this.location = location; + } - /** - * Performs a deep copy on the grid cell - * - * @return a new copy of the grid cell that is independent of this one - */ - public GridCell copy() { - GridCell copy = new GridCell<>(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setModified(isModified); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the grid cell + * + * @return a new copy of the grid cell that is independent of this one + */ + public GridCell copy() { + GridCell copy = new GridCell<>(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setModified(isModified); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java b/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java index 4ce030a04..215419d54 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java @@ -4,181 +4,181 @@ import java.awt.event.MouseEvent; public abstract class PuzzleElement { - protected int index; - protected T data; - protected boolean isModifiable; - protected boolean isModified; - protected boolean isGiven; - protected boolean isValid; - protected int casesDepended; - - /** PuzzleElement Constructor creates a new puzzle element. */ - public PuzzleElement() { - this.index = -1; - this.data = null; - this.isModifiable = true; - this.isModified = false; - this.isGiven = false; - this.isValid = true; - this.casesDepended = 0; - } - - /** - * PuzzleElement Constructor creates a new puzzle element from the specified data. - * - * @param data data used to create the puzzle element - */ - public PuzzleElement(T data) { - this(); - this.data = data; - } - - /** - * Gets the data that represents this puzzle element. - * - * @return data value - */ - public T getData() { - return data; - } - - /** - * Sets the data value that represents this puzzle element. - * - * @param data data value that represents this puzzle element - */ - public void setData(T data) { - this.data = data; - } - - public void setType(Element e, MouseEvent m) { - return; - } - - /** - * Gets whether this puzzle element is modifiable. - * - * @return true if this puzzle element is modifiable, false otherwise - */ - public boolean isModifiable() { - return isModifiable; - } - - /** - * Sets whether this puzzle element is modifiable. - * - * @param isModifiable true if this puzzle element is modifiable, false otherwise - */ - public void setModifiable(boolean isModifiable) { - this.isModifiable = isModifiable; - } - - /** - * Gets whether the puzzle element has been modified. - * - * @return true if the puzzle element has been modified, false otherwise - */ - public boolean isModified() { - return isModified; - } - - /** - * Sets whether the puzzle element has been modified. - * - * @param isModified true if the puzzle element has been modified, false otherwise - */ - public void setModified(boolean isModified) { - this.isModified = isModified; - } - - /** - * Gets the index of this puzzle element - * - * @return index of this puzzle element - */ - public int getIndex() { - return index; - } - - /** - * Sets the index of this puzzle element - * - * @param index index of this puzzle element - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Gets whether this puzzle element is given - * - * @return true if the puzzle element is given, false otherwise - */ - public boolean isGiven() { - return isGiven; - } - - /** - * Sets whether this puzzle element is given - * - * @param given true if the puzzle element is given, false otherwise - */ - public void setGiven(boolean given) { - isGiven = given; - } - - /** - * Get whether this puzzle element data is a valid change according to the rule applied to the - * transition that this puzzle element is contained in. - * - * @return true if the puzzle element logically follows from the rule, otherwise false. - */ - public boolean isValid() { - return this.isValid; - } - - /** - * Sets whether this puzzle element data is a valid change according to the rule applied to the - * transition that this puzzle element is contained in. - * - * @param isValid true if the puzzle element logically follows from the rule, otherwise false. - */ - public void setValid(boolean isValid) { - this.isValid = isValid; - } - - /** - * Get the number of case rules that depend upon the state of this element - * - * @return number of cases - */ - public int getCasesDepended() { - return this.casesDepended; - } - - /** - * Sets the number of case rules that depend upon the state of this element - * - * @param cases number of cases - */ - public void setCasesDepended(int cases) { - this.casesDepended = cases; - } - - /** - * Tests whether two puzzle elements objects have the same puzzle element - * - * @param puzzleElement puzzle element to check for equality - * @return true if the puzzle element are equal, false otherwise - */ - public boolean equalsData(PuzzleElement puzzleElement) { - return data.equals(puzzleElement.data); - } - - /** - * Copies this puzzle element to a new puzzle element object - * - * @return copied puzzle element object - */ - public abstract PuzzleElement copy(); + protected int index; + protected T data; + protected boolean isModifiable; + protected boolean isModified; + protected boolean isGiven; + protected boolean isValid; + protected int casesDepended; + + /** PuzzleElement Constructor creates a new puzzle element. */ + public PuzzleElement() { + this.index = -1; + this.data = null; + this.isModifiable = true; + this.isModified = false; + this.isGiven = false; + this.isValid = true; + this.casesDepended = 0; + } + + /** + * PuzzleElement Constructor creates a new puzzle element from the specified data. + * + * @param data data used to create the puzzle element + */ + public PuzzleElement(T data) { + this(); + this.data = data; + } + + /** + * Gets the data that represents this puzzle element. + * + * @return data value + */ + public T getData() { + return data; + } + + /** + * Sets the data value that represents this puzzle element. + * + * @param data data value that represents this puzzle element + */ + public void setData(T data) { + this.data = data; + } + + public void setType(Element e, MouseEvent m) { + return; + } + + /** + * Gets whether this puzzle element is modifiable. + * + * @return true if this puzzle element is modifiable, false otherwise + */ + public boolean isModifiable() { + return isModifiable; + } + + /** + * Sets whether this puzzle element is modifiable. + * + * @param isModifiable true if this puzzle element is modifiable, false otherwise + */ + public void setModifiable(boolean isModifiable) { + this.isModifiable = isModifiable; + } + + /** + * Gets whether the puzzle element has been modified. + * + * @return true if the puzzle element has been modified, false otherwise + */ + public boolean isModified() { + return isModified; + } + + /** + * Sets whether the puzzle element has been modified. + * + * @param isModified true if the puzzle element has been modified, false otherwise + */ + public void setModified(boolean isModified) { + this.isModified = isModified; + } + + /** + * Gets the index of this puzzle element + * + * @return index of this puzzle element + */ + public int getIndex() { + return index; + } + + /** + * Sets the index of this puzzle element + * + * @param index index of this puzzle element + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Gets whether this puzzle element is given + * + * @return true if the puzzle element is given, false otherwise + */ + public boolean isGiven() { + return isGiven; + } + + /** + * Sets whether this puzzle element is given + * + * @param given true if the puzzle element is given, false otherwise + */ + public void setGiven(boolean given) { + isGiven = given; + } + + /** + * Get whether this puzzle element data is a valid change according to the rule applied to the + * transition that this puzzle element is contained in. + * + * @return true if the puzzle element logically follows from the rule, otherwise false. + */ + public boolean isValid() { + return this.isValid; + } + + /** + * Sets whether this puzzle element data is a valid change according to the rule applied to the + * transition that this puzzle element is contained in. + * + * @param isValid true if the puzzle element logically follows from the rule, otherwise false. + */ + public void setValid(boolean isValid) { + this.isValid = isValid; + } + + /** + * Get the number of case rules that depend upon the state of this element + * + * @return number of cases + */ + public int getCasesDepended() { + return this.casesDepended; + } + + /** + * Sets the number of case rules that depend upon the state of this element + * + * @param cases number of cases + */ + public void setCasesDepended(int cases) { + this.casesDepended = cases; + } + + /** + * Tests whether two puzzle elements objects have the same puzzle element + * + * @param puzzleElement puzzle element to check for equality + * @return true if the puzzle element are equal, false otherwise + */ + public boolean equalsData(PuzzleElement puzzleElement) { + return data.equals(puzzleElement.data); + } + + /** + * Copies this puzzle element to a new puzzle element object + * + * @return copied puzzle element object + */ + public abstract PuzzleElement copy(); } diff --git a/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java b/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java index 461128562..b5c712ead 100644 --- a/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java +++ b/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java @@ -5,24 +5,24 @@ import edu.rpi.legup.model.tree.TreeElement; public interface IBoardListener { - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - void onTreeElementChanged(TreeElement treeElement); + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + void onTreeElementChanged(TreeElement treeElement); - /** - * Called when the a case board has been added to the view. - * - * @param caseBoard case board to be added - */ - void onCaseBoardAdded(CaseBoard caseBoard); + /** + * Called when the a case board has been added to the view. + * + * @param caseBoard case board to be added + */ + void onCaseBoardAdded(CaseBoard caseBoard); - /** - * Called when a {@link PuzzleElement}'s data on the board has changed. - * - * @param puzzleElement puzzleElement that has changed - */ - void onBoardDataChanged(PuzzleElement puzzleElement); + /** + * Called when a {@link PuzzleElement}'s data on the board has changed. + * + * @param puzzleElement puzzleElement that has changed + */ + void onBoardDataChanged(PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java b/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java index c7bf13141..73bd2b6f8 100644 --- a/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java +++ b/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface IBoardSubject { - /** - * Adds a board listener. - * - * @param listener listener to add - */ - void addBoardListener(IBoardListener listener); + /** + * Adds a board listener. + * + * @param listener listener to add + */ + void addBoardListener(IBoardListener listener); - /** - * Removes a board listener. - * - * @param listener listener to remove - */ - void removeBoardListener(IBoardListener listener); + /** + * Removes a board listener. + * + * @param listener listener to remove + */ + void removeBoardListener(IBoardListener listener); - /** - * Notifies all of the listeners using the specified algorithm. - * - * @param algorithm algorithm used to notify the listeners - */ - void notifyBoardListeners(Consumer algorithm); + /** + * Notifies all of the listeners using the specified algorithm. + * + * @param algorithm algorithm used to notify the listeners + */ + void notifyBoardListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java b/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java index d5e7fdb2d..915b0adc9 100644 --- a/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java +++ b/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java @@ -4,27 +4,27 @@ import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; public interface ITreeListener { - /** - * Called when a {@link TreeElement} is added to the tree. - * - * @param treeElement tree element that was added to the tree - */ - void onTreeElementAdded(TreeElement treeElement); + /** + * Called when a {@link TreeElement} is added to the tree. + * + * @param treeElement tree element that was added to the tree + */ + void onTreeElementAdded(TreeElement treeElement); - /** - * Called when a {@link TreeElement} is removed from the tree. - * - * @param element TreeElement that was removed to the tree - */ - void onTreeElementRemoved(TreeElement element); + /** + * Called when a {@link TreeElement} is removed from the tree. + * + * @param element TreeElement that was removed to the tree + */ + void onTreeElementRemoved(TreeElement element); - /** - * Called when the {@link TreeViewSelection} was changed. - * - * @param selection tree view selection that was changed - */ - void onTreeSelectionChanged(TreeViewSelection selection); + /** + * Called when the {@link TreeViewSelection} was changed. + * + * @param selection tree view selection that was changed + */ + void onTreeSelectionChanged(TreeViewSelection selection); - /** Called when the model has finished updating the tree. */ - void onUpdateTree(); + /** Called when the model has finished updating the tree. */ + void onUpdateTree(); } diff --git a/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java b/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java index 66d5d9a5e..7cf1bb1ef 100644 --- a/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java +++ b/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface ITreeSubject { - /** - * Adds a board listener. - * - * @param listener listener to add - */ - void addTreeListener(ITreeListener listener); + /** + * Adds a board listener. + * + * @param listener listener to add + */ + void addTreeListener(ITreeListener listener); - /** - * Removes a tree listener. - * - * @param listener listener to remove - */ - void removeTreeListener(ITreeListener listener); + /** + * Removes a tree listener. + * + * @param listener listener to remove + */ + void removeTreeListener(ITreeListener listener); - /** - * Notifies all of the listeners using the specified algorithm. - * - * @param algorithm algorithm used to notify the listeners - */ - void notifyTreeListeners(Consumer algorithm); + /** + * Notifies all of the listeners using the specified algorithm. + * + * @param algorithm algorithm used to notify the listeners + */ + void notifyTreeListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/model/rules/CaseRule.java b/src/main/java/edu/rpi/legup/model/rules/CaseRule.java index e87896fcc..4fcd69065 100644 --- a/src/main/java/edu/rpi/legup/model/rules/CaseRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/CaseRule.java @@ -13,135 +13,135 @@ public abstract class CaseRule extends Rule { - private final String INVALID_USE_MESSAGE; - - /** - * CaseRule Constructor creates a new case rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public CaseRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = CASE; - this.INVALID_USE_MESSAGE = "Invalid use of the case rule " + this.ruleName; + private final String INVALID_USE_MESSAGE; + + /** + * CaseRule Constructor creates a new case rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public CaseRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = CASE; + this.INVALID_USE_MESSAGE = "Invalid use of the case rule " + this.ruleName; + } + + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + public abstract CaseBoard getCaseBoard(Board board); + + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + public abstract List getCases(Board board, PuzzleElement puzzleElement); + + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + List parentNodes = transition.getParents(); + if (parentNodes.size() != 1) { + return "Must not have multiple parent nodes"; } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - public abstract CaseBoard getCaseBoard(Board board); - - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - public abstract List getCases(Board board, PuzzleElement puzzleElement); - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - List parentNodes = transition.getParents(); - if (parentNodes.size() != 1) { - return "Must not have multiple parent nodes"; - } - - for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { - if (childTrans.getRule() == null - || !childTrans.getRule().getClass().equals(this.getClass())) { - return "All children nodes must be justified with the same case rule."; - } - } - - String check = checkRuleRaw(transition); - - // Mark transition and new data as valid or not - boolean isCorrect = (check == null); - for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { - childTrans.setCorrect(isCorrect); - for (PuzzleElement element : childTrans.getBoard().getModifiedData()) { - element.setValid(isCorrect); - } - } - - return check; + for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { + if (childTrans.getRule() == null + || !childTrans.getRule().getClass().equals(this.getClass())) { + return "All children nodes must be justified with the same case rule."; + } } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public abstract String checkRuleRaw(TreeTransition transition); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return this.INVALID_USE_MESSAGE; + String check = checkRuleRaw(transition); + + // Mark transition and new data as valid or not + boolean isCorrect = (check == null); + for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { + childTrans.setCorrect(isCorrect); + for (PuzzleElement element : childTrans.getBoard().getModifiedData()) { + element.setValid(isCorrect); + } } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - List cases = getCases(board, puzzleElement); - for (Board caseBoard : cases) { - Set data = caseBoard.getModifiedData(); - for (PuzzleElement element : data) { - if (!elements.contains(board.getPuzzleElement(element))) { - elements.add(board.getPuzzleElement(element)); - } - } + return check; + } + + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public abstract String checkRuleRaw(TreeTransition transition); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return this.INVALID_USE_MESSAGE; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + List cases = getCases(board, puzzleElement); + for (Board caseBoard : cases) { + Set data = caseBoard.getModifiedData(); + for (PuzzleElement element : data) { + if (!elements.contains(board.getPuzzleElement(element))) { + elements.add(board.getPuzzleElement(element)); } - - return elements; + } } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java b/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java index b38a95fd2..8ae3f02c6 100644 --- a/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java @@ -8,102 +8,102 @@ public abstract class ContradictionRule extends Rule { - private final String NO_CONTRADICTION_MESSAGE = - "No instance of the contradiction " + this.ruleName + " here"; + private final String NO_CONTRADICTION_MESSAGE = + "No instance of the contradiction " + this.ruleName + " here"; - /** - * ContradictionRule Constructor creates a new contradiction rule - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public ContradictionRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - ruleType = CONTRADICTION; - } + /** + * ContradictionRule Constructor creates a new contradiction rule + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public ContradictionRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + ruleType = CONTRADICTION; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - return checkContradiction(transition.getBoard()); - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + return checkContradiction(transition.getBoard()); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkContradictionAt(transition.getBoard(), puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkContradictionAt(transition.getBoard(), puzzleElement); + } - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return checkContradiction(transition.getBoard()); - } + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return checkContradiction(transition.getBoard()); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkContradictionAt(transition.getBoard(), puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkContradictionAt(transition.getBoard(), puzzleElement); + } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - public String checkContradiction(Board board) { - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - String checkStr = checkContradictionAt(board, puzzleElement); - if (checkStr == null) { - return checkStr; - } - } - return this.NO_CONTRADICTION_MESSAGE; + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + public String checkContradiction(Board board) { + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + String checkStr = checkContradictionAt(board, puzzleElement); + if (checkStr == null) { + return checkStr; + } } + return this.NO_CONTRADICTION_MESSAGE; + } - public String getNoContradictionMessage() { - return this.NO_CONTRADICTION_MESSAGE; - } + public String getNoContradictionMessage() { + return this.NO_CONTRADICTION_MESSAGE; + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - public abstract String checkContradictionAt(Board board, PuzzleElement puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + public abstract String checkContradictionAt(Board board, PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java index d550bc02c..1ce44318a 100644 --- a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java @@ -8,97 +8,96 @@ import edu.rpi.legup.model.tree.TreeTransition; public abstract class DirectRule extends Rule { - /** - * DirectRule Constructor creates a new basic rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public DirectRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = BASIC; - } + /** + * DirectRule Constructor creates a new basic rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public DirectRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = BASIC; + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRule(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - // System.out.println(finalBoard.getModifiedData().size()); - if (transition.getParents().size() != 1 - || transition.getParents().get(0).getChildren().size() != 1) { - return "State must have only 1 parent and 1 child"; - } else if (finalBoard.getModifiedData().isEmpty()) { - // null transition - return null; - } else { - return checkRuleRaw(transition); - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRule(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + // System.out.println(finalBoard.getModifiedData().size()); + if (transition.getParents().size() != 1 + || transition.getParents().get(0).getChildren().size() != 1) { + return "State must have only 1 parent and 1 child"; + } else if (finalBoard.getModifiedData().isEmpty()) { + // null transition + return null; + } else { + return checkRuleRaw(transition); } + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRuleRaw(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - String checkStr = null; + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRuleRaw(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + String checkStr = null; - // Go directly to specific direct rule's judgement if no cell's are edited - if (finalBoard.getModifiedData().size() == 0) { - checkStr = checkRuleRawAt(transition, null); - } - for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { - String tempStr = checkRuleAt(transition, puzzleElement); - if (tempStr != null) { - checkStr = tempStr; - } - } - return checkStr; + // Go directly to specific direct rule's judgement if no cell's are edited + if (finalBoard.getModifiedData().size() == 0) { + checkStr = checkRuleRawAt(transition, null); + } + for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { + String tempStr = checkRuleAt(transition, puzzleElement); + if (tempStr != null) { + checkStr = tempStr; + } } + return checkStr; + } - /** - * Checks whether the child node logically follows from the parent node at the specific {@link - * PuzzleElement} using this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - Board finalBoard = transition.getBoard(); - puzzleElement = finalBoard.getPuzzleElement(puzzleElement); - String checkStr; - if (!puzzleElement.isModified()) { - checkStr = "PuzzleElement must be modified"; - } else { - if (transition.getParents().size() != 1 - || transition.getParents().get(0).getChildren().size() != 1) { - checkStr = "State must have only 1 parent and 1 child"; - } else { - checkStr = checkRuleRawAt(transition, puzzleElement); - } - } - puzzleElement.setValid(checkStr == null); - return checkStr; + /** + * Checks whether the child node logically follows from the parent node at the specific {@link + * PuzzleElement} using this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + Board finalBoard = transition.getBoard(); + puzzleElement = finalBoard.getPuzzleElement(puzzleElement); + String checkStr; + if (!puzzleElement.isModified()) { + checkStr = "PuzzleElement must be modified"; + } else { + if (transition.getParents().size() != 1 + || transition.getParents().get(0).getChildren().size() != 1) { + checkStr = "State must have only 1 parent and 1 child"; + } else { + checkStr = checkRuleRawAt(transition, puzzleElement); + } } + puzzleElement.setValid(checkStr == null); + return checkStr; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - public abstract Board getDefaultBoard(TreeNode node); + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + public abstract Board getDefaultBoard(TreeNode node); } diff --git a/src/main/java/edu/rpi/legup/model/rules/MergeRule.java b/src/main/java/edu/rpi/legup/model/rules/MergeRule.java index f7badcd8b..25c543abb 100644 --- a/src/main/java/edu/rpi/legup/model/rules/MergeRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/MergeRule.java @@ -11,88 +11,88 @@ import java.util.List; public class MergeRule extends Rule { - /** MergeRule Constructor merges to board states together */ - public MergeRule() { - super( - "MERGE", - "Merge Rule", - "Merge any number of nodes into one", - "edu/rpi/legup/images/Legup/MergeRule.png"); - this.ruleType = MERGE; - } - - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @SuppressWarnings("unchecked") - @Override - public String checkRuleRaw(TreeTransition transition) { - Board board = transition.getBoard(); - List mergingNodes = new ArrayList<>(); - List mergingBoards = new ArrayList<>(); - for (TreeNode treeNode : transition.getParents()) { - mergingNodes.add(treeNode); - mergingBoards.add(treeNode.getBoard()); - } + /** MergeRule Constructor merges to board states together */ + public MergeRule() { + super( + "MERGE", + "Merge Rule", + "Merge any number of nodes into one", + "edu/rpi/legup/images/Legup/MergeRule.png"); + this.ruleType = MERGE; + } - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - return "Merge was not correctly created."; - } - Board lcaBoard = lca.getBoard(); + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @SuppressWarnings("unchecked") + @Override + public String checkRuleRaw(TreeTransition transition) { + Board board = transition.getBoard(); + List mergingNodes = new ArrayList<>(); + List mergingBoards = new ArrayList<>(); + for (TreeNode treeNode : transition.getParents()) { + mergingNodes.add(treeNode); + mergingBoards.add(treeNode.getBoard()); + } - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + return "Merge was not correctly created."; + } + Board lcaBoard = lca.getBoard(); - for (PuzzleElement m : mergedBoard.getPuzzleElements()) { - if (!m.equalsData(board.getPuzzleElement(m))) { - return "Merge was not correctly created."; - } - } + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); - return null; + for (PuzzleElement m : mergedBoard.getPuzzleElements()) { + if (!m.equalsData(board.getPuzzleElement(m))) { + return "Merge was not correctly created."; + } } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRule(transition); - } + return null; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - return checkRuleRaw(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRule(transition); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRawAt(transition, puzzleElement); - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + return checkRuleRaw(transition); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRawAt(transition, puzzleElement); + } } diff --git a/src/main/java/edu/rpi/legup/model/rules/Rule.java b/src/main/java/edu/rpi/legup/model/rules/Rule.java index f70bb2889..d15b79e5e 100644 --- a/src/main/java/edu/rpi/legup/model/rules/Rule.java +++ b/src/main/java/edu/rpi/legup/model/rules/Rule.java @@ -10,156 +10,154 @@ @RegisterRule public abstract class Rule { - protected String ruleID; - protected String ruleName; - protected String description; - protected String imageName; - protected ImageIcon image; - protected RuleType ruleType; - - private final String INVALID_USE_MESSAGE; - - /** - * Rule Constructor creates a new rule - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public Rule(String ruleID, String ruleName, String description, String imageName) { - this.ruleID = ruleID; - this.ruleName = ruleName; - this.description = description; - this.imageName = imageName; - this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.ruleName; - loadImage(); - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public abstract String checkRule(TreeTransition transition); - - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - protected abstract String checkRuleRaw(TreeTransition transition); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public abstract String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - protected abstract String checkRuleRawAt( - TreeTransition transition, PuzzleElement puzzleElement); - - /** Loads the image file */ - public void loadImage() { - if (imageName != null) { - String name = imageName; - LegupPreferences prefs = LegupPreferences.getInstance(); - if (name.contains("shorttruthtable") - && prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - name = name.replace("ruleimages", "ruleimages_cb"); - } - this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(name)); - // Resize images to be 100px wide - Image image = this.image.getImage(); - if (this.image.getIconWidth() < 120) return; - int height = - (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); - if (height == 0) { - System.out.println("height is 0 error"); - System.out.println("height: " + this.image.getIconHeight()); - System.out.println("width: " + this.image.getIconWidth()); - return; - } - BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = bimage.createGraphics(); - g.drawImage(image, 0, 0, 100, height, null); - this.image = new ImageIcon(bimage); - } - } - - /** - * Gets the name of the rule - * - * @return name of the rule - */ - public String getRuleName() { - return ruleName; - } - - /** - * Gets the name of the rule - * - * @return name of the rule - */ - public String getRuleID() { - return ruleID; - } - - /** - * Sets the rule name - * - * @param ruleName new name of the rule - */ - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - - /** - * Gets the description of the rule - * - * @return the description of the rule - */ - public String getDescription() { - return description; - } - - /** - * Gets the image icon of the rule - * - * @return image icon of the rule - */ - public ImageIcon getImageIcon() { - return image; - } - - /** - * Gets the rule type - * - * @return rule type - */ - public RuleType getRuleType() { - return ruleType; - } - - public String getInvalidUseOfRuleMessage() { - return this.INVALID_USE_MESSAGE; + protected String ruleID; + protected String ruleName; + protected String description; + protected String imageName; + protected ImageIcon image; + protected RuleType ruleType; + + private final String INVALID_USE_MESSAGE; + + /** + * Rule Constructor creates a new rule + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public Rule(String ruleID, String ruleName, String description, String imageName) { + this.ruleID = ruleID; + this.ruleName = ruleName; + this.description = description; + this.imageName = imageName; + this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.ruleName; + loadImage(); + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public abstract String checkRule(TreeTransition transition); + + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + protected abstract String checkRuleRaw(TreeTransition transition); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public abstract String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + protected abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** Loads the image file */ + public void loadImage() { + if (imageName != null) { + String name = imageName; + LegupPreferences prefs = LegupPreferences.getInstance(); + if (name.contains("shorttruthtable") + && prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + name = name.replace("ruleimages", "ruleimages_cb"); + } + this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(name)); + // Resize images to be 100px wide + Image image = this.image.getImage(); + if (this.image.getIconWidth() < 120) return; + int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); + if (height == 0) { + System.out.println("height is 0 error"); + System.out.println("height: " + this.image.getIconHeight()); + System.out.println("width: " + this.image.getIconWidth()); + return; + } + BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = bimage.createGraphics(); + g.drawImage(image, 0, 0, 100, height, null); + this.image = new ImageIcon(bimage); } + } + + /** + * Gets the name of the rule + * + * @return name of the rule + */ + public String getRuleName() { + return ruleName; + } + + /** + * Gets the name of the rule + * + * @return name of the rule + */ + public String getRuleID() { + return ruleID; + } + + /** + * Sets the rule name + * + * @param ruleName new name of the rule + */ + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + + /** + * Gets the description of the rule + * + * @return the description of the rule + */ + public String getDescription() { + return description; + } + + /** + * Gets the image icon of the rule + * + * @return image icon of the rule + */ + public ImageIcon getImageIcon() { + return image; + } + + /** + * Gets the rule type + * + * @return rule type + */ + public RuleType getRuleType() { + return ruleType; + } + + public String getInvalidUseOfRuleMessage() { + return this.INVALID_USE_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/model/rules/RuleType.java b/src/main/java/edu/rpi/legup/model/rules/RuleType.java index 06aa1844b..48589e836 100644 --- a/src/main/java/edu/rpi/legup/model/rules/RuleType.java +++ b/src/main/java/edu/rpi/legup/model/rules/RuleType.java @@ -1,8 +1,8 @@ package edu.rpi.legup.model.rules; public enum RuleType { - BASIC, - CASE, - CONTRADICTION, - MERGE + BASIC, + CASE, + CONTRADICTION, + MERGE } diff --git a/src/main/java/edu/rpi/legup/model/tree/Tree.java b/src/main/java/edu/rpi/legup/model/tree/Tree.java index a0746db87..2e5604a2c 100644 --- a/src/main/java/edu/rpi/legup/model/tree/Tree.java +++ b/src/main/java/edu/rpi/legup/model/tree/Tree.java @@ -7,186 +7,185 @@ import java.util.Set; public class Tree { - private TreeNode rootNode; - - /** - * Tree Constructor creates the tree structure from the initial {@link Board} - * - * @param initBoard initial board - */ - public Tree(Board initBoard) { - this.rootNode = new TreeNode(initBoard); - this.rootNode.setRoot(true); + private TreeNode rootNode; + + /** + * Tree Constructor creates the tree structure from the initial {@link Board} + * + * @param initBoard initial board + */ + public Tree(Board initBoard) { + this.rootNode = new TreeNode(initBoard); + this.rootNode.setRoot(true); + } + + /** Tree Constructor creates the tree structure with null root node */ + public Tree() { + this.rootNode = null; + } + + public TreeTransition addNewTransition(TreeNode treeNode) { + TreeTransition transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + treeNode.addChild(transition); + treeNode.getChildren().forEach(TreeTransition::reverify); + return transition; + } + + public TreeNode addNode(TreeTransition transition) { + TreeNode treeNode = new TreeNode(transition.getBoard().copy()); + transition.setChildNode(treeNode); + treeNode.setParent(transition); + return treeNode; + } + + public TreeElement addTreeElement(TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) element; + return addTreeElement(treeNode, new TreeTransition(treeNode, treeNode.getBoard().copy())); + } else { + TreeTransition transition = (TreeTransition) element; + Board copyBoard = transition.board.copy(); + copyBoard.setModifiable(false); + return addTreeElement(transition, new TreeNode(copyBoard)); } - - /** Tree Constructor creates the tree structure with null root node */ - public Tree() { - this.rootNode = null; - } - - public TreeTransition addNewTransition(TreeNode treeNode) { - TreeTransition transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - treeNode.addChild(transition); - treeNode.getChildren().forEach(TreeTransition::reverify); - return transition; - } - - public TreeNode addNode(TreeTransition transition) { - TreeNode treeNode = new TreeNode(transition.getBoard().copy()); - transition.setChildNode(treeNode); - treeNode.setParent(transition); - return treeNode; - } - - public TreeElement addTreeElement(TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) element; - return addTreeElement( - treeNode, new TreeTransition(treeNode, treeNode.getBoard().copy())); - } else { - TreeTransition transition = (TreeTransition) element; - Board copyBoard = transition.board.copy(); - copyBoard.setModifiable(false); - return addTreeElement(transition, new TreeNode(copyBoard)); - } - } - - public TreeElement addTreeElement(TreeNode treeNode, TreeTransition transition) { - treeNode.addChild(transition); - treeNode.getChildren().forEach(TreeTransition::reverify); - return transition; + } + + public TreeElement addTreeElement(TreeNode treeNode, TreeTransition transition) { + treeNode.addChild(transition); + treeNode.getChildren().forEach(TreeTransition::reverify); + return transition; + } + + public TreeElement addTreeElement(TreeTransition transition, TreeNode treeNode) { + transition.setChildNode(treeNode); + treeNode.setParent(transition); + return treeNode; + } + + public void removeTreeElement(TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getParent().setChildNode(null); + } else { + TreeTransition transition = (TreeTransition) element; + transition.getParents().forEach(n -> n.removeChild(transition)); + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); } - - public TreeElement addTreeElement(TreeTransition transition, TreeNode treeNode) { - transition.setChildNode(treeNode); - treeNode.setParent(transition); - return treeNode; + } + + /** + * Determines if the tree is valid by checking whether this tree puzzleElement and all descendants + * of this tree puzzleElement is justified and justified correctly + * + * @return true if tree is valid, false otherwise + */ + public boolean isValid() { + return rootNode.isValidBranch(); + } + + /** + * Gets a Set of TreeNodes that are leaf nodes + * + * @return Set of TreeNodes that are leaf nodes + */ + public Set getLeafTreeElements() { + Set leafs = new HashSet<>(); + getLeafTreeElements(leafs, rootNode); + return leafs; + } + + /** + * Gets a Set of TreeNodes that are leaf nodes from the sub tree rooted at the specified node + * + * @param node node that is input + * @return Set of TreeNodes that are leaf nodes from the sub tree + */ + public Set getLeafTreeElements(TreeNode node) { + Set leafs = new HashSet<>(); + getLeafTreeElements(leafs, node); + return leafs; + } + + /** + * Recursively gets a Set of TreeNodes that are leaf nodes + * + * @param leafs Set of TreeNodes that are leaf nodes + * @param element current TreeNode being evaluated + */ + private void getLeafTreeElements(Set leafs, TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + List childTrans = node.getChildren(); + if (childTrans.isEmpty()) { + leafs.add(node); + } else { + childTrans.forEach(t -> getLeafTreeElements(leafs, t)); + } + } else { + TreeTransition transition = (TreeTransition) element; + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + leafs.add(transition); + } else { + getLeafTreeElements(leafs, childNode); + } } - - public void removeTreeElement(TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getParent().setChildNode(null); - } else { - TreeTransition transition = (TreeTransition) element; - transition.getParents().forEach(n -> n.removeChild(transition)); - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + } + + /** + * Gets the lowest common ancestor (LCA) among the list of {@link TreeNode} passed into the + * function. This lowest common ancestor is the most immediate ancestor node such that the list of + * tree nodes specified are descendants of the node. This will return null if no such ancestor + * exists + * + * @param nodes list of tree nodes to find the LCA + * @return the first ancestor node that all tree nodes have in common, otherwise null if none + * exists + */ + public static TreeNode getLowestCommonAncestor(List nodes) { + if (nodes.isEmpty()) { + return null; + } else { + if (nodes.size() == 1) { + return nodes.get(0); + } else { + List> ancestors = new ArrayList<>(); + for (TreeNode node : nodes) { + ancestors.add(node.getAncestors()); } - } - - /** - * Determines if the tree is valid by checking whether this tree puzzleElement and all - * descendants of this tree puzzleElement is justified and justified correctly - * - * @return true if tree is valid, false otherwise - */ - public boolean isValid() { - return rootNode.isValidBranch(); - } - /** - * Gets a Set of TreeNodes that are leaf nodes - * - * @return Set of TreeNodes that are leaf nodes - */ - public Set getLeafTreeElements() { - Set leafs = new HashSet<>(); - getLeafTreeElements(leafs, rootNode); - return leafs; - } - - /** - * Gets a Set of TreeNodes that are leaf nodes from the sub tree rooted at the specified node - * - * @param node node that is input - * @return Set of TreeNodes that are leaf nodes from the sub tree - */ - public Set getLeafTreeElements(TreeNode node) { - Set leafs = new HashSet<>(); - getLeafTreeElements(leafs, node); - return leafs; - } + List first = ancestors.get(0); - /** - * Recursively gets a Set of TreeNodes that are leaf nodes - * - * @param leafs Set of TreeNodes that are leaf nodes - * @param element current TreeNode being evaluated - */ - private void getLeafTreeElements(Set leafs, TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - List childTrans = node.getChildren(); - if (childTrans.isEmpty()) { - leafs.add(node); - } else { - childTrans.forEach(t -> getLeafTreeElements(leafs, t)); - } - } else { - TreeTransition transition = (TreeTransition) element; - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - leafs.add(transition); - } else { - getLeafTreeElements(leafs, childNode); - } - } - } + for (TreeNode node : first) { + boolean isCommon = true; + for (List nList : ancestors) { + isCommon &= nList.contains(node); + } - /** - * Gets the lowest common ancestor (LCA) among the list of {@link TreeNode} passed into the - * function. This lowest common ancestor is the most immediate ancestor node such that the list - * of tree nodes specified are descendants of the node. This will return null if no such - * ancestor exists - * - * @param nodes list of tree nodes to find the LCA - * @return the first ancestor node that all tree nodes have in common, otherwise null if none - * exists - */ - public static TreeNode getLowestCommonAncestor(List nodes) { - if (nodes.isEmpty()) { - return null; - } else { - if (nodes.size() == 1) { - return nodes.get(0); - } else { - List> ancestors = new ArrayList<>(); - for (TreeNode node : nodes) { - ancestors.add(node.getAncestors()); - } - - List first = ancestors.get(0); - - for (TreeNode node : first) { - boolean isCommon = true; - for (List nList : ancestors) { - isCommon &= nList.contains(node); - } - - if (isCommon) { - return node; - } - } - } + if (isCommon) { + return node; + } } - return null; - } - - /** - * Gets the root node of this tree - * - * @return the root node of the tree - */ - public TreeNode getRootNode() { - return rootNode; - } - - /** - * Sets the root node of this tree - * - * @param rootNode the root node of the tree - */ - public void setRootNode(TreeNode rootNode) { - this.rootNode = rootNode; + } } + return null; + } + + /** + * Gets the root node of this tree + * + * @return the root node of the tree + */ + public TreeNode getRootNode() { + return rootNode; + } + + /** + * Sets the root node of this tree + * + * @param rootNode the root node of the tree + */ + public void setRootNode(TreeNode rootNode) { + this.rootNode = rootNode; + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeElement.java b/src/main/java/edu/rpi/legup/model/tree/TreeElement.java index 59f75acf3..d7f21c3b7 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeElement.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeElement.java @@ -3,61 +3,61 @@ import edu.rpi.legup.model.gameboard.Board; public abstract class TreeElement { - protected TreeElementType type; - protected Board board; - - /** - * TreeElement Constructor creates a tree puzzleElement that is part of a tree - * - * @param type type of tree puzzleElement (NODE or TRANSITION) - */ - public TreeElement(TreeElementType type) { - this.type = type; - } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must - * lead to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - public abstract boolean isContradictoryBranch(); - - /** - * Recursively determines if the sub-tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified - * and justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - public abstract boolean isValidBranch(); - - /** - * Gets the type of tree puzzleElement - * - * @return NODE if this tree puzzleElement is a tree node, TRANSITION, if this tree - * puzzleElement is a transition - */ - public TreeElementType getType() { - return type; - } - - /** - * Gets the board at this TreeElement - * - * @return the board at this TreeElement - */ - public Board getBoard() { - return board; - } - - /** - * Sets the board at this TreeElement - * - * @param board the board at this TreeElement - */ - public void setBoard(Board board) { - this.board = board; - } + protected TreeElementType type; + protected Board board; + + /** + * TreeElement Constructor creates a tree puzzleElement that is part of a tree + * + * @param type type of tree puzzleElement (NODE or TRANSITION) + */ + public TreeElement(TreeElementType type) { + this.type = type; + } + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must lead + * to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + public abstract boolean isContradictoryBranch(); + + /** + * Recursively determines if the sub-tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and + * justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + public abstract boolean isValidBranch(); + + /** + * Gets the type of tree puzzleElement + * + * @return NODE if this tree puzzleElement is a tree node, TRANSITION, if this tree puzzleElement + * is a transition + */ + public TreeElementType getType() { + return type; + } + + /** + * Gets the board at this TreeElement + * + * @return the board at this TreeElement + */ + public Board getBoard() { + return board; + } + + /** + * Sets the board at this TreeElement + * + * @param board the board at this TreeElement + */ + public void setBoard(Board board) { + this.board = board; + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java b/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java index 67437a535..42eeb6c34 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.model.tree; public enum TreeElementType { - NODE, - TRANSITION + NODE, + TRANSITION } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeNode.java b/src/main/java/edu/rpi/legup/model/tree/TreeNode.java index a2ac7cb21..4d1652a3c 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeNode.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeNode.java @@ -5,328 +5,328 @@ import java.util.*; public class TreeNode extends TreeElement { - private TreeTransition parent; - private List children; - private boolean isRoot; - - /** - * TreeNode Constructor creates a tree node whenever a rule has been made - * - * @param board board associated with this tree node - */ - public TreeNode(Board board) { - super(TreeElementType.NODE); - this.board = board; - this.parent = null; - this.children = new ArrayList<>(); - this.isRoot = false; + private TreeTransition parent; + private List children; + private boolean isRoot; + + /** + * TreeNode Constructor creates a tree node whenever a rule has been made + * + * @param board board associated with this tree node + */ + public TreeNode(Board board) { + super(TreeElementType.NODE); + this.board = board; + this.parent = null; + this.children = new ArrayList<>(); + this.isRoot = false; + } + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must lead + * to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + @Override + public boolean isContradictoryBranch() { + boolean leadsToContra = true; + for (TreeTransition child : children) { + leadsToContra &= child.isContradictoryBranch(); } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must - * lead to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - @Override - public boolean isContradictoryBranch() { - boolean leadsToContra = true; - for (TreeTransition child : children) { - leadsToContra &= child.isContradictoryBranch(); - } - return leadsToContra && !children.isEmpty(); + return leadsToContra && !children.isEmpty(); + } + + /** + * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and + * justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + @Override + public boolean isValidBranch() { + for (TreeTransition transition : children) { + if (!transition.isValidBranch()) { + return false; + } } - - /** - * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified - * and justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - @Override - public boolean isValidBranch() { - for (TreeTransition transition : children) { - if (!transition.isValidBranch()) { - return false; - } + return true; + } + + /** + * Gets all of the ancestors of this node + * + * @return list of all of the ancestors for this node + */ + public List getAncestors() { + List ancestors = new ArrayList<>(); + Queue it = new LinkedList<>(); + it.add(this); + + while (!it.isEmpty()) { + TreeNode next = it.poll(); + if (next.getParent() != null) { + for (TreeNode treeNode : next.getParent().getParents()) { + if (!it.contains(treeNode)) { + it.add(treeNode); + } } - return true; - } + } - /** - * Gets all of the ancestors of this node - * - * @return list of all of the ancestors for this node - */ - public List getAncestors() { - List ancestors = new ArrayList<>(); - Queue it = new LinkedList<>(); - it.add(this); - - while (!it.isEmpty()) { - TreeNode next = it.poll(); - if (next.getParent() != null) { - for (TreeNode treeNode : next.getParent().getParents()) { - if (!it.contains(treeNode)) { - it.add(treeNode); - } - } - } - - if (!ancestors.contains(next)) { - ancestors.add(next); - } - } - return ancestors; + if (!ancestors.contains(next)) { + ancestors.add(next); + } } - - /** - * Gets a list of the descendants of this node - * - * @return list of all the descendants for this node - */ - public List getDescendants() { - List descendants = new ArrayList<>(); - Queue it = new LinkedList<>(); - it.add(this); - - while (!it.isEmpty()) { - TreeElement next = it.poll(); - - if (next.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) next; - for (TreeTransition transition : node.getChildren()) { - if (!descendants.contains(transition)) { - descendants.add(transition); - it.add(transition); - } - } - } else { - TreeTransition trans = (TreeTransition) next; - TreeNode childNode = trans.getChildNode(); - if (childNode != null && !descendants.contains(childNode)) { - descendants.add(childNode); - it.add(childNode); - } - } + return ancestors; + } + + /** + * Gets a list of the descendants of this node + * + * @return list of all the descendants for this node + */ + public List getDescendants() { + List descendants = new ArrayList<>(); + Queue it = new LinkedList<>(); + it.add(this); + + while (!it.isEmpty()) { + TreeElement next = it.poll(); + + if (next.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) next; + for (TreeTransition transition : node.getChildren()) { + if (!descendants.contains(transition)) { + descendants.add(transition); + it.add(transition); + } } - return descendants; + } else { + TreeTransition trans = (TreeTransition) next; + TreeNode childNode = trans.getChildNode(); + if (childNode != null && !descendants.contains(childNode)) { + descendants.add(childNode); + it.add(childNode); + } + } } - - /** - * Gets a DisjointSets containing the children of this node such that the sets contained within - * the DisjointSets are such that elements in the same set are branches of this tree node that - * will eventually merge. This could mean that multiple merges take place before this happens. - * - * @return DisjointSets of tree transitions containing unique non-merging branches - */ - public DisjointSets findMergingBranches() { - DisjointSets branches = new DisjointSets<>(); - children.forEach(branches::createSet); - - for (TreeTransition tran : children) { - branches.createSet(tran); - - TreeNode child = tran.getChildNode(); - if (child != null) { - List nodes = new ArrayList<>(); - nodes.add(child); - while (!nodes.isEmpty()) { - TreeElement element = nodes.get(0); - branches.createSet(element); - branches.union(tran, element); - - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - nodes.addAll(node.getChildren()); - } else { - TreeTransition childTran = (TreeTransition) element; - if (childTran.getChildNode() != null) { - nodes.add(childTran.getChildNode()); - } - } - nodes.remove(element); - } + return descendants; + } + + /** + * Gets a DisjointSets containing the children of this node such that the sets contained within + * the DisjointSets are such that elements in the same set are branches of this tree node that + * will eventually merge. This could mean that multiple merges take place before this happens. + * + * @return DisjointSets of tree transitions containing unique non-merging branches + */ + public DisjointSets findMergingBranches() { + DisjointSets branches = new DisjointSets<>(); + children.forEach(branches::createSet); + + for (TreeTransition tran : children) { + branches.createSet(tran); + + TreeNode child = tran.getChildNode(); + if (child != null) { + List nodes = new ArrayList<>(); + nodes.add(child); + while (!nodes.isEmpty()) { + TreeElement element = nodes.get(0); + branches.createSet(element); + branches.union(tran, element); + + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + nodes.addAll(node.getChildren()); + } else { + TreeTransition childTran = (TreeTransition) element; + if (childTran.getChildNode() != null) { + nodes.add(childTran.getChildNode()); } + } + nodes.remove(element); } + } + } - DisjointSets mergingBranches = new DisjointSets<>(); - children.forEach(mergingBranches::createSet); + DisjointSets mergingBranches = new DisjointSets<>(); + children.forEach(mergingBranches::createSet); - for (TreeTransition tran : children) { - for (TreeTransition tran1 : children) { - if (branches.find(tran) == branches.find(tran1)) { - mergingBranches.union(tran, tran1); - } - } + for (TreeTransition tran : children) { + for (TreeTransition tran1 : children) { + if (branches.find(tran) == branches.find(tran1)) { + mergingBranches.union(tran, tran1); } - return mergingBranches; + } } - - /** - * Finds the point at which the set of tree elements passed in will merge. This must be a set - * gotten from findMergingBranches method DisjointSets - * - * @param branches tree elements to find the merging point - * @return tree transition of the merging point or null if no such point exists - */ - @SuppressWarnings("unchecked") - public static TreeTransition findMergingPoint(Set branches) { - DisjointSets mergeSet = new DisjointSets<>(); - Set branchesCopy = new HashSet<>(branches); - TreeElement headBranch = branchesCopy.iterator().next(); - branchesCopy.remove(headBranch); - - for (TreeElement element : branchesCopy) { - mergeSet.createSet(element); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getDescendants() - .forEach( - (TreeElement e) -> { - if (!mergeSet.contains(e)) { - mergeSet.createSet(e); - } - mergeSet.union(element, e); - }); - } else { - TreeTransition transition = (TreeTransition) element; - TreeNode childNode = transition.getChildNode(); - if (childNode != null) { - List des = childNode.getDescendants(); - for (TreeElement e : des) { - if (!mergeSet.contains(e)) { - mergeSet.createSet(e); - } - mergeSet.union(element, e); - } - } + return mergingBranches; + } + + /** + * Finds the point at which the set of tree elements passed in will merge. This must be a set + * gotten from findMergingBranches method DisjointSets + * + * @param branches tree elements to find the merging point + * @return tree transition of the merging point or null if no such point exists + */ + @SuppressWarnings("unchecked") + public static TreeTransition findMergingPoint(Set branches) { + DisjointSets mergeSet = new DisjointSets<>(); + Set branchesCopy = new HashSet<>(branches); + TreeElement headBranch = branchesCopy.iterator().next(); + branchesCopy.remove(headBranch); + + for (TreeElement element : branchesCopy) { + mergeSet.createSet(element); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getDescendants() + .forEach( + (TreeElement e) -> { + if (!mergeSet.contains(e)) { + mergeSet.createSet(e); + } + mergeSet.union(element, e); + }); + } else { + TreeTransition transition = (TreeTransition) element; + TreeNode childNode = transition.getChildNode(); + if (childNode != null) { + List des = childNode.getDescendants(); + for (TreeElement e : des) { + if (!mergeSet.contains(e)) { + mergeSet.createSet(e); } + mergeSet.union(element, e); + } } + } + } - Queue next = new LinkedList<>(); - next.add(headBranch); - - while (!next.isEmpty()) { - TreeElement element = next.poll(); - if (!mergeSet.contains(element)) { - mergeSet.createSet(element); - } - mergeSet.union(headBranch, element); + Queue next = new LinkedList<>(); + next.add(headBranch); - if (mergeSet.setCount() == 1) { - if (element.getType() == TreeElementType.TRANSITION) { - return (TreeTransition) element; - } - return null; - } + while (!next.isEmpty()) { + TreeElement element = next.poll(); + if (!mergeSet.contains(element)) { + mergeSet.createSet(element); + } + mergeSet.union(headBranch, element); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - next.addAll(node.getChildren()); - } else { - TreeTransition tran = (TreeTransition) element; - next.add(tran.getChildNode()); - } + if (mergeSet.setCount() == 1) { + if (element.getType() == TreeElementType.TRANSITION) { + return (TreeTransition) element; } return null; + } + + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + next.addAll(node.getChildren()); + } else { + TreeTransition tran = (TreeTransition) element; + next.add(tran.getChildNode()); + } } - - /** - * Determines if the specified tree transition is a parent of this node - * - * @param parent tree transition that could be a parent - * @return true if the specified tree transition is a parent of this node, false otherwise - */ - public boolean isParent(TreeTransition parent) { - return this.parent == parent; - } - - /** - * Adds a child to this tree node - * - * @param child child to add - */ - public void addChild(TreeTransition child) { - children.add(child); - } - - /** - * Removes a child to this tree node - * - * @param child child to remove - */ - public void removeChild(TreeTransition child) { - children.remove(child); - } - - /** - * Determines if the specified tree node is a child of this node - * - * @param child tree node that could be a child - * @return true if the specified tree node is a child of this node, false otherwise - */ - public boolean isChild(TreeNode child) { - return children.contains(child); - } - - /** - * Gets the TreeNode's parent - * - * @return the TreeNode's parent - */ - public TreeTransition getParent() { - return parent; - } - - /** - * Sets the TreeNode's parent - * - * @param parent the TreeNode's parent - */ - public void setParent(TreeTransition parent) { - this.parent = parent; - } - - /** - * Gets the TreeNode's children - * - * @return the TreeNode's children - */ - public List getChildren() { - return children; - } - - /** - * Sets the TreeNode's children - * - * @param children the TreeNode's children - */ - public void setChildren(List children) { - this.children = children; - } - - /** - * Is this node the root of the tree - * - * @return true if this node is the root of the tree, false otherwise - */ - public boolean isRoot() { - return isRoot; - } - - /** - * Sets the root of the tree - * - * @param isRoot true if this node is the root of the tree, false otherwise - */ - public void setRoot(boolean isRoot) { - this.isRoot = isRoot; - } - - public void clearChildren() { - this.children.clear(); - } + return null; + } + + /** + * Determines if the specified tree transition is a parent of this node + * + * @param parent tree transition that could be a parent + * @return true if the specified tree transition is a parent of this node, false otherwise + */ + public boolean isParent(TreeTransition parent) { + return this.parent == parent; + } + + /** + * Adds a child to this tree node + * + * @param child child to add + */ + public void addChild(TreeTransition child) { + children.add(child); + } + + /** + * Removes a child to this tree node + * + * @param child child to remove + */ + public void removeChild(TreeTransition child) { + children.remove(child); + } + + /** + * Determines if the specified tree node is a child of this node + * + * @param child tree node that could be a child + * @return true if the specified tree node is a child of this node, false otherwise + */ + public boolean isChild(TreeNode child) { + return children.contains(child); + } + + /** + * Gets the TreeNode's parent + * + * @return the TreeNode's parent + */ + public TreeTransition getParent() { + return parent; + } + + /** + * Sets the TreeNode's parent + * + * @param parent the TreeNode's parent + */ + public void setParent(TreeTransition parent) { + this.parent = parent; + } + + /** + * Gets the TreeNode's children + * + * @return the TreeNode's children + */ + public List getChildren() { + return children; + } + + /** + * Sets the TreeNode's children + * + * @param children the TreeNode's children + */ + public void setChildren(List children) { + this.children = children; + } + + /** + * Is this node the root of the tree + * + * @return true if this node is the root of the tree, false otherwise + */ + public boolean isRoot() { + return isRoot; + } + + /** + * Sets the root of the tree + * + * @param isRoot true if this node is the root of the tree, false otherwise + */ + public void setRoot(boolean isRoot) { + this.isRoot = isRoot; + } + + public void clearChildren() { + this.children.clear(); + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java b/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java index e79cd4b96..e20ba8b6a 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java @@ -9,412 +9,413 @@ import java.util.List; public class TreeTransition extends TreeElement { - private ArrayList parents; - private TreeNode childNode; - private Rule rule; - - private PuzzleElement selection; - private boolean isCorrect; - private boolean isVerified; - - /** - * TreeTransition Constructor create a transition from one node to another - * - * @param board board state of the transition - */ - public TreeTransition(Board board) { - super(TreeElementType.TRANSITION); - this.parents = new ArrayList<>(); - this.childNode = null; - this.board = board; - this.rule = null; - this.selection = null; - this.isCorrect = false; - this.isVerified = false; - } - - /** - * TreeTransition Constructor - create a transition from one node to another - * - * @param parent parent tree node associated with the transition - * @param board board state of the transition - */ - public TreeTransition(TreeNode parent, Board board) { - this(board); - this.parents.add(parent); - } - - /** - * Recursively propagates the change of puzzleElement down the tree - * - * @param element puzzleElement of the change made - */ - @SuppressWarnings("unchecked") - public void propagateChange(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyChange(element); - changed = true; - } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyChange(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyChange(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - PuzzleElement copy = element.copy(); - copy.setModifiable(false); - child.propagateChange(copy); - } - } - } + private ArrayList parents; + private TreeNode childNode; + private Rule rule; + + private PuzzleElement selection; + private boolean isCorrect; + private boolean isVerified; + + /** + * TreeTransition Constructor create a transition from one node to another + * + * @param board board state of the transition + */ + public TreeTransition(Board board) { + super(TreeElementType.TRANSITION); + this.parents = new ArrayList<>(); + this.childNode = null; + this.board = board; + this.rule = null; + this.selection = null; + this.isCorrect = false; + this.isVerified = false; + } + + /** + * TreeTransition Constructor - create a transition from one node to another + * + * @param parent parent tree node associated with the transition + * @param board board state of the transition + */ + public TreeTransition(TreeNode parent, Board board) { + this(board); + this.parents.add(parent); + } + + /** + * Recursively propagates the change of puzzleElement down the tree + * + * @param element puzzleElement of the change made + */ + @SuppressWarnings("unchecked") + public void propagateChange(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyChange(element); + changed = true; } else { - // Overwrite previous modifications to this element - board.removeModifiedData(board.getPuzzleElement(element)); - - // apply changes to tranistion + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); board.notifyChange(element); - - // mark first transition as modified - if (!board.getPuzzleElement(element) - .equalsData(parents.get(0).getBoard().getPuzzleElement(element))) { - board.addModifiedData(element); - } - - // propagate to children - if (childNode != null) { - - // find starting board - TreeNode head = childNode; - while (head.getParent() != null) { - head = head.getParent().getParents().get(0); - } - Board headBoard = head.getBoard(); - - PuzzleElement copy = element.copy(); - // Set as modifiable if reverted to starting value (and started modifiable) - if (headBoard.getPuzzleElement(element).equalsData(element)) { - copy.setModifiable(headBoard.getPuzzleElement(element).isModifiable()); - } else { - copy.setModifiable(false); - } - - // apply changes to result node - childNode.getBoard().notifyChange(copy); - - // apply to all child transitions - for (TreeTransition child : childNode.getChildren()) { - child.propagateChange(copy.copy()); - } - } + changed = true; + } } - reverify(); - } - - /** - * Recursively propagates the addition of puzzleElement down the tree - * - * @param element puzzleElement of the addition made - */ - @SuppressWarnings("unchecked") - public void propagateAddition(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyDeletion(element); - changed = true; - } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyAddition(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyAddition(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateAddition(element.copy()); - } - } - } - } else { - if (childNode != null) { - board.notifyAddition(element); - childNode.getBoard().notifyAddition(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateAddition(element.copy()); - } - } + if (changed && childNode != null) { + childNode.getBoard().notifyChange(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + PuzzleElement copy = element.copy(); + copy.setModifiable(false); + child.propagateChange(copy); + } } - reverify(); - } - - /** - * Recursively propagates the change of puzzleElement down the tree - * - * @param element puzzleElement of the change made - */ - @SuppressWarnings("unchecked") - public void propagateDeletion(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyDeletion(element); - changed = true; - } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyAddition(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyDeletion(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateDeletion(element.copy()); - } - } - } - } else { - if (childNode != null) { - board.notifyDeletion(element); - childNode.getBoard().notifyDeletion(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateDeletion(element.copy()); - } - } + } + } else { + // Overwrite previous modifications to this element + board.removeModifiedData(board.getPuzzleElement(element)); + + // apply changes to tranistion + board.notifyChange(element); + + // mark first transition as modified + if (!board + .getPuzzleElement(element) + .equalsData(parents.get(0).getBoard().getPuzzleElement(element))) { + board.addModifiedData(element); + } + + // propagate to children + if (childNode != null) { + + // find starting board + TreeNode head = childNode; + while (head.getParent() != null) { + head = head.getParent().getParents().get(0); } - reverify(); - } + Board headBoard = head.getBoard(); - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must - * lead to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - @Override - public boolean isContradictoryBranch() { - if (isJustified() && isCorrect() && rule.getRuleType() == RuleType.CONTRADICTION) { - return true; + PuzzleElement copy = element.copy(); + // Set as modifiable if reverted to starting value (and started modifiable) + if (headBoard.getPuzzleElement(element).equalsData(element)) { + copy.setModifiable(headBoard.getPuzzleElement(element).isModifiable()); } else { - if (childNode == null) { - return false; - } else { - return childNode.isContradictoryBranch() && isJustified() && isCorrect(); - } + copy.setModifiable(false); } - } - - /** - * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified - * and justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - @Override - public boolean isValidBranch() { - return isJustified() && isCorrect() && childNode != null && childNode.isValidBranch(); - } - - /** - * Gets the parent tree nodes of this transition - * - * @return parent tree nodes of this tree transition - */ - public ArrayList getParents() { - return parents; - } - - /** - * Sets the parent tree nodes of this transition - * - * @param parents parents tree nodes of this tree transition - */ - public void setParents(ArrayList parents) { - this.parents = parents; - } - - /** - * Adds a parent tree node to this tree transition - * - * @param parent parent tree node to add - */ - public void addParent(TreeNode parent) { - parents.add(parent); - } - - /** - * Removes a parent tree node to this tree transition - * - * @param parent parent tree node to remove - */ - public void removeParent(TreeNode parent) { - parents.remove(parent); - } - - /** - * Determines if the specified tree node is a parent of this transition - * - * @param parent tree node that could be a parent - * @return true if the specified tree node is a parent of this transition, false otherwise - */ - public boolean isParent(TreeNode parent) { - return parents.contains(parent); - } - - /** - * Gets the childNode tree node of this transition - * - * @return childNode tree node - */ - public TreeNode getChildNode() { - return childNode; - } - - /** - * Sets the childNode tree node of this transition - * - * @param childNode childNode tree node - */ - public void setChildNode(TreeNode childNode) { - this.childNode = childNode; - } - - /** - * Gets the rule associated with this transition - * - * @return rule of this transition - */ - public Rule getRule() { - return rule; - } - /** - * Sets the rule associated with this transition - * - * @param rule rule of this transition - */ - public void setRule(Rule rule) { - this.rule = rule; - isVerified = false; - } + // apply changes to result node + childNode.getBoard().notifyChange(copy); - /** - * Gets he selected element associated with this transition - * - * @return If this is a case rule, the selected element for that rule, null otherwise - */ - public PuzzleElement getSelection() { - if (this.rule instanceof CaseRule) { - return selection; + // apply to all child transitions + for (TreeTransition child : childNode.getChildren()) { + child.propagateChange(copy.copy()); } - return null; + } } - - /** - * Sets the selected element associated with this transition - * - * @param selection selected element for this transition - */ - public void setSelection(PuzzleElement selection) { - this.selection = selection; + reverify(); + } + + /** + * Recursively propagates the addition of puzzleElement down the tree + * + * @param element puzzleElement of the addition made + */ + @SuppressWarnings("unchecked") + public void propagateAddition(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyDeletion(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyAddition(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyAddition(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateAddition(element.copy()); + } + } + } + } else { + if (childNode != null) { + board.notifyAddition(element); + childNode.getBoard().notifyAddition(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateAddition(element.copy()); + } + } } - - /** - * Gets whether this transition is correctly justified - * - * @return true if this transition is correctly justified, false otherwise - */ - public boolean isCorrect() { - if (isJustified() && !isVerified) { - isCorrect = rule.checkRule(this) == null; - isVerified = true; + reverify(); + } + + /** + * Recursively propagates the change of puzzleElement down the tree + * + * @param element puzzleElement of the change made + */ + @SuppressWarnings("unchecked") + public void propagateDeletion(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyDeletion(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyAddition(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyDeletion(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateDeletion(element.copy()); + } } - return isJustified() && isCorrect; + } + } else { + if (childNode != null) { + board.notifyDeletion(element); + childNode.getBoard().notifyDeletion(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateDeletion(element.copy()); + } + } } - - /** - * Sets whether this transition is correctly justified - * - * @param isCorrect true if this transition is correctly justified, false otherwise - */ - public void setCorrect(boolean isCorrect) { - this.isCorrect = isCorrect; - this.isVerified = true; + reverify(); + } + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must lead + * to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + @Override + public boolean isContradictoryBranch() { + if (isJustified() && isCorrect() && rule.getRuleType() == RuleType.CONTRADICTION) { + return true; + } else { + if (childNode == null) { + return false; + } else { + return childNode.isContradictoryBranch() && isJustified() && isCorrect(); + } } - - /** - * Forces check of rule on this transition regardless if it has been cached already - * - * @return true if this transition is correctly justified, false otherwise - */ - public boolean reverify() { - isVerified = false; - return isCorrect(); + } + + /** + * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and + * justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + @Override + public boolean isValidBranch() { + return isJustified() && isCorrect() && childNode != null && childNode.isValidBranch(); + } + + /** + * Gets the parent tree nodes of this transition + * + * @return parent tree nodes of this tree transition + */ + public ArrayList getParents() { + return parents; + } + + /** + * Sets the parent tree nodes of this transition + * + * @param parents parents tree nodes of this tree transition + */ + public void setParents(ArrayList parents) { + this.parents = parents; + } + + /** + * Adds a parent tree node to this tree transition + * + * @param parent parent tree node to add + */ + public void addParent(TreeNode parent) { + parents.add(parent); + } + + /** + * Removes a parent tree node to this tree transition + * + * @param parent parent tree node to remove + */ + public void removeParent(TreeNode parent) { + parents.remove(parent); + } + + /** + * Determines if the specified tree node is a parent of this transition + * + * @param parent tree node that could be a parent + * @return true if the specified tree node is a parent of this transition, false otherwise + */ + public boolean isParent(TreeNode parent) { + return parents.contains(parent); + } + + /** + * Gets the childNode tree node of this transition + * + * @return childNode tree node + */ + public TreeNode getChildNode() { + return childNode; + } + + /** + * Sets the childNode tree node of this transition + * + * @param childNode childNode tree node + */ + public void setChildNode(TreeNode childNode) { + this.childNode = childNode; + } + + /** + * Gets the rule associated with this transition + * + * @return rule of this transition + */ + public Rule getRule() { + return rule; + } + + /** + * Sets the rule associated with this transition + * + * @param rule rule of this transition + */ + public void setRule(Rule rule) { + this.rule = rule; + isVerified = false; + } + + /** + * Gets he selected element associated with this transition + * + * @return If this is a case rule, the selected element for that rule, null otherwise + */ + public PuzzleElement getSelection() { + if (this.rule instanceof CaseRule) { + return selection; } - - /** - * Gets whether this transition is justified - * - * @return true if this transition is justified, false otherwise - */ - public boolean isJustified() { - return rule != null; + return null; + } + + /** + * Sets the selected element associated with this transition + * + * @param selection selected element for this transition + */ + public void setSelection(PuzzleElement selection) { + this.selection = selection; + } + + /** + * Gets whether this transition is correctly justified + * + * @return true if this transition is correctly justified, false otherwise + */ + public boolean isCorrect() { + if (isJustified() && !isVerified) { + isCorrect = rule.checkRule(this) == null; + isVerified = true; } - - /*public int modifiedData_size(){ - return board.getModifiedData().size(); - }*/ + return isJustified() && isCorrect; + } + + /** + * Sets whether this transition is correctly justified + * + * @param isCorrect true if this transition is correctly justified, false otherwise + */ + public void setCorrect(boolean isCorrect) { + this.isCorrect = isCorrect; + this.isVerified = true; + } + + /** + * Forces check of rule on this transition regardless if it has been cached already + * + * @return true if this transition is correctly justified, false otherwise + */ + public boolean reverify() { + isVerified = false; + return isCorrect(); + } + + /** + * Gets whether this transition is justified + * + * @return true if this transition is justified, false otherwise + */ + public boolean isJustified() { + return rule != null; + } + + /*public int modifiedData_size(){ + return board.getModifiedData().size(); + }*/ } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java b/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java index 41af3f626..fcfa70cd4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java @@ -6,164 +6,164 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Battleship extends Puzzle { - public Battleship() { - super(); + public Battleship() { + super(); - this.name = "Battleship"; + this.name = "Battleship"; - this.importer = new BattleshipImporter(this); - this.exporter = new BattleshipExporter(this); + this.importer = new BattleshipImporter(this); + this.exporter = new BattleshipExporter(this); - this.factory = new BattleshipCellFactory(); - } + this.factory = new BattleshipCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new BattleshipView((BattleshipBoard) currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new BattleshipView((BattleshipBoard) currentBoard); + addBoardListener(boardView); + } - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Battleship - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Battleship, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for Battleship + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Battleship, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - BattleshipBoard battleShipBoard = (BattleshipBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + BattleshipBoard battleShipBoard = (BattleshipBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(battleShipBoard) == null) { - return false; - } - } - for (PuzzleElement data : battleShipBoard.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) data; - if (cell.getType() == BattleshipType.UNKNOWN) { - return false; - } - } - return true; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(battleShipBoard) == null) { + return false; + } } + for (PuzzleElement data : battleShipBoard.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) data; + if (cell.getType() == BattleshipType.UNKNOWN) { + return false; + } + } + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + // + // @Override + // public void onTreeSelectionChange(ArrayList newSelection) + // { + // + // } + @Override + public void importPuzzle(String fileName) { + // if(fileName != null) + // { + // InputStream inputStream = new FileInputStream(fileName); + // DocumentBuilder builder = null;//factory.newDocumentBuilder(); + // Document document = builder.parse(inputStream); // - // @Override - // public void onTreeSelectionChange(ArrayList newSelection) - // { + // BattleShipBoard battleShipBoard; // - // } - - @Override - public void importPuzzle(String fileName) { - // if(fileName != null) - // { - // InputStream inputStream = new FileInputStream(fileName); - // DocumentBuilder builder = null;//factory.newDocumentBuilder(); - // Document document = builder.parse(inputStream); - // - // BattleShipBoard battleShipBoard; - // - // PuzzleElement rootNode = document.getDocumentElement(); - // PuzzleElement puzzleElement = (PuzzleElement) - // rootNode.getElementsByTagName("edu.rpi.legup.puzzle").item(0); - // PuzzleElement boardElement = (PuzzleElement) - // puzzleElement.getElementsByTagName("board").item(0); - // PuzzleElement axesElement = (PuzzleElement) - // boardElement.getElementsByTagName("axes").item(0); - // PuzzleElement shipElement = (PuzzleElement) - // boardElement.getElementsByTagName("ships").item(0); - // PuzzleElement cellElement = (PuzzleElement) - // boardElement.getElementsByTagName("cells").item(0); - // PuzzleElement rightElement = (PuzzleElement) - // axesElement.getElementsByTagName("right").item(0); - // PuzzleElement bottomElement = (PuzzleElement) - // axesElement.getElementsByTagName("bottom").item(0); - // NodeList rightClueList = rightElement.getElementsByTagName("clue"); - // NodeList bottomClueList = bottomElement.getElementsByTagName("clue"); - // NodeList shipList = shipElement.getElementsByTagName("ship"); - // NodeList cells = cellElement.getElementsByTagName("cell"); - // - // int size = Integer.valueOf(boardElement.getAttribute("size")); - // battleShipBoard = new BattleShipBoard(size); - // - // ArrayList battleShipData = new ArrayList<>(); - // for(int i = 0; i < size * size; i++) - // { - // battleShipData.add(null); - // } - // - // for (int i = 0; i < rightClueList.getLength(); i++) { - // battleShipBoard.getRight()[i] = - // Integer.valueOf(rightClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); - // } - // - // for (int i = 0; i < bottomClueList.getLength(); i++) { - // battleShipBoard.getBottom()[i] = - // Integer.valueOf(bottomClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); - // } - // - // for (int i = 0; i < shipList.getLength(); i++) { - // int length = - // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("length").getNodeValue()); - // int count = - // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("count").getNodeValue()); - // battleShipBoard.getShips().add(new Ship(length, count)); - // } - // - // for (int i = 0; i < cells.getLength(); i++) { - // int x = - // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("x").getNodeValue()); - // int y = - // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("y").getNodeValue()); - // String value = - // cells.item(i).getAttributes().getNamedItem("value").getNodeValue().toUpperCase(); - // - // BattleShipCell cell = new - // BattleShipCell(BattleShipType.valueOf(value).ordinal(), new Point(x, y)); - // battleShipBoard.setCell(x, y, cell); - // cell.setModifiable(false); - // cell.setGiven(true); - // } - // - // for (int x = 0; x < size; x++) { - // for (int y = 0; y < size; y++) { - // if (battleShipBoard.getCell(x, y) == null) { - // BattleShipCell cell = new BattleShipCell(9, new Point(x, y)); - // cell.setModifiable(true); - // battleShipBoard.setCell(x, y, cell); - // } - // } - // } - // this.currentBoard = battleShipBoard; - // this.tree = new Tree(currentBoard); - // } - } + // PuzzleElement rootNode = document.getDocumentElement(); + // PuzzleElement puzzleElement = (PuzzleElement) + // rootNode.getElementsByTagName("edu.rpi.legup.puzzle").item(0); + // PuzzleElement boardElement = (PuzzleElement) + // puzzleElement.getElementsByTagName("board").item(0); + // PuzzleElement axesElement = (PuzzleElement) + // boardElement.getElementsByTagName("axes").item(0); + // PuzzleElement shipElement = (PuzzleElement) + // boardElement.getElementsByTagName("ships").item(0); + // PuzzleElement cellElement = (PuzzleElement) + // boardElement.getElementsByTagName("cells").item(0); + // PuzzleElement rightElement = (PuzzleElement) + // axesElement.getElementsByTagName("right").item(0); + // PuzzleElement bottomElement = (PuzzleElement) + // axesElement.getElementsByTagName("bottom").item(0); + // NodeList rightClueList = rightElement.getElementsByTagName("clue"); + // NodeList bottomClueList = bottomElement.getElementsByTagName("clue"); + // NodeList shipList = shipElement.getElementsByTagName("ship"); + // NodeList cells = cellElement.getElementsByTagName("cell"); + // + // int size = Integer.valueOf(boardElement.getAttribute("size")); + // battleShipBoard = new BattleShipBoard(size); + // + // ArrayList battleShipData = new ArrayList<>(); + // for(int i = 0; i < size * size; i++) + // { + // battleShipData.add(null); + // } + // + // for (int i = 0; i < rightClueList.getLength(); i++) { + // battleShipBoard.getRight()[i] = + // Integer.valueOf(rightClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); + // } + // + // for (int i = 0; i < bottomClueList.getLength(); i++) { + // battleShipBoard.getBottom()[i] = + // Integer.valueOf(bottomClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); + // } + // + // for (int i = 0; i < shipList.getLength(); i++) { + // int length = + // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("length").getNodeValue()); + // int count = + // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("count").getNodeValue()); + // battleShipBoard.getShips().add(new Ship(length, count)); + // } + // + // for (int i = 0; i < cells.getLength(); i++) { + // int x = + // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("x").getNodeValue()); + // int y = + // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("y").getNodeValue()); + // String value = + // cells.item(i).getAttributes().getNamedItem("value").getNodeValue().toUpperCase(); + // + // BattleShipCell cell = new + // BattleShipCell(BattleShipType.valueOf(value).ordinal(), new Point(x, y)); + // battleShipBoard.setCell(x, y, cell); + // cell.setModifiable(false); + // cell.setGiven(true); + // } + // + // for (int x = 0; x < size; x++) { + // for (int y = 0; y < size; y++) { + // if (battleShipBoard.getCell(x, y) == null) { + // BattleShipCell cell = new BattleShipCell(9, new Point(x, y)); + // cell.setModifiable(true); + // battleShipBoard.setCell(x, y, cell); + // } + // } + // } + // this.currentBoard = battleShipBoard; + // this.tree = new Tree(currentBoard); + // } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java index 555c8471f..cbf7ffbcd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java @@ -8,148 +8,148 @@ public class BattleshipBoard extends GridBoard { - private List east; - private List south; + private List east; + private List south; - /** - * Constructor for creating a rectangular battleship board. - * - * @param width width of the board - * @param height height of the board - */ - public BattleshipBoard(int width, int height) { - super(width, height); + /** + * Constructor for creating a rectangular battleship board. + * + * @param width width of the board + * @param height height of the board + */ + public BattleshipBoard(int width, int height) { + super(width, height); - this.east = new ArrayList<>(); - this.south = new ArrayList<>(); + this.east = new ArrayList<>(); + this.south = new ArrayList<>(); - for (int i = 0; i < height; i++) { - east.add(null); - } - for (int i = 0; i < width; i++) { - south.add(null); - } + for (int i = 0; i < height; i++) { + east.add(null); } - - /** - * Constructor for creating a square-sized battleship board. - * - * @param size size of the board - */ - public BattleshipBoard(int size) { - this(size, size); + for (int i = 0; i < width; i++) { + south.add(null); } + } - /** - * Gets the east {@link BattleshipClue} - * - * @return List of BattleShipClue objects on the east side of the board - */ - public List getEast() { - return east; - } + /** + * Constructor for creating a square-sized battleship board. + * + * @param size size of the board + */ + public BattleshipBoard(int size) { + this(size, size); + } - /** - * Gets the east {@link BattleshipClue} - * - * @return east battle ship clues - */ - public List getSouth() { - return south; - } + /** + * Gets the east {@link BattleshipClue} + * + * @return List of BattleShipClue objects on the east side of the board + */ + public List getEast() { + return east; + } - @Override - public BattleshipCell getCell(int x, int y) { - return (BattleshipCell) super.getCell(x, y); - } + /** + * Gets the east {@link BattleshipClue} + * + * @return east battle ship clues + */ + public List getSouth() { + return south; + } - @Override - /** - * Creates a copy of the current board - * - * @return the copy of the board - */ - public BattleshipBoard copy() { - BattleshipBoard copy = new BattleshipBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.east = this.east; - copy.south = this.south; - return copy; - } + @Override + public BattleshipCell getCell(int x, int y) { + return (BattleshipCell) super.getCell(x, y); + } - /** - * Get a list of all orthogonally adjacent cells. - * - * @param cell The cell to get adjacent cells from. - * @return List of adjacent cells in clockwise order: { up, right, down, left } - */ - public List getAdjOrthogonals(BattleshipCell cell) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - BattleshipCell up = getCell(loc.x, loc.y - 1); - BattleshipCell right = getCell(loc.x + 1, loc.y); - BattleshipCell down = getCell(loc.x, loc.y + 1); - BattleshipCell left = getCell(loc.x - 1, loc.y); - adj.add(up); - adj.add(right); - adj.add(down); - adj.add(left); - return adj; + @Override + /** + * Creates a copy of the current board + * + * @return the copy of the board + */ + public BattleshipBoard copy() { + BattleshipBoard copy = new BattleshipBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } - - /** - * Get a list of all diagonally adjacent cells. - * - * @param cell The cell to get diagonally adjacent cells from. - * @return List of diagonally adjacent cells in clockwise order: - * { upRight, downRight, downLeft, upLeft } - */ - public List getAdjDiagonals(BattleshipCell cell) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - BattleshipCell upRight = getCell(loc.x + 1, loc.y - 1); - BattleshipCell downRight = getCell(loc.x + 1, loc.y + 1); - BattleshipCell downLeft = getCell(loc.x - 1, loc.y + 1); - BattleshipCell upLeft = getCell(loc.x - 1, loc.y - 1); - dia.add(upRight); - dia.add(downRight); - dia.add(downLeft); - dia.add(upLeft); - return dia; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + copy.east = this.east; + copy.south = this.south; + return copy; + } + + /** + * Get a list of all orthogonally adjacent cells. + * + * @param cell The cell to get adjacent cells from. + * @return List of adjacent cells in clockwise order: { up, right, down, left } + */ + public List getAdjOrthogonals(BattleshipCell cell) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + BattleshipCell up = getCell(loc.x, loc.y - 1); + BattleshipCell right = getCell(loc.x + 1, loc.y); + BattleshipCell down = getCell(loc.x, loc.y + 1); + BattleshipCell left = getCell(loc.x - 1, loc.y); + adj.add(up); + adj.add(right); + adj.add(down); + adj.add(left); + return adj; + } + + /** + * Get a list of all diagonally adjacent cells. + * + * @param cell The cell to get diagonally adjacent cells from. + * @return List of diagonally adjacent cells in clockwise order: + * { upRight, downRight, downLeft, upLeft } + */ + public List getAdjDiagonals(BattleshipCell cell) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + BattleshipCell upRight = getCell(loc.x + 1, loc.y - 1); + BattleshipCell downRight = getCell(loc.x + 1, loc.y + 1); + BattleshipCell downLeft = getCell(loc.x - 1, loc.y + 1); + BattleshipCell upLeft = getCell(loc.x - 1, loc.y - 1); + dia.add(upRight); + dia.add(downRight); + dia.add(downLeft); + dia.add(upLeft); + return dia; + } - /** - * Get a list of cells in a row. - * - * @param y The y-coordinate of the row. - * @return List of cells in the row in increasing x-coordinate order. - */ - public List getRow(int y) { - List row = new ArrayList<>(); - for (int x = 0; x < dimension.width; x++) { - row.add(getCell(x, y)); - } - return row; + /** + * Get a list of cells in a row. + * + * @param y The y-coordinate of the row. + * @return List of cells in the row in increasing x-coordinate order. + */ + public List getRow(int y) { + List row = new ArrayList<>(); + for (int x = 0; x < dimension.width; x++) { + row.add(getCell(x, y)); } + return row; + } - /** - * Get a list of cells in a column. - * - * @param x The x-coordinate of the column. - * @return List of cells in the column in increasing y-coordinate order. - */ - public List getColumn(int x) { - List column = new ArrayList<>(); - for (int y = 0; y < dimension.height; y++) { - column.add(getCell(x, y)); - } - return column; + /** + * Get a list of cells in a column. + * + * @param x The x-coordinate of the column. + * @return List of cells in the column in increasing y-coordinate order. + */ + public List getColumn(int x) { + List column = new ArrayList<>(); + for (int y = 0; y < dimension.height; y++) { + column.add(getCell(x, y)); } + return column; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java index 5a5b86094..1e902633e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java @@ -5,35 +5,35 @@ public class BattleshipCell extends GridCell { - /** - * BattleShipCell Constructor - creates a BattleShipCell from the specified value and location - * - * @param value value of the BattleShipCell - * @param location position of the BattleShipCell - */ - public BattleshipCell(BattleshipType value, Point location) { - super(value, location); - } + /** + * BattleShipCell Constructor - creates a BattleShipCell from the specified value and location + * + * @param value value of the BattleShipCell + * @param location position of the BattleShipCell + */ + public BattleshipCell(BattleshipType value, Point location) { + super(value, location); + } - /** - * Gets the type of this BattleShipCell - * - * @return type of BattleShipCell - */ - public BattleshipType getType() { - return data; - } + /** + * Gets the type of this BattleShipCell + * + * @return type of BattleShipCell + */ + public BattleshipType getType() { + return data; + } - /** - * Performs a deep copy on the BattleShipCell - * - * @return a new copy of the BattleShipCell that is independent of this one - */ - public BattleshipCell copy() { - BattleshipCell copy = new BattleshipCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the BattleShipCell + * + * @return a new copy of the BattleShipCell that is independent of this one + */ + public BattleshipCell copy() { + BattleshipCell copy = new BattleshipCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java index 9db0cca84..d97a44034 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java @@ -5,39 +5,39 @@ import java.awt.event.MouseEvent; public class BattleshipCellController extends ElementController { - /** - * Controller class for the Battleship puzzle - receives user mouse input and changes what's - * shown on the GUI - * - * @param data the PuzzleElement to be changed - * @param e the user mouse input - */ - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - BattleshipCell cell = (BattleshipCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == BattleshipType.SHIP_MIDDLE) { - cell.setData(BattleshipType.UNKNOWN); - } else { - cell.setData(BattleshipType.getType(cell.getData().value + 1)); - } - } + /** + * Controller class for the Battleship puzzle - receives user mouse input and changes what's shown + * on the GUI + * + * @param data the PuzzleElement to be changed + * @param e the user mouse input + */ + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + BattleshipCell cell = (BattleshipCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == BattleshipType.SHIP_MIDDLE) { + cell.setData(BattleshipType.UNKNOWN); } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == BattleshipType.UNKNOWN) { - cell.setData(BattleshipType.SHIP_MIDDLE); - } else { - cell.setData(BattleshipType.getType(cell.getData().value - 1)); - } - } + cell.setData(BattleshipType.getType(cell.getData().value + 1)); } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == BattleshipType.UNKNOWN) { + cell.setData(BattleshipType.SHIP_MIDDLE); + } else { + cell.setData(BattleshipType.getType(cell.getData().value - 1)); + } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java index 1b3b6c427..f967a677e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java @@ -10,68 +10,66 @@ import org.w3c.dom.Node; public class BattleshipCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) - throws InvalidFileFormatException { - try { - BattleshipBoard battleShipBoard = (BattleshipBoard) board; - int width = battleShipBoard.getWidth(); - int height = battleShipBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - if (node.getNodeName().equalsIgnoreCase("cell")) { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) + throws InvalidFileFormatException { + try { + BattleshipBoard battleShipBoard = (BattleshipBoard) board; + int width = battleShipBoard.getWidth(); + int height = battleShipBoard.getHeight(); + NamedNodeMap attributeList = node.getAttributes(); + if (node.getNodeName().equalsIgnoreCase("cell")) { - int value = Integer.parseInt(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.parseInt(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.parseInt(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException( - "BattleShip Factory: cell location out of bounds"); - } - if (value < 0 || value > 3) { - throw new InvalidFileFormatException("BattleShip Factory: cell unknown value"); - } - - BattleshipCell cell = - new BattleshipCell(BattleshipType.getType(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } else { - throw new InvalidFileFormatException( - "BattleShip Factory: unknown puzzleElement puzzleElement"); - } - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "BattleShip Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("BattleShip Factory: could not find attribute(s)"); + int value = Integer.parseInt(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.parseInt(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.parseInt(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("BattleShip Factory: cell location out of bounds"); + } + if (value < 0 || value > 3) { + throw new InvalidFileFormatException("BattleShip Factory: cell unknown value"); } + + BattleshipCell cell = new BattleshipCell(BattleshipType.getType(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } else { + throw new InvalidFileFormatException( + "BattleShip Factory: unknown puzzleElement puzzleElement"); + } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "BattleShip Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("BattleShip Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - BattleshipCell cell = (BattleshipCell) puzzleElement; - Point loc = cell.getLocation(); + BattleshipCell cell = (BattleshipCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java index 6b5856639..1ed0face1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java @@ -4,75 +4,75 @@ public class BattleshipClue extends PuzzleElement { - private BattleshipType type; + private BattleshipType type; - public BattleshipClue(int value, int index, BattleshipType type) { - super(value); - this.index = index; - this.type = type; - } + public BattleshipClue(int value, int index, BattleshipType type) { + super(value); + this.index = index; + this.type = type; + } - /** - * Returns the column number as a string - * - * @param col the column number that is to be converted and returned - * @return int value - */ - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; - } - return sb.reverse().toString(); + /** + * Returns the column number as a string + * + * @param col the column number that is to be converted and returned + * @return int value + */ + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; } + return sb.reverse().toString(); + } - /** - * Returns the column string as an integer - * - * @param col the column number as a string that is to be converted and returned - * @return string value - */ - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; - } - return result; + /** + * Returns the column string as an integer + * + * @param col the column number as a string that is to be converted and returned + * @return string value + */ + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; } + return result; + } - /** - * Gets the int value that represents this puzzleElement - * - * @return int value - */ - @Override - public Integer getData() { - return (Integer) super.getData(); - } + /** + * Gets the int value that represents this puzzleElement + * + * @return int value + */ + @Override + public Integer getData() { + return (Integer) super.getData(); + } - /** - * Returns the type of the battleship object (ship or clue) - * - * @return BattleshipType type - */ - public BattleshipType getType() { - return type; - } + /** + * Returns the type of the battleship object (ship or clue) + * + * @return BattleshipType type + */ + public BattleshipType getType() { + return type; + } - /** - * Sets the type of the battleship object (ship or clue) to the given type - * - * @param type given Battleship type - */ - public void setType(BattleshipType type) { - this.type = type; - } + /** + * Sets the type of the battleship object (ship or clue) to the given type + * + * @param type given Battleship type + */ + public void setType(BattleshipType type) { + this.type = type; + } - public BattleshipClue copy() { - return null; - } + public BattleshipClue copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java index 788c860f3..e2ad8b863 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java @@ -5,55 +5,55 @@ public class BattleshipClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public BattleshipClueView(BattleshipClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public BattleshipClue getPuzzleElement() { - return (BattleshipClue) super.getPuzzleElement(); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public BattleshipClueView(BattleshipClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public BattleshipClue getPuzzleElement() { + return (BattleshipClue) super.getPuzzleElement(); + } + + @Override + /** + * Draws the clue from the PuzzleElement associated with this view on the given frame + * + * @param graphics2D the frame the clue is to be drawn on + */ + public void draw(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + BattleshipClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + value = String.valueOf(clue.getData() + 1); + break; + case CLUE_EAST: + value = String.valueOf(clue.getData()); + break; + case CLUE_SOUTH: + value = String.valueOf(clue.getData()); + break; + case CLUE_WEST: + value = BattleshipClue.colNumToString(clue.getData() + 1); + break; + default: + value = ""; } - @Override - /** - * Draws the clue from the PuzzleElement associated with this view on the given frame - * - * @param graphics2D the frame the clue is to be drawn on - */ - public void draw(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - BattleshipClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - value = String.valueOf(clue.getData() + 1); - break; - case CLUE_EAST: - value = String.valueOf(clue.getData()); - break; - case CLUE_SOUTH: - value = String.valueOf(clue.getData()); - break; - case CLUE_WEST: - value = BattleshipClue.colNumToString(clue.getData() + 1); - break; - default: - value = ""; - } - - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java index 1898468ce..fed0afaf3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java @@ -4,107 +4,94 @@ import java.awt.*; public class BattleshipElementView extends GridElementView { - private static final Stroke OUTLINE_STROKE = new BasicStroke(1); - private static final Color OUTLINE_COLOR = new Color(0x212121); + private static final Stroke OUTLINE_STROKE = new BasicStroke(1); + private static final Color OUTLINE_COLOR = new Color(0x212121); - private static final Color UNKNOWN_COLOR = new Color(0xE0E0E0); - private static final Color WATER_COLOR = new Color(0x1565C0); - private static final Color SHIP_COLOR = new Color(0x757575); + private static final Color UNKNOWN_COLOR = new Color(0xE0E0E0); + private static final Color WATER_COLOR = new Color(0x1565C0); + private static final Color SHIP_COLOR = new Color(0x757575); - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 10); - private static final Color FONT_COLOR = new Color(0xFFEB3B); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 10); + private static final Color FONT_COLOR = new Color(0xFFEB3B); - public BattleshipElementView(BattleshipCell cell) { - super(cell); - } - - @Override - /** - * Draws on the given frame based on the type of the cell of the current puzzleElement - * - * @param graphics2D the frame to be drawn on - */ - public void drawElement(Graphics2D graphics2D) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - BattleshipType type = cell.getType(); + public BattleshipElementView(BattleshipCell cell) { + super(cell); + } - switch (type) { - case UNKNOWN: - graphics2D.setColor(UNKNOWN_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - case WATER: - graphics2D.setColor(WATER_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - case SHIP_UNKNOWN: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillRect( - location.x + 3 * size.width / 8, - location.y + 3 * size.height / 8, - size.width / 4, - size.height / 4); + @Override + /** + * Draws on the given frame based on the type of the cell of the current puzzleElement + * + * @param graphics2D the frame to be drawn on + */ + public void drawElement(Graphics2D graphics2D) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + BattleshipType type = cell.getType(); - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = "?"; - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = - location.y - + ((size.height - metrics.getHeight()) / 2) - + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - break; - case SUBMARINE: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillOval( - location.x + size.width / 4, - location.y + size.width / 4, - size.width / 2, - size.height / 2); - break; - case SHIP_TOP: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x, - location.y - size.height / 2, - size.width, - size.height, - 180, - 180); - break; - case SHIP_RIGHT: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x + size.height / 2, location.y, size.width, size.height, 90, 180); - break; - case SHIP_BOTTOM: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x, location.y + size.height / 2, size.width, size.height, 0, 180); - break; - case SHIP_LEFT: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x - size.height / 2, - location.y, - size.width, - size.height, - 270, - 180); - break; - case SHIP_MIDDLE: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - default: - graphics2D.setColor(new Color(0xE040FB)); - break; - } + switch (type) { + case UNKNOWN: + graphics2D.setColor(UNKNOWN_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + case WATER: + graphics2D.setColor(WATER_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + case SHIP_UNKNOWN: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillRect( + location.x + 3 * size.width / 8, + location.y + 3 * size.height / 8, + size.width / 4, + size.height / 4); - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.setStroke(OUTLINE_STROKE); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = "?"; + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + break; + case SUBMARINE: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillOval( + location.x + size.width / 4, + location.y + size.width / 4, + size.width / 2, + size.height / 2); + break; + case SHIP_TOP: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x, location.y - size.height / 2, size.width, size.height, 180, 180); + break; + case SHIP_RIGHT: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x + size.height / 2, location.y, size.width, size.height, 90, 180); + break; + case SHIP_BOTTOM: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x, location.y + size.height / 2, size.width, size.height, 0, 180); + break; + case SHIP_LEFT: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x - size.height / 2, location.y, size.width, size.height, 270, 180); + break; + case SHIP_MIDDLE: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + default: + graphics2D.setColor(new Color(0xE040FB)); + break; } + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.setStroke(OUTLINE_STROKE); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java index cbc364842..d9ec97a58 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java @@ -6,60 +6,60 @@ public class BattleshipExporter extends PuzzleExporter { - public BattleshipExporter(Battleship battleShip) { - super(battleShip); - } - - /** - * Creates and returns a new board element in the XML document specified - * - * @param newDocument the XML document to append to - * @return the new board element - */ - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - BattleshipBoard board; - if (puzzle.getTree() != null) { - board = (BattleshipBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (BattleshipBoard) puzzle.getBoardView().getBoard(); - } + public BattleshipExporter(Battleship battleShip) { + super(battleShip); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + /** + * Creates and returns a new board element in the XML document specified + * + * @param newDocument the XML document to append to + * @return the new board element + */ + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + BattleshipBoard board; + if (puzzle.getTree() != null) { + board = (BattleshipBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (BattleshipBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - if (cell.getData() != BattleshipType.getType(0)) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (BattleshipClue clue : board.getEast()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", BattleshipClue.colNumToString(clue.getIndex())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + if (cell.getData() != BattleshipType.getType(0)) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (BattleshipClue clue : board.getEast()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", String.valueOf(clue.getIndex())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (BattleshipClue clue : board.getEast()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", BattleshipClue.colNumToString(clue.getIndex())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); - return boardElement; + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (BattleshipClue clue : board.getEast()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", String.valueOf(clue.getIndex())); + axisSouth.appendChild(clueElement); } + boardElement.appendChild(axisSouth); + + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java index cbc1dd02b..012bf9b5c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java @@ -8,183 +8,176 @@ import org.w3c.dom.NodeList; public class BattleshipImporter extends PuzzleImporter { - public BattleshipImporter(Battleship battleShip) { - super(battleShip); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + public BattleshipImporter(Battleship battleShip) { + super(battleShip); + } + + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } + + @Override + public boolean acceptsTextInput() { + return false; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + BattleshipBoard battleShipBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + battleShipBoard = new BattleshipBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + battleShipBoard = new BattleshipBoard(width, height); + } + } + + if (battleShipBoard == null) { + throw new InvalidFileFormatException("BattleShip Importer: " + "invalid board dimensions"); + } + + int width = battleShipBoard.getWidth(); + int height = battleShipBoard.getHeight(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + BattleshipCell cell = + (BattleshipCell) + puzzle.getFactory().importCell(elementDataList.item(i), battleShipBoard); + Point loc = cell.getLocation(); + if (cell.getData() != BattleshipType.getType(0)) { + cell.setModifiable(false); + cell.setGiven(true); + } + battleShipBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (battleShipBoard.getCell(x, y) == null) { + BattleshipCell cell = new BattleshipCell(BattleshipType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + battleShipBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("BattleShip Importer: " + "cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis2.hasAttribute("side")) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != battleShipBoard.getHeight() + || southClues.getLength() != battleShipBoard.getWidth()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + + "there must be same number of clues as the dimension " + + "of the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = BattleshipClue.colStringToColNum(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > battleShipBoard.getHeight()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "clue index out of bounds"); + } - @Override - public boolean acceptsTextInput() { - return false; - } + if (battleShipBoard.getEast().get(index - 1) != null) { + throw new InvalidFileFormatException("BattleShip Importer: " + "duplicate clue index"); + } + battleShipBoard + .getEast() + .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > battleShipBoard.getWidth()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "clue index out of bounds"); + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - BattleshipBoard battleShipBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - battleShipBoard = new BattleshipBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - battleShipBoard = new BattleshipBoard(width, height); - } - } - - if (battleShipBoard == null) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "invalid board dimensions"); - } - - int width = battleShipBoard.getWidth(); - int height = battleShipBoard.getHeight(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - BattleshipCell cell = - (BattleshipCell) - puzzle.getFactory() - .importCell(elementDataList.item(i), battleShipBoard); - Point loc = cell.getLocation(); - if (cell.getData() != BattleshipType.getType(0)) { - cell.setModifiable(false); - cell.setGiven(true); - } - battleShipBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (battleShipBoard.getCell(x, y) == null) { - BattleshipCell cell = - new BattleshipCell(BattleshipType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - battleShipBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("BattleShip Importer: " + "cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis2.hasAttribute("side")) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != battleShipBoard.getHeight() - || southClues.getLength() != battleShipBoard.getWidth()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " - + "there must be same number of clues as the dimension " - + "of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = BattleshipClue.colStringToColNum(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > battleShipBoard.getHeight()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "clue index out of bounds"); - } - - if (battleShipBoard.getEast().get(index - 1) != null) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "duplicate clue index"); - } - battleShipBoard - .getEast() - .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > battleShipBoard.getWidth()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "clue index out of bounds"); - } - - if (battleShipBoard.getSouth().get(index - 1) != null) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "duplicate clue index"); - } - battleShipBoard - .getSouth() - .set( - index - 1, - new BattleshipClue(value, index, BattleshipType.CLUE_SOUTH)); - } - - puzzle.setCurrentBoard(battleShipBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "unknown value where integer expected"); + if (battleShipBoard.getSouth().get(index - 1) != null) { + throw new InvalidFileFormatException("BattleShip Importer: " + "duplicate clue index"); } + battleShipBoard + .getSouth() + .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_SOUTH)); + } + + puzzle.setCurrentBoard(battleShipBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Battleship cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Battleship cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java index 0d505f43c..2cee10469 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java @@ -1,52 +1,52 @@ package edu.rpi.legup.puzzle.battleship; public enum BattleshipType { - UNKNOWN, - WATER, - SUBMARINE, - SHIP_UNKNOWN, - SHIP_TOP, - SHIP_RIGHT, - SHIP_BOTTOM, - SHIP_LEFT, - SHIP_MIDDLE, - CLUE_NORTH, - CLUE_EAST, - CLUE_SOUTH, - CLUE_WEST; + UNKNOWN, + WATER, + SUBMARINE, + SHIP_UNKNOWN, + SHIP_TOP, + SHIP_RIGHT, + SHIP_BOTTOM, + SHIP_LEFT, + SHIP_MIDDLE, + CLUE_NORTH, + CLUE_EAST, + CLUE_SOUTH, + CLUE_WEST; - public int value; + public int value; - BattleshipType() { - this.value = this.ordinal(); - } + BattleshipType() { + this.value = this.ordinal(); + } - /** - * Gets the enum of this BattleShipType - * - * @param value the integer value input - * @return enum equivalent BattleShipType of integer value - */ - public static BattleshipType getType(int value) { - BattleshipType[] vals = values(); - if (value >= 0 && value < vals.length) { - return vals[value]; - } - return null; + /** + * Gets the enum of this BattleShipType + * + * @param value the integer value input + * @return enum equivalent BattleShipType of integer value + */ + public static BattleshipType getType(int value) { + BattleshipType[] vals = values(); + if (value >= 0 && value < vals.length) { + return vals[value]; } + return null; + } - /** - * Checks if the type is a ship. - * - * @param type the {@link BattleshipType} to check - * @return true if the type is a ship, false otherwise - */ - public static boolean isShip(BattleshipType type) { - return type == SHIP_UNKNOWN - || type == SHIP_TOP - || type == SHIP_RIGHT - || type == SHIP_BOTTOM - || type == SHIP_LEFT - || type == SHIP_MIDDLE; - } + /** + * Checks if the type is a ship. + * + * @param type the {@link BattleshipType} to check + * @return true if the type is a ship, false otherwise + */ + public static boolean isShip(BattleshipType type) { + return type == SHIP_UNKNOWN + || type == SHIP_TOP + || type == SHIP_RIGHT + || type == SHIP_BOTTOM + || type == SHIP_LEFT + || type == SHIP_MIDDLE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java index 4095db54a..b82828fb8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java @@ -7,23 +7,22 @@ public class BattleshipView extends GridBoardView { - public BattleshipView(BattleshipBoard board) { - super(new BoardController(), new BattleshipCellController(), board.getDimension()); + public BattleshipView(BattleshipBoard board) { + super(new BoardController(), new BattleshipCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - Point loc = cell.getLocation(); - BattleshipElementView elementView = new BattleshipElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + Point loc = cell.getLocation(); + BattleshipElementView elementView = new BattleshipElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); - } + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java index f1ecd6685..41abeabe1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java @@ -10,79 +10,79 @@ public class AdjacentShipsContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "No instance of the contradiction " + this.ruleName + " here"; + private final String NO_CONTRADICTION_MESSAGE = + "No instance of the contradiction " + this.ruleName + " here"; - public AdjacentShipsContradictionRule() { - super( - "BTSP-CONT-0001", - "Adjacent Ships", - "Cells next to the battleship must be water.", - "edu/rpi/legup/images/battleship/contradictions" + "/AdjacentShips.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule. - * - * @param board board to check contradiction - * @param puzzleElement equivalent {@link PuzzleElement} - * @return null if the transition contains a contradiction at the specified {@link - * PuzzleElement}, otherwise return a no contradiction message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - BattleshipBoard bsBoard = (BattleshipBoard) board; - BattleshipCell cell = (BattleshipCell) bsBoard.getPuzzleElement(puzzleElement); + public AdjacentShipsContradictionRule() { + super( + "BTSP-CONT-0001", + "Adjacent Ships", + "Cells next to the battleship must be water.", + "edu/rpi/legup/images/battleship/contradictions" + "/AdjacentShips.png"); + } - // rule only applies to battleship cells - if (!BattleshipType.isShip(cell.getType())) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule. + * + * @param board board to check contradiction + * @param puzzleElement equivalent {@link PuzzleElement} + * @return null if the transition contains a contradiction at the specified {@link + * PuzzleElement}, otherwise return a no contradiction message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + BattleshipBoard bsBoard = (BattleshipBoard) board; + BattleshipCell cell = (BattleshipCell) bsBoard.getPuzzleElement(puzzleElement); - // check orthogonally adjacent cells - List orthoAdjCells = bsBoard.getAdjOrthogonals(cell); + // rule only applies to battleship cells + if (!BattleshipType.isShip(cell.getType())) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } - BattleshipCell up = orthoAdjCells.get(0); - BattleshipCell right = orthoAdjCells.get(1); - BattleshipCell down = orthoAdjCells.get(2); - BattleshipCell left = orthoAdjCells.get(3); + // check orthogonally adjacent cells + List orthoAdjCells = bsBoard.getAdjOrthogonals(cell); - boolean isVertical = - (up != null && BattleshipType.isShip(up.getData())) - || (down != null && BattleshipType.isShip(down.getData())); + BattleshipCell up = orthoAdjCells.get(0); + BattleshipCell right = orthoAdjCells.get(1); + BattleshipCell down = orthoAdjCells.get(2); + BattleshipCell left = orthoAdjCells.get(3); - boolean isHorizontal = - (left != null && BattleshipType.isShip(left.getData())) - || (right != null && BattleshipType.isShip(right.getData())); + boolean isVertical = + (up != null && BattleshipType.isShip(up.getData())) + || (down != null && BattleshipType.isShip(down.getData())); - // ships cannot be both vertical and horizontal - if (isVertical && isHorizontal) { - return null; - } + boolean isHorizontal = + (left != null && BattleshipType.isShip(left.getData())) + || (right != null && BattleshipType.isShip(right.getData())); - // check diagonally adjacent cells - List diagAdjCells = bsBoard.getAdjDiagonals(cell); + // ships cannot be both vertical and horizontal + if (isVertical && isHorizontal) { + return null; + } - BattleshipCell upRight = diagAdjCells.get(0); - BattleshipCell downRight = diagAdjCells.get(1); - BattleshipCell downLeft = diagAdjCells.get(2); - BattleshipCell upLeft = diagAdjCells.get(3); + // check diagonally adjacent cells + List diagAdjCells = bsBoard.getAdjDiagonals(cell); - // diagonally adjacent cells must be water - if (upRight != null && BattleshipType.isShip(upRight.getData())) { - return null; - } - if (downRight != null && BattleshipType.isShip(downRight.getData())) { - return null; - } - if (downLeft != null && BattleshipType.isShip(downLeft.getData())) { - return null; - } - if (upLeft != null && BattleshipType.isShip(upLeft.getData())) { - return null; - } + BattleshipCell upRight = diagAdjCells.get(0); + BattleshipCell downRight = diagAdjCells.get(1); + BattleshipCell downLeft = diagAdjCells.get(2); + BattleshipCell upLeft = diagAdjCells.get(3); - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + // diagonally adjacent cells must be water + if (upRight != null && BattleshipType.isShip(upRight.getData())) { + return null; } + if (downRight != null && BattleshipType.isShip(downRight.getData())) { + return null; + } + if (downLeft != null && BattleshipType.isShip(downLeft.getData())) { + return null; + } + if (upLeft != null && BattleshipType.isShip(upLeft.getData())) { + return null; + } + + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java index 670a136a4..ab9a88525 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java @@ -8,38 +8,37 @@ public class ContinueShipDirectRule extends DirectRule { - public ContinueShipDirectRule() { - super( - "BTSP-BASC-0001", - "Continue Ship", - "", - "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); - } + public ContinueShipDirectRule() { + super( + "BTSP-BASC-0001", + "Continue Ship", + "", + "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should be overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should be overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java index 9bc4065aa..c4f4432d7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java @@ -14,95 +14,94 @@ public class FinishWithShipsDirectRule extends DirectRule { - public FinishWithShipsDirectRule() { - super( - "BTSP-BASC-0002", - "Finish with Ships", - "The number of undetermined squares is equal to the number " - + "of segments remaining for each clue.", - "edu/rpi/legup/images/battleship/rules/finishShip.png"); - } + public FinishWithShipsDirectRule() { + super( + "BTSP-BASC-0002", + "Finish with Ships", + "The number of undetermined squares is equal to the number " + + "of segments remaining for each clue.", + "edu/rpi/legup/images/battleship/rules/finishShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should be overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message. - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - BattleshipBoard initBoard = (BattleshipBoard) transition.getParents().get(0).getBoard(); - BattleshipCell initCell = (BattleshipCell) initBoard.getPuzzleElement(puzzleElement); - BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); - BattleshipCell finalCell = (BattleshipCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == BattleshipType.UNKNOWN - && BattleshipType.isShip(finalCell.getType()))) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should be overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message. + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + BattleshipBoard initBoard = (BattleshipBoard) transition.getParents().get(0).getBoard(); + BattleshipCell initCell = (BattleshipCell) initBoard.getPuzzleElement(puzzleElement); + BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); + BattleshipCell finalCell = (BattleshipCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == BattleshipType.UNKNOWN + && BattleshipType.isShip(finalCell.getType()))) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; + } - if (isForced(initBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() - + ": This cell is not forced to" - + "be a ship segment."; - } + if (isForced(initBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This cell is not forced to" + + "be a ship segment."; } + } + + private boolean isForced(BattleshipBoard board, BattleshipCell cell) { + Point loc = cell.getLocation(); - private boolean isForced(BattleshipBoard board, BattleshipCell cell) { - Point loc = cell.getLocation(); + // count the number of ship segments and unknowns in the row + List row = board.getRow(loc.y); + int rowCount = 0; + for (BattleshipCell c : row) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { + rowCount++; + } + } - // count the number of ship segments and unknowns in the row - List row = board.getRow(loc.y); - int rowCount = 0; - for (BattleshipCell c : row) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { - rowCount++; - } - } + // count the number of ship segments and unknowns in the column + List col = board.getColumn(loc.x); + int colCount = 0; + for (BattleshipCell c : col) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { + colCount++; + } + } - // count the number of ship segments and unknowns in the column - List col = board.getColumn(loc.x); - int colCount = 0; - for (BattleshipCell c : col) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { - colCount++; - } - } + // compare the counts with the clues + BattleshipClue east = board.getEast().get(loc.y); + BattleshipClue south = board.getSouth().get(loc.x); - // compare the counts with the clues - BattleshipClue east = board.getEast().get(loc.y); - BattleshipClue south = board.getSouth().get(loc.x); + return rowCount <= east.getData() && colCount <= south.getData(); + } - return rowCount <= east.getData() && colCount <= south.getData(); + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board. + * @return default board or null if this rule cannot be applied to this tree node. + */ + @Override + public Board getDefaultBoard(TreeNode node) { + BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); + for (PuzzleElement element : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) element; + if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { + cell.setData(BattleshipType.SHIP_UNKNOWN); + board.addModifiedData(cell); + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board. - * @return default board or null if this rule cannot be applied to this tree node. - */ - @Override - public Board getDefaultBoard(TreeNode node) { - BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); - for (PuzzleElement element : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) element; - if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { - cell.setData(BattleshipType.SHIP_UNKNOWN); - board.addModifiedData(cell); - } - } - - if (board.getModifiedData().isEmpty()) { - return null; - } else { - return board; - } + if (board.getModifiedData().isEmpty()) { + return null; + } else { + return board; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java index 99e5925e0..6f32b35a6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java @@ -8,38 +8,37 @@ public class FinishWithWaterDirectRule extends DirectRule { - public FinishWithWaterDirectRule() { - super( - "BTSP-BASC-0003", - "Finish with Water", - "", - "edu/rpi/legup/images/battleship/rules/finishWater.png"); - } + public FinishWithWaterDirectRule() { + super( + "BTSP-BASC-0003", + "Finish with Water", + "", + "edu/rpi/legup/images/battleship/rules/finishWater.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java index e8cfebb90..05ed95fbd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java @@ -6,25 +6,25 @@ public class IncompleteShipContradictionRule extends ContradictionRule { - public IncompleteShipContradictionRule() { - super( - "BTSP-CONT-0002", - "Incomplete Ship", - "", - "edu/rpi/legup/images/battleship/contradictions/IncompleteShip.png"); - } + public IncompleteShipContradictionRule() { + super( + "BTSP-CONT-0002", + "Incomplete Ship", + "", + "edu/rpi/legup/images/battleship/contradictions/IncompleteShip.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java index 93079fb71..afc4f8fc0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java @@ -8,63 +8,63 @@ import java.util.List; public class SegmentTypeCaseRule extends CaseRule { - public SegmentTypeCaseRule() { - super( - "BTSP-CASE-0001", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/cases/SegmentType.png"); - } + public SegmentTypeCaseRule() { + super( + "BTSP-CASE-0001", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/cases/SegmentType.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java index 8576ef722..f95625e5e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java @@ -8,38 +8,37 @@ public class SegmentTypeDirectRule extends DirectRule { - public SegmentTypeDirectRule() { - super( - "BTSP-BASC-0004", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); - } + public SegmentTypeDirectRule() { + super( + "BTSP-BASC-0004", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java index da8f33cc2..3033bafbd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java @@ -9,63 +9,63 @@ public class ShipLocationCaseRule extends CaseRule { - public ShipLocationCaseRule() { - super( - "BTSP-CASE-0002", - "Ship Location", - "", - "edu/rpi/legup/images/battleship/cases/ShipLocations.png"); - } + public ShipLocationCaseRule() { + super( + "BTSP-CASE-0002", + "Ship Location", + "", + "edu/rpi/legup/images/battleship/cases/ShipLocations.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java index 3c123d7c1..3696049eb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java @@ -9,63 +9,63 @@ public class ShipOrWaterCaseRule extends CaseRule { - public ShipOrWaterCaseRule() { - super( - "BTSP-CASE-0003", - "Ship or Water", - "", - "edu/rpi/legup/images/battleship/cases/ShipOrWater.png"); - } + public ShipOrWaterCaseRule() { + super( + "BTSP-CASE-0003", + "Ship or Water", + "", + "edu/rpi/legup/images/battleship/cases/ShipOrWater.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java index d26c3ed29..5a1821be0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java @@ -8,38 +8,37 @@ public class SurroundShipDirectRule extends DirectRule { - public SurroundShipDirectRule() { - super( - "BTSP-BASC-0005", - "Surround Ship", - "", - "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); - } + public SurroundShipDirectRule() { + super( + "BTSP-BASC-0005", + "Surround Ship", + "", + "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java index d10e086d2..a3dbba9c4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java @@ -6,25 +6,25 @@ public class TooFewInFleetContradictionRule extends ContradictionRule { - public TooFewInFleetContradictionRule() { - super( - "BTSP-CONT-0003", - "Too Few in Fleet", - "", - "edu/rpi/legup/images/battleship/contradictions/too_few_in_fleet.png"); - } + public TooFewInFleetContradictionRule() { + super( + "BTSP-CONT-0003", + "Too Few in Fleet", + "", + "edu/rpi/legup/images/battleship/contradictions/too_few_in_fleet.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java index 382ba6e39..b4814796d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java @@ -6,25 +6,25 @@ public class TooFewRowColContradictionRule extends ContradictionRule { - public TooFewRowColContradictionRule() { - super( - "BTSP-CONT-0004", - "Too few in row/col", - "", - "edu/rpi/legup/images/battleship/contradictions/too_few_segments.png"); - } + public TooFewRowColContradictionRule() { + super( + "BTSP-CONT-0004", + "Too few in row/col", + "", + "edu/rpi/legup/images/battleship/contradictions/too_few_segments.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java index d58701c0b..a375b63e2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java @@ -6,25 +6,25 @@ public class TooManyInFleetContradictionRule extends ContradictionRule { - public TooManyInFleetContradictionRule() { - super( - "BTSP-CONT-0005", - "Too Many in Fleet", - "", - "edu/rpi/legup/images/battleship/contradictions/too_many_in_fleet.png"); - } + public TooManyInFleetContradictionRule() { + super( + "BTSP-CONT-0005", + "Too Many in Fleet", + "", + "edu/rpi/legup/images/battleship/contradictions/too_many_in_fleet.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java index 27caa0524..abb72b5ca 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java @@ -6,25 +6,25 @@ public class TooManyRowColContradiction extends ContradictionRule { - public TooManyRowColContradiction() { - super( - "BTSP-CONT-0006", - "Too Many row/col", - "", - "edu/rpi/legup/images/battleship/contradictions/too_many_segments.png"); - } + public TooManyRowColContradiction() { + super( + "BTSP-CONT-0006", + "Too Many row/col", + "", + "edu/rpi/legup/images/battleship/contradictions/too_many_segments.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java index 79574caa6..28d2a2790 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java @@ -6,60 +6,60 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Fillapix extends Puzzle { - /** Fillapix Constructor */ - public Fillapix() { - super(); + /** Fillapix Constructor */ + public Fillapix() { + super(); - this.name = "Fillapix"; + this.name = "Fillapix"; - this.importer = new FillapixImporter(this); - this.exporter = new FillapixExporter(this); + this.importer = new FillapixImporter(this); + this.exporter = new FillapixExporter(this); - this.factory = new FillapixCellFactory(); - } + this.factory = new FillapixCellFactory(); + } - /** Initializes the game board */ - @Override - public void initializeView() { - boardView = new FillapixView((FillapixBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board */ + @Override + public void initializeView() { + boardView = new FillapixView((FillapixBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Fillapix - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Fillapix, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return super.isValidDimensions(rows, columns); - } + @Override + /** + * Determines if the given dimensions are valid for Fillapix + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Fillapix, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return super.isValidDimensions(rows, columns); + } - @Override - public boolean isBoardComplete(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(fillapixBoard) == null) { - return false; - } - } - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN) { - return false; - } - } - return true; + @Override + public boolean isBoardComplete(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(fillapixBoard) == null) { + return false; + } + } + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN) { + return false; + } } + return true; + } - @Override - public void onBoardChange(Board board) {} + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java index a6672bd4f..eaf408fcd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java @@ -6,62 +6,62 @@ import java.util.logging.Logger; public class FillapixBoard extends GridBoard { - private static final Logger LOGGER = Logger.getLogger(FillapixBoard.class.getName()); + private static final Logger LOGGER = Logger.getLogger(FillapixBoard.class.getName()); - public FillapixBoard(int width, int height) { - super(width, height); - } + public FillapixBoard(int width, int height) { + super(width, height); + } - public FillapixBoard(int size) { - this(size, size); - } + public FillapixBoard(int size) { + this(size, size); + } - public FillapixCell getCell(int x, int y) { - return (FillapixCell) super.getCell(x, y); - } + public FillapixCell getCell(int x, int y) { + return (FillapixCell) super.getCell(x, y); + } - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - @Override - public FillapixBoard copy() { - FillapixBoard copy = new FillapixBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + @Override + public FillapixBoard copy() { + FillapixBoard copy = new FillapixBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; + } - /** - * Finds the number of cells that match the specified type around and on a particular cell - * - * @param cell the cell we're looking around - * @param type the CellState whether it's black, white, or unknown - * @return integer number of cells that match specified type - */ - public int getNumCells(FillapixCell cell, FillapixCellType type) { - Point loc = cell.getLocation(); + /** + * Finds the number of cells that match the specified type around and on a particular cell + * + * @param cell the cell we're looking around + * @param type the CellState whether it's black, white, or unknown + * @return integer number of cells that match specified type + */ + public int getNumCells(FillapixCell cell, FillapixCellType type) { + Point loc = cell.getLocation(); - int numCells = 0; - for (int i = -1; i < 2; i++) { - for (int j = -1; j < 2; j++) { - if (loc.x + i > dimension.width || loc.y + j > dimension.height) { - continue; - } - FillapixCell c = getCell(loc.x + i, loc.y + j); - if (c != null && c.getType() == type) { - numCells++; - } - } + int numCells = 0; + for (int i = -1; i < 2; i++) { + for (int j = -1; j < 2; j++) { + if (loc.x + i > dimension.width || loc.y + j > dimension.height) { + continue; } - - return numCells; + FillapixCell c = getCell(loc.x + i, loc.y + j); + if (c != null && c.getType() == type) { + numCells++; + } + } } + + return numCells; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java index a9e5aa2df..772006cc8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java @@ -8,98 +8,98 @@ public class FillapixCell extends GridCell implements Comparable { - public static final int DEFAULT_VALUE = 10; + public static final int DEFAULT_VALUE = 10; - public FillapixCell(int value, Point location) { - super(value, location); - } + public FillapixCell(int value, Point location) { + super(value, location); + } - public int getNumber() { - int temp = (data % 100); - return temp == 10 ? -1 : temp; - } + public int getNumber() { + int temp = (data % 100); + return temp == 10 ? -1 : temp; + } - public void setNumber(int number) { - int temp = number == -1 ? 10 : number; - data = (data / 100) * 100 + temp; - } + public void setNumber(int number) { + int temp = number == -1 ? 10 : number; + data = (data / 100) * 100 + temp; + } - public FillapixCellType getType() { - switch (data / 100) { - case 0: - return FillapixCellType.UNKNOWN; - case 1: - return FillapixCellType.BLACK; - default: - return FillapixCellType.WHITE; - } + public FillapixCellType getType() { + switch (data / 100) { + case 0: + return FillapixCellType.UNKNOWN; + case 1: + return FillapixCellType.BLACK; + default: + return FillapixCellType.WHITE; } + } - public void setCellType(FillapixCellType type) { - data = type.value * 100 + (data % 100); - } + public void setCellType(FillapixCellType type) { + data = type.value * 100 + (data % 100); + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "FPIX-PLAC-0001": - this.setCellType(FillapixCellType.BLACK); - break; - case "FPIX-PLAC-0002": - this.setCellType(FillapixCellType.WHITE); - break; - case "FPIX-UNPL-0001": - int n = this.getNumber(); - switch (m.getButton()) { - case MouseEvent.BUTTON1: - n++; - break; - case MouseEvent.BUTTON3: - n--; - break; - } - if (n > 9) { - n = 0; - } - if (n < 0) { - n = 9; - } - this.setNumber(n); - break; - default: - this.setCellType(FillapixCellType.UNKNOWN); - this.data = -1; - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "FPIX-PLAC-0001": + this.setCellType(FillapixCellType.BLACK); + break; + case "FPIX-PLAC-0002": + this.setCellType(FillapixCellType.WHITE); + break; + case "FPIX-UNPL-0001": + int n = this.getNumber(); + switch (m.getButton()) { + case MouseEvent.BUTTON1: + n++; + break; + case MouseEvent.BUTTON3: + n--; + break; + } + if (n > 9) { + n = 0; } + if (n < 0) { + n = 9; + } + this.setNumber(n); + break; + default: + this.setCellType(FillapixCellType.UNKNOWN); + this.data = -1; + break; } + } - /** - * Performs a deep copy on the FillapixCell - * - * @return a new copy of the FillapixCell that is independent of this one - */ - @Override - public FillapixCell copy() { - FillapixCell cell = new FillapixCell(data, (Point) location.clone()); - cell.setIndex(index); - cell.setModifiable(isModifiable); - return cell; - } + /** + * Performs a deep copy on the FillapixCell + * + * @return a new copy of the FillapixCell that is independent of this one + */ + @Override + public FillapixCell copy() { + FillapixCell cell = new FillapixCell(data, (Point) location.clone()); + cell.setIndex(index); + cell.setModifiable(isModifiable); + return cell; + } - public boolean equals(FillapixCell otherCell) { - // return this.location.equals(otherCell.location) && this.index == otherCell.index - // && - // this.data == otherCell.data; - // return this.index == otherCell.index && this.data == otherCell.data; - // return this.index == otherCell.index; - return this.location.x == otherCell.location.x && this.location.y == otherCell.location.y; - } + public boolean equals(FillapixCell otherCell) { + // return this.location.equals(otherCell.location) && this.index == otherCell.index + // && + // this.data == otherCell.data; + // return this.index == otherCell.index && this.data == otherCell.data; + // return this.index == otherCell.index; + return this.location.x == otherCell.location.x && this.location.y == otherCell.location.y; + } - public int compareTo(FillapixCell otherCell) { - return this.index - otherCell.index; - } + public int compareTo(FillapixCell otherCell) { + return this.index - otherCell.index; + } - public int hashCode() { - return Objects.hash(this.index); - } + public int hashCode() { + return Objects.hash(this.index); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java index f59c0df47..45182c88f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java @@ -5,44 +5,44 @@ import java.awt.event.MouseEvent; public class FillapixCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement puzzleElement) { - FillapixCell cell = (FillapixCell) puzzleElement; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getType() == FillapixCellType.UNKNOWN) { - cell.setCellType(FillapixCellType.BLACK); - } else { - if (cell.getType() == FillapixCellType.BLACK) { - cell.setCellType(FillapixCellType.WHITE); - } else { - if (cell.getType() == FillapixCellType.WHITE) { - cell.setCellType(FillapixCellType.UNKNOWN); - } - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement puzzleElement) { + FillapixCell cell = (FillapixCell) puzzleElement; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getType() == FillapixCellType.UNKNOWN) { + cell.setCellType(FillapixCellType.BLACK); + } else { + if (cell.getType() == FillapixCellType.BLACK) { + cell.setCellType(FillapixCellType.WHITE); + } else { + if (cell.getType() == FillapixCellType.WHITE) { + cell.setCellType(FillapixCellType.UNKNOWN); } + } + } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getType() == FillapixCellType.UNKNOWN) { + cell.setCellType(FillapixCellType.WHITE); } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getType() == FillapixCellType.UNKNOWN) { - cell.setCellType(FillapixCellType.WHITE); - } else { - if (cell.getType() == FillapixCellType.BLACK) { - cell.setCellType(FillapixCellType.UNKNOWN); - } else { - if (cell.getType() == FillapixCellType.WHITE) { - cell.setCellType(FillapixCellType.BLACK); - } - } - } + if (cell.getType() == FillapixCellType.BLACK) { + cell.setCellType(FillapixCellType.UNKNOWN); + } else { + if (cell.getType() == FillapixCellType.WHITE) { + cell.setCellType(FillapixCellType.BLACK); } + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java index 9f689bc96..37b4130b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java @@ -10,66 +10,65 @@ import org.w3c.dom.Node; public class FillapixCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public FillapixCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Fillapix Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public FillapixCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Fillapix Factory: unknown puzzleElement puzzleElement"); + } - FillapixBoard fillapixBoard = (FillapixBoard) board; - int width = fillapixBoard.getWidth(); - int height = fillapixBoard.getHeight(); + FillapixBoard fillapixBoard = (FillapixBoard) board; + int width = fillapixBoard.getWidth(); + int height = fillapixBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException( - "Fillapix Factory: cell location out of bounds"); - } - if (value / 100 > 2 || value % 100 > 10) { - throw new InvalidFileFormatException("Fillapix Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("Fillapix Factory: cell location out of bounds"); + } + if (value / 100 > 2 || value % 100 > 10) { + throw new InvalidFileFormatException("Fillapix Factory: cell unknown value"); + } - FillapixCell cell = new FillapixCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Fillapix Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Fillapix Factory: could not find attribute(s)"); - } + FillapixCell cell = new FillapixCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Fillapix Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Fillapix Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - FillapixCell cell = (FillapixCell) puzzleElement; - Point loc = cell.getLocation(); + FillapixCell cell = (FillapixCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java index 28a263467..659cebb1b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java @@ -1,17 +1,17 @@ package edu.rpi.legup.puzzle.fillapix; public enum FillapixCellType { - UNKNOWN(0), - BLACK(1), - WHITE(2); + UNKNOWN(0), + BLACK(1), + WHITE(2); - public int value; + public int value; - FillapixCellType(int value) { - this.value = value; - } + FillapixCellType(int value) { + this.value = value; + } - public String toString() { - return super.toString().toLowerCase(); - } + public String toString() { + return super.toString().toLowerCase(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java index 47465a522..97b864bc9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java @@ -4,59 +4,58 @@ import java.awt.*; public class FillapixElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); - public FillapixElementView(FillapixCell cell) { - super(cell); - } + public FillapixElementView(FillapixCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public FillapixCell getPuzzleElement() { - return (FillapixCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public FillapixCell getPuzzleElement() { + return (FillapixCell) super.getPuzzleElement(); + } - /** - * Draws the fillapix puzzleElement to the screen - * - * @param graphics2D graphics object - */ - @Override - public void drawElement(Graphics2D graphics2D) { - FillapixCell cell = (FillapixCell) puzzleElement; - FillapixCellType type = cell.getType(); - graphics2D.setStroke(new BasicStroke(1)); - switch (type) { - case UNKNOWN: - graphics2D.setColor(GRAY_COLOR); - break; - case BLACK: - graphics2D.setColor(BLACK_COLOR); - break; - default: - graphics2D.setColor(WHITE_COLOR); - break; - } - graphics2D.fillRect(location.x, location.y, size.width, size.height); - if (cell.getNumber() >= 0 && cell.getNumber() < 10) { - graphics2D.setColor(type == FillapixCellType.WHITE ? BLACK_COLOR : WHITE_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getNumber()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = - location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + /** + * Draws the fillapix puzzleElement to the screen + * + * @param graphics2D graphics object + */ + @Override + public void drawElement(Graphics2D graphics2D) { + FillapixCell cell = (FillapixCell) puzzleElement; + FillapixCellType type = cell.getType(); + graphics2D.setStroke(new BasicStroke(1)); + switch (type) { + case UNKNOWN: + graphics2D.setColor(GRAY_COLOR); + break; + case BLACK: graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + break; + default: + graphics2D.setColor(WHITE_COLOR); + break; + } + graphics2D.fillRect(location.x, location.y, size.width, size.height); + if (cell.getNumber() >= 0 && cell.getNumber() < 10) { + graphics2D.setColor(type == FillapixCellType.WHITE ? BLACK_COLOR : WHITE_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getNumber()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); } + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java index ffabd8762..1df8157cf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java @@ -6,34 +6,34 @@ public class FillapixExporter extends PuzzleExporter { - public FillapixExporter(Fillapix fillapix) { - super(fillapix); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - FillapixBoard board; - if (puzzle.getTree() != null) { - board = (FillapixBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (FillapixBoard) puzzle.getBoardView().getBoard(); - } + public FillapixExporter(Fillapix fillapix) { + super(fillapix); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + FillapixBoard board; + if (puzzle.getTree() != null) { + board = (FillapixBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (FillapixBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) puzzleElement; - if (cell.getNumber() != -1 || cell.getType() != FillapixCellType.UNKNOWN) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) puzzleElement; + if (cell.getNumber() != -1 || cell.getType() != FillapixCellType.UNKNOWN) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java index d16bc8219..5877fd25b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java @@ -8,116 +8,110 @@ import org.w3c.dom.NodeList; public class FillapixImporter extends PuzzleImporter { - public FillapixImporter(Fillapix fillapix) { - super(fillapix); - } + public FillapixImporter(Fillapix fillapix) { + super(fillapix); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be made - */ - @Override - public void initializeBoard(int rows, int columns) { - FillapixBoard fillapixBoard = new FillapixBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be made + */ + @Override + public void initializeBoard(int rows, int columns) { + FillapixBoard fillapixBoard = new FillapixBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - FillapixCell cell = - new FillapixCell(FillapixCellType.UNKNOWN.value, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setNumber(FillapixCell.DEFAULT_VALUE); - cell.setModifiable(true); - fillapixBoard.setCell(x, y, cell); - } - } - puzzle.setCurrentBoard(fillapixBoard); + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + FillapixCell cell = new FillapixCell(FillapixCellType.UNKNOWN.value, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setNumber(FillapixCell.DEFAULT_VALUE); + cell.setModifiable(true); + fillapixBoard.setCell(x, y, cell); + } } + puzzle.setCurrentBoard(fillapixBoard); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "Fillapix Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "Fillapix Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("Fillapix Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("Fillapix Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - FillapixBoard fillapixBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - fillapixBoard = new FillapixBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - fillapixBoard = new FillapixBoard(width, height); - } - } + FillapixBoard fillapixBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + fillapixBoard = new FillapixBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + fillapixBoard = new FillapixBoard(width, height); + } + } - if (fillapixBoard == null) { - throw new InvalidFileFormatException("Fillapix Importer: invalid board dimensions"); - } + if (fillapixBoard == null) { + throw new InvalidFileFormatException("Fillapix Importer: invalid board dimensions"); + } - int width = fillapixBoard.getWidth(); - int height = fillapixBoard.getHeight(); + int width = fillapixBoard.getWidth(); + int height = fillapixBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - FillapixCell cell = - (FillapixCell) - puzzle.getFactory() - .importCell(elementDataList.item(i), fillapixBoard); - Point loc = cell.getLocation(); - cell.setModifiable(true); - cell.setGiven(true); - fillapixBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + FillapixCell cell = + (FillapixCell) puzzle.getFactory().importCell(elementDataList.item(i), fillapixBoard); + Point loc = cell.getLocation(); + cell.setModifiable(true); + cell.setGiven(true); + fillapixBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (fillapixBoard.getCell(x, y) == null) { - FillapixCell cell = - new FillapixCell(FillapixCell.DEFAULT_VALUE, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - fillapixBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(fillapixBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Fillapix Importer: unknown value where integer expected"); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (fillapixBoard.getCell(x, y) == null) { + FillapixCell cell = new FillapixCell(FillapixCell.DEFAULT_VALUE, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + fillapixBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(fillapixBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Fillapix Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Fillapix cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Fillapix cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java index 571a0c7f7..6eeb4bd25 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java @@ -8,234 +8,231 @@ public class FillapixUtilities { - public static boolean isForcedBlack(FillapixBoard board, FillapixCell cell) { - TooFewBlackCellsContradictionRule tooManyBlackCells = - new TooFewBlackCellsContradictionRule(); - FillapixBoard whiteCaseBoard = board.copy(); - FillapixCell whiteCell = (FillapixCell) whiteCaseBoard.getPuzzleElement(cell); - whiteCell.setCellType(FillapixCellType.WHITE); - ArrayList adjCells = getAdjacentCells(whiteCaseBoard, whiteCell); - for (FillapixCell adjCell : adjCells) { - if (tooManyBlackCells.checkContradictionAt(whiteCaseBoard, adjCell) == null) { - return true; - } - } - return false; + public static boolean isForcedBlack(FillapixBoard board, FillapixCell cell) { + TooFewBlackCellsContradictionRule tooManyBlackCells = new TooFewBlackCellsContradictionRule(); + FillapixBoard whiteCaseBoard = board.copy(); + FillapixCell whiteCell = (FillapixCell) whiteCaseBoard.getPuzzleElement(cell); + whiteCell.setCellType(FillapixCellType.WHITE); + ArrayList adjCells = getAdjacentCells(whiteCaseBoard, whiteCell); + for (FillapixCell adjCell : adjCells) { + if (tooManyBlackCells.checkContradictionAt(whiteCaseBoard, adjCell) == null) { + return true; + } } + return false; + } - public static boolean isForcedWhite(FillapixBoard board, FillapixCell cell) { - TooManyBlackCellsContradictionRule tooManyBlackCells = - new TooManyBlackCellsContradictionRule(); - FillapixBoard blackCaseBoard = board.copy(); - FillapixCell blackCell = (FillapixCell) blackCaseBoard.getPuzzleElement(cell); - blackCell.setCellType(FillapixCellType.BLACK); - ArrayList adjCells = getAdjacentCells(blackCaseBoard, blackCell); - for (FillapixCell adjCell : adjCells) { - if (tooManyBlackCells.checkContradictionAt(blackCaseBoard, adjCell) == null) { - return true; - } - } - return false; - } - - public static boolean isComplete(FillapixBoard board, FillapixCell cell) { - int cellNum = cell.getNumber(); - int cellTouchBlack = 0; - ArrayList adjCells = getAdjacentCells(board, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - cellTouchBlack++; - } - } - return cellNum == cellTouchBlack; + public static boolean isForcedWhite(FillapixBoard board, FillapixCell cell) { + TooManyBlackCellsContradictionRule tooManyBlackCells = new TooManyBlackCellsContradictionRule(); + FillapixBoard blackCaseBoard = board.copy(); + FillapixCell blackCell = (FillapixCell) blackCaseBoard.getPuzzleElement(cell); + blackCell.setCellType(FillapixCellType.BLACK); + ArrayList adjCells = getAdjacentCells(blackCaseBoard, blackCell); + for (FillapixCell adjCell : adjCells) { + if (tooManyBlackCells.checkContradictionAt(blackCaseBoard, adjCell) == null) { + return true; + } } + return false; + } - public static boolean hasEmptyAdjacent(FillapixBoard board, FillapixCell cell) { - ArrayList adjCells = getAdjacentCells(board, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - return true; - } - } - return false; + public static boolean isComplete(FillapixBoard board, FillapixCell cell) { + int cellNum = cell.getNumber(); + int cellTouchBlack = 0; + ArrayList adjCells = getAdjacentCells(board, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + cellTouchBlack++; + } } + return cellNum == cellTouchBlack; + } - /** Gets all cells adjacent to a specific cell. The cell itself will be included. */ - public static ArrayList getAdjacentCells(FillapixBoard board, FillapixCell cell) { - ArrayList adjCells = new ArrayList(); - Point cellLoc = cell.getLocation(); - for (int i = -1; i <= 1; i++) { - for (int j = -1; j <= 1; j++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - } - return adjCells; + public static boolean hasEmptyAdjacent(FillapixBoard board, FillapixCell cell) { + ArrayList adjCells = getAdjacentCells(board, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + return true; + } } + return false; + } - /** - * Gets all cells that are contained in the square defined as having 'distance' cells between - * the center and the outer wall. For example, distance = 1: - * - *

|X|X|X|X|X| - * - *

|X| | | |X| - * - *

|X| |O| |X| - * - *

|X| | | |X| - * - *

|X|X|X|X|X| - * - *

O is 'cell', and all 'X' will be returned in the ArrayList - */ - public static ArrayList getCellsAtDistance( - FillapixBoard board, FillapixCell cell, int distance) { - ArrayList adjCells = new ArrayList(); - Point cellLoc = cell.getLocation(); - int i = 0, j = 0; - // top line - for (i = cellLoc.x - (distance), j = cellLoc.y - (distance + 1); - i <= cellLoc.x + (distance + 1); - i++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // right line - for (i = cellLoc.x + (distance + 1), j = cellLoc.y - (distance); - j <= cellLoc.y + (distance + 1); - j++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); + /** Gets all cells adjacent to a specific cell. The cell itself will be included. */ + public static ArrayList getAdjacentCells(FillapixBoard board, FillapixCell cell) { + ArrayList adjCells = new ArrayList(); + Point cellLoc = cell.getLocation(); + for (int i = -1; i <= 1; i++) { + for (int j = -1; j <= 1; j++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; } - // bottom line - for (i = cellLoc.x + (distance), j = cellLoc.y + (distance + 1); - i <= cellLoc.x - (distance + 1); - i--) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // left line - for (i = cellLoc.x - (distance + 1), j = cellLoc.y + (distance); - j <= cellLoc.y - (distance + 1); - j--) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; } + adjCells.add(adjCell); + } + } + return adjCells; + } - return adjCells; + /** + * Gets all cells that are contained in the square defined as having 'distance' cells between the + * center and the outer wall. For example, distance = 1: + * + *

|X|X|X|X|X| + * + *

|X| | | |X| + * + *

|X| |O| |X| + * + *

|X| | | |X| + * + *

|X|X|X|X|X| + * + *

O is 'cell', and all 'X' will be returned in the ArrayList + */ + public static ArrayList getCellsAtDistance( + FillapixBoard board, FillapixCell cell, int distance) { + ArrayList adjCells = new ArrayList(); + Point cellLoc = cell.getLocation(); + int i = 0, j = 0; + // top line + for (i = cellLoc.x - (distance), j = cellLoc.y - (distance + 1); + i <= cellLoc.x + (distance + 1); + i++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // right line + for (i = cellLoc.x + (distance + 1), j = cellLoc.y - (distance); + j <= cellLoc.y + (distance + 1); + j++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // bottom line + for (i = cellLoc.x + (distance), j = cellLoc.y + (distance + 1); + i <= cellLoc.x - (distance + 1); + i--) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // left line + for (i = cellLoc.x - (distance + 1), j = cellLoc.y + (distance); + j <= cellLoc.y - (distance + 1); + j--) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); } - /** - * Finds all possible combinations of chosenNumObj items can be chosen from - * totalNumObj total items. For example, if 1 item is chosen from 2 possible items, the - * combinations are: - * - *

[ [true,false], [false,true] ]
- * - * @param totalNumItems the total number of items that can possibly be chosen - * @param chosenNumItems the number of items to be chosen - * @return an ArrayList of Boolean arrays. Each index in the ArrayList represents a distinct - * combination. Each Boolean array will be totalNumItems long and each index - * will be true if the corresponding item is included in that combination, and - * - * false otherwise. - */ - public static ArrayList getCombinations(int chosenNumItems, int totalNumItems) { - ArrayList combinations = new ArrayList(); + return adjCells; + } - // calculate all combinations - boolean[] array = new boolean[totalNumItems]; - recurseCombinations(combinations, 0, chosenNumItems, 0, totalNumItems, array); + /** + * Finds all possible combinations of chosenNumObj items can be chosen from + * totalNumObj total items. For example, if 1 item is chosen from 2 possible items, the + * combinations are: + * + *
[ [true,false], [false,true] ]
+ * + * @param totalNumItems the total number of items that can possibly be chosen + * @param chosenNumItems the number of items to be chosen + * @return an ArrayList of Boolean arrays. Each index in the ArrayList represents a distinct + * combination. Each Boolean array will be totalNumItems long and each index will + * be true if the corresponding item is included in that combination, and + * false otherwise. + */ + public static ArrayList getCombinations(int chosenNumItems, int totalNumItems) { + ArrayList combinations = new ArrayList(); - return combinations; - } + // calculate all combinations + boolean[] array = new boolean[totalNumItems]; + recurseCombinations(combinations, 0, chosenNumItems, 0, totalNumItems, array); - private static void recurseCombinations( - ArrayList result, - int curIndex, - int maxBlack, - int numBlack, - int len, - boolean[] workingArray) { - if (curIndex == len) { - // complete, but not valid solution - if (numBlack != maxBlack) { - return; - } - // complete and valid solution - result.add(workingArray.clone()); - return; - } - // there is no chance of completing the required number of solutions, so quit - if (len - curIndex < maxBlack - numBlack) { - return; - } + return combinations; + } - if (numBlack < maxBlack) { - workingArray[curIndex] = true; - recurseCombinations(result, curIndex + 1, maxBlack, numBlack + 1, len, workingArray); - } - workingArray[curIndex] = false; - recurseCombinations(result, curIndex + 1, maxBlack, numBlack, len, workingArray); + private static void recurseCombinations( + ArrayList result, + int curIndex, + int maxBlack, + int numBlack, + int len, + boolean[] workingArray) { + if (curIndex == len) { + // complete, but not valid solution + if (numBlack != maxBlack) { + return; + } + // complete and valid solution + result.add(workingArray.clone()); + return; + } + // there is no chance of completing the required number of solutions, so quit + if (len - curIndex < maxBlack - numBlack) { + return; + } + + if (numBlack < maxBlack) { + workingArray[curIndex] = true; + recurseCombinations(result, curIndex + 1, maxBlack, numBlack + 1, len, workingArray); } + workingArray[curIndex] = false; + recurseCombinations(result, curIndex + 1, maxBlack, numBlack, len, workingArray); + } - public static boolean checkBoardForContradiction(FillapixBoard board) { - ContradictionRule tooManyBlack = new TooManyBlackCellsContradictionRule(); - ContradictionRule tooManyWhite = new TooFewBlackCellsContradictionRule(); - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - if (tooManyBlack.checkContradictionAt(board, board.getCell(i, j)) == null - || tooManyWhite.checkContradictionAt(board, board.getCell(i, j)) == null) { - return true; - } - } + public static boolean checkBoardForContradiction(FillapixBoard board) { + ContradictionRule tooManyBlack = new TooManyBlackCellsContradictionRule(); + ContradictionRule tooManyWhite = new TooFewBlackCellsContradictionRule(); + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + if (tooManyBlack.checkContradictionAt(board, board.getCell(i, j)) == null + || tooManyWhite.checkContradictionAt(board, board.getCell(i, j)) == null) { + return true; } - return false; + } } + return false; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java index 55332e47d..eea7c7a4d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java @@ -6,18 +6,17 @@ import java.awt.*; public class FillapixView extends GridBoardView { - public FillapixView(FillapixBoard board) { - super(new BoardController(), new FillapixCellController(), board.getDimension()); + public FillapixView(FillapixBoard board) { + super(new BoardController(), new FillapixCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) puzzleElement; - Point loc = cell.getLocation(); - FillapixElementView elementView = new FillapixElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) puzzleElement; + Point loc = cell.getLocation(); + FillapixElementView elementView = new FillapixElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java index 1d7c038a3..ce4ba520c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BlackTile extends PlaceableElement { - public BlackTile() { - super( - "FPIX-PLAC-0001", - "Black Tile", - "The black tile", - "edu/rpi/legup/images/fillapix/tiles/BlackTile.png"); - } + public BlackTile() { + super( + "FPIX-PLAC-0001", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/fillapix/tiles/BlackTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java index e869aeaf9..0b76b1b57 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java @@ -3,28 +3,28 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super( - "FPIX-UNPL-0001", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/fillapix/tiles/NumberTile.png"); - object_num = 0; - } + public NumberTile() { + super( + "FPIX-UNPL-0001", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/fillapix/tiles/NumberTile.png"); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java index 6778c1758..25104eb60 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "FPIX-UNPL-0002", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/fillapix/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "FPIX-UNPL-0002", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/fillapix/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java index 67065a7e9..935c9bc1b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class WhiteTile extends PlaceableElement { - public WhiteTile() { - super( - "FPIX-PLAC-0002", - "White Tile", - "The white tile", - "edu/rpi/legup/images/fillapix/tiles/WhiteTile.png"); - } + public WhiteTile() { + super( + "FPIX-PLAC-0002", + "White Tile", + "The white tile", + "edu/rpi/legup/images/fillapix/tiles/WhiteTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java index 860a6c011..02699327e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java @@ -12,81 +12,81 @@ import java.util.List; public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "FPIX-CASE-0001", - "Black or White", - "Each cell is either black or white.", - "edu/rpi/legup/images/fillapix/cases/BlackOrWhite.png"); - } + public BlackOrWhiteCaseRule() { + super( + "FPIX-CASE-0001", + "Black or White", + "Each cell is either black or white.", + "edu/rpi/legup/images/fillapix/cases/BlackOrWhite.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); - fillapixBoard.setModifiable(false); - for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) data; - if (cell.getType() == FillapixCellType.UNKNOWN) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); + fillapixBoard.setModifiable(false); + for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) data; + if (cell.getType() == FillapixCellType.UNKNOWN) { + caseBoard.addPickableElement(data); + } } + return caseBoard; + } - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - - Board case1 = board.copy(); - FillapixCell cell1 = (FillapixCell) case1.getPuzzleElement(puzzleElement); - cell1.setCellType(FillapixCellType.BLACK); - case1.addModifiedData(cell1); - cases.add(case1); + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); - Board case2 = board.copy(); - FillapixCell cell2 = (FillapixCell) case2.getPuzzleElement(puzzleElement); - cell2.setCellType(FillapixCellType.WHITE); - case2.addModifiedData(cell2); - cases.add(case2); - - return cases; - } + Board case1 = board.copy(); + FillapixCell cell1 = (FillapixCell) case1.getPuzzleElement(puzzleElement); + cell1.setCellType(FillapixCellType.BLACK); + case1.addModifiedData(cell1); + cases.add(case1); - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; - } + Board case2 = board.copy(); + FillapixCell cell2 = (FillapixCell) case2.getPuzzleElement(puzzleElement); + cell2.setCellType(FillapixCellType.WHITE); + case2.addModifiedData(cell2); + cases.add(case2); - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + return cases; + } - FillapixCell mod1 = (FillapixCell) case1.getBoard().getModifiedData().iterator().next(); - FillapixCell mod2 = (FillapixCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - if (!((mod1.getType() == FillapixCellType.BLACK && mod2.getType() == FillapixCellType.WHITE) - || (mod2.getType() == FillapixCellType.BLACK - && mod1.getType() == FillapixCellType.WHITE))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty cell and a lit cell."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - return null; + FillapixCell mod1 = (FillapixCell) case1.getBoard().getModifiedData().iterator().next(); + FillapixCell mod2 = (FillapixCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; + if (!((mod1.getType() == FillapixCellType.BLACK && mod2.getType() == FillapixCellType.WHITE) + || (mod2.getType() == FillapixCellType.BLACK + && mod1.getType() == FillapixCellType.WHITE))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty cell and a lit cell."; } + + return null; + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java index ccc002f46..da0ccb057 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java @@ -11,56 +11,55 @@ import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; public class FinishWithBlackDirectRule extends DirectRule { - public FinishWithBlackDirectRule() { - super( - "FPIX-BASC-0001", - "Finish with Black", - "The remaining unknowns around and on a cell must be black to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); - } + public FinishWithBlackDirectRule() { + super( + "FPIX-BASC-0001", + "Finish with Black", + "The remaining unknowns around and on a cell must be black to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == FillapixCellType.UNKNOWN - && cell.getType() == FillapixCellType.BLACK)) { - return super.getInvalidUseOfRuleMessage() - + ": This cell must be black to be applicable with this rule."; - } + if (!(parentCell.getType() == FillapixCellType.UNKNOWN + && cell.getType() == FillapixCellType.BLACK)) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must be black to be applicable with this rule."; + } - if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; - } + if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN - && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.BLACK); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } else { - return fillapixBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN + && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.BLACK); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } else { + return fillapixBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java index 6735fb8f4..0d8423c0c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java @@ -11,56 +11,55 @@ import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; public class FinishWithWhiteDirectRule extends DirectRule { - public FinishWithWhiteDirectRule() { - super( - "FPIX-BASC-0002", - "Finish with White", - "The remaining unknowns around and on a cell must be white to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); - } + public FinishWithWhiteDirectRule() { + super( + "FPIX-BASC-0002", + "Finish with White", + "The remaining unknowns around and on a cell must be white to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == FillapixCellType.UNKNOWN - && cell.getType() == FillapixCellType.WHITE)) { - return super.getInvalidUseOfRuleMessage() - + ": This cell must be white to be applicable with this rule"; - } + if (!(parentCell.getType() == FillapixCellType.UNKNOWN + && cell.getType() == FillapixCellType.WHITE)) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must be white to be applicable with this rule"; + } - if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; - } + if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN - && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.WHITE); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } else { - return fillapixBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN + && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.WHITE); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } else { + return fillapixBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java index e91931bd4..9ce860c33 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java @@ -15,93 +15,89 @@ import java.util.List; public class MirrorDirectRule extends DirectRule { - public MirrorDirectRule() { - super( - "FPIX-BASC-0003", - "Mirror", - "Two adjacent clues with the same value must have the same number of black squares" - + " in their unshared regions", - "edu/rpi/legup/images/fillapix/rules/Mirror.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = - (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + public MirrorDirectRule() { + super( + "FPIX-BASC-0003", + "Mirror", + "Two adjacent clues with the same value must have the same number of black squares" + + " in their unshared regions", + "edu/rpi/legup/images/fillapix/rules/Mirror.png"); + } - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // find all cells adjacent to cell that are numbered - ArrayList adjCells = - FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - ArrayList adjNums = new ArrayList(); - for (int i = 0; i < adjCells.size(); i++) { - if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { - adjNums.add(adjCells.get(i)); - } - } - // the numbered cells must be next to another numbered cell of the same value - Iterator itr = adjNums.iterator(); - while (itr.hasNext()) { - FillapixCell adjNum = itr.next(); - adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); - boolean found = false; - for (FillapixCell adjCell : adjCells) { - if (adjCell.getNumber() == adjNum.getNumber() - && adjCell.getIndex() != adjNum.getIndex()) { - found = true; - } - } - if (!found) { - itr.remove(); - } - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // change the color of the parentCell, and check if there exists a valid board - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); - } - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjNum : adjNums) { - caseBoards = completeClue.getCases(parentBoard, adjNum); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } + // find all cells adjacent to cell that are numbered + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + ArrayList adjNums = new ArrayList(); + for (int i = 0; i < adjCells.size(); i++) { + if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { + adjNums.add(adjCells.get(i)); + } + } + // the numbered cells must be next to another numbered cell of the same value + Iterator itr = adjNums.iterator(); + while (itr.hasNext()) { + FillapixCell adjNum = itr.next(); + adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); + boolean found = false; + for (FillapixCell adjCell : adjCells) { + if (adjCell.getNumber() == adjNum.getNumber() && adjCell.getIndex() != adjNum.getIndex()) { + found = true; } - - return super.getInvalidUseOfRuleMessage(); + } + if (!found) { + itr.remove(); + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + // change the color of the parentCell, and check if there exists a valid board + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjNum : adjNums) { + caseBoards = completeClue.getCases(parentBoard, adjNum); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { return null; + } } + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java index 71a85a95b..e38ec65e1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java @@ -15,89 +15,86 @@ import java.util.List; public class NonTouchingSharedDirectRule extends DirectRule { - public NonTouchingSharedDirectRule() { - super( - "FPIX-BASC-0005", - "NonTouching Shared", - "Clues with shared cells have the same difference in black cells in their unshared" - + " regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = - (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + public NonTouchingSharedDirectRule() { + super( + "FPIX-BASC-0005", + "NonTouching Shared", + "Clues with shared cells have the same difference in black cells in their unshared" + + " regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // get all adjCells that have a number - ArrayList adjCells = - FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell not - * touching, but sharing cells */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - ArrayList sharingCells = - FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); - boolean found = false; - for (FillapixCell sharingCell : sharingCells) { - if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { - found = true; - } - } - if (!found) { - itr.remove(); - } - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell not + * touching, but sharing cells */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + ArrayList sharingCells = + FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); + boolean found = false; + for (FillapixCell sharingCell : sharingCells) { + if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { + found = true; } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } - } - - return super.getInvalidUseOfRuleMessage(); + } + if (!found) { + itr.remove(); + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { return null; + } } + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java index 7db833f76..fdfe2e765 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java @@ -18,216 +18,215 @@ import java.util.TreeSet; public class SatisfyClueCaseRule extends CaseRule { - public SatisfyClueCaseRule() { - super( - "FPIX-CASE-0002", - "Satisfy Clue", - "Each clue must touch that number of squares.", - "edu/rpi/legup/images/fillapix/cases/SatisfyClue.png"); + public SatisfyClueCaseRule() { + super( + "FPIX-CASE-0002", + "Satisfy Clue", + "Each clue must touch that number of squares.", + "edu/rpi/legup/images/fillapix/cases/SatisfyClue.png"); + } + + @Override + public CaseBoard getCaseBoard(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); + fillapixBoard.setModifiable(false); + for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) data; + if (cell.getNumber() >= 0 + && cell.getNumber() <= 9 + && FillapixUtilities.hasEmptyAdjacent(fillapixBoard, cell)) { + caseBoard.addPickableElement(data); + } } - - @Override - public CaseBoard getCaseBoard(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); - fillapixBoard.setModifiable(false); - for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) data; - if (cell.getNumber() >= 0 - && cell.getNumber() <= 9 - && FillapixUtilities.hasEmptyAdjacent(fillapixBoard, cell)) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; + return caseBoard; + } + + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + + // get value of cell + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + int cellMaxBlack = cell.getNumber(); + if (cellMaxBlack < 0 || cellMaxBlack > 9) { // cell is not valid cell + return null; } - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - - // get value of cell - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellMaxBlack = cell.getNumber(); - if (cellMaxBlack < 0 || cellMaxBlack > 9) { // cell is not valid cell - return null; - } + // find number of black & empty squares + int cellNumBlack = 0; + int cellNumEmpty = 0; + ArrayList emptyCells = new ArrayList(); + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + cellNumBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + cellNumEmpty++; + emptyCells.add(adjCell); + } + } + // no cases if no empty or if too many black already + if (cellNumBlack > cellMaxBlack || cellNumEmpty == 0) { + return cases; + } - // find number of black & empty squares - int cellNumBlack = 0; - int cellNumEmpty = 0; - ArrayList emptyCells = new ArrayList(); - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - cellNumBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - cellNumEmpty++; - emptyCells.add(adjCell); - } - } - // no cases if no empty or if too many black already - if (cellNumBlack > cellMaxBlack || cellNumEmpty == 0) { - return cases; + // generate all cases as boolean expressions + ArrayList combinations; + combinations = FillapixUtilities.getCombinations(cellMaxBlack - cellNumBlack, cellNumEmpty); + + for (int i = 0; i < combinations.size(); i++) { + Board case_ = board.copy(); + for (int j = 0; j < combinations.get(i).length; j++) { + cell = (FillapixCell) case_.getPuzzleElement(emptyCells.get(j)); + if (combinations.get(i)[j]) { + cell.setCellType(FillapixCellType.BLACK); + } else { + cell.setCellType(FillapixCellType.WHITE); } + case_.addModifiedData(cell); + } + cases.add(case_); + } - // generate all cases as boolean expressions - ArrayList combinations; - combinations = FillapixUtilities.getCombinations(cellMaxBlack - cellNumBlack, cellNumEmpty); - - for (int i = 0; i < combinations.size(); i++) { - Board case_ = board.copy(); - for (int j = 0; j < combinations.get(i).length; j++) { - cell = (FillapixCell) case_.getPuzzleElement(emptyCells.get(j)); - if (combinations.get(i)[j]) { - cell.setCellType(FillapixCellType.BLACK); - } else { - cell.setCellType(FillapixCellType.WHITE); - } - case_.addModifiedData(cell); - } - cases.add(case_); - } + return cases; + } + + @Override + public String checkRuleRaw(TreeTransition transition) { + TreeNode parent = transition.getParents().get(0); + List childTransitions = parent.getChildren(); + + /* + * In order for the transition to be valid, it can only be applied to + * one cell, thus: + * * there must be modified cells + * * all modified cells must share at least one common adjacent + * cell + * * all modified cells must fit within a 3X3 square + * * the center of one of the possible squaress must be a cell + * with a number + * * that cells possible combinations must match the transitions + * If all the above is verified, then the transition is valid + */ + + /* ensure there are modified cells */ + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() <= 0) { + return super.getInvalidUseOfRuleMessage(); + } - return cases; + /* ensure modified cells occur within a 3X3 square */ + int minVertLoc = Integer.MAX_VALUE, maxVertLoc = Integer.MIN_VALUE; + int minHorzLoc = Integer.MAX_VALUE, maxHorzLoc = Integer.MIN_VALUE; + for (PuzzleElement modCell : modCells) { + Point loc = ((FillapixCell) modCell).getLocation(); + if (loc.x < minHorzLoc) { + minHorzLoc = loc.x; + } + if (loc.x > maxHorzLoc) { + maxHorzLoc = loc.x; + } + if (loc.y < minVertLoc) { + minVertLoc = loc.y; + } + if (loc.y > maxVertLoc) { + maxVertLoc = loc.y; + } + } + if (maxVertLoc - minVertLoc > 3 || maxHorzLoc - minHorzLoc > 3) { + return super.getInvalidUseOfRuleMessage(); } - @Override - public String checkRuleRaw(TreeTransition transition) { - TreeNode parent = transition.getParents().get(0); - List childTransitions = parent.getChildren(); - - /* - * In order for the transition to be valid, it can only be applied to - * one cell, thus: - * * there must be modified cells - * * all modified cells must share at least one common adjacent - * cell - * * all modified cells must fit within a 3X3 square - * * the center of one of the possible squaress must be a cell - * with a number - * * that cells possible combinations must match the transitions - * If all the above is verified, then the transition is valid - */ - - /* ensure there are modified cells */ - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() <= 0) { - return super.getInvalidUseOfRuleMessage(); - } + /* get the center of all possible 3X3 squares, + * and collect all that have numbers */ + FillapixBoard board = (FillapixBoard) transition.getParents().get(0).getBoard(); + Set possibleCenters = new TreeSet(); + possibleCenters.addAll( + FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCells.iterator().next())); + for (PuzzleElement modCell : modCells) { + possibleCenters.retainAll( + (FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCell))); + } + // removing all elements without a valid number + possibleCenters.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + if (possibleCenters.isEmpty()) { + return super.getInvalidUseOfRuleMessage(); + } - /* ensure modified cells occur within a 3X3 square */ - int minVertLoc = Integer.MAX_VALUE, maxVertLoc = Integer.MIN_VALUE; - int minHorzLoc = Integer.MAX_VALUE, maxHorzLoc = Integer.MIN_VALUE; - for (PuzzleElement modCell : modCells) { - Point loc = ((FillapixCell) modCell).getLocation(); - if (loc.x < minHorzLoc) { - minHorzLoc = loc.x; - } - if (loc.x > maxHorzLoc) { - maxHorzLoc = loc.x; - } - if (loc.y < minVertLoc) { - minVertLoc = loc.y; - } - if (loc.y > maxVertLoc) { - maxVertLoc = loc.y; - } + /* Now go through the remaining centers, and check if their combinations + * match the transitions */ + for (FillapixCell possibleCenter : possibleCenters) { + int numBlack = 0; + int numEmpty = 0; + int maxBlack = possibleCenter.getNumber(); + for (FillapixCell adjCell : FillapixUtilities.getAdjacentCells(board, possibleCenter)) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; } - if (maxVertLoc - minVertLoc > 3 || maxHorzLoc - minHorzLoc > 3) { - return super.getInvalidUseOfRuleMessage(); + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + numEmpty++; } - - /* get the center of all possible 3X3 squares, - * and collect all that have numbers */ - FillapixBoard board = (FillapixBoard) transition.getParents().get(0).getBoard(); - Set possibleCenters = new TreeSet(); - possibleCenters.addAll( - FillapixUtilities.getAdjacentCells( - board, (FillapixCell) modCells.iterator().next())); + } + if (numEmpty <= 0 || numBlack > maxBlack) { + // this cell has no cases (no empty) or is already broken (too many black) + continue; + } + + ArrayList combinations = + FillapixUtilities.getCombinations(maxBlack - numBlack, numEmpty); + if (combinations.size() != childTransitions.size()) { + // not this center because combinations do not match transitions + continue; + } + boolean quitEarly = false; + for (TreeTransition trans : childTransitions) { + /* convert the transition board into boolean format, so that it + * can be compared to the combinations */ + FillapixBoard transBoard = (FillapixBoard) trans.getBoard(); + ArrayList transModCells = new ArrayList(); for (PuzzleElement modCell : modCells) { - possibleCenters.retainAll( - (FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCell))); - } - // removing all elements without a valid number - possibleCenters.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - if (possibleCenters.isEmpty()) { - return super.getInvalidUseOfRuleMessage(); + transModCells.add((FillapixCell) transBoard.getPuzzleElement(modCell)); } - /* Now go through the remaining centers, and check if their combinations - * match the transitions */ - for (FillapixCell possibleCenter : possibleCenters) { - int numBlack = 0; - int numEmpty = 0; - int maxBlack = possibleCenter.getNumber(); - for (FillapixCell adjCell : FillapixUtilities.getAdjacentCells(board, possibleCenter)) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - numEmpty++; - } - } - if (numEmpty <= 0 || numBlack > maxBlack) { - // this cell has no cases (no empty) or is already broken (too many black) - continue; - } - - ArrayList combinations = - FillapixUtilities.getCombinations(maxBlack - numBlack, numEmpty); - if (combinations.size() != childTransitions.size()) { - // not this center because combinations do not match transitions - continue; - } - boolean quitEarly = false; - for (TreeTransition trans : childTransitions) { - /* convert the transition board into boolean format, so that it - * can be compared to the combinations */ - FillapixBoard transBoard = (FillapixBoard) trans.getBoard(); - ArrayList transModCells = new ArrayList(); - for (PuzzleElement modCell : modCells) { - transModCells.add((FillapixCell) transBoard.getPuzzleElement(modCell)); - } - - boolean[] translatedModCells = new boolean[transModCells.size()]; - for (int i = 0; i < transModCells.size(); i++) { - if (transModCells.get(i).getType() == FillapixCellType.BLACK) { - translatedModCells[i] = true; - } else { - translatedModCells[i] = false; - } - } - - // try to find the above state in the combinations, remove if found - boolean removed = false; - for (boolean[] combination : combinations) { - if (Arrays.equals(combination, translatedModCells)) { - combinations.remove(combination); - removed = true; - break; - } - } - // if combination not found, no need to check further, just quit - if (!removed) { - quitEarly = true; - break; - } - } - - /* we found a center that is valid */ - if (combinations.isEmpty() && !quitEarly) { - return null; - } + boolean[] translatedModCells = new boolean[transModCells.size()]; + for (int i = 0; i < transModCells.size(); i++) { + if (transModCells.get(i).getType() == FillapixCellType.BLACK) { + translatedModCells[i] = true; + } else { + translatedModCells[i] = false; + } } - return super.getInvalidUseOfRuleMessage(); - } + // try to find the above state in the combinations, remove if found + boolean removed = false; + for (boolean[] combination : combinations) { + if (Arrays.equals(combination, translatedModCells)) { + combinations.remove(combination); + removed = true; + break; + } + } + // if combination not found, no need to check further, just quit + if (!removed) { + quitEarly = true; + break; + } + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + /* we found a center that is valid */ + if (combinations.isEmpty() && !quitEarly) { return null; + } } + + return super.getInvalidUseOfRuleMessage(); + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java index df5954d63..09d031421 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java @@ -11,46 +11,46 @@ public class TooFewBlackCellsContradictionRule extends ContradictionRule { - public TooFewBlackCellsContradictionRule() { - super( - "FPIX-CONT-0001", - "Too Few Black Cells", - "There may not be fewer black cells than the number.", - "edu/rpi/legup/images/fillapix/contradictions/TooFewBlackCells.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + public TooFewBlackCellsContradictionRule() { + super( + "FPIX-CONT-0001", + "Too Few Black Cells", + "There may not be fewer black cells than the number.", + "edu/rpi/legup/images/fillapix/contradictions/TooFewBlackCells.png"); + } - int cellNum = cell.getNumber(); - if (cellNum < 0 || cellNum >= 10) { - return super.getNoContradictionMessage(); - } - int numBlack = 0, numEmpty = 0; - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - numEmpty++; - } - } - if (numBlack + numEmpty < cellNum) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - return super.getNoContradictionMessage(); + int cellNum = cell.getNumber(); + if (cellNum < 0 || cellNum >= 10) { + return super.getNoContradictionMessage(); + } + int numBlack = 0, numEmpty = 0; + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + numEmpty++; + } } + if (numBlack + numEmpty < cellNum) { + return null; + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java index 38b47c972..9184212bb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java @@ -11,43 +11,43 @@ public class TooManyBlackCellsContradictionRule extends ContradictionRule { - public TooManyBlackCellsContradictionRule() { - super( - "FPIX-CONT-0002", - "Too Many Black Cells", - "There may not be more black cells than the number", - "edu/rpi/legup/images/fillapix/contradictions/TooManyBlackCells.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + public TooManyBlackCellsContradictionRule() { + super( + "FPIX-CONT-0002", + "Too Many Black Cells", + "There may not be more black cells than the number", + "edu/rpi/legup/images/fillapix/contradictions/TooManyBlackCells.png"); + } - int cellNum = cell.getNumber(); - if (cellNum < 0 || cellNum >= 10) { - return super.getNoContradictionMessage(); - } - int numBlack = 0; - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - } - if (numBlack > cellNum) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - return super.getNoContradictionMessage(); + int cellNum = cell.getNumber(); + if (cellNum < 0 || cellNum >= 10) { + return super.getNoContradictionMessage(); + } + int numBlack = 0; + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } } + if (numBlack > cellNum) { + return null; + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java index 72e2def47..78caf6a56 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java @@ -15,99 +15,96 @@ import java.util.List; public class TouchingCornersDirectRule extends DirectRule { - public TouchingCornersDirectRule() { - super( - "FPIX-BASC-0005", - "Touching Corners", - "Clues with touching corners have the same difference in black cells in their" - + " unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = - (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + public TouchingCornersDirectRule() { + super( + "FPIX-BASC-0005", + "Touching Corners", + "Clues with touching corners have the same difference in black cells in their" + + " unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); + } - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // get all adjCells that have a number - ArrayList adjCells = - FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell diagonally - * adjacent to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - FillapixCell adjCell = itr.next(); + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - boolean found = false; - ArrayList adjAdjCells = - FillapixUtilities.getAdjacentCells(parentBoard, adjCell); - for (FillapixCell adjAdjCell : adjAdjCells) { - if (adjAdjCell.getLocation().x != adjCell.getLocation().x - && adjAdjCell.getLocation().y != adjCell.getLocation().y - && adjAdjCell.getNumber() >= 0 - && adjAdjCell.getNumber() < 10 - && adjAdjCell.getIndex() != parentCell.getIndex()) { - // adjAdjCell is diagonally adjacent to adjCell && it has a - // number && it is not parentCell - found = true; - } - } + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell diagonally + * adjacent to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + FillapixCell adjCell = itr.next(); - // does not qualify for this rule - if (!found) { - itr.remove(); - } + boolean found = false; + ArrayList adjAdjCells = + FillapixUtilities.getAdjacentCells(parentBoard, adjCell); + for (FillapixCell adjAdjCell : adjAdjCells) { + if (adjAdjCell.getLocation().x != adjCell.getLocation().x + && adjAdjCell.getLocation().y != adjCell.getLocation().y + && adjAdjCell.getNumber() >= 0 + && adjAdjCell.getNumber() < 10 + && adjAdjCell.getIndex() != parentCell.getIndex()) { + // adjAdjCell is diagonally adjacent to adjCell && it has a + // number && it is not parentCell + found = true; } + } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } - } - - return super.getInvalidUseOfRuleMessage(); + // does not qualify for this rule + if (!found) { + itr.remove(); + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { return null; + } } + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java index 281dd5392..c64202245 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java @@ -15,112 +15,109 @@ import java.util.List; public class TouchingSidesDirectRule extends DirectRule { - public TouchingSidesDirectRule() { - super( - "FPIX-BASC-0004", - "Touching Sides", - "Clues with touching sides have the same difference in black cells in their" - + " unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = - (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + public TouchingSidesDirectRule() { + super( + "FPIX-BASC-0004", + "Touching Sides", + "Clues with touching sides have the same difference in black cells in their" + + " unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // get all adjCells that have a number - ArrayList adjCells = - FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell adjacent - * to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - // calculate x and y offset of adjCell from cell - FillapixCell adjCell = itr.next(); - int xOffset = adjCell.getLocation().x - cell.getLocation().x; - int yOffset = adjCell.getLocation().y - cell.getLocation().y; + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - boolean found = false; - // check vertically for numbered cell in opposite direction of cell - if (adjCell.getLocation().x + xOffset >= 0 - && adjCell.getLocation().x < parentBoard.getWidth()) { - int adjNum = - parentBoard - .getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y) - .getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; - } - } - // check horizontally for numbered cell in opposite direction of cell - if (adjCell.getLocation().y + yOffset >= 0 - && adjCell.getLocation().y < parentBoard.getHeight()) { - int adjNum = - parentBoard - .getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset) - .getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; - } - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, - // then adjCell is not valid, so should be removed - if (!found) { - itr.remove(); - } - } + // get all adjCells that have a number + ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell adjacent + * to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + // calculate x and y offset of adjCell from cell + FillapixCell adjCell = itr.next(); + int xOffset = adjCell.getLocation().x - cell.getLocation().x; + int yOffset = adjCell.getLocation().y - cell.getLocation().y; - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); + boolean found = false; + // check vertically for numbered cell in opposite direction of cell + if (adjCell.getLocation().x + xOffset >= 0 + && adjCell.getLocation().x < parentBoard.getWidth()) { + int adjNum = + parentBoard + .getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y) + .getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { - return null; - } + } + // check horizontally for numbered cell in opposite direction of cell + if (adjCell.getLocation().y + yOffset >= 0 + && adjCell.getLocation().y < parentBoard.getHeight()) { + int adjNum = + parentBoard + .getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset) + .getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; } + } - return super.getInvalidUseOfRuleMessage(); + // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, + // then adjCell is not valid, so should be removed + if (!found) { + itr.remove(); + } } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { return null; + } } + + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java index afe3dd652..119362a88 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java @@ -5,63 +5,63 @@ public class Heyawake extends Puzzle { - public Heyawake() { - super(); + public Heyawake() { + super(); - this.name = "Heyawake"; + this.name = "Heyawake"; - this.factory = new HeyawakeFactory(); + this.factory = new HeyawakeFactory(); - this.exporter = new HeyawakeExporter(this); - this.importer = new HeyawakeImporter(this); - } + this.exporter = new HeyawakeExporter(this); + this.importer = new HeyawakeImporter(this); + } - /** Initializes the view. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new HeyawakeView((HeyawakeBoard) currentBoard); - } + /** Initializes the view. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new HeyawakeView((HeyawakeBoard) currentBoard); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for HeyAwake - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for HeyAwake, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for HeyAwake + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for HeyAwake, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java index cedb3a91b..2dfe35138 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java @@ -10,46 +10,46 @@ public class HeyawakeBoard extends GridBoard { - private Map> regions; - - public HeyawakeBoard(int width, int height) { - super(width, height); - this.regions = new HashMap<>(); - } - - public HeyawakeBoard(int size) { - this(size, size); - } - - @Override - public HeyawakeCell getCell(int x, int y) { - return (HeyawakeCell) super.getCell(x, y); + private Map> regions; + + public HeyawakeBoard(int width, int height) { + super(width, height); + this.regions = new HashMap<>(); + } + + public HeyawakeBoard(int size) { + this(size, size); + } + + @Override + public HeyawakeCell getCell(int x, int y) { + return (HeyawakeCell) super.getCell(x, y); + } + + public List getRegion(int regionIndex) { + return this.regions.get(regionIndex); + } + + public Map> getRegions() { + return this.regions; + } + + @Override + public HeyawakeBoard copy() { + HeyawakeBoard copy = new HeyawakeBoard(dimension.width, dimension.height); + for (List region : regions.values()) { + List newCpy = new ArrayList<>(); + for (HeyawakeCell cell : region) { + Point point = cell.getLocation(); + HeyawakeCell cellCpy = cell.copy(); + copy.setCell(point.x, point.y, cellCpy); + newCpy.add(cellCpy); + } + copy.regions.put(region.get(0).getRegionIndex(), newCpy); } - - public List getRegion(int regionIndex) { - return this.regions.get(regionIndex); - } - - public Map> getRegions() { - return this.regions; - } - - @Override - public HeyawakeBoard copy() { - HeyawakeBoard copy = new HeyawakeBoard(dimension.width, dimension.height); - for (List region : regions.values()) { - List newCpy = new ArrayList<>(); - for (HeyawakeCell cell : region) { - Point point = cell.getLocation(); - HeyawakeCell cellCpy = cell.copy(); - copy.setCell(point.x, point.y, cellCpy); - newCpy.add(cellCpy); - } - copy.regions.put(region.get(0).getRegionIndex(), newCpy); - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java index 480e2e39b..e75271355 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java @@ -5,23 +5,23 @@ public class HeyawakeCell extends GridCell { - private int regionIndex; + private int regionIndex; - public HeyawakeCell(int valueInt, Point location, int regionIndex) { - super(valueInt, location); - this.regionIndex = regionIndex; - } + public HeyawakeCell(int valueInt, Point location, int regionIndex) { + super(valueInt, location); + this.regionIndex = regionIndex; + } - public int getRegionIndex() { - return this.regionIndex; - } + public int getRegionIndex() { + return this.regionIndex; + } - @Override - public HeyawakeCell copy() { - HeyawakeCell copy = new HeyawakeCell(data, (Point) location.clone(), regionIndex); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public HeyawakeCell copy() { + HeyawakeCell copy = new HeyawakeCell(data, (Point) location.clone(), regionIndex); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java index d30159856..f1ca1c79e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java @@ -5,42 +5,41 @@ public class HeyawakeElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); - - public HeyawakeElementView(HeyawakeCell cell) { - super(cell); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public HeyawakeCell getPuzzleElement() { - return (HeyawakeCell) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - - if (cell.getData() >= 0) { - graphics2D.setColor(BLACK_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = - location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); + + public HeyawakeElementView(HeyawakeCell cell) { + super(cell); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public HeyawakeCell getPuzzleElement() { + return (HeyawakeCell) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + + if (cell.getData() >= 0) { + graphics2D.setColor(BLACK_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java index 4470d77be..0856bf0de 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java @@ -6,34 +6,34 @@ public class HeyawakeExporter extends PuzzleExporter { - public HeyawakeExporter(Heyawake heyawake) { - super(heyawake); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - HeyawakeBoard board; - if (puzzle.getTree() != null) { - board = (HeyawakeBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (HeyawakeBoard) puzzle.getBoardView().getBoard(); - } + public HeyawakeExporter(Heyawake heyawake) { + super(heyawake); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + HeyawakeBoard board; + if (puzzle.getTree() != null) { + board = (HeyawakeBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (HeyawakeBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java index 8ecf24135..f6853d75f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java @@ -10,69 +10,68 @@ import org.w3c.dom.Node; public class HeyawakeFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public HeyawakeCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Heyawake Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public HeyawakeCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Heyawake Factory: unknown puzzleElement puzzleElement"); + } - HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; - int width = heyawakeBoard.getWidth(); - int height = heyawakeBoard.getHeight(); + HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; + int width = heyawakeBoard.getWidth(); + int height = heyawakeBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - int regionIndex = Integer.valueOf(attributeList.getNamedItem("region").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException( - "Heyawake Factory: cell location out of bounds"); - } - if (value < -4 || value > 4) { - throw new InvalidFileFormatException("Heyawake Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + int regionIndex = Integer.valueOf(attributeList.getNamedItem("region").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("Heyawake Factory: cell location out of bounds"); + } + if (value < -4 || value > 4) { + throw new InvalidFileFormatException("Heyawake Factory: cell unknown value"); + } - HeyawakeCell cell = new HeyawakeCell(value, new Point(x, y), regionIndex); - cell.setIndex(y * height + x); - heyawakeBoard.getRegions(); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Heyawake Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Heyawake Factory: could not find attribute(s)"); - } + HeyawakeCell cell = new HeyawakeCell(value, new Point(x, y), regionIndex); + cell.setIndex(y * height + x); + heyawakeBoard.getRegions(); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Heyawake Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Heyawake Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - Point loc = cell.getLocation(); + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); - cellElement.setAttribute("region", String.valueOf(cell.getRegionIndex())); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("region", String.valueOf(cell.getRegionIndex())); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java index 6bbabd54d..f85a0b46d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java @@ -9,103 +9,99 @@ public class HeyawakeImporter extends PuzzleImporter { - public HeyawakeImporter(Heyawake heyawake) { - super(heyawake); - } + public HeyawakeImporter(Heyawake heyawake) { + super(heyawake); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "Heyawake Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "Heyawake Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("Heyawake Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("Heyawake Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - HeyawakeBoard heyawakeBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - heyawakeBoard = new HeyawakeBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - heyawakeBoard = new HeyawakeBoard(width, height); - } - } + HeyawakeBoard heyawakeBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + heyawakeBoard = new HeyawakeBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + heyawakeBoard = new HeyawakeBoard(width, height); + } + } - if (heyawakeBoard == null) { - throw new InvalidFileFormatException("Heyawake Importer: invalid board dimensions"); - } + if (heyawakeBoard == null) { + throw new InvalidFileFormatException("Heyawake Importer: invalid board dimensions"); + } - int width = heyawakeBoard.getWidth(); - int height = heyawakeBoard.getHeight(); + int width = heyawakeBoard.getWidth(); + int height = heyawakeBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - HeyawakeCell cell = - (HeyawakeCell) - puzzle.getFactory() - .importCell(elementDataList.item(i), heyawakeBoard); - Point loc = cell.getLocation(); - if (cell.getData() != -2) { - cell.setModifiable(false); - cell.setGiven(true); - } - heyawakeBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + HeyawakeCell cell = + (HeyawakeCell) puzzle.getFactory().importCell(elementDataList.item(i), heyawakeBoard); + Point loc = cell.getLocation(); + if (cell.getData() != -2) { + cell.setModifiable(false); + cell.setGiven(true); + } + heyawakeBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (heyawakeBoard.getCell(x, y) == null) { - HeyawakeCell cell = new HeyawakeCell(0, new Point(x, y), -1); - cell.setIndex(y * height + x); - cell.setModifiable(false); - heyawakeBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(heyawakeBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Heyawake Importer: unknown value where integer expected"); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (heyawakeBoard.getCell(x, y) == null) { + HeyawakeCell cell = new HeyawakeCell(0, new Point(x, y), -1); + cell.setIndex(y * height + x); + cell.setModifiable(false); + heyawakeBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(heyawakeBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Heyawake Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Hey Awake cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Hey Awake cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java index fba5f0eb7..0c349ca87 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java @@ -11,44 +11,43 @@ public class HeyawakeView extends GridBoardView { - private Map regionsBoundaries; - - public HeyawakeView(HeyawakeBoard board) { - super(new BoardController(), new HeyawakeController(), board.getDimension()); - - this.regionsBoundaries = new HashMap<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - Point loc = cell.getLocation(); - HeyawakeElementView elementView = new HeyawakeElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - - int regionIndex = cell.getRegionIndex(); - if (regionsBoundaries.get(regionIndex) == null) { - regionsBoundaries.put(regionIndex, new Area(elementView.getBounds())); - } else { - regionsBoundaries.get(regionIndex).add(new Area(elementView.getBounds())); - } - } + private Map regionsBoundaries; + + public HeyawakeView(HeyawakeBoard board) { + super(new BoardController(), new HeyawakeController(), board.getDimension()); + + this.regionsBoundaries = new HashMap<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + Point loc = cell.getLocation(); + HeyawakeElementView elementView = new HeyawakeElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + + int regionIndex = cell.getRegionIndex(); + if (regionsBoundaries.get(regionIndex) == null) { + regionsBoundaries.put(regionIndex, new Area(elementView.getBounds())); + } else { + regionsBoundaries.get(regionIndex).add(new Area(elementView.getBounds())); + } } + } - @Override - public void drawBoard(Graphics2D graphics2D) { - HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; + @Override + public void drawBoard(Graphics2D graphics2D) { + HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; - for (ElementView elementView : elementViews) { - elementView.draw(graphics2D); - } + for (ElementView elementView : elementViews) { + elementView.draw(graphics2D); + } - graphics2D.setColor(Color.BLACK); - graphics2D.setStroke(new BasicStroke(3)); - for (Area s : regionsBoundaries.values()) { - graphics2D.draw(s); - } + graphics2D.setColor(Color.BLACK); + graphics2D.setStroke(new BasicStroke(3)); + for (Area s : regionsBoundaries.values()) { + graphics2D.draw(s); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java index 88d293f5e..1a46e5265 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java @@ -6,25 +6,25 @@ public class AdjacentBlacksContradictionRule extends ContradictionRule { - public AdjacentBlacksContradictionRule() { - super( - "HEYA-CONT-0001", - "Adjacent Blacks", - "", - "edu/rpi/legup/images/heyawake/contradictions/adjacentBlacks.png"); - } + public AdjacentBlacksContradictionRule() { + super( + "HEYA-CONT-0001", + "Adjacent Blacks", + "", + "edu/rpi/legup/images/heyawake/contradictions/adjacentBlacks.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java index 251be46ee..882372372 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java @@ -9,63 +9,63 @@ public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "HEYA-CASE-0001", - "Black or White", - "", - "edu/rpi/legup/images/heyawake/cases/BlackOrWhite.png"); - } + public BlackOrWhiteCaseRule() { + super( + "HEYA-CASE-0001", + "Black or White", + "", + "edu/rpi/legup/images/heyawake/cases/BlackOrWhite.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java index 1fc3d0776..d687569ff 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class BlackPathDirectRule { - public BlackPathDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public BlackPathDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java index 41d950378..033bce643 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class BottleNeckDirectRule { - public BottleNeckDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public BottleNeckDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java index aee1ae4bf..8fe0f66e5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java @@ -8,38 +8,37 @@ public class FillRoomBlackDirectRule extends DirectRule { - public FillRoomBlackDirectRule() { - super( - "HEYA-BASC-0003", - "Fill Room Black", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); - } + public FillRoomBlackDirectRule() { + super( + "HEYA-BASC-0003", + "Fill Room Black", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java index c4609b239..95473aa9c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java @@ -8,38 +8,37 @@ public class FillRoomWhiteDirectRule extends DirectRule { - public FillRoomWhiteDirectRule() { - super( - "HEYA-BASC-0004", - "Fill Room White", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); - } + public FillRoomWhiteDirectRule() { + super( + "HEYA-BASC-0004", + "Fill Room White", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java index 8b6f21564..233136061 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class OneRowDirectRule { - public OneRowDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public OneRowDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java index f5d4e78b7..14b3ef0a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class PreventWhiteLineDirectRule { - public PreventWhiteLineDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public PreventWhiteLineDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java index 762b435a2..af2448b13 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java @@ -6,25 +6,25 @@ public class RoomTooEmptyContradictionRule extends ContradictionRule { - public RoomTooEmptyContradictionRule() { - super( - "HEYA-CONT-0002", - "Room too Empty", - "", - "edu/rpi/legup/images/heyawake/contradictions/RoomTooEmpty.png"); - } + public RoomTooEmptyContradictionRule() { + super( + "HEYA-CONT-0002", + "Room too Empty", + "", + "edu/rpi/legup/images/heyawake/contradictions/RoomTooEmpty.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java index 643f75f13..d46ae27a0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java @@ -6,25 +6,25 @@ public class RoomTooFullContradictionRule extends ContradictionRule { - public RoomTooFullContradictionRule() { - super( - "HEYA-CONT-0003", - "Room too Full", - "", - "edu/rpi/legup/images/heyawake/contradictions/RoomTooFull.png"); - } + public RoomTooFullContradictionRule() { + super( + "HEYA-CONT-0003", + "Room too Full", + "", + "edu/rpi/legup/images/heyawake/contradictions/RoomTooFull.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java index cf2c241e3..b6782e380 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ThreeByThreeDirectRule { - public ThreeByThreeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ThreeByThreeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java index 83f1ca72f..0af7fbc15 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class TwoInCornerDirectRule { - public TwoInCornerDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public TwoInCornerDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java index c0987d4f9..377ba5911 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java @@ -6,25 +6,25 @@ public class WhiteAreaContradictionRule extends ContradictionRule { - public WhiteAreaContradictionRule() { - super( - "HEYA-CONT-0004", - "White Area", - "", - "edu/rpi/legup/images/heyawake/contradictions/WhiteArea.png"); - } + public WhiteAreaContradictionRule() { + super( + "HEYA-CONT-0004", + "White Area", + "", + "edu/rpi/legup/images/heyawake/contradictions/WhiteArea.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java index 2e3bc1812..c6c7b7d6b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java @@ -8,38 +8,37 @@ public class WhiteAroundBlackDirectRule extends DirectRule { - public WhiteAroundBlackDirectRule() { - super( - "HEYA-BASC-0009", - "White Around Black", - "", - "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); - } + public WhiteAroundBlackDirectRule() { + super( + "HEYA-BASC-0009", + "White Around Black", + "", + "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java index f151ec12a..d4d547677 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class WhiteEscapeDirectRule { - public WhiteEscapeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public WhiteEscapeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java index b695b8206..813dd45ed 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java @@ -6,25 +6,25 @@ public class WhiteLineContradictionRule extends ContradictionRule { - public WhiteLineContradictionRule() { - super( - "HEYA-CONT-0005", - "White Line", - "", - "edu/rpi/legup/images/heyawake/contradictions/WhiteLine.png"); - } + public WhiteLineContradictionRule() { + super( + "HEYA-CONT-0005", + "White Line", + "", + "edu/rpi/legup/images/heyawake/contradictions/WhiteLine.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java index d44491a6e..9f9212861 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ZigZagCaseRule { - public ZigZagCaseRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ZigZagCaseRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java index 9df735b0b..531cf030e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ZigZagWhiteDirectRule { - public ZigZagWhiteDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ZigZagWhiteDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java index ab95c4658..73878706f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java @@ -9,80 +9,79 @@ @RegisterPuzzle public class LightUp extends Puzzle { - public LightUp() { - super(); - this.name = "LightUp"; + public LightUp() { + super(); + this.name = "LightUp"; - this.importer = new LightUpImporter(this); - this.exporter = new LightUpExporter(this); + this.importer = new LightUpImporter(this); + this.exporter = new LightUpExporter(this); - this.factory = new LightUpCellFactory(); - } + this.factory = new LightUpCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new LightUpView((LightUpBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new LightUpView((LightUpBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Light Up - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Light Up, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows > 0 && columns > 0; - } + @Override + /** + * Determines if the given dimensions are valid for Light Up + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Light Up, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows > 0 && columns > 0; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - lightUpBoard.fillWithLight(); + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + lightUpBoard.fillWithLight(); - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(lightUpBoard) == null) { - System.out.println(rule.getRuleName()); - return false; - } - } - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) data; - if ((cell.getType() == LightUpCellType.UNKNOWN - || cell.getType() == LightUpCellType.EMPTY) - && !cell.isLite()) { - return false; - } - } - return true; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(lightUpBoard) == null) { + System.out.println(rule.getRuleName()); + return false; + } + } + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) data; + if ((cell.getType() == LightUpCellType.UNKNOWN || cell.getType() == LightUpCellType.EMPTY) + && !cell.isLite()) { + return false; + } } + return true; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java index 217ef79a8..5d0d66648 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java @@ -7,172 +7,168 @@ import java.util.Set; public class LightUpBoard extends GridBoard { - public LightUpBoard(int width, int height) { - super(width, height); - } + public LightUpBoard(int width, int height) { + super(width, height); + } + + public LightUpBoard(int size) { + super(size, size); + } - public LightUpBoard(int size) { - super(size, size); + /** + * Sets cells in board to lite depending on whether there is a bulb cell in the current row or + * column + */ + public void fillWithLight() { + for (int y = 0; y < this.dimension.height; y++) { + for (int x = 0; x < this.dimension.width; x++) { + getCell(x, y).setLite(false); + } } - /** - * Sets cells in board to lite depending on whether there is a bulb cell in the current row or - * column - */ - public void fillWithLight() { - for (int y = 0; y < this.dimension.height; y++) { - for (int x = 0; x < this.dimension.width; x++) { - getCell(x, y).setLite(false); + for (int y = 0; y < this.dimension.height; y++) { + for (int x = 0; x < this.dimension.width; x++) { + LightUpCell cell = getCell(x, y); + if (cell.getType() == LightUpCellType.BULB) { + cell.setLite(true); + for (int i = x + 1; i < this.dimension.width; i++) { + LightUpCell c = getCell(i, y); + if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { + break; } - } - - for (int y = 0; y < this.dimension.height; y++) { - for (int x = 0; x < this.dimension.width; x++) { - LightUpCell cell = getCell(x, y); - if (cell.getType() == LightUpCellType.BULB) { - cell.setLite(true); - for (int i = x + 1; i < this.dimension.width; i++) { - LightUpCell c = getCell(i, y); - if (c.getType() == LightUpCellType.NUMBER - || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = x - 1; i >= 0; i--) { - LightUpCell c = getCell(i, y); - if (c.getType() == LightUpCellType.NUMBER - || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = y + 1; i < this.dimension.height; i++) { - LightUpCell c = getCell(x, i); - if (c.getType() == LightUpCellType.NUMBER - || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = y - 1; i >= 0; i--) { - LightUpCell c = getCell(x, i); - if (c.getType() == LightUpCellType.NUMBER - || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - } + c.setLite(true); + } + for (int i = x - 1; i >= 0; i--) { + LightUpCell c = getCell(i, y); + if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { + break; } + c.setLite(true); + } + for (int i = y + 1; i < this.dimension.height; i++) { + LightUpCell c = getCell(x, i); + if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = y - 1; i >= 0; i--) { + LightUpCell c = getCell(x, i); + if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } } + } } + } - /** - * Gets adjancent cells to the specified cell - * - * @param cell LightUpCell - * @return Set of adjacent LightUpCells - */ - public Set getAdj(LightUpCell cell) { - Set adjCells = new HashSet<>(); - cell = (LightUpCell) getPuzzleElement(cell); + /** + * Gets adjancent cells to the specified cell + * + * @param cell LightUpCell + * @return Set of adjacent LightUpCells + */ + public Set getAdj(LightUpCell cell) { + Set adjCells = new HashSet<>(); + cell = (LightUpCell) getPuzzleElement(cell); - Point loc = cell.getLocation(); - LightUpCell up = getCell(loc.x, loc.y + 1); - if (up != null) { - adjCells.add(up); - } - LightUpCell down = getCell(loc.x, loc.y - 1); - if (down != null) { - adjCells.add(down); - } - LightUpCell right = getCell(loc.x + 1, loc.y); - if (right != null) { - adjCells.add(right); - } - LightUpCell left = getCell(loc.x - 1, loc.y); - if (left != null) { - adjCells.add(left); - } - return adjCells; + Point loc = cell.getLocation(); + LightUpCell up = getCell(loc.x, loc.y + 1); + if (up != null) { + adjCells.add(up); } - - /** - * Gets the number of adjacent cells of the specified type - * - * @param cell base cell - * @param type specified type - * @return the number of adjacent cells - */ - public int getNumAdj(LightUpCell cell, LightUpCellType type) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.getType() == type) { - num++; - } - } - return num; + LightUpCell down = getCell(loc.x, loc.y - 1); + if (down != null) { + adjCells.add(down); } - - /** - * Gets the number of adjacent cells - * - * @param cell LightUpCell - * @return number of adjacent cells - */ - public int getNumAdjLite(LightUpCell cell) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.isLite()) { - num++; - } - } - return num; + LightUpCell right = getCell(loc.x + 1, loc.y); + if (right != null) { + adjCells.add(right); } + LightUpCell left = getCell(loc.x - 1, loc.y); + if (left != null) { + adjCells.add(left); + } + return adjCells; + } - /** - * Gets the number of adjacent cells that are placable - * - * @param cell specified cell - * @return number of adjacent cells that are placable - */ - public int getNumPlacble(LightUpCell cell) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - num++; - } - } - return num; + /** + * Gets the number of adjacent cells of the specified type + * + * @param cell base cell + * @param type specified type + * @return the number of adjacent cells + */ + public int getNumAdj(LightUpCell cell, LightUpCellType type) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.getType() == type) { + num++; + } } + return num; + } - @Override - public LightUpCell getCell(int x, int y) { - return (LightUpCell) super.getCell(x, y); + /** + * Gets the number of adjacent cells + * + * @param cell LightUpCell + * @return number of adjacent cells + */ + public int getNumAdjLite(LightUpCell cell) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.isLite()) { + num++; + } } + return num; + } - @Override - public void notifyChange(PuzzleElement puzzleElement) { - super.notifyChange(puzzleElement); - fillWithLight(); + /** + * Gets the number of adjacent cells that are placable + * + * @param cell specified cell + * @return number of adjacent cells that are placable + */ + public int getNumPlacble(LightUpCell cell) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + num++; + } } + return num; + } - @Override - public LightUpBoard copy() { - LightUpBoard copy = new LightUpBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.fillWithLight(); - return copy; + @Override + public LightUpCell getCell(int x, int y) { + return (LightUpCell) super.getCell(x, y); + } + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + super.notifyChange(puzzleElement); + fillWithLight(); + } + + @Override + public LightUpBoard copy() { + LightUpBoard copy = new LightUpBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + copy.fillWithLight(); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java index 8adf84cb4..f21f42fd6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java @@ -6,78 +6,78 @@ import java.awt.event.MouseEvent; public class LightUpCell extends GridCell { - private boolean isLite; + private boolean isLite; - public LightUpCell(int valueInt, Point location) { - super(valueInt, location); - this.isLite = false; - } + public LightUpCell(int valueInt, Point location) { + super(valueInt, location); + this.isLite = false; + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "LTUP-PLAC-0001": - this.data = -4; - break; - case "LTUP-UNPL-0002": - this.data = -1; - break; - case "LTUP-UNPL-0003": - this.data = -2; - break; - case "LTUP-UNPL-0001": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data < 0 || this.data > 3) { - this.data = 0; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 0) { - this.data = this.data - 1; - } else { - this.data = 4; - } - break; - } - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "LTUP-PLAC-0001": + this.data = -4; + break; + case "LTUP-UNPL-0002": + this.data = -1; + break; + case "LTUP-UNPL-0003": + this.data = -2; + break; + case "LTUP-UNPL-0001": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data < 0 || this.data > 3) { + this.data = 0; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 0) { + this.data = this.data - 1; + } else { + this.data = 4; + } + break; } + break; } + } - public LightUpCellType getType() { - switch (data) { - case -4: - return LightUpCellType.BULB; - case -3: - return LightUpCellType.EMPTY; - case -2: - return LightUpCellType.UNKNOWN; - case -1: - return LightUpCellType.BLACK; - default: - if (data >= 0) { - return LightUpCellType.NUMBER; - } + public LightUpCellType getType() { + switch (data) { + case -4: + return LightUpCellType.BULB; + case -3: + return LightUpCellType.EMPTY; + case -2: + return LightUpCellType.UNKNOWN; + case -1: + return LightUpCellType.BLACK; + default: + if (data >= 0) { + return LightUpCellType.NUMBER; } - return null; } + return null; + } - public boolean isLite() { - return isLite; - } + public boolean isLite() { + return isLite; + } - public void setLite(boolean isLite) { - this.isLite = isLite; - } + public void setLite(boolean isLite) { + this.isLite = isLite; + } - @Override - public LightUpCell copy() { - LightUpCell copy = new LightUpCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public LightUpCell copy() { + LightUpCell copy = new LightUpCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java index d4049897d..07217869e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java @@ -5,40 +5,40 @@ import java.awt.event.MouseEvent; public class LightUpCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - LightUpCell cell = (LightUpCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == -2) { - data.setData(-4); - } else { - if (cell.getData() == -4) { - data.setData(-3); - } else { - data.setData(-2); - } - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + LightUpCell cell = (LightUpCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == -2) { + data.setData(-4); } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == -4) { - data.setData(-2); - } else { - if (cell.getData() == -2) { - data.setData(-3); - } else { - data.setData(-4); - } - } - } + if (cell.getData() == -4) { + data.setData(-3); + } else { + data.setData(-2); + } } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == -4) { + data.setData(-2); + } else { + if (cell.getData() == -2) { + data.setData(-3); + } else { + data.setData(-4); + } + } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java index 384aa2b74..10a44ca85 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java @@ -10,66 +10,64 @@ import org.w3c.dom.Node; public class LightUpCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public LightUpCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "lightup Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public LightUpCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "lightup Factory: unknown puzzleElement puzzleElement"); + } - LightUpBoard lightUpBoard = (LightUpBoard) board; - int width = lightUpBoard.getWidth(); - int height = lightUpBoard.getHeight(); + LightUpBoard lightUpBoard = (LightUpBoard) board; + int width = lightUpBoard.getWidth(); + int height = lightUpBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException( - "lightup Factory: cell location out of bounds"); - } - if (value < -4 || value > 4) { - throw new InvalidFileFormatException("lightup Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("lightup Factory: cell location out of bounds"); + } + if (value < -4 || value > 4) { + throw new InvalidFileFormatException("lightup Factory: cell unknown value"); + } - LightUpCell cell = new LightUpCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "lightup Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("lightup Factory: could not find attribute(s)"); - } + LightUpCell cell = new LightUpCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("lightup Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("lightup Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java index 8472be7a6..3d28a0604 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java @@ -1,15 +1,15 @@ package edu.rpi.legup.puzzle.lightup; public enum LightUpCellType { - BULB(-4), - EMPTY(-3), - UNKNOWN(-2), - BLACK(-1), - NUMBER(0); + BULB(-4), + EMPTY(-3), + UNKNOWN(-2), + BLACK(-1), + NUMBER(0); - public int value; + public int value; - LightUpCellType(int value) { - this.value = value; - } + LightUpCellType(int value) { + this.value = value; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java index 1b00b007d..6805d9d29 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java @@ -4,86 +4,85 @@ import java.awt.*; public class LightUpElementView extends GridElementView { - private static final Color LITE = new Color(0xFFF176); - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color LITE = new Color(0xFFF176); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); - public LightUpElementView(LightUpCell cell) { - super(cell); - } + public LightUpElementView(LightUpCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public LightUpCell getPuzzleElement() { - return (LightUpCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public LightUpCell getPuzzleElement() { + return (LightUpCell) super.getPuzzleElement(); + } - @Override - public void drawElement(Graphics2D graphics2D) { - LightUpCell cell = (LightUpCell) puzzleElement; - LightUpCellType type = cell.getType(); - if (type == LightUpCellType.NUMBER) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + LightUpCell cell = (LightUpCell) puzzleElement; + LightUpCellType type = cell.getType(); + if (type == LightUpCellType.NUMBER) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(WHITE_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = - location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + graphics2D.setColor(WHITE_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } else { + if (type == LightUpCellType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.EMPTY) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(cell.isLite() ? LITE : WHITE_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect( + location.x + size.width * 7 / 16, + location.y + size.height * 7 / 16, + size.width / 8, + size.height / 8); + graphics2D.drawRect(location.x, location.y, size.width, size.height); } else { - if (type == LightUpCellType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.EMPTY) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(cell.isLite() ? LITE : WHITE_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect( - location.x + size.width * 7 / 16, - location.y + size.height * 7 / 16, - size.width / 8, - size.height / 8); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(cell.isLite() ? LITE : Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.BULB) { - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.drawImage( - LightUpView.lightImage, - location.x, - location.y, - size.width, - size.height, - LITE, - null); - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - } - } + if (type == LightUpCellType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(cell.isLite() ? LITE : Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.BULB) { + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.drawImage( + LightUpView.lightImage, + location.x, + location.y, + size.width, + size.height, + LITE, + null); + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); } + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java index 0e8987020..d632879d5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java @@ -6,34 +6,34 @@ public class LightUpExporter extends PuzzleExporter { - public LightUpExporter(LightUp lightUp) { - super(lightUp); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - LightUpBoard board; - if (puzzle.getTree() != null) { - board = (LightUpBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (LightUpBoard) puzzle.getBoardView().getBoard(); - } + public LightUpExporter(LightUp lightUp) { + super(lightUp); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + LightUpBoard board; + if (puzzle.getTree() != null) { + board = (LightUpBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (LightUpBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java index 336b063f6..bce9f10ee 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java @@ -8,117 +8,113 @@ import org.w3c.dom.NodeList; public class LightUpImporter extends PuzzleImporter { - public LightUpImporter(LightUp lightUp) { - super(lightUp); - } + public LightUpImporter(LightUp lightUp) { + super(lightUp); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - LightUpBoard lightUpBoard = new LightUpBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + LightUpBoard lightUpBoard = new LightUpBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - if (lightUpBoard.getCell(x, y) == null) { - LightUpCell cell = new LightUpCell(-2, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - lightUpBoard.setCell(x, y, cell); - } - } + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + if (lightUpBoard.getCell(x, y) == null) { + LightUpCell cell = new LightUpCell(-2, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + lightUpBoard.setCell(x, y, cell); } - puzzle.setCurrentBoard(lightUpBoard); + } } + puzzle.setCurrentBoard(lightUpBoard); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "lightup Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "lightup Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("lightup Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("lightup Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - LightUpBoard lightUpBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - lightUpBoard = new LightUpBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - lightUpBoard = new LightUpBoard(width, height); - } - } + LightUpBoard lightUpBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + lightUpBoard = new LightUpBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + lightUpBoard = new LightUpBoard(width, height); + } + } - if (lightUpBoard == null) { - throw new InvalidFileFormatException("lightup Importer: invalid board dimensions"); - } + if (lightUpBoard == null) { + throw new InvalidFileFormatException("lightup Importer: invalid board dimensions"); + } - int width = lightUpBoard.getWidth(); - int height = lightUpBoard.getHeight(); + int width = lightUpBoard.getWidth(); + int height = lightUpBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - LightUpCell cell = - (LightUpCell) - puzzle.getFactory() - .importCell(elementDataList.item(i), lightUpBoard); - Point loc = cell.getLocation(); - if (cell.getData() != -2) { - cell.setModifiable(false); - cell.setGiven(true); - } - lightUpBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + LightUpCell cell = + (LightUpCell) puzzle.getFactory().importCell(elementDataList.item(i), lightUpBoard); + Point loc = cell.getLocation(); + if (cell.getData() != -2) { + cell.setModifiable(false); + cell.setGiven(true); + } + lightUpBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (lightUpBoard.getCell(x, y) == null) { - LightUpCell cell = new LightUpCell(-2, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - lightUpBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(lightUpBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "lightup Importer: unknown value where integer expected"); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (lightUpBoard.getCell(x, y) == null) { + LightUpCell cell = new LightUpCell(-2, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + lightUpBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(lightUpBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "lightup Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Light Up cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Light Up cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java index ebce6a682..b8122ffff 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java @@ -15,90 +15,86 @@ import org.apache.logging.log4j.Logger; public class LightUpView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(LightUpView.class.getName()); - static Image lightImage; + private static final Logger LOGGER = LogManager.getLogger(LightUpView.class.getName()); + static Image lightImage; - static { - try { - lightImage = - ImageIO.read( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/lightup/light.png")); - } catch (IOException e) { - LOGGER.error("Failed to open TreeTent images"); - } + static { + try { + lightImage = + ImageIO.read( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/lightup/light.png")); + } catch (IOException e) { + LOGGER.error("Failed to open TreeTent images"); } + } - public LightUpView(LightUpBoard board) { - super(new BoardController(), new LightUpCellController(), board.getDimension()); + public LightUpView(LightUpBoard board) { + super(new BoardController(), new LightUpCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); - LightUpElementView elementView = new LightUpElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); + LightUpElementView elementView = new LightUpElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - super.onTreeElementChanged(treeElement); - LightUpBoard lightUpBoard = - board instanceof CaseBoard - ? (LightUpBoard) ((CaseBoard) board).getBaseBoard() - : (LightUpBoard) board; - lightUpBoard.fillWithLight(); - repaint(); - } + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + super.onTreeElementChanged(treeElement); + LightUpBoard lightUpBoard = + board instanceof CaseBoard + ? (LightUpBoard) ((CaseBoard) board).getBaseBoard() + : (LightUpBoard) board; + lightUpBoard.fillWithLight(); + repaint(); + } - /** Returns a DataSelectionView popup menu */ - public DataSelectionView getSelectionPopupMenu() { - DataSelectionView selectionView = new DataSelectionView(elementController); - GridLayout layout = new GridLayout(3, 1); - selectionView.setLayout(layout); + /** Returns a DataSelectionView popup menu */ + public DataSelectionView getSelectionPopupMenu() { + DataSelectionView selectionView = new DataSelectionView(elementController); + GridLayout layout = new GridLayout(3, 1); + selectionView.setLayout(layout); - Dimension iconSize = new Dimension(32, 32); - Point loc = new Point(0, 0); + Dimension iconSize = new Dimension(32, 32); + Point loc = new Point(0, 0); - LightUpElementView element1 = new LightUpElementView(new LightUpCell(-2, null)); - element1.setSize(iconSize); - element1.setLocation(loc); - SelectionItemView item1 = - new SelectionItemView( - element1.getPuzzleElement(), new ImageIcon(element1.getImage())); - item1.addActionListener(elementController); - item1.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item1); + LightUpElementView element1 = new LightUpElementView(new LightUpCell(-2, null)); + element1.setSize(iconSize); + element1.setLocation(loc); + SelectionItemView item1 = + new SelectionItemView(element1.getPuzzleElement(), new ImageIcon(element1.getImage())); + item1.addActionListener(elementController); + item1.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item1); - LightUpElementView element2 = new LightUpElementView(new LightUpCell(-4, null)); - element2.setSize(iconSize); - element2.setLocation(loc); - SelectionItemView item2 = - new SelectionItemView( - element2.getPuzzleElement(), new ImageIcon(element2.getImage())); - item2.addActionListener(elementController); - item2.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item2); + LightUpElementView element2 = new LightUpElementView(new LightUpCell(-4, null)); + element2.setSize(iconSize); + element2.setLocation(loc); + SelectionItemView item2 = + new SelectionItemView(element2.getPuzzleElement(), new ImageIcon(element2.getImage())); + item2.addActionListener(elementController); + item2.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item2); - LightUpElementView element3 = new LightUpElementView(new LightUpCell(-3, null)); - element3.setSize(iconSize); - element3.setLocation(loc); - SelectionItemView item3 = - new SelectionItemView( - element3.getPuzzleElement(), new ImageIcon(element3.getImage())); - item3.addActionListener(elementController); - item3.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item3); + LightUpElementView element3 = new LightUpElementView(new LightUpCell(-3, null)); + element3.setSize(iconSize); + element3.setLocation(loc); + SelectionItemView item3 = + new SelectionItemView(element3.getPuzzleElement(), new ImageIcon(element3.getImage())); + item3.addActionListener(elementController); + item3.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item3); - return selectionView; - } + return selectionView; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java index 2ddb4f754..bac5aa4ba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java @@ -3,11 +3,8 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class BlackTile extends NonPlaceableElement { - public BlackTile() { - super( - "LTUP-UNPL-0002", - "Black Tile", - "The black tile", - "edu/rpi/legup/images/lightup/black.gif"); - } + public BlackTile() { + super( + "LTUP-UNPL-0002", "Black Tile", "The black tile", "edu/rpi/legup/images/lightup/black.gif"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java index d238baa56..ce0629fbe 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java @@ -3,11 +3,7 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BulbTile extends PlaceableElement { - public BulbTile() { - super( - "LTUP-PLAC-0001", - "Bulb Tile", - "The bulb tile", - "edu/rpi/legup/images/lightup/light.png"); - } + public BulbTile() { + super("LTUP-PLAC-0001", "Bulb Tile", "The bulb tile", "edu/rpi/legup/images/lightup/light.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java index ae314a4cf..9a2fba5c7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java @@ -4,24 +4,20 @@ public class NumberTile extends NonPlaceableElement { - int object_number; + int object_number; - // Follow the default format and resolves the NoSuchMethod error - public NumberTile() { - super( - "LTUP-UNPL-0001", - "Number Tile", - "The number tile", - "edu/rpi/legup/images/lightup/1.gif"); - } + // Follow the default format and resolves the NoSuchMethod error + public NumberTile() { + super("LTUP-UNPL-0001", "Number Tile", "The number tile", "edu/rpi/legup/images/lightup/1.gif"); + } - public NumberTile(int num) { - super( - "LTUP-UNPL-0001", - "Number Tile", - "The number tile", - "edu/rpi/legup/images/lightup/" + num + ".gif"); - if (num > 3 || num < 1) num = 1; - object_number = num; - } + public NumberTile(int num) { + super( + "LTUP-UNPL-0001", + "Number Tile", + "The number tile", + "edu/rpi/legup/images/lightup/" + num + ".gif"); + if (num > 3 || num < 1) num = 1; + object_number = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java index 24d420fe8..4e17c6b37 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "LTUP-UNPL-0003", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/lightup/UnknownTile.png"); - } + public UnknownTile() { + super( + "LTUP-UNPL-0003", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/lightup/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java index 90652888c..1adf449d0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java @@ -10,72 +10,72 @@ public class BulbsInPathContradictionRule extends ContradictionRule { - public BulbsInPathContradictionRule() { - super( - "LTUP-CONT-0001", - "Bulbs In Path", - "A bulb cannot be placed in another bulb's path.", - "edu/rpi/legup/images/lightup/contradictions/BulbsInPath.png"); - } + public BulbsInPathContradictionRule() { + super( + "LTUP-CONT-0001", + "Bulbs In Path", + "A bulb cannot be placed in another bulb's path.", + "edu/rpi/legup/images/lightup/contradictions/BulbsInPath.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.BULB) { - return super.getNoContradictionMessage(); - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.BULB) { + return super.getNoContradictionMessage(); + } - Point location = cell.getLocation(); - for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; - } - } + Point location = cell.getLocation(); + for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; } - for (int i = location.x - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; - } - } + } + } + for (int i = location.x - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; } - for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; - } - } + } + } + for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; } - for (int i = location.y - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; - } - } + } + } + for (int i = location.y - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; } - return super.getNoContradictionMessage(); + } } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java index 0ed88636c..b9b93620a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java @@ -10,80 +10,80 @@ public class CannotLightACellContradictionRule extends ContradictionRule { - public CannotLightACellContradictionRule() { - super( - "LTUP-CONT-0002", - "Cannot Light A Cell", - "All cells must be able to be lit.", - "edu/rpi/legup/images/lightup/contradictions/CannotLightACell.png"); - } + public CannotLightACellContradictionRule() { + super( + "LTUP-CONT-0002", + "Cannot Light A Cell", + "All cells must be able to be lit.", + "edu/rpi/legup/images/lightup/contradictions/CannotLightACell.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - /*if (cell.getType() == LightUpCellType.BLACK || cell.getType() == LightUpCellType.NUMBER || cell.isLite()) { - return "This cell does not contain a contradiction"; - }*/ - if (cell.getType() != LightUpCellType.EMPTY || cell.isLite()) { - return super.getNoContradictionMessage(); - } - Point location = cell.getLocation(); - int ver_count = 0; - int hor_count = 0; - for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - hor_count += 1; - } - } - } - for (int i = location.x - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - hor_count += 1; - } - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + /*if (cell.getType() == LightUpCellType.BLACK || cell.getType() == LightUpCellType.NUMBER || cell.isLite()) { + return "This cell does not contain a contradiction"; + }*/ + if (cell.getType() != LightUpCellType.EMPTY || cell.isLite()) { + return super.getNoContradictionMessage(); + } + Point location = cell.getLocation(); + int ver_count = 0; + int hor_count = 0; + for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + hor_count += 1; } - for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - ver_count += 1; - } - } + } + } + for (int i = location.x - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + hor_count += 1; } - for (int i = location.y - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - ver_count += 1; - } - } + } + } + for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + ver_count += 1; } - System.out.printf("%d, %d, %d, %d\n", location.x, location.y, hor_count, ver_count); - if (hor_count == 0 && ver_count == 0) { - return null; + } + } + for (int i = location.y - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + ver_count += 1; } - return super.getNoContradictionMessage(); + } + } + System.out.printf("%d, %d, %d, %d\n", location.x, location.y, hor_count, ver_count); + if (hor_count == 0 && ver_count == 0) { + return null; } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java index 269ef0ad5..857d2333d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java @@ -11,58 +11,57 @@ public class EmptyCellinLightDirectRule extends DirectRule { - public EmptyCellinLightDirectRule() { - super( - "LTUP-BASC-0002", - "Empty Cells in Light", - "Cells in light must be empty.", - "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); - } + public EmptyCellinLightDirectRule() { + super( + "LTUP-BASC-0002", + "Empty Cells in Light", + "Cells in light must be empty.", + "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - initialBoard.fillWithLight(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); - if (finalCell.getType() == LightUpCellType.EMPTY - && initCell.getType() == LightUpCellType.UNKNOWN - && initCell.isLite()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + initialBoard.fillWithLight(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); + if (finalCell.getType() == LightUpCellType.EMPTY + && initCell.getType() == LightUpCellType.UNKNOWN + && initCell.isLite()) { + return null; } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java index 702c116c1..f4da5a73e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java @@ -14,104 +14,102 @@ public class EmptyCornersDirectRule extends DirectRule { - public EmptyCornersDirectRule() { - super( - "LTUP-BASC-0003", - "Empty Corners", - "Cells on the corners of a number must be empty if placing bulbs would prevent the" - + " number from being satisfied.", - "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); - } + public EmptyCornersDirectRule() { + super( + "LTUP-BASC-0003", + "Empty Corners", + "Cells on the corners of a number must be empty if placing bulbs would prevent the" + + " number from being satisfied.", + "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(cell.getType() == LightUpCellType.UNKNOWN - && finalCell.getType() == LightUpCellType.EMPTY)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; - } + if (!(cell.getType() == LightUpCellType.UNKNOWN + && finalCell.getType() == LightUpCellType.EMPTY)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; + } - Point loc = finalCell.getLocation(); - List numberedCells = new ArrayList<>(); - LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); - if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperRight); - } - LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); - if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperLeft); - } - LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); - if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerRight); - } - LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); - if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerLeft); - } - if (numberedCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() - + ": This cell must diagonal to a numbered cell"; - } + Point loc = finalCell.getLocation(); + List numberedCells = new ArrayList<>(); + LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); + if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperRight); + } + LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); + if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperLeft); + } + LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); + if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerRight); + } + LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); + if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerLeft); + } + if (numberedCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + ": This cell must diagonal to a numbered cell"; + } - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - LightUpBoard bulbCaseBoard = finalBoard.copy(); - LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); - bulbCaseCell.setData(LightUpCellType.BULB.value); - bulbCaseBoard.fillWithLight(); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + LightUpBoard bulbCaseBoard = finalBoard.copy(); + LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); + bulbCaseCell.setData(LightUpCellType.BULB.value); + bulbCaseBoard.fillWithLight(); - boolean createsContra = false; - for (LightUpCell c : numberedCells) { - createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; - } - if (createsContra) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; - } + boolean createsContra = false; + for (LightUpCell c : numberedCells) { + createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; } + if (createsContra) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; + } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); - TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); - for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - int temp = cell.getData(); - cell.setData(LightUpCellType.EMPTY.value); - if (checkRuleRawAt(transition, cell) == null) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(modCell); - } else { - cell.setData(temp); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); + TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); + for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + int temp = cell.getData(); + cell.setData(LightUpCellType.EMPTY.value); + if (checkRuleRawAt(transition, cell) == null) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(modCell); + } else { + cell.setData(temp); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java index 3f884d459..b2ae63788 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java @@ -12,99 +12,97 @@ public class FinishWithBulbsDirectRule extends DirectRule { - public FinishWithBulbsDirectRule() { - super( - "LTUP-BASC-0004", - "Finish with Bulbs", - "The remaining unknowns around a block must be bulbs to satisfy the number.", - "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); - } + public FinishWithBulbsDirectRule() { + super( + "LTUP-BASC-0004", + "Finish with Bulbs", + "The remaining unknowns around a block must be bulbs to satisfy the number.", + "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == LightUpCellType.UNKNOWN - && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == LightUpCellType.UNKNOWN + && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } - Set adjCells = finalBoard.getAdj(finalCell); - adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() - + ": This cell is not adjacent to a numbered cell"; - } + Set adjCells = finalBoard.getAdj(finalCell); + adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + ": This cell is not adjacent to a numbered cell"; + } - LightUpBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return null; - } - } - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; + LightUpBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return null; + } } + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; + } - /** - * Determines whether the specified cell is forced to be a bulb or not - * - * @param board the entire board - * @param cell specified cell - * @return whether cell is forced to be a bulb or not - */ - private boolean isForced(LightUpBoard board, LightUpCell cell) { - Set adjCells = board.getAdj(cell); - adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return false; - } + /** + * Determines whether the specified cell is forced to be a bulb or not + * + * @param board the entire board + * @param cell specified cell + * @return whether cell is forced to be a bulb or not + */ + private boolean isForced(LightUpBoard board, LightUpCell cell) { + Set adjCells = board.getAdj(cell); + adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return false; + } - LightUpBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return true; - } - } - return false; + LightUpBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return true; + } } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { - cell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { + cell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java index 678ee67a2..dc2647eb9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java @@ -12,111 +12,108 @@ public class FinishWithEmptyDirectRule extends DirectRule { - public FinishWithEmptyDirectRule() { - super( - "LTUP-BASC-0005", - "Finish with Empty", - "The remaining unknowns around a block must be empty if the number is satisfied.", - "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.EMPTY) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; - } + public FinishWithEmptyDirectRule() { + super( + "LTUP-BASC-0005", + "Finish with Empty", + "The remaining unknowns around a block must be empty if the number is satisfied.", + "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); + } - if (isForced(initialBoard, cell.getLocation())) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.EMPTY) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; } - /** - * Checks whether a certain cell is forced to not be a bulb - * - * @param board specified board - * @param location location of cell to check - * @return boolean value based on whether a certain cell has an adjacent cell that has the - * required amount of adjacent bulbs - */ - private boolean isForced(LightUpBoard board, Point location) { - return isForcedEmpty(board, new Point(location.x + 1, location.y)) - || isForcedEmpty(board, new Point(location.x, location.y + 1)) - || isForcedEmpty(board, new Point(location.x - 1, location.y)) - || isForcedEmpty(board, new Point(location.x, location.y - 1)); + if (isForced(initialBoard, cell.getLocation())) { + return null; } + return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; + } - /** - * Checks whether a certain cell has the required amount of adjacent bulbs - * - * @param board specified board - * @param loc location of cell to check - * @return boolean value based on whether a certain cell has the required amount of adjacent - * bulbs - */ - private boolean isForcedEmpty(LightUpBoard board, Point loc) { - LightUpCell cell = board.getCell(loc.x, loc.y); - if (cell == null || cell.getType() != LightUpCellType.NUMBER) { - return false; - } + /** + * Checks whether a certain cell is forced to not be a bulb + * + * @param board specified board + * @param location location of cell to check + * @return boolean value based on whether a certain cell has an adjacent cell that has the + * required amount of adjacent bulbs + */ + private boolean isForced(LightUpBoard board, Point location) { + return isForcedEmpty(board, new Point(location.x + 1, location.y)) + || isForcedEmpty(board, new Point(location.x, location.y + 1)) + || isForcedEmpty(board, new Point(location.x - 1, location.y)) + || isForcedEmpty(board, new Point(location.x, location.y - 1)); + } + + /** + * Checks whether a certain cell has the required amount of adjacent bulbs + * + * @param board specified board + * @param loc location of cell to check + * @return boolean value based on whether a certain cell has the required amount of adjacent bulbs + */ + private boolean isForcedEmpty(LightUpBoard board, Point loc) { + LightUpCell cell = board.getCell(loc.x, loc.y); + if (cell == null || cell.getType() != LightUpCellType.NUMBER) { + return false; + } - int bulbs = 0; - int bulbsNeeded = cell.getData(); - cell = board.getCell(loc.x + 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y + 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x - 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y - 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - return bulbs == bulbsNeeded; + int bulbs = 0; + int bulbsNeeded = cell.getData(); + cell = board.getCell(loc.x + 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; } + cell = board.getCell(loc.x, loc.y + 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x - 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y - 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + return bulbs == bulbsNeeded; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN - && isForced(initialBoard, cell.getLocation())) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell.getLocation())) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java index 4ba754731..39ad146a7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java @@ -13,101 +13,100 @@ public class LightOrEmptyCaseRule extends CaseRule { - public LightOrEmptyCaseRule() { - super( - "LTUP-CASE-0001", - "Light or Empty", - "Each blank cell is either a light or empty.", - "edu/rpi/legup/images/lightup/cases/LightOrEmpty.png"); - } + public LightOrEmptyCaseRule() { + super( + "LTUP-CASE-0001", + "Light or Empty", + "Each blank cell is either a light or empty.", + "edu/rpi/legup/images/lightup/cases/LightOrEmpty.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); - lightUpBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((LightUpCell) data).getType() == LightUpCellType.UNKNOWN) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); + lightUpBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((LightUpCell) data).getType() == LightUpCellType.UNKNOWN) { + caseBoard.addPickableElement(data); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(-4); - case1.addModifiedData(data1); - cases.add(case1); - - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(-3); - case2.addModifiedData(data2); - cases.add(case2); - - return cases; - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(-4); + case1.addModifiedData(data1); + cases.add(case1); - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children"; - } + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(-3); + case2.addModifiedData(data2); + cases.add(case2); - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } + return cases; + } - LightUpCell mod1 = (LightUpCell) case1.getBoard().getModifiedData().iterator().next(); - LightUpCell mod2 = (LightUpCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case"; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children"; + } - if (!((mod1.getType() == LightUpCellType.EMPTY && mod2.getType() == LightUpCellType.BULB) - || (mod2.getType() == LightUpCellType.EMPTY - && mod1.getType() == LightUpCellType.BULB))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty cell and a bulb cell"; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; + } - return null; + LightUpCell mod1 = (LightUpCell) case1.getBoard().getModifiedData().iterator().next(); + LightUpCell mod2 = (LightUpCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case"; } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + if (!((mod1.getType() == LightUpCellType.EMPTY && mod2.getType() == LightUpCellType.BULB) + || (mod2.getType() == LightUpCellType.EMPTY && mod1.getType() == LightUpCellType.BULB))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty cell and a bulb cell"; } + + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java index bf1843728..272450959 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java @@ -12,142 +12,141 @@ public class MustLightDirectRule extends DirectRule { - public MustLightDirectRule() { - super( - "LTUP-BASC-0006", - "Must Light", - "A cell must be a bulb if it is the only cell to be able to light another.", - "edu/rpi/legup/images/lightup/rules/MustLight.png"); - } + public MustLightDirectRule() { + super( + "LTUP-BASC-0006", + "Must Light", + "A cell must be a bulb if it is the only cell to be able to light another.", + "edu/rpi/legup/images/lightup/rules/MustLight.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == LightUpCellType.UNKNOWN - && !parentCell.isLite() - && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(parentCell.getType() == LightUpCellType.UNKNOWN + && !parentCell.isLite() + && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } - finalBoard.fillWithLight(); - boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); - finalCell.setData(LightUpCellType.BULB.value); - finalBoard.fillWithLight(); + finalBoard.fillWithLight(); + boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); + finalCell.setData(LightUpCellType.BULB.value); + finalBoard.fillWithLight(); - if (isForced) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; - } + if (isForced) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; } + } - private boolean isForcedBulb(LightUpBoard board, Point loc) { - CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); - LightUpBoard modifiedBoard = board.copy(); - LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); - modifiedCell.setData(LightUpCellType.EMPTY.value); - // Check if this cell itself (the one with the bulb) has no other lighting option - if ((modifiedCell.getType() == LightUpCellType.EMPTY - || modifiedCell.getType() == LightUpCellType.UNKNOWN) - && !modifiedCell.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { - return true; - } - // Look right - for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } + private boolean isForcedBulb(LightUpBoard board, Point loc) { + CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); + LightUpBoard modifiedBoard = board.copy(); + LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); + modifiedCell.setData(LightUpCellType.EMPTY.value); + // Check if this cell itself (the one with the bulb) has no other lighting option + if ((modifiedCell.getType() == LightUpCellType.EMPTY + || modifiedCell.getType() == LightUpCellType.UNKNOWN) + && !modifiedCell.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { + return true; + } + // Look right + for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; } - // Look left - for (int i = loc.x - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } + } + } + // Look left + for (int i = loc.x - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; } - // Look down - for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } + } + } + // Look down + for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; } - // Look up - for (int i = loc.y - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; - } - } + } + } + // Look up + for (int i = loc.y - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; } - return false; + } } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : tempBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - if (isForcedBulb(initialBoard, cell.getLocation())) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(modCell); - } - cell.setData(LightUpCellType.UNKNOWN.value); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : tempBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + if (isForcedBulb(initialBoard, cell.getLocation())) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(modCell); } + cell.setData(LightUpCellType.UNKNOWN.value); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java index ac656721d..7e9f258a3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java @@ -17,341 +17,337 @@ public class SatisfyNumberCaseRule extends CaseRule { - public SatisfyNumberCaseRule() { - super( - "LTUP-CASE-0002", - "Satisfy Number", - "The different ways a blocks number can be satisfied.", - "edu/rpi/legup/images/lightup/cases/SatisfyNumber.png"); + public SatisfyNumberCaseRule() { + super( + "LTUP-CASE-0002", + "Satisfy Number", + "The different ways a blocks number can be satisfied.", + "edu/rpi/legup/images/lightup/cases/SatisfyNumber.png"); + } + + @Override + public CaseBoard getCaseBoard(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + lightUpBoard.setModifiable(false); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((LightUpCell) data).getType() == LightUpCellType.NUMBER) { + caseBoard.addPickableElement(data); + } } - - @Override - public CaseBoard getCaseBoard(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - lightUpBoard.setModifiable(false); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((LightUpCell) data).getType() == LightUpCellType.NUMBER) { - caseBoard.addPickableElement(data); - } + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); + + List openSpots = new ArrayList<>(); + + int numNeeded = cell.getData(); + + LightUpCell checkCell = lightUpBoard.getCell(loc.x + 1, loc.y); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; } - return caseBoard; + } } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); - - List openSpots = new ArrayList<>(); - - int numNeeded = cell.getData(); - - LightUpCell checkCell = lightUpBoard.getCell(loc.x + 1, loc.y); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; - } - } - } - checkCell = lightUpBoard.getCell(loc.x, loc.y + 1); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; - } - } + checkCell = lightUpBoard.getCell(loc.x, loc.y + 1); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; } - checkCell = lightUpBoard.getCell(loc.x - 1, loc.y); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; - } - } + } + } + checkCell = lightUpBoard.getCell(loc.x - 1, loc.y); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; } - checkCell = lightUpBoard.getCell(loc.x, loc.y - 1); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; - } - } + } + } + checkCell = lightUpBoard.getCell(loc.x, loc.y - 1); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; } + } + } - ArrayList cases = new ArrayList<>(); - if (numNeeded == 0) { - return cases; - } + ArrayList cases = new ArrayList<>(); + if (numNeeded == 0) { + return cases; + } - generateCases(lightUpBoard, numNeeded, openSpots, cases); + generateCases(lightUpBoard, numNeeded, openSpots, cases); - return cases; - } + return cases; + } - private void generateCases( - final LightUpBoard board, - final int num, - List openSpots, - List cases) { - if (num > openSpots.size()) { - return; - } + private void generateCases( + final LightUpBoard board, final int num, List openSpots, List cases) { + if (num > openSpots.size()) { + return; + } - for (int i = 0; i < openSpots.size(); i++) { - LightUpCell c = openSpots.get(i); - LightUpBoard newCase = board.copy(); - LightUpCell newCell = c.copy(); - Point loc = c.getLocation(); + for (int i = 0; i < openSpots.size(); i++) { + LightUpCell c = openSpots.get(i); + LightUpBoard newCase = board.copy(); + LightUpCell newCell = c.copy(); + Point loc = c.getLocation(); - newCell.setData(-4); - newCase.setCell(loc.x, loc.y, newCell); - newCase.addModifiedData(newCell); + newCell.setData(-4); + newCase.setCell(loc.x, loc.y, newCell); + newCase.addModifiedData(newCell); - generateCases(board, num, openSpots, cases, newCase, i); - } + generateCases(board, num, openSpots, cases, newCase, i); + } + } + + private void generateCases( + final LightUpBoard board, + final int num, + List openSpots, + List cases, + LightUpBoard curBoard, + int index) { + if (num <= curBoard.getModifiedData().size()) { + cases.add(curBoard); + return; } - private void generateCases( - final LightUpBoard board, - final int num, - List openSpots, - List cases, - LightUpBoard curBoard, - int index) { - if (num <= curBoard.getModifiedData().size()) { - cases.add(curBoard); - return; - } - - for (int i = index + 1; i < openSpots.size(); i++) { - LightUpCell c = openSpots.get(i); - Point loc = c.getLocation(); - LightUpCell cc = curBoard.getCell(loc.x, loc.y); - if (!curBoard.getModifiedData().contains(cc)) { - LightUpBoard newCase = board.copy(); - LightUpCell newCell = c.copy(); + for (int i = index + 1; i < openSpots.size(); i++) { + LightUpCell c = openSpots.get(i); + Point loc = c.getLocation(); + LightUpCell cc = curBoard.getCell(loc.x, loc.y); + if (!curBoard.getModifiedData().contains(cc)) { + LightUpBoard newCase = board.copy(); + LightUpCell newCell = c.copy(); - for (PuzzleElement mod : curBoard.getModifiedData()) { - LightUpCell modCell = (LightUpCell) mod.copy(); - Point modLoc = modCell.getLocation(); + for (PuzzleElement mod : curBoard.getModifiedData()) { + LightUpCell modCell = (LightUpCell) mod.copy(); + Point modLoc = modCell.getLocation(); - modCell.setData(-4); + modCell.setData(-4); - newCase.setCell(modLoc.x, modLoc.y, modCell); - newCase.addModifiedData(modCell); - } + newCase.setCell(modLoc.x, modLoc.y, modCell); + newCase.addModifiedData(modCell); + } - newCell.setData(-4); + newCell.setData(-4); - newCase.setCell(loc.x, loc.y, newCell); - newCase.addModifiedData(newCell); + newCase.setCell(loc.x, loc.y, newCell); + newCase.addModifiedData(newCell); - generateCases(board, num, openSpots, cases, newCase, i); - } - } + generateCases(board, num, openSpots, cases, newCase, i); + } + } + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + TreeNode parent = transition.getParents().get(0); + List childTransitions = parent.getChildren(); + + List spots = getPossibleSpots(transition); + if (spots == null) { + return super.getInvalidUseOfRuleMessage(); } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - TreeNode parent = transition.getParents().get(0); - List childTransitions = parent.getChildren(); - - List spots = getPossibleSpots(transition); - if (spots == null) { - return super.getInvalidUseOfRuleMessage(); - } - - for (LightUpCell c : spots) { - ArrayList cases = getCases(parent.getBoard(), c); - - // We will allow case rules to have only one option - if (cases.size() == childTransitions.size() && cases.size() >= 1) { - boolean foundSpot = true; - for (TreeTransition childTrans : childTransitions) { - LightUpBoard actCase = (LightUpBoard) childTrans.getBoard(); - boolean foundBoard = false; - for (Board b : cases) { - LightUpBoard posCase = (LightUpBoard) b; - boolean foundAllCells = false; - if (posCase.getModifiedData().size() == actCase.getModifiedData().size()) { - foundAllCells = true; - for (PuzzleElement actEle : actCase.getModifiedData()) { - LightUpCell actCell = (LightUpCell) actEle; - boolean foundCell = false; - for (PuzzleElement posEle : posCase.getModifiedData()) { - LightUpCell posCell = (LightUpCell) posEle; - if (actCell.getType() == posCell.getType() - && actCell.getLocation() - .equals(posCell.getLocation())) { - foundCell = true; - break; - } - } - if (!foundCell) { - foundAllCells = false; - break; - } - } - } - if (foundAllCells) { - foundBoard = true; - break; - } - } - if (!foundBoard) { - foundSpot = false; - break; - } + for (LightUpCell c : spots) { + ArrayList cases = getCases(parent.getBoard(), c); + + // We will allow case rules to have only one option + if (cases.size() == childTransitions.size() && cases.size() >= 1) { + boolean foundSpot = true; + for (TreeTransition childTrans : childTransitions) { + LightUpBoard actCase = (LightUpBoard) childTrans.getBoard(); + boolean foundBoard = false; + for (Board b : cases) { + LightUpBoard posCase = (LightUpBoard) b; + boolean foundAllCells = false; + if (posCase.getModifiedData().size() == actCase.getModifiedData().size()) { + foundAllCells = true; + for (PuzzleElement actEle : actCase.getModifiedData()) { + LightUpCell actCell = (LightUpCell) actEle; + boolean foundCell = false; + for (PuzzleElement posEle : posCase.getModifiedData()) { + LightUpCell posCell = (LightUpCell) posEle; + if (actCell.getType() == posCell.getType() + && actCell.getLocation().equals(posCell.getLocation())) { + foundCell = true; + break; + } } - if (foundSpot) { - return null; + if (!foundCell) { + foundAllCells = false; + break; } + } + } + if (foundAllCells) { + foundBoard = true; + break; } + } + if (!foundBoard) { + foundSpot = false; + break; + } } - return super.getInvalidUseOfRuleMessage(); + if (foundSpot) { + return null; + } + } } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Gets all cells in the TreeTransition board that are adjacent to all modified cells + * + * @param transition TreeTransition object + * @return list of cells that are adjacent to all modified cells, returns null if the number of + * modified cells is =0 || >4 + */ + private List getPossibleSpots(TreeTransition transition) { + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Set modCells = transition.getBoard().getModifiedData(); + + int size = modCells.size(); + if (size == 0 || size > 4) { + return null; + } else { + Iterator it = modCells.iterator(); + List spots = getAdjacentCells(board, (LightUpCell) it.next()); + + while (it.hasNext()) { + spots.retainAll(getAdjacentCells(board, (LightUpCell) it.next())); + } + return spots; } - - /** - * Gets all cells in the TreeTransition board that are adjacent to all modified cells - * - * @param transition TreeTransition object - * @return list of cells that are adjacent to all modified cells, returns null if the number of - * modified cells is =0 || >4 - */ - private List getPossibleSpots(TreeTransition transition) { - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Set modCells = transition.getBoard().getModifiedData(); - - int size = modCells.size(); - if (size == 0 || size > 4) { - return null; - } else { - Iterator it = modCells.iterator(); - List spots = getAdjacentCells(board, (LightUpCell) it.next()); - - while (it.hasNext()) { - spots.retainAll(getAdjacentCells(board, (LightUpCell) it.next())); - } - return spots; - } + } + + private List getAdjacentCells(LightUpBoard board, LightUpCell cell) { + List cells = new ArrayList<>(); + Point point = cell.getLocation(); + LightUpCell right = board.getCell(point.x + 1, point.y); + if (right != null) { + cells.add(right); } - - private List getAdjacentCells(LightUpBoard board, LightUpCell cell) { - List cells = new ArrayList<>(); - Point point = cell.getLocation(); - LightUpCell right = board.getCell(point.x + 1, point.y); - if (right != null) { - cells.add(right); + LightUpCell down = board.getCell(point.x, point.y + 1); + if (down != null) { + cells.add(down); + } + LightUpCell left = board.getCell(point.x - 1, point.y); + if (left != null) { + cells.add(left); + } + LightUpCell up = board.getCell(point.x, point.y - 1); + if (up != null) { + cells.add(up); + } + return cells; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + LightUpBoard puzzleBoard = (LightUpBoard) board; + LightUpCell point = (LightUpCell) puzzleBoard.getPuzzleElement(puzzleElement); + + List cells = getAdjacentCells(puzzleBoard, point); + + for (LightUpCell cell : cells) { + // add cells that can light adjacents from any direction + Point location = cell.getLocation(); + for (int i = location.x; i < puzzleBoard.getWidth(); i++) { + System.out.println(i); + LightUpCell c = puzzleBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); } - LightUpCell down = board.getCell(point.x, point.y + 1); - if (down != null) { - cells.add(down); + } + for (int i = location.x; i >= 0; i--) { + LightUpCell c = puzzleBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); } - LightUpCell left = board.getCell(point.x - 1, point.y); - if (left != null) { - cells.add(left); + } + for (int i = location.y; i < puzzleBoard.getHeight(); i++) { + LightUpCell c = puzzleBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); } - LightUpCell up = board.getCell(point.x, point.y - 1); - if (up != null) { - cells.add(up); + } + for (int i = location.y; i >= 0; i--) { + LightUpCell c = puzzleBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); } - return cells; + } } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - LightUpBoard puzzleBoard = (LightUpBoard) board; - LightUpCell point = (LightUpCell) puzzleBoard.getPuzzleElement(puzzleElement); - - List cells = getAdjacentCells(puzzleBoard, point); - - for (LightUpCell cell : cells) { - // add cells that can light adjacents from any direction - Point location = cell.getLocation(); - for (int i = location.x; i < puzzleBoard.getWidth(); i++) { - System.out.println(i); - LightUpCell c = puzzleBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); - } - } - for (int i = location.x; i >= 0; i--) { - LightUpCell c = puzzleBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); - } - } - for (int i = location.y; i < puzzleBoard.getHeight(); i++) { - LightUpCell c = puzzleBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); - } - } - for (int i = location.y; i >= 0; i--) { - LightUpCell c = puzzleBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); - } - } - } - - return elements; - } + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java index 8cf68e570..8b00e537e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java @@ -10,37 +10,37 @@ public class TooFewBulbsContradictionRule extends ContradictionRule { - public TooFewBulbsContradictionRule() { - super( - "LTUP-CONT-0003", - "Too Few Bulbs", - "There cannot be less bulbs around a block than its number states.", - "edu/rpi/legup/images/lightup/contradictions/TooFewBulbs.png"); - } + public TooFewBulbsContradictionRule() { + super( + "LTUP-CONT-0003", + "Too Few Bulbs", + "There cannot be less bulbs around a block than its number states.", + "edu/rpi/legup/images/lightup/contradictions/TooFewBulbs.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.NUMBER) { - return super.getNoContradictionMessage(); - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.NUMBER) { + return super.getNoContradictionMessage(); + } - int bulbs = lightUpBoard.getNumAdj(cell, LightUpCellType.BULB); - int placeable = lightUpBoard.getNumPlacble(cell); + int bulbs = lightUpBoard.getNumAdj(cell, LightUpCellType.BULB); + int placeable = lightUpBoard.getNumPlacble(cell); - if (bulbs + placeable < cell.getData()) { - return null; - } - return super.getNoContradictionMessage(); + if (bulbs + placeable < cell.getData()) { + return null; } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java index 64cd4adcb..8d1403663 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java @@ -10,55 +10,55 @@ public class TooManyBulbsContradictionRule extends ContradictionRule { - public TooManyBulbsContradictionRule() { - super( - "LTUP-CONT-0004", - "Too Many Bulbs", - "There cannot be more bulbs around a block than its number states.", - "edu/rpi/legup/images/lightup/contradictions/TooManyBulbs.png"); - } + public TooManyBulbsContradictionRule() { + super( + "LTUP-CONT-0004", + "Too Many Bulbs", + "There cannot be more bulbs around a block than its number states.", + "edu/rpi/legup/images/lightup/contradictions/TooManyBulbs.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.NUMBER) { - return super.getNoContradictionMessage(); - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.NUMBER) { + return super.getNoContradictionMessage(); + } - Point location = cell.getLocation(); + Point location = cell.getLocation(); - int bulbs = 0; + int bulbs = 0; - LightUpCell up = lightUpBoard.getCell(location.x, location.y + 1); - if (up != null && up.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell down = lightUpBoard.getCell(location.x, location.y - 1); - if (down != null && down.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell right = lightUpBoard.getCell(location.x + 1, location.y); - if (right != null && right.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell left = lightUpBoard.getCell(location.x - 1, location.y); - if (left != null && left.getType() == LightUpCellType.BULB) { - bulbs++; - } + LightUpCell up = lightUpBoard.getCell(location.x, location.y + 1); + if (up != null && up.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell down = lightUpBoard.getCell(location.x, location.y - 1); + if (down != null && down.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell right = lightUpBoard.getCell(location.x + 1, location.y); + if (right != null && right.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell left = lightUpBoard.getCell(location.x - 1, location.y); + if (left != null && left.getType() == LightUpCellType.BULB) { + bulbs++; + } - if (bulbs > cell.getData()) { - return null; - } - return super.getNoContradictionMessage(); + if (bulbs > cell.getData()) { + return null; } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java b/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java index 9986a1eda..98e22173e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java @@ -17,157 +17,154 @@ import java.awt.event.MouseEvent; public class EditLineCommand extends PuzzleCommand { - private TreeTransition transition; - private PuzzleElement oldData; - private PuzzleElement newData; - - private ElementView elementView; - private TreeElementView selectedView; - private TreeElementView newSelectedView; - private MouseEvent event; - - private TreeTransitionView transitionView; - - public EditLineCommand( - ElementView elementView, - TreeElementView selectedView, - MouseEvent event, - MasyuLine line) { - this.elementView = elementView; - this.selectedView = selectedView; - this.event = event; - this.newData = line; - this.oldData = newData.copy(); - this.transition = null; + private TreeTransition transition; + private PuzzleElement oldData; + private PuzzleElement newData; + + private ElementView elementView; + private TreeElementView selectedView; + private TreeElementView newSelectedView; + private MouseEvent event; + + private TreeTransitionView transitionView; + + public EditLineCommand( + ElementView elementView, TreeElementView selectedView, MouseEvent event, MasyuLine line) { + this.elementView = elementView; + this.selectedView = selectedView; + this.event = event; + this.newData = line; + this.oldData = newData.copy(); + this.transition = null; + } + + /** Executes a command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + Puzzle puzzle = getInstance().getPuzzleModule(); + + MasyuBoard board = (MasyuBoard) selectedView.getTreeElement().getBoard(); + int index = elementView.getIndex(); + + if (selectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); + + if (transition == null) { + transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + } + + treeNode.getChildren().add(transition); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeElementAdded(transition)); + transitionView = (TreeTransitionView) treeView.getElementView(transition); + + selection.newSelection(transitionView); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeSelectionChanged(selection)); + + getInstance().getLegupUI().repaintTree(); + board = (MasyuBoard) transition.getBoard(); + getInstance().getPuzzleModule().setCurrentBoard(board); + oldData = newData.copy(); + } else { + transitionView = (TreeTransitionView) selectedView; + transition = transitionView.getTreeElement(); } - - /** Executes a command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - Puzzle puzzle = getInstance().getPuzzleModule(); - - MasyuBoard board = (MasyuBoard) selectedView.getTreeElement().getBoard(); - int index = elementView.getIndex(); - - if (selectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); - - if (transition == null) { - transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - } - - treeNode.getChildren().add(transition); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeElementAdded(transition)); - transitionView = (TreeTransitionView) treeView.getElementView(transition); - - selection.newSelection(transitionView); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeSelectionChanged(selection)); - - getInstance().getLegupUI().repaintTree(); - board = (MasyuBoard) transition.getBoard(); - getInstance().getPuzzleModule().setCurrentBoard(board); - oldData = newData.copy(); - } else { - transitionView = (TreeTransitionView) selectedView; - transition = transitionView.getTreeElement(); - } - newSelectedView = transitionView; - PuzzleElement dup_line = null; - boolean mod_contains = false; - boolean contains = false; - final MasyuBoard editBoard = board; - System.out.println("Size: " + board.getModifiedData().size()); - for (PuzzleElement puzzleElement : board.getModifiedData()) { - if (puzzleElement instanceof MasyuLine) { - if (((MasyuLine) newData).compare((MasyuLine) puzzleElement)) { - System.out.println("contains"); - dup_line = puzzleElement; - mod_contains = true; - } - } - } - for (int i = 0; i < board.getLines().size(); i++) { - if (board.getLines().get(i).compare((MasyuLine) newData)) { - contains = true; - } + newSelectedView = transitionView; + PuzzleElement dup_line = null; + boolean mod_contains = false; + boolean contains = false; + final MasyuBoard editBoard = board; + System.out.println("Size: " + board.getModifiedData().size()); + for (PuzzleElement puzzleElement : board.getModifiedData()) { + if (puzzleElement instanceof MasyuLine) { + if (((MasyuLine) newData).compare((MasyuLine) puzzleElement)) { + System.out.println("contains"); + dup_line = puzzleElement; + mod_contains = true; } - if (contains || mod_contains) { - System.out.println("delete"); - board.getModifiedData().remove(dup_line); - board.getLines().remove(dup_line); - // puzzle.notifyBoardListeners((IBoardListener listener) -> - // listener.onTreeElementChanged(editBoard)); - } else { - System.out.println("adding"); - board.getModifiedData().add(newData); - board.getLines().add((MasyuLine) newData); - // puzzle.notifyBoardListeners((IBoardListener listener) -> - // listener.onTreeElementChanged(editBoard)); - } - - transition.propagateChange(newData); + } + } + for (int i = 0; i < board.getLines().size(); i++) { + if (board.getLines().get(i).compare((MasyuLine) newData)) { + contains = true; + } + } + if (contains || mod_contains) { + System.out.println("delete"); + board.getModifiedData().remove(dup_line); + board.getLines().remove(dup_line); + // puzzle.notifyBoardListeners((IBoardListener listener) -> + // listener.onTreeElementChanged(editBoard)); + } else { + System.out.println("adding"); + board.getModifiedData().add(newData); + board.getLines().add((MasyuLine) newData); + // puzzle.notifyBoardListeners((IBoardListener listener) -> + // listener.onTreeElementChanged(editBoard)); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - Board board = selectedView.getTreeElement().getBoard(); - if (!board.isModifiable()) { - return "Board is not modifiable"; - } else { - if (!board.getPuzzleElement(elementView.getPuzzleElement()).isModifiable()) { - return "Data is not modifiable"; - } - } - return null; + transition.propagateChange(newData); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + Board board = selectedView.getTreeElement().getBoard(); + if (!board.isModifiable()) { + return "Board is not modifiable"; + } else { + if (!board.getPuzzleElement(elementView.getPuzzleElement()).isModifiable()) { + return "Data is not modifiable"; + } } + return null; + } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); - Board board = transition.getBoard(); + Board board = transition.getBoard(); - if (selectedView.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); + if (selectedView.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); - tree.removeTreeElement(transition); - treeView.removeTreeElement(newSelectedView); + tree.removeTreeElement(transition); + treeView.removeTreeElement(newSelectedView); - selection.newSelection(selectedView); + selection.newSelection(selectedView); - getInstance().getLegupUI().repaintTree(); - getInstance().getPuzzleModule().setCurrentBoard(treeNode.getBoard()); - } + getInstance().getLegupUI().repaintTree(); + getInstance().getPuzzleModule().setCurrentBoard(treeNode.getBoard()); + } - Board prevBoard = null; // transition.getParentNode().getBoard(); + Board prevBoard = null; // transition.getParentNode().getBoard(); - newData.setData(oldData.getData()); - board.notifyChange(newData); + newData.setData(oldData.getData()); + board.notifyChange(newData); - // System.err.println(newData.getData() + " : " + oldData.getData()); + // System.err.println(newData.getData() + " : " + oldData.getData()); - if (prevBoard.getPuzzleElement(elementView.getPuzzleElement()).equalsData(newData)) { - board.removeModifiedData(newData); - } else { - board.addModifiedData(newData); - } - transition.propagateChange(newData); + if (prevBoard.getPuzzleElement(elementView.getPuzzleElement()).equalsData(newData)) { + board.removeModifiedData(newData); + } else { + board.addModifiedData(newData); } + transition.propagateChange(newData); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java b/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java index 1ab74d56b..1c5d19e08 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java @@ -5,63 +5,63 @@ public class Masyu extends Puzzle { - public Masyu() { - super(); + public Masyu() { + super(); - this.name = "Masyu"; + this.name = "Masyu"; - this.importer = new MasyuImporter(this); - this.exporter = new MasyuExporter(this); + this.importer = new MasyuImporter(this); + this.exporter = new MasyuExporter(this); - this.factory = new MasyuCellFactory(); - } + this.factory = new MasyuCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new MasyuView((MasyuBoard) currentBoard); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new MasyuView((MasyuBoard) currentBoard); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Masyu - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Masyu, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for Masyu + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Masyu, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java index f347ff4c4..554408dd3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java @@ -7,53 +7,53 @@ public class MasyuBoard extends GridBoard { - private List lines; - - public MasyuBoard(int width, int height) { - super(width, height); - this.lines = new ArrayList<>(); - } - - public MasyuBoard(int size) { - this(size, size); - } - - @Override - public MasyuCell getCell(int x, int y) { - return (MasyuCell) super.getCell(x, y); + private List lines; + + public MasyuBoard(int width, int height) { + super(width, height); + this.lines = new ArrayList<>(); + } + + public MasyuBoard(int size) { + this(size, size); + } + + @Override + public MasyuCell getCell(int x, int y) { + return (MasyuCell) super.getCell(x, y); + } + + public List getLines() { + return lines; + } + + public void setLines(List lines) { + this.lines = lines; + } + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + if (puzzleElement instanceof MasyuLine) { + lines.add((MasyuLine) puzzleElement); + } else { + super.notifyChange(puzzleElement); } - - public List getLines() { - return lines; + } + + @Override + public MasyuBoard copy() { + MasyuBoard copy = new MasyuBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } - - public void setLines(List lines) { - this.lines = lines; + for (MasyuLine line : lines) { + copy.lines.add(line.copy()); } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - if (puzzleElement instanceof MasyuLine) { - lines.add((MasyuLine) puzzleElement); - } else { - super.notifyChange(puzzleElement); - } - } - - @Override - public MasyuBoard copy() { - MasyuBoard copy = new MasyuBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (MasyuLine line : lines) { - copy.lines.add(line.copy()); - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java index af0811c55..7d23cdf37 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java @@ -5,20 +5,20 @@ public class MasyuCell extends GridCell { - public MasyuCell(MasyuType value, Point location) { - super(value, location); - } + public MasyuCell(MasyuType value, Point location) { + super(value, location); + } - public MasyuType getType() { - return data; - } + public MasyuType getType() { + return data; + } - @Override - public MasyuCell copy() { - MasyuCell copy = new MasyuCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public MasyuCell copy() { + MasyuCell copy = new MasyuCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java index 50e3c4cc0..803edfbea 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java @@ -10,65 +10,63 @@ import org.w3c.dom.Node; public class MasyuCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public MasyuCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Masyu Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public MasyuCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException("Masyu Factory: unknown puzzleElement puzzleElement"); + } - MasyuBoard masyuBoard = (MasyuBoard) board; - int width = masyuBoard.getWidth(); - int height = masyuBoard.getHeight(); + MasyuBoard masyuBoard = (MasyuBoard) board; + int width = masyuBoard.getWidth(); + int height = masyuBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Masyu Factory: cell location out of bounds"); - } - if (value < 0 || value > 2) { - throw new InvalidFileFormatException("Masyu Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("Masyu Factory: cell location out of bounds"); + } + if (value < 0 || value > 2) { + throw new InvalidFileFormatException("Masyu Factory: cell unknown value"); + } - MasyuCell cell = new MasyuCell(MasyuType.convertToMasyuType(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Masyu Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Masyu Factory: could not find attribute(s)"); - } + MasyuCell cell = new MasyuCell(MasyuType.convertToMasyuType(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("Masyu Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Masyu Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - MasyuCell cell = (MasyuCell) puzzleElement; - Point loc = cell.getLocation(); + MasyuCell cell = (MasyuCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java index 202c43a1e..1644e4d11 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java @@ -14,93 +14,89 @@ public class MasyuController extends ElementController { - private MasyuElementView mousePressedCell; - private MasyuElementView mouseDraggedCell; - private List masyuLine; + private MasyuElementView mousePressedCell; + private MasyuElementView mouseDraggedCell; + private List masyuLine; - public MasyuController() { - super(); - this.mousePressedCell = null; - this.mouseDraggedCell = null; - this.masyuLine = new ArrayList<>(); - } + public MasyuController() { + super(); + this.mousePressedCell = null; + this.mouseDraggedCell = null; + this.masyuLine = new ArrayList<>(); + } - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e the event to be processed - */ - @Override - public void mousePressed(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - this.masyuLine.clear(); - mousePressedCell = (MasyuElementView) boardView.getElement(e.getPoint()); - masyuLine.add(mousePressedCell); - } + /** + * Invoked when a mouse button has been pressed on a component. + * + * @param e the event to be processed + */ + @Override + public void mousePressed(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + this.masyuLine.clear(); + mousePressedCell = (MasyuElementView) boardView.getElement(e.getPoint()); + masyuLine.add(mousePressedCell); + } - @Override - public void mouseDragged(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - MasyuElementView elementView = (MasyuElementView) boardView.getElement(e.getPoint()); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (mousePressedCell != null && elementView != null) { - if (mouseDraggedCell == null) { - mouseDraggedCell = elementView; - Point p1 = mousePressedCell.getPuzzleElement().getLocation(); - Point p2 = mouseDraggedCell.getPuzzleElement().getLocation(); + @Override + public void mouseDragged(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + MasyuElementView elementView = (MasyuElementView) boardView.getElement(e.getPoint()); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (mousePressedCell != null && elementView != null) { + if (mouseDraggedCell == null) { + mouseDraggedCell = elementView; + Point p1 = mousePressedCell.getPuzzleElement().getLocation(); + Point p2 = mouseDraggedCell.getPuzzleElement().getLocation(); - if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { - masyuLine.add(elementView); - MasyuLine newLine = - new MasyuLine( - mousePressedCell.getPuzzleElement(), - mouseDraggedCell.getPuzzleElement()); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); - } - } else { - if (mouseDraggedCell != elementView) { - Point p1 = mouseDraggedCell.getPuzzleElement().getLocation(); - Point p2 = elementView.getPuzzleElement().getLocation(); + if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { + masyuLine.add(elementView); + MasyuLine newLine = + new MasyuLine( + mousePressedCell.getPuzzleElement(), mouseDraggedCell.getPuzzleElement()); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); + } + } else { + if (mouseDraggedCell != elementView) { + Point p1 = mouseDraggedCell.getPuzzleElement().getLocation(); + Point p2 = elementView.getPuzzleElement().getLocation(); - if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { - masyuLine.add(elementView); - MasyuLine newLine = - new MasyuLine( - mouseDraggedCell.getPuzzleElement(), - elementView.getPuzzleElement()); - puzzle.notifyBoardListeners( - listener -> listener.onBoardDataChanged(newLine)); - } - mouseDraggedCell = elementView; - } - } + if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { + masyuLine.add(elementView); + MasyuLine newLine = + new MasyuLine(mouseDraggedCell.getPuzzleElement(), elementView.getPuzzleElement()); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); + } + mouseDraggedCell = elementView; } + } } + } - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - mousePressedCell = null; - mouseDraggedCell = null; - masyuLine.clear(); - } + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + mousePressedCell = null; + mouseDraggedCell = null; + masyuLine.clear(); + } - /** - * Alters the cells as they are being dragged over or clicked - * - * @param e Mouse event being used - * @param data Data of selected cell - */ - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - MasyuCell cell = (MasyuCell) data; - if (cell.getData() == MasyuType.BLACK || cell.getData() == MasyuType.WHITE) { - return; - } - if (cell.getData() == MasyuType.UNKNOWN) { - data.setData(3); - } else { - data.setData(0); - } + /** + * Alters the cells as they are being dragged over or clicked + * + * @param e Mouse event being used + * @param data Data of selected cell + */ + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + MasyuCell cell = (MasyuCell) data; + if (cell.getData() == MasyuType.BLACK || cell.getData() == MasyuType.WHITE) { + return; + } + if (cell.getData() == MasyuType.UNKNOWN) { + data.setData(3); + } else { + data.setData(0); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java index 942e1ffd2..d01e74033 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java @@ -4,48 +4,48 @@ import java.awt.*; public class MasyuElementView extends GridElementView { - public MasyuElementView(MasyuCell masyuCell) { - super(masyuCell); - } + public MasyuElementView(MasyuCell masyuCell) { + super(masyuCell); + } - @Override - public MasyuCell getPuzzleElement() { - return (MasyuCell) super.getPuzzleElement(); - } + @Override + public MasyuCell getPuzzleElement() { + return (MasyuCell) super.getPuzzleElement(); + } - @Override - public void drawElement(Graphics2D graphics2D) { - MasyuCell cell = (MasyuCell) puzzleElement; - MasyuType type = cell.getType(); - if (type == MasyuType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == MasyuType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == MasyuType.WHITE) { - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.WHITE); - graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); - graphics2D.setColor(Color.BLACK); - graphics2D.drawOval(location.x + 6, location.y + 6, 18, 18); - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - } + @Override + public void drawElement(Graphics2D graphics2D) { + MasyuCell cell = (MasyuCell) puzzleElement; + MasyuType type = cell.getType(); + if (type == MasyuType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == MasyuType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == MasyuType.WHITE) { + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.WHITE); + graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); + graphics2D.setColor(Color.BLACK); + graphics2D.drawOval(location.x + 6, location.y + 6, 18, 18); + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java index 0c692193a..0f8555ce0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java @@ -6,32 +6,31 @@ public class MasyuExporter extends PuzzleExporter { - public MasyuExporter(Masyu masyu) { - super(masyu); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - MasyuBoard board; - if (puzzle.getTree() != null) { - board = (MasyuBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (MasyuBoard) puzzle.getBoardView().getBoard(); - } + public MasyuExporter(Masyu masyu) { + super(masyu); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + MasyuBoard board; + if (puzzle.getTree() != null) { + board = (MasyuBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (MasyuBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - MasyuCell cell = (MasyuCell) puzzleElement; - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + MasyuCell cell = (MasyuCell) puzzleElement; + org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java index 2170da3ee..b5db71234 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java @@ -8,102 +8,98 @@ import org.w3c.dom.NodeList; public class MasyuImporter extends PuzzleImporter { - public MasyuImporter(Masyu masyu) { - super(masyu); - } + public MasyuImporter(Masyu masyu) { + super(masyu); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "Masyu Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "Masyu Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("Masyu Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("Masyu Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - MasyuBoard masyuBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - masyuBoard = new MasyuBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - masyuBoard = new MasyuBoard(width, height); - } - } + MasyuBoard masyuBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + masyuBoard = new MasyuBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + masyuBoard = new MasyuBoard(width, height); + } + } - if (masyuBoard == null) { - throw new InvalidFileFormatException("Masyu Importer: invalid board dimensions"); - } + if (masyuBoard == null) { + throw new InvalidFileFormatException("Masyu Importer: invalid board dimensions"); + } - int width = masyuBoard.getWidth(); - int height = masyuBoard.getHeight(); + int width = masyuBoard.getWidth(); + int height = masyuBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - MasyuCell cell = - (MasyuCell) - puzzle.getFactory().importCell(elementDataList.item(i), masyuBoard); - Point loc = cell.getLocation(); - if (cell.getData() != MasyuType.UNKNOWN) { - cell.setModifiable(false); - cell.setGiven(true); - } - masyuBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + MasyuCell cell = + (MasyuCell) puzzle.getFactory().importCell(elementDataList.item(i), masyuBoard); + Point loc = cell.getLocation(); + if (cell.getData() != MasyuType.UNKNOWN) { + cell.setModifiable(false); + cell.setGiven(true); + } + masyuBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (masyuBoard.getCell(x, y) == null) { - MasyuCell cell = new MasyuCell(MasyuType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - masyuBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(masyuBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Masyu Importer: unknown value where integer expected"); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (masyuBoard.getCell(x, y) == null) { + MasyuCell cell = new MasyuCell(MasyuType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + masyuBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(masyuBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("Masyu Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Masyu cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Masyu cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java index eda51c839..30924ea57 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java @@ -4,40 +4,40 @@ import edu.rpi.legup.utility.Entry; public class MasyuLine extends PuzzleElement> { - public MasyuLine(MasyuCell c1, MasyuCell c2) { - this.data = new Entry<>(c1, c2); - } - - public MasyuCell getC1() { - return data.getKey(); - } - - public void setC1(MasyuCell c1) { - this.data.setKey(c1); - } - - public MasyuCell getC2() { - return data.getValue(); - } - - public void setC2(MasyuCell c2) { - this.data.setValue(c2); - } - - public boolean compare(MasyuLine line) { - return ((line.getC1().getLocation().equals(data.getKey().getLocation()) - && line.getC2().getLocation().equals(data.getValue().getLocation())) - || (line.getC1().getLocation().equals(data.getValue().getLocation()) - && line.getC2().getLocation().equals(data.getKey().getLocation()))); - } - - /** - * Copies this elements puzzleElement to a new PuzzleElement object - * - * @return copied PuzzleElement object - */ - @Override - public MasyuLine copy() { - return new MasyuLine(data.getKey().copy(), data.getValue().copy()); - } + public MasyuLine(MasyuCell c1, MasyuCell c2) { + this.data = new Entry<>(c1, c2); + } + + public MasyuCell getC1() { + return data.getKey(); + } + + public void setC1(MasyuCell c1) { + this.data.setKey(c1); + } + + public MasyuCell getC2() { + return data.getValue(); + } + + public void setC2(MasyuCell c2) { + this.data.setValue(c2); + } + + public boolean compare(MasyuLine line) { + return ((line.getC1().getLocation().equals(data.getKey().getLocation()) + && line.getC2().getLocation().equals(data.getValue().getLocation())) + || (line.getC1().getLocation().equals(data.getValue().getLocation()) + && line.getC2().getLocation().equals(data.getKey().getLocation()))); + } + + /** + * Copies this elements puzzleElement to a new PuzzleElement object + * + * @return copied PuzzleElement object + */ + @Override + public MasyuLine copy() { + return new MasyuLine(data.getKey().copy(), data.getValue().copy()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java index c967f4865..54efc335f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java @@ -4,27 +4,27 @@ import java.awt.*; public class MasyuLineView extends ElementView { - private final Color LINE_COLOR = Color.GREEN; + private final Color LINE_COLOR = Color.GREEN; - private final Stroke LINE_STROKE = new BasicStroke(3); + private final Stroke LINE_STROKE = new BasicStroke(3); - public MasyuLineView(MasyuLine line) { - super(line); - } + public MasyuLineView(MasyuLine line) { + super(line); + } - @Override - public void draw(Graphics2D graphics2D) { - MasyuLine line = (MasyuLine) puzzleElement; - Point p1 = line.getC1().getLocation(); - Point p2 = line.getC2().getLocation(); - int x1 = p1.x * size.width + size.width / 2; - int y1 = p1.y * size.height + size.height / 2; + @Override + public void draw(Graphics2D graphics2D) { + MasyuLine line = (MasyuLine) puzzleElement; + Point p1 = line.getC1().getLocation(); + Point p2 = line.getC2().getLocation(); + int x1 = p1.x * size.width + size.width / 2; + int y1 = p1.y * size.height + size.height / 2; - int x2 = p2.x * size.width + size.width / 2; - int y2 = p2.y * size.height + size.height / 2; + int x2 = p2.x * size.width + size.width / 2; + int y2 = p2.y * size.height + size.height / 2; - graphics2D.setColor(line.isModified() ? Color.GREEN : Color.BLACK); - graphics2D.setStroke(LINE_STROKE); - graphics2D.drawLine(x1, y1, x2, y2); - } + graphics2D.setColor(line.isModified() ? Color.GREEN : Color.BLACK); + graphics2D.setStroke(LINE_STROKE); + graphics2D.drawLine(x1, y1, x2, y2); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java index 4029d259d..114e4bf71 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java @@ -1,21 +1,21 @@ package edu.rpi.legup.puzzle.masyu; public enum MasyuType { - UNKNOWN, - BLACK, - WHITE, - LINE; + UNKNOWN, + BLACK, + WHITE, + LINE; - public static MasyuType convertToMasyuType(int num) { - switch (num) { - case 1: - return BLACK; - case 2: - return WHITE; - case 3: - return LINE; - default: - return UNKNOWN; - } + public static MasyuType convertToMasyuType(int num) { + switch (num) { + case 1: + return BLACK; + case 2: + return WHITE; + case 3: + return LINE; + default: + return UNKNOWN; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java index e962a6ebf..dc81b24cd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java @@ -8,49 +8,47 @@ import java.util.List; public class MasyuView extends GridBoardView { - private List lineViews; + private List lineViews; - public MasyuView(MasyuBoard board) { - super(new BoardController(), new MasyuController(), board.getDimension()); + public MasyuView(MasyuBoard board) { + super(new BoardController(), new MasyuController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - MasyuCell cell = (MasyuCell) puzzleElement; - Point loc = cell.getLocation(); - MasyuElementView elementView = new MasyuElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } - lineViews = new ArrayList<>(); - for (MasyuLine line : board.getLines()) { - MasyuLineView lineView = new MasyuLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + MasyuCell cell = (MasyuCell) puzzleElement; + Point loc = cell.getLocation(); + MasyuElementView elementView = new MasyuElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } - - @Override - public void drawBoard(Graphics2D graphics2D) { - graphics2D.setRenderingHint( - RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - super.drawBoard(graphics2D); - lineViews.forEach(masyuLineView -> masyuLineView.draw(graphics2D)); + lineViews = new ArrayList<>(); + for (MasyuLine line : board.getLines()) { + MasyuLineView lineView = new MasyuLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); } + } + + @Override + public void drawBoard(Graphics2D graphics2D) { + graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + super.drawBoard(graphics2D); + lineViews.forEach(masyuLineView -> masyuLineView.draw(graphics2D)); + } - /** - * Called when the board puzzleElement changed - * - * @param puzzleElement puzzleElement of the puzzleElement that changed - */ - @Override - public void onBoardDataChanged(PuzzleElement puzzleElement) { - if (puzzleElement instanceof MasyuLine) { - MasyuLineView lineView = new MasyuLineView((MasyuLine) puzzleElement); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - repaint(); + /** + * Called when the board puzzleElement changed + * + * @param puzzleElement puzzleElement of the puzzleElement that changed + */ + @Override + public void onBoardDataChanged(PuzzleElement puzzleElement) { + if (puzzleElement instanceof MasyuLine) { + MasyuLineView lineView = new MasyuLineView((MasyuLine) puzzleElement); + lineView.setSize(elementSize); + lineViews.add(lineView); } + repaint(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java index 1681446cd..f4dd95268 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java @@ -6,25 +6,25 @@ public class BadLoopingContradictionRule extends ContradictionRule { - public BadLoopingContradictionRule() { - super( - "MASY-CONT-0001", - "Bad Looping", - "", - "edu/rpi/legup/images/masyu/ContradictionBadLooping.png"); - } + public BadLoopingContradictionRule() { + super( + "MASY-CONT-0001", + "Bad Looping", + "", + "edu/rpi/legup/images/masyu/ContradictionBadLooping.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java index c219eeaa3..f4e95eb14 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java @@ -6,21 +6,21 @@ public class BlackContradictionRule extends ContradictionRule { - public BlackContradictionRule() { - super("MASY-CONT-0002", "Black", "", "edu/rpi/legup/images/masyu/ContradictionBlack.png"); - } + public BlackContradictionRule() { + super("MASY-CONT-0002", "Black", "", "edu/rpi/legup/images/masyu/ContradictionBlack.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java index 665a74204..63b40d7f3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java @@ -8,34 +8,33 @@ public class BlackEdgeDirectRule extends DirectRule { - public BlackEdgeDirectRule() { - super("MASY-BASC-0001", "Black Edge", "", "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); - } + public BlackEdgeDirectRule() { + super("MASY-BASC-0001", "Black Edge", "", "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java index c7e3ff500..2b598321c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java @@ -9,59 +9,59 @@ public class BlackSplitCaseRule extends CaseRule { - public BlackSplitCaseRule() { - super("MASY-CASE-0001", "Black Split", "", "edu/rpi/legup/images/masyu/CaseBlackSplit.png"); - } + public BlackSplitCaseRule() { + super("MASY-CASE-0001", "Black Split", "", "edu/rpi/legup/images/masyu/CaseBlackSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java index 5c284eb45..faa311450 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java @@ -8,38 +8,33 @@ public class BlockedBlackDirectRule extends DirectRule { - public BlockedBlackDirectRule() { - super( - "MASY-BASC-0002", - "Blocked Black", - "", - "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); - } + public BlockedBlackDirectRule() { + super("MASY-BASC-0002", "Blocked Black", "", "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java index 6aee8ba5f..1a49b83a1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java @@ -8,38 +8,37 @@ public class ConnectedCellsDirectRule extends DirectRule { - public ConnectedCellsDirectRule() { - super( - "MASY-BASC-0003", - "Connected Cells", - "", - "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); - } + public ConnectedCellsDirectRule() { + super( + "MASY-BASC-0003", + "Connected Cells", + "", + "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java index 27b39bc04..f6c95050b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java @@ -8,38 +8,33 @@ public class FinishPathDirectRule extends DirectRule { - public FinishPathDirectRule() { - super( - "MASY-BASC-0004", - "Finished Path", - "", - "edu/rpi/legup/images/masyu/RuleFinishPath.png"); - } + public FinishPathDirectRule() { + super("MASY-BASC-0004", "Finished Path", "", "edu/rpi/legup/images/masyu/RuleFinishPath.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java index 6a565bc82..67ed25d64 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java @@ -8,34 +8,33 @@ public class NearWhiteDirectRule extends DirectRule { - public NearWhiteDirectRule() { - super("MASY-BASC-0005", "Near White", "", "edu/rpi/legup/images/masyu/RuleNearWhite.png"); - } + public NearWhiteDirectRule() { + super("MASY-BASC-0005", "Near White", "", "edu/rpi/legup/images/masyu/RuleNearWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java index c41999b9c..f068c6503 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java @@ -6,25 +6,25 @@ public class NoOptionsContradictionRule extends ContradictionRule { - public NoOptionsContradictionRule() { - super( - "MASY-CONT-0003", - "No Options", - "", - "edu/rpi/legup/images/masyu/ContradictionNoOptions.png"); - } + public NoOptionsContradictionRule() { + super( + "MASY-CONT-0003", + "No Options", + "", + "edu/rpi/legup/images/masyu/ContradictionNoOptions.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java index 382ac6466..015a7dcf9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java @@ -9,63 +9,59 @@ public class NormalSplitCaseRule extends CaseRule { - public NormalSplitCaseRule() { - super( - "MASY-CASE-0002", - "Normal Split", - "", - "edu/rpi/legup/images/masyu/CaseNormalSplit.png"); - } + public NormalSplitCaseRule() { + super("MASY-CASE-0002", "Normal Split", "", "edu/rpi/legup/images/masyu/CaseNormalSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java index bc7353e5d..b25ac8c09 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java @@ -8,38 +8,37 @@ public class OnlyOneChoiceDirectRule extends DirectRule { - public OnlyOneChoiceDirectRule() { - super( - "MASY-BASC-0006", - "Only One Choice", - "", - "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); - } + public OnlyOneChoiceDirectRule() { + super( + "MASY-BASC-0006", + "Only One Choice", + "", + "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java index ee71ee2bc..bda563b2e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java @@ -6,25 +6,21 @@ public class OnlyTwoContradictionRule extends ContradictionRule { - public OnlyTwoContradictionRule() { - super( - "MASY-CONT-0004", - "Only Two", - "", - "edu/rpi/legup/images/masyu/ContradictionOnly2.png"); - } + public OnlyTwoContradictionRule() { + super("MASY-CONT-0004", "Only Two", "", "edu/rpi/legup/images/masyu/ContradictionOnly2.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java index efc523b8d..4ae418c36 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java @@ -6,21 +6,21 @@ public class WhiteContradictionRule extends ContradictionRule { - public WhiteContradictionRule() { - super("MASY-CONT-0005", "White", "", "edu/rpi/legup/images/masyu/ContradictionWhite.png"); - } + public WhiteContradictionRule() { + super("MASY-CONT-0005", "White", "", "edu/rpi/legup/images/masyu/ContradictionWhite.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java index 4d2982d00..e653c96b0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java @@ -7,34 +7,33 @@ import edu.rpi.legup.model.tree.TreeTransition; public class WhiteEdgeDirectRule extends DirectRule { - public WhiteEdgeDirectRule() { - super("MASY-BASC-0007", "White Edge", "", "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); - } + public WhiteEdgeDirectRule() { + super("MASY-BASC-0007", "White Edge", "", "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java index d50ddacfa..e8eb97cd8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java @@ -9,59 +9,59 @@ public class WhiteSplitCaseRule extends CaseRule { - public WhiteSplitCaseRule() { - super("MASY-CASE-0003", "White Split", "", "edu/rpi/legup/images/masyu/CaseWhiteSplit.png"); - } + public WhiteSplitCaseRule() { + super("MASY-CASE-0003", "White Split", "", "edu/rpi/legup/images/masyu/CaseWhiteSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java index 8366d905f..c8aa80012 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java @@ -6,77 +6,77 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Nurikabe extends Puzzle { - public Nurikabe() { - super(); + public Nurikabe() { + super(); - this.name = "Nurikabe"; + this.name = "Nurikabe"; - this.importer = new NurikabeImporter(this); - this.exporter = new NurikabeExporter(this); + this.importer = new NurikabeImporter(this); + this.exporter = new NurikabeExporter(this); - this.factory = new NurikabeCellFactory(); - } + this.factory = new NurikabeCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new NurikabeView((NurikabeBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new NurikabeView((NurikabeBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Nurikabe - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Nurikabe, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows >= 2 && columns >= 2; - } + @Override + /** + * Determines if the given dimensions are valid for Nurikabe + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Nurikabe, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows >= 2 && columns >= 2; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(nurikabeBoard) == null) { - return false; - } - } - for (PuzzleElement data : nurikabeBoard.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.UNKNOWN) { - return false; - } - } - return true; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(nurikabeBoard) == null) { + return false; + } + } + for (PuzzleElement data : nurikabeBoard.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.UNKNOWN) { + return false; + } } + return true; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java index 1f80611e8..7be7813ac 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java @@ -4,53 +4,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class NurikabeBoard extends GridBoard { - public NurikabeBoard(int width, int height) { - super(width, height); - } + public NurikabeBoard(int width, int height) { + super(width, height); + } - public NurikabeBoard(int size) { - super(size, size); - } + public NurikabeBoard(int size) { + super(size, size); + } - @Override - public NurikabeCell getCell(int x, int y) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return null; - } - return (NurikabeCell) super.getCell(x, y); + @Override + public NurikabeCell getCell(int x, int y) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return null; } + return (NurikabeCell) super.getCell(x, y); + } - /** - * Gets the cells as an int array - * - * @return int array of values - */ - public int[][] getIntArray() { - int[][] arr = new int[dimension.height][dimension.width]; - for (int i = 0; i < dimension.height; i++) { - for (int k = 0; k < dimension.width; k++) { - arr[i][k] = getCell(k, i).getData(); - } - } - return arr; + /** + * Gets the cells as an int array + * + * @return int array of values + */ + public int[][] getIntArray() { + int[][] arr = new int[dimension.height][dimension.width]; + for (int i = 0; i < dimension.height; i++) { + for (int k = 0; k < dimension.width; k++) { + arr[i][k] = getCell(k, i).getData(); + } } + return arr; + } - @Override - public NurikabeBoard copy() { - // System.out.println("NurikabeBoard copy()"); - NurikabeBoard copy = new NurikabeBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + @Override + public NurikabeBoard copy() { + // System.out.println("NurikabeBoard copy()"); + NurikabeBoard copy = new NurikabeBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java index c6cd2c64e..4f92c6227 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java @@ -7,86 +7,86 @@ public class NurikabeCell extends GridCell { - /** - * NurikabeCell Constructor - creates a NurikabeCell from the specified value and location - * - * @param value value of the NurikabeCell - * @param location position of the NurikabeCell - */ - public NurikabeCell(int value, Point location) { - super(value, location); - } + /** + * NurikabeCell Constructor - creates a NurikabeCell from the specified value and location + * + * @param value value of the NurikabeCell + * @param location position of the NurikabeCell + */ + public NurikabeCell(int value, Point location) { + super(value, location); + } - /** - * Gets the type of this NurikabeCell - * - * @return type of NurikabeCell - */ - public NurikabeType getType() { - switch (data) { - case -2: - return NurikabeType.UNKNOWN; - case -1: - return NurikabeType.BLACK; - case 0: - return NurikabeType.WHITE; - default: - if (data > 0) { - return NurikabeType.NUMBER; - } + /** + * Gets the type of this NurikabeCell + * + * @return type of NurikabeCell + */ + public NurikabeType getType() { + switch (data) { + case -2: + return NurikabeType.UNKNOWN; + case -1: + return NurikabeType.BLACK; + case 0: + return NurikabeType.WHITE; + default: + if (data > 0) { + return NurikabeType.NUMBER; } - return null; } + return null; + } - /** - * Sets the type of this NurikabeCell - * - * @param e element to set the type of this nurikabe cell to - */ - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "NURI-PLAC-0001": - this.data = -1; - break; - case "NURI-PLAC-0002": - this.data = 0; - break; - case "NURI-UNPL-0001": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data <= 0 || this.data > 8) { - this.data = 1; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 1) { - this.data = this.data - 1; - } else { - this.data = 9; - } - break; - } - break; - default: - this.data = -2; - break; + /** + * Sets the type of this NurikabeCell + * + * @param e element to set the type of this nurikabe cell to + */ + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "NURI-PLAC-0001": + this.data = -1; + break; + case "NURI-PLAC-0002": + this.data = 0; + break; + case "NURI-UNPL-0001": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data <= 0 || this.data > 8) { + this.data = 1; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 1) { + this.data = this.data - 1; + } else { + this.data = 9; + } + break; } + break; + default: + this.data = -2; + break; } + } - /** - * Performs a deep copy on the NurikabeCell - * - * @return a new copy of the NurikabeCell that is independent of this one - */ - @Override - public NurikabeCell copy() { - NurikabeCell copy = new NurikabeCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the NurikabeCell + * + * @return a new copy of the NurikabeCell that is independent of this one + */ + @Override + public NurikabeCell copy() { + NurikabeCell copy = new NurikabeCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java index 7241608ac..298acfb7b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java @@ -10,66 +10,65 @@ import org.w3c.dom.Node; public class NurikabeCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public NurikabeCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public NurikabeCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown puzzleElement puzzleElement"); + } - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int width = nurikabeBoard.getWidth(); - int height = nurikabeBoard.getHeight(); + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException( - "nurikabe Factory: cell location out of bounds"); - } - if (value < -2) { - throw new InvalidFileFormatException("nurikabe Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("nurikabe Factory: cell location out of bounds"); + } + if (value < -2) { + throw new InvalidFileFormatException("nurikabe Factory: cell unknown value"); + } - NurikabeCell cell = new NurikabeCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); - } + NurikabeCell cell = new NurikabeCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - NurikabeCell cell = (NurikabeCell) puzzleElement; - Point loc = cell.getLocation(); + NurikabeCell cell = (NurikabeCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java index 158abe7b4..e87f661eb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java @@ -6,40 +6,40 @@ public class NurikabeController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - NurikabeCell cell = (NurikabeCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == -2) { - data.setData(0); - } else { - if (cell.getData() == 0) { - data.setData(-1); - } else { - data.setData(-2); - } - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + NurikabeCell cell = (NurikabeCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == -2) { + data.setData(0); } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == -2) { - data.setData(-1); - } else { - if (cell.getData() == 0) { - data.setData(-2); - } else { - data.setData(0); - } - } - } + if (cell.getData() == 0) { + data.setData(-1); + } else { + data.setData(-2); + } } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == -2) { + data.setData(-1); + } else { + if (cell.getData() == 0) { + data.setData(-2); + } else { + data.setData(0); + } + } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java index 116b727d2..6569cfaf7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java @@ -5,65 +5,64 @@ public class NurikabeElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; - public NurikabeElementView(NurikabeCell cell) { - super(cell); - } + public NurikabeElementView(NurikabeCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public NurikabeCell getPuzzleElement() { - return (NurikabeCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public NurikabeCell getPuzzleElement() { + return (NurikabeCell) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + NurikabeType type = cell.getType(); + if (type == NurikabeType.NUMBER) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.WHITE); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - @Override - public void drawElement(Graphics2D graphics2D) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - NurikabeType type = cell.getType(); - if (type == NurikabeType.NUMBER) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } else { + if (type == NurikabeType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.BLACK); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } else { + if (type == NurikabeType.WHITE) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.WHITE); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == NurikabeType.UNKNOWN) { graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.WHITE); + graphics2D.setColor(Color.LIGHT_GRAY); graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); graphics2D.drawRect(location.x, location.y, size.width, size.height); - - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = - location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } else { - if (type == NurikabeType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.BLACK); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } else { - if (type == NurikabeType.WHITE) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.WHITE); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == NurikabeType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - } - } + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java index 23efd4724..1a0f06bb2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java @@ -6,34 +6,34 @@ public class NurikabeExporter extends PuzzleExporter { - public NurikabeExporter(Nurikabe nurikabe) { - super(nurikabe); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - NurikabeBoard board; - if (puzzle.getTree() != null) { - board = (NurikabeBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (NurikabeBoard) puzzle.getBoardView().getBoard(); - } + public NurikabeExporter(Nurikabe nurikabe) { + super(nurikabe); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + NurikabeBoard board; + if (puzzle.getTree() != null) { + board = (NurikabeBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (NurikabeBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java index ec4ed3ac1..2be1ba899 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java @@ -8,117 +8,111 @@ import org.w3c.dom.NodeList; public class NurikabeImporter extends PuzzleImporter { - public NurikabeImporter(Nurikabe nurikabe) { - super(nurikabe); - } + public NurikabeImporter(Nurikabe nurikabe) { + super(nurikabe); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - NurikabeBoard nurikabeBoard = new NurikabeBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + NurikabeBoard nurikabeBoard = new NurikabeBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - NurikabeCell cell = - new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - nurikabeBoard.setCell(x, y, cell); - } - } - puzzle.setCurrentBoard(nurikabeBoard); + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + nurikabeBoard.setCell(x, y, cell); + } } + puzzle.setCurrentBoard(nurikabeBoard); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "nurikabe Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "nurikabe Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("nurikabe Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("nurikabe Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - NurikabeBoard nurikabeBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - nurikabeBoard = new NurikabeBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - nurikabeBoard = new NurikabeBoard(width, height); - } - } + NurikabeBoard nurikabeBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + nurikabeBoard = new NurikabeBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + nurikabeBoard = new NurikabeBoard(width, height); + } + } - if (nurikabeBoard == null) { - throw new InvalidFileFormatException("nurikabe Importer: invalid board dimensions"); - } + if (nurikabeBoard == null) { + throw new InvalidFileFormatException("nurikabe Importer: invalid board dimensions"); + } - int width = nurikabeBoard.getWidth(); - int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - NurikabeCell cell = - (NurikabeCell) - puzzle.getFactory() - .importCell(elementDataList.item(i), nurikabeBoard); - Point loc = cell.getLocation(); - if (cell.getData() != NurikabeType.UNKNOWN.toValue()) { - cell.setModifiable(false); - cell.setGiven(true); - } - nurikabeBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + NurikabeCell cell = + (NurikabeCell) puzzle.getFactory().importCell(elementDataList.item(i), nurikabeBoard); + Point loc = cell.getLocation(); + if (cell.getData() != NurikabeType.UNKNOWN.toValue()) { + cell.setModifiable(false); + cell.setGiven(true); + } + nurikabeBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (nurikabeBoard.getCell(x, y) == null) { - NurikabeCell cell = - new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - nurikabeBoard.setCell(x, y, cell); - } - } - } - puzzle.setCurrentBoard(nurikabeBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Importer: unknown value where integer expected"); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (nurikabeBoard.getCell(x, y) == null) { + NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + nurikabeBoard.setCell(x, y, cell); + } } + } + puzzle.setCurrentBoard(nurikabeBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Importer: unknown value where integer expected"); } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Nurikabe cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Nurikabe cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java index 8acf9fc02..a692a27fe 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java @@ -1,12 +1,12 @@ package edu.rpi.legup.puzzle.nurikabe; public enum NurikabeType { - UNKNOWN, - BLACK, - WHITE, - NUMBER; + UNKNOWN, + BLACK, + WHITE, + NUMBER; - public int toValue() { - return this.ordinal() - 2; - } + public int toValue() { + return this.ordinal() - 2; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java index 71ffa08e5..f6b1a02a4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java @@ -10,305 +10,303 @@ public class NurikabeUtilities { - /** - * Gets all of the numbered cells in the Nurikabe board - * - * @param board nurikabe board - * @return a list of all of the numbered cells - */ - public static Set getNurikabeNumberedCells(NurikabeBoard board) { - Set numberedCells = new HashSet<>(); + /** + * Gets all of the numbered cells in the Nurikabe board + * + * @param board nurikabe board + * @return a list of all of the numbered cells + */ + public static Set getNurikabeNumberedCells(NurikabeBoard board) { + Set numberedCells = new HashSet<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.NUMBER) { - numberedCells.add(cell); - } - } - return numberedCells; + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.NUMBER) { + numberedCells.add(cell); + } } + return numberedCells; + } - /** - * Gets nurikabe regions of black, white, and unknown cells - * - * @param board nurikabe board - * @return a disjoint set of the regions - */ - public static DisjointSets getNurikabeRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets nurikabe regions of black, white, and unknown cells + * + * @param board nurikabe board + * @return a disjoint set of the regions + */ + public static DisjointSets getNurikabeRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets regions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - regions.createSet((NurikabeCell) data); - } + DisjointSets regions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + regions.createSet((NurikabeCell) data); + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.NUMBER || cell.getType() == NurikabeType.WHITE) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.NUMBER - || rightCell.getType() == NurikabeType.WHITE)) { - regions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.NUMBER - || downCell.getType() == NurikabeType.WHITE)) { - regions.union(cell, downCell); - } - } else { - if (cell.getType() == NurikabeType.BLACK) { - if (rightCell != null && rightCell.getType() == NurikabeType.BLACK) { - regions.union(cell, rightCell); - } - if (downCell != null && downCell.getType() == NurikabeType.BLACK) { - regions.union(cell, downCell); - } - } else { - if (cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null && rightCell.getType() == NurikabeType.UNKNOWN) { - regions.union(cell, rightCell); - } - if (downCell != null && downCell.getType() == NurikabeType.UNKNOWN) { - regions.union(cell, downCell); - } - } - } - } + if (cell.getType() == NurikabeType.NUMBER || cell.getType() == NurikabeType.WHITE) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.NUMBER + || rightCell.getType() == NurikabeType.WHITE)) { + regions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.NUMBER + || downCell.getType() == NurikabeType.WHITE)) { + regions.union(cell, downCell); + } + } else { + if (cell.getType() == NurikabeType.BLACK) { + if (rightCell != null && rightCell.getType() == NurikabeType.BLACK) { + regions.union(cell, rightCell); } + if (downCell != null && downCell.getType() == NurikabeType.BLACK) { + regions.union(cell, downCell); + } + } else { + if (cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null && rightCell.getType() == NurikabeType.UNKNOWN) { + regions.union(cell, rightCell); + } + if (downCell != null && downCell.getType() == NurikabeType.UNKNOWN) { + regions.union(cell, downCell); + } + } + } } - return regions; + } } + return regions; + } - /** - * Gets the disjoint set containing the possible black regions be interpreting all unknown cells - * as black cells - * - * @param board nurikabe board - * @return the disjoint set containing the possible black regions - */ - public static DisjointSets getPossibleBlackRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets the disjoint set containing the possible black regions be interpreting all unknown cells + * as black cells + * + * @param board nurikabe board + * @return the disjoint set containing the possible black regions + */ + public static DisjointSets getPossibleBlackRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets blackRegions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { - blackRegions.createSet(cell); - } - } + DisjointSets blackRegions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { + blackRegions.createSet(cell); + } + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.BLACK - || cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.BLACK - || rightCell.getType() == NurikabeType.UNKNOWN)) { - blackRegions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.BLACK - || downCell.getType() == NurikabeType.UNKNOWN)) { - blackRegions.union(cell, downCell); - } - } - } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.BLACK + || rightCell.getType() == NurikabeType.UNKNOWN)) { + blackRegions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.BLACK + || downCell.getType() == NurikabeType.UNKNOWN)) { + blackRegions.union(cell, downCell); + } } - return blackRegions; + } } + return blackRegions; + } - /** - * Gets the disjoint set containing the possible white regions be interpreting all unknown cells - * as white cells - * - * @param board nurikabe board - * @return the disjoint set containing the possible white regions - */ - public static DisjointSets getPossibleWhiteRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets the disjoint set containing the possible white regions be interpreting all unknown cells + * as white cells + * + * @param board nurikabe board + * @return the disjoint set containing the possible white regions + */ + public static DisjointSets getPossibleWhiteRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets whiteRegions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.WHITE - || cell.getType() == NurikabeType.NUMBER - || cell.getType() == NurikabeType.UNKNOWN) { - whiteRegions.createSet(cell); - } - } + DisjointSets whiteRegions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.WHITE + || cell.getType() == NurikabeType.NUMBER + || cell.getType() == NurikabeType.UNKNOWN) { + whiteRegions.createSet(cell); + } + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.WHITE - || cell.getType() == NurikabeType.NUMBER - || cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.WHITE - || rightCell.getType() == NurikabeType.NUMBER - || rightCell.getType() == NurikabeType.UNKNOWN)) { - whiteRegions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.WHITE - || downCell.getType() == NurikabeType.NUMBER - || downCell.getType() == NurikabeType.UNKNOWN)) { - whiteRegions.union(cell, downCell); - } - } - } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + if (cell.getType() == NurikabeType.WHITE + || cell.getType() == NurikabeType.NUMBER + || cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.WHITE + || rightCell.getType() == NurikabeType.NUMBER + || rightCell.getType() == NurikabeType.UNKNOWN)) { + whiteRegions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.WHITE + || downCell.getType() == NurikabeType.NUMBER + || downCell.getType() == NurikabeType.UNKNOWN)) { + whiteRegions.union(cell, downCell); + } } - return whiteRegions; + } } + return whiteRegions; + } - /** - * Makes a map where the keys are white/numbered cells and the values are the amount of cells - * that need to be added to the region - * - * @param board nurikabe board - * @return a map of cell keys to integer values - */ - public static HashMap getWhiteRegionMap(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Makes a map where the keys are white/numbered cells and the values are the amount of cells that + * need to be added to the region + * + * @param board nurikabe board + * @return a map of cell keys to integer values + */ + public static HashMap getWhiteRegionMap(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - Set numberedCells = getNurikabeNumberedCells(board); - // Final mapping of cell to size - HashMap whiteRegionMap = new HashMap<>(); - for (NurikabeCell center : numberedCells) { - // BFS for each center to find the size of the region - int size = 1; - // Mark all the vertices as not visited(By default - // set as false) - HashMap visited = new HashMap<>(); + Set numberedCells = getNurikabeNumberedCells(board); + // Final mapping of cell to size + HashMap whiteRegionMap = new HashMap<>(); + for (NurikabeCell center : numberedCells) { + // BFS for each center to find the size of the region + int size = 1; + // Mark all the vertices as not visited(By default + // set as false) + HashMap visited = new HashMap<>(); - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - // Mark the current node as visited and enqueue it - visited.put(center, true); - queue.add(center); + // Mark the current node as visited and enqueue it + visited.put(center, true); + queue.add(center); - // Set of cells in the current region - Set connected = new HashSet<>(); + // Set of cells in the current region + Set connected = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - // s is the source node in the graph - NurikabeCell s = queue.poll(); - System.out.print(s + " "); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + // s is the source node in the graph + NurikabeCell s = queue.poll(); + System.out.print(s + " "); - // Make a linked list of all adjacent squares - Set adj = new HashSet<>(); + // Make a linked list of all adjacent squares + Set adj = new HashSet<>(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(board.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(board.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(board.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(board.getCell(loc.x, loc.y + 1)); - } - // Get all adjacent vertices of the dequeued vertex s - // If a adjacent has not been visited, then mark it - // visited and enqueue it - for (NurikabeCell n : adj) { - if (!visited.getOrDefault(n, false) && n.getType() == NurikabeType.WHITE) { - connected.add(n); - visited.put(n, true); - queue.add(n); - ++size; - } - } - } - // Map the cells to the center-size (including the center) - whiteRegionMap.put(center, center.getData() - size); - for (NurikabeCell member : connected) { - whiteRegionMap.put(member, center.getData() - size); - } + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(board.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(board.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(board.getCell(loc.x, loc.y - 1)); } - return whiteRegionMap; + if (loc.y < height - 1) { + adj.add(board.getCell(loc.x, loc.y + 1)); + } + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (NurikabeCell n : adj) { + if (!visited.getOrDefault(n, false) && n.getType() == NurikabeType.WHITE) { + connected.add(n); + visited.put(n, true); + queue.add(n); + ++size; + } + } + } + // Map the cells to the center-size (including the center) + whiteRegionMap.put(center, center.getData() - size); + for (NurikabeCell member : connected) { + whiteRegionMap.put(member, center.getData() - size); + } } + return whiteRegionMap; + } - /** - * Gets all the non-black cells connected to the given cell - * - * @param board nurikabe board - * @param center nurikabe cell - * @return a set of all white/numbered cells in the region - */ - public static Set getSurroundedRegionOf( - NurikabeBoard board, NurikabeCell center) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets all the non-black cells connected to the given cell + * + * @param board nurikabe board + * @param center nurikabe cell + * @return a set of all white/numbered cells in the region + */ + public static Set getSurroundedRegionOf(NurikabeBoard board, NurikabeCell center) { + int width = board.getWidth(); + int height = board.getHeight(); - // Mark all the vertices as not visited(By default - // set as false) - Set visited = new HashSet<>(); + // Mark all the vertices as not visited(By default + // set as false) + Set visited = new HashSet<>(); - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - // Mark the current node as visited and enqueue it - visited.add(center); - queue.add(center); + // Mark the current node as visited and enqueue it + visited.add(center); + queue.add(center); - // Set of cells in the current region - Set connected = new HashSet<>(); + // Set of cells in the current region + Set connected = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - // s is the source node in the graph - NurikabeCell s = queue.poll(); - System.out.print(s + " "); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + // s is the source node in the graph + NurikabeCell s = queue.poll(); + System.out.print(s + " "); - // Make a set of all adjacent squares - Set adj = new HashSet<>(); + // Make a set of all adjacent squares + Set adj = new HashSet<>(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(board.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(board.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(board.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(board.getCell(loc.x, loc.y + 1)); - } - // Get all adjacent vertices of the dequeued vertex s - // If a adjacent has not been visited, then mark it - // visited and enqueue it - for (NurikabeCell n : adj) { - if (!visited.contains(n) && n.getType() != NurikabeType.BLACK) { - connected.add(n); - visited.add(n); - queue.add(n); - } - } + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(board.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(board.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(board.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(board.getCell(loc.x, loc.y + 1)); + } + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (NurikabeCell n : adj) { + if (!visited.contains(n) && n.getType() != NurikabeType.BLACK) { + connected.add(n); + visited.add(n); + queue.add(n); } - - return connected; + } } + + return connected; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java index 0bac7e3e5..04e1910e4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java @@ -7,18 +7,17 @@ public class NurikabeView extends GridBoardView { - public NurikabeView(NurikabeBoard board) { - super(new BoardController(), new NurikabeController(), board.getDimension()); + public NurikabeView(NurikabeBoard board) { + super(new BoardController(), new NurikabeController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - Point loc = cell.getLocation(); - NurikabeElementView elementView = new NurikabeElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + Point loc = cell.getLocation(); + NurikabeElementView elementView = new NurikabeElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java index 459a809e0..25f817ff2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BlackTile extends PlaceableElement { - public BlackTile() { - super( - "NURI-PLAC-0001", - "Black Tile", - "The black tile", - "edu/rpi/legup/images/nurikabe/tiles/BlackTile.png"); - } + public BlackTile() { + super( + "NURI-PLAC-0001", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/nurikabe/tiles/BlackTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java index 475b278da..9c0f3ff94 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java @@ -3,28 +3,28 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super( - "NURI-UNPL-0001", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/nurikabe/tiles/NumberTile.png"); - object_num = 0; - } + public NumberTile() { + super( + "NURI-UNPL-0001", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/nurikabe/tiles/NumberTile.png"); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java index 85d47e208..0b16d4a17 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "NURI-UNPL-0002", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/nurikabe/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "NURI-UNPL-0002", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/nurikabe/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java index 35eb63b81..c086ce55c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class WhiteTile extends PlaceableElement { - public WhiteTile() { - super( - "NURI-PLAC-0002", - "White Tile", - "The white tile", - "edu/rpi/legup/images/nurikabe/tiles/WhiteTile.png"); - } + public WhiteTile() { + super( + "NURI-PLAC-0002", + "White Tile", + "The white tile", + "edu/rpi/legup/images/nurikabe/tiles/WhiteTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java index 7428ac204..f8fb66110 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java @@ -17,106 +17,103 @@ public class BlackBetweenRegionsDirectRule extends DirectRule { - public BlackBetweenRegionsDirectRule() { - super( - "NURI-BASC-0001", - "Black Between Regions", - "Any unknowns between two regions must be black.", - "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new MultipleNumbersContradictionRule()); - contras.add(new TooManySpacesContradictionRule()); - - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + public BlackBetweenRegionsDirectRule() { + super( + "NURI-BASC-0001", + "Black Between Regions", + "Any unknowns between two regions must be black.", + "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); + } - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new MultipleNumbersContradictionRule()); + contras.add(new TooManySpacesContradictionRule()); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() - + ": Only black cells are allowed for this rule!"; - } + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - int x = cell.getLocation().x; - int y = cell.getLocation().y; + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adjacentWhiteRegions = new HashSet<>(); - NurikabeCell upCell = destBoardState.getCell(x, y - 1); - NurikabeCell rightCell = destBoardState.getCell(x + 1, y); - NurikabeCell downCell = destBoardState.getCell(x, y + 1); - NurikabeCell leftCell = destBoardState.getCell(x - 1, y); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; + } - if (upCell != null - && (upCell.getType() == NurikabeType.WHITE - || upCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(upCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (rightCell != null - && (rightCell.getType() == NurikabeType.WHITE - || rightCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(rightCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (downCell != null - && (downCell.getType() == NurikabeType.WHITE - || downCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(downCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (leftCell != null - && (leftCell.getType() == NurikabeType.WHITE - || leftCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(leftCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } + int x = cell.getLocation().x; + int y = cell.getLocation().y; - if (adjacentWhiteRegions.size() < 2) { - return "The new black cell must separate two white regions for this rule!"; - } + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adjacentWhiteRegions = new HashSet<>(); + NurikabeCell upCell = destBoardState.getCell(x, y - 1); + NurikabeCell rightCell = destBoardState.getCell(x + 1, y); + NurikabeCell downCell = destBoardState.getCell(x, y + 1); + NurikabeCell leftCell = destBoardState.getCell(x - 1, y); - NurikabeBoard modified = origBoardState.copy(); - modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); + if (upCell != null + && (upCell.getType() == NurikabeType.WHITE || upCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(upCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (rightCell != null + && (rightCell.getType() == NurikabeType.WHITE + || rightCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(rightCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (downCell != null + && (downCell.getType() == NurikabeType.WHITE + || downCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(downCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (leftCell != null + && (leftCell.getType() == NurikabeType.WHITE + || leftCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(leftCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } - for (ContradictionRule c : contras) { - if (c.checkContradiction(modified) == null) { - return null; - } - } - return "Does not follow from the rule"; + if (adjacentWhiteRegions.size() < 2) { + return "The new black cell must separate two white regions for this rule!"; } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + NurikabeBoard modified = origBoardState.copy(); + modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); + + for (ContradictionRule c : contras) { + if (c.checkContradiction(modified) == null) { return null; + } } + return "Does not follow from the rule"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java index a8a94178b..31c05f9b4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java @@ -12,58 +12,54 @@ public class BlackBottleNeckDirectRule extends DirectRule { - public BlackBottleNeckDirectRule() { - super( - "NURI-BASC-0002", - "Black Bottle Neck", - "If there is only one path for a black to escape, then those unknowns must be" - + " black.", - "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new IsolateBlackContradictionRule(); + public BlackBottleNeckDirectRule() { + super( + "NURI-BASC-0002", + "Black Bottle Neck", + "If there is only one path for a black to escape, then those unknowns must be" + " black.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); + } - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new IsolateBlackContradictionRule(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() - + ": Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (contraRule.checkContradiction(modified) == null) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() - + ": This is not the only way for black to escape!"; - } + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + if (contraRule.checkContradiction(modified) == null) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This is not the only way for black to escape!"; } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java index fe1ffcf91..9c6bf1a63 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java @@ -13,102 +13,101 @@ public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "NURI-CASE-0001", - "Black or White", - "Each blank cell is either black or white.", - "edu/rpi/legup/images/nurikabe/cases/BlackOrWhite.png"); - } - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; - } + public BlackOrWhiteCaseRule() { + super( + "NURI-CASE-0001", + "Black or White", + "Each blank cell is either black or white.", + "edu/rpi/legup/images/nurikabe/cases/BlackOrWhite.png"); + } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - NurikabeCell mod1 = (NurikabeCell) case1.getBoard().getModifiedData().iterator().next(); - NurikabeCell mod2 = (NurikabeCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - if (!((mod1.getType() == NurikabeType.WHITE && mod2.getType() == NurikabeType.BLACK) - || (mod2.getType() == NurikabeType.WHITE - && mod1.getType() == NurikabeType.BLACK))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty white and black cell."; - } + NurikabeCell mod1 = (NurikabeCell) case1.getBoard().getModifiedData().iterator().next(); + NurikabeCell mod2 = (NurikabeCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } - return null; + if (!((mod1.getType() == NurikabeType.WHITE && mod2.getType() == NurikabeType.BLACK) + || (mod2.getType() == NurikabeType.WHITE && mod1.getType() == NurikabeType.BLACK))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty white and black cell."; } - @Override - public CaseBoard getCaseBoard(Board board) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(nurikabeBoard, this); - nurikabeBoard.setModifiable(false); - for (PuzzleElement element : nurikabeBoard.getPuzzleElements()) { - if (((NurikabeCell) element).getType() == NurikabeType.UNKNOWN) { - caseBoard.addPickableElement(element); - } - } - return caseBoard; + return null; + } + + @Override + public CaseBoard getCaseBoard(Board board) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(nurikabeBoard, this); + nurikabeBoard.setModifiable(false); + for (PuzzleElement element : nurikabeBoard.getPuzzleElements()) { + if (((NurikabeCell) element).getType() == NurikabeType.UNKNOWN) { + caseBoard.addPickableElement(element); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(NurikabeType.WHITE.toValue()); - case1.addModifiedData(data1); - cases.add(case1); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(NurikabeType.WHITE.toValue()); + case1.addModifiedData(data1); + cases.add(case1); - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(NurikabeType.BLACK.toValue()); - case2.addModifiedData(data2); - cases.add(case2); + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(NurikabeType.BLACK.toValue()); + case2.addModifiedData(data2); + cases.add(case2); - return cases; - } + return cases; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java index 751c88881..bdc72d921 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java @@ -9,52 +9,52 @@ public class BlackSquareContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "No 2x2 square of black exists."; - private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - - public BlackSquareContradictionRule() { - super( - "NURI-CONT-0001", - "Black Square", - "There cannot be a 2x2 square of black.", - "edu/rpi/legup/images/nurikabe/contradictions/BlackSquare.png"); + private final String NO_CONTRADICTION_MESSAGE = "No 2x2 square of black exists."; + private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; + + public BlackSquareContradictionRule() { + super( + "NURI-CONT-0001", + "Black Square", + "There cannot be a 2x2 square of black.", + "edu/rpi/legup/images/nurikabe/contradictions/BlackSquare.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int height = nurikabeBoard.getHeight(); - int width = nurikabeBoard.getWidth(); - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + for (int x = cell.getLocation().x - 1; + x >= 0 && x < cell.getLocation().x + 1 && x < width - 1; + x++) { + for (int y = cell.getLocation().y - 1; + y >= 0 && y < cell.getLocation().y + 1 && y < height - 1; + y++) { + if (nurikabeBoard.getCell(x, y).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x + 1, y).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x, y + 1).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x + 1, y + 1).getType() == NurikabeType.BLACK) { + return null; } - - for (int x = cell.getLocation().x - 1; - x >= 0 && x < cell.getLocation().x + 1 && x < width - 1; - x++) { - for (int y = cell.getLocation().y - 1; - y >= 0 && y < cell.getLocation().y + 1 && y < height - 1; - y++) { - if (nurikabeBoard.getCell(x, y).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x + 1, y).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x, y + 1).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x + 1, y + 1).getType() == NurikabeType.BLACK) { - return null; - } - } - } - - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } + + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java index f3d3ee8f2..0b699b7bd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java @@ -11,54 +11,52 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; public class CannotReachCellDirectRule extends DirectRule { - public CannotReachCellDirectRule() { - super( - "NURI-BASC-0008", - "Can't Reach Cell", - "A cell must be black if it cannot be reached by any white region", - "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); - } + public CannotReachCellDirectRule() { + super( + "NURI-BASC-0008", + "Can't Reach Cell", + "A cell must be black if it cannot be reached by any white region", + "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() - + ": Only black cells are allowed for this rule!"; - } + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; + } - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeBoard modified = origBoardState.copy(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modifiedCell.setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; + NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modifiedCell.setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { + return null; } + return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java index 84ec45e99..7c974eba7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java @@ -15,119 +15,117 @@ public class CornerBlackDirectRule extends DirectRule { - public CornerBlackDirectRule() { - super( - "NURI-BASC-0003", - "Corners Black", - "If there is only one white square connected to unknowns and one more white is" - + " needed then the angles of that white square are black", - "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); + public CornerBlackDirectRule() { + super( + "NURI-BASC-0003", + "Corners Black", + "If there is only one white square connected to unknowns and one more white is" + + " needed then the angles of that white square are black", + "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; + ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); + Point cellLocation = cell.getLocation(); + // 1. Find the coordinates of the white space (should be a corner of cell) + for (int i = -1; i < 2; i += 2) { + for (int j = -1; j < 2; j += 2) { + // If the corner does not exist, skip the corner + if (!(cellLocation.x + i >= 0 + && cellLocation.x + i < board.getWidth() + && cellLocation.y + j >= 0 + && cellLocation.y + j < board.getHeight())) { + continue; } - ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); - Point cellLocation = cell.getLocation(); - // 1. Find the coordinates of the white space (should be a corner of cell) - for (int i = -1; i < 2; i += 2) { - for (int j = -1; j < 2; j += 2) { - // If the corner does not exist, skip the corner - if (!(cellLocation.x + i >= 0 - && cellLocation.x + i < board.getWidth() - && cellLocation.y + j >= 0 - && cellLocation.y + j < board.getHeight())) { - continue; - } - - NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); - NurikabeType cornerType = corner.getType(); - if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { - Point cornerLocation = corner.getLocation(); - // 2. Check if the intersecting adjacent spaces of the white space and the black - // corner - // are empty - if (board.getCell(cornerLocation.x, cellLocation.y).getType() - == NurikabeType.UNKNOWN - && board.getCell(cellLocation.x, cornerLocation.y).getType() - == NurikabeType.UNKNOWN) { - // System.out.println("Went inside if statement"); - NurikabeBoard modified = board.copy(); - modified.getCell(cornerLocation.x, cellLocation.y) - .setData(NurikabeType.BLACK.toValue()); - modified.getCell(cellLocation.x, cornerLocation.y) - .setData(NurikabeType.BLACK.toValue()); - boolean containsContradiction = - tooFewContra.checkContradiction(modified) == null; - if (containsContradiction) { - // 3. Check if the connected region is 1 under what is needed - Set region = - ConnectedRegions.getRegionAroundPoint( - cornerLocation, - NurikabeType.BLACK.toValue(), - modified.getIntArray(), - modified.getWidth(), - modified.getHeight()); - int regionNumber = 0; - // System.out.println("Region set size: " + region.size()); - for (Point p : region) { - NurikabeCell pCell = modified.getCell(p.x, p.y); - if (pCell.getType() == NurikabeType.NUMBER) { - if (regionNumber == 0) { - regionNumber = pCell.getData(); - } else { - return "There is a MultipleNumbers Contradiction on the" - + " board."; - } - } - } - // If the region size is 0, there is a possibility that there was only 1 - // cell in the - // white - // region, and that white cell was a NurikabeType.NUMBER cell - if (regionNumber == 0 - && corner.getType() == NurikabeType.NUMBER - && corner.getData() == 2) { - return null; - } - // If the region size is not 0, make sure the regionNumber and the - // region size match - // (need - // to add 1 to account for the cell that was surrounded - if (regionNumber != 0 && region.size() + 1 == regionNumber) { - return null; - } - } - } + NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); + NurikabeType cornerType = corner.getType(); + if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { + Point cornerLocation = corner.getLocation(); + // 2. Check if the intersecting adjacent spaces of the white space and the black + // corner + // are empty + if (board.getCell(cornerLocation.x, cellLocation.y).getType() == NurikabeType.UNKNOWN + && board.getCell(cellLocation.x, cornerLocation.y).getType() + == NurikabeType.UNKNOWN) { + // System.out.println("Went inside if statement"); + NurikabeBoard modified = board.copy(); + modified + .getCell(cornerLocation.x, cellLocation.y) + .setData(NurikabeType.BLACK.toValue()); + modified + .getCell(cellLocation.x, cornerLocation.y) + .setData(NurikabeType.BLACK.toValue()); + boolean containsContradiction = tooFewContra.checkContradiction(modified) == null; + if (containsContradiction) { + // 3. Check if the connected region is 1 under what is needed + Set region = + ConnectedRegions.getRegionAroundPoint( + cornerLocation, + NurikabeType.BLACK.toValue(), + modified.getIntArray(), + modified.getWidth(), + modified.getHeight()); + int regionNumber = 0; + // System.out.println("Region set size: " + region.size()); + for (Point p : region) { + NurikabeCell pCell = modified.getCell(p.x, p.y); + if (pCell.getType() == NurikabeType.NUMBER) { + if (regionNumber == 0) { + regionNumber = pCell.getData(); + } else { + return "There is a MultipleNumbers Contradiction on the" + " board."; + } } + } + // If the region size is 0, there is a possibility that there was only 1 + // cell in the + // white + // region, and that white cell was a NurikabeType.NUMBER cell + if (regionNumber == 0 + && corner.getType() == NurikabeType.NUMBER + && corner.getData() == 2) { + return null; + } + // If the region size is not 0, make sure the regionNumber and the + // region size match + // (need + // to add 1 to account for the cell that was surrounded + if (regionNumber != 0 && region.size() + 1 == regionNumber) { + return null; + } } + } } - return "This is not a valid use of the corner black rule!"; + } } + return "This is not a valid use of the corner black rule!"; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java index 7c4629f65..3507d0a7f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java @@ -12,51 +12,50 @@ public class FillinBlackDirectRule extends DirectRule { - public FillinBlackDirectRule() { - super( - "NURI-BASC-0004", - "Fill In Black", - "If there an unknown region surrounded by black, it must be black.", - "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); - } + public FillinBlackDirectRule() { + super( + "NURI-BASC-0004", + "Fill In Black", + "If there an unknown region surrounded by black, it must be black.", + "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new NoNumberContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new NoNumberContradictionRule(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "Black cells must be placed in a region of black cells!"; - } - return null; + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "Black cells must be placed in a region of black cells!"; } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java index 05bb2f046..30d5a3a51 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java @@ -12,51 +12,50 @@ public class FillinWhiteDirectRule extends DirectRule { - public FillinWhiteDirectRule() { - super( - "NURI-BASC-0005", - "Fill In White", - "If there an unknown region surrounded by white, it must be white.", - "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); - } + public FillinWhiteDirectRule() { + super( + "NURI-BASC-0005", + "Fill In White", + "If there an unknown region surrounded by white, it must be white.", + "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new IsolateBlackContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new IsolateBlackContradictionRule(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "white cells must be placed in a region of white cells!"; - } - return null; + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "white cells must be placed in a region of white cells!"; } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java index f26f0c3fe..831dd134b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java @@ -12,50 +12,50 @@ public class IsolateBlackContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "Contradiction applied incorrectly. No isolated Blacks."; - private final String INVALID_USE_MESSAGE = "Contradiction must be a black cell"; + private final String NO_CONTRADICTION_MESSAGE = + "Contradiction applied incorrectly. No isolated Blacks."; + private final String INVALID_USE_MESSAGE = "Contradiction must be a black cell"; - public IsolateBlackContradictionRule() { - super( - "NURI-CONT-0003", - "Isolated Black", - "There must still be a possibility to connect every Black cell", - "edu/rpi/legup/images/nurikabe/contradictions/BlackArea.png"); - } + public IsolateBlackContradictionRule() { + super( + "NURI-CONT-0003", + "Isolated Black", + "There must still be a possibility to connect every Black cell", + "edu/rpi/legup/images/nurikabe/contradictions/BlackArea.png"); + } - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule. - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified {@link - * PuzzleElement}, otherwise return a no contradiction message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule. + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified {@link + * PuzzleElement}, otherwise return a no contradiction message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - DisjointSets blackRegions = - NurikabeUtilities.getPossibleBlackRegions(nurikabeBoard); - boolean oneRegion = false; - for (Set region : blackRegions.getAllSets()) { - for (NurikabeCell c : region) { - if (c.getType() == NurikabeType.BLACK) { - if (oneRegion) { - return null; - } else { - oneRegion = true; - break; - } - } - } + DisjointSets blackRegions = + NurikabeUtilities.getPossibleBlackRegions(nurikabeBoard); + boolean oneRegion = false; + for (Set region : blackRegions.getAllSets()) { + for (NurikabeCell c : region) { + if (c.getType() == NurikabeType.BLACK) { + if (oneRegion) { + return null; + } else { + oneRegion = true; + break; + } } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java index 1925a68ec..d19cde25a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java @@ -12,42 +12,41 @@ public class MultipleNumbersContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a numbered cell"; + private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a numbered cell"; - public MultipleNumbersContradictionRule() { - super( - "NURI-CONT-0004", - "Multiple Numbers", - "All white regions cannot have more than one number.", - "edu/rpi/legup/images/nurikabe/contradictions/MultipleNumbers.png"); - } + public MultipleNumbersContradictionRule() { + super( + "NURI-CONT-0004", + "Multiple Numbers", + "All white regions cannot have more than one number.", + "edu/rpi/legup/images/nurikabe/contradictions/MultipleNumbers.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + INVALID_USE_MESSAGE; - } - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); - Set numberedRegion = regions.getSet(cell); - for (NurikabeCell c : numberedRegion) { - if (c != cell && c.getType() == NurikabeType.NUMBER) { - return null; - } - } - return super.getNoContradictionMessage() + ": " + NO_CONTRADICTION_MESSAGE; + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + INVALID_USE_MESSAGE; + } + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); + Set numberedRegion = regions.getSet(cell); + for (NurikabeCell c : numberedRegion) { + if (c != cell && c.getType() == NurikabeType.NUMBER) { + return null; + } } + return super.getNoContradictionMessage() + ": " + NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java index 6c69136b2..64d3383e1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java @@ -11,63 +11,62 @@ public class NoNumberContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white cell"; - private final String NOT_SURROUNDED_BY_BLACK_MESSAGE = "Must be surrounded by black cells"; + private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white cell"; + private final String NOT_SURROUNDED_BY_BLACK_MESSAGE = "Must be surrounded by black cells"; - public NoNumberContradictionRule() { - super( - "NURI-CONT-0005", - "No Number", - "All enclosed white regions must have a number.", - "edu/rpi/legup/images/nurikabe/contradictions/NoNumber.png"); - } + public NoNumberContradictionRule() { + super( + "NURI-CONT-0005", + "No Number", + "All enclosed white regions must have a number.", + "edu/rpi/legup/images/nurikabe/contradictions/NoNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - Set region = NurikabeUtilities.getSurroundedRegionOf(nurikabeBoard, cell); + Set region = NurikabeUtilities.getSurroundedRegionOf(nurikabeBoard, cell); - boolean numberExists = false; - for (NurikabeCell c : region) { - if (c.getType() == NurikabeType.NUMBER) { - numberExists = true; - break; - } - } - if (!numberExists) { - return null; - } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + boolean numberExists = false; + for (NurikabeCell c : region) { + if (c.getType() == NurikabeType.NUMBER) { + numberExists = true; + break; + } + } + if (!numberExists) { + return null; } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } - /** - * Checks whether a give NurikabeCell is empty. - * - * @param cell NurikabeCell to check if empty - * @return false if the NurikabeCell is not empty or null, true otherwise - */ - private boolean isEmptyCell(NurikabeCell cell) { - if (cell == null) { - return false; - } - NurikabeType cellType = cell.getType(); - return cellType != NurikabeType.BLACK && cellType != NurikabeType.WHITE; + /** + * Checks whether a give NurikabeCell is empty. + * + * @param cell NurikabeCell to check if empty + * @return false if the NurikabeCell is not empty or null, true otherwise + */ + private boolean isEmptyCell(NurikabeCell cell) { + if (cell == null) { + return false; } + NurikabeType cellType = cell.getType(); + return cellType != NurikabeType.BLACK && cellType != NurikabeType.WHITE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java index 106c22f7a..a9ae5441f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java @@ -12,56 +12,55 @@ public class PreventBlackSquareDirectRule extends DirectRule { - public PreventBlackSquareDirectRule() { - super( - "NURI-BASC-0006", - "Prevent Black Square", - "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", - "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); - } + public PreventBlackSquareDirectRule() { + super( + "NURI-BASC-0006", + "Prevent Black Square", + "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", + "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new BlackSquareContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new BlackSquareContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradiction(modified) == null) { - return null; - } else { - return "Does not contain a contradiction at this index"; - } + if (contraRule.checkContradiction(modified) == null) { + return null; + } else { + return "Does not contain a contradiction at this index"; } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java index 8e260cf42..e471de3b1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java @@ -19,85 +19,80 @@ public class SurroundRegionDirectRule extends DirectRule { - public SurroundRegionDirectRule() { - super( - "NURI-BASC-0007", - "Surround Region", - "Surround Region", - "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); - } + public SurroundRegionDirectRule() { + super( + "NURI-BASC-0007", + "Surround Region", + "Surround Region", + "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); - if (cell.getType() == NurikabeType.BLACK) { - DisjointSets regions = - NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adj = new HashSet<>(); // set to hold adjacent cells - Point loc = cell.getLocation(); // position of placed cell - List directions = - Arrays.asList( - new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); - for (Point direction : directions) { - NurikabeCell curr = - destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); - if (curr != null) { - if (curr.getType() == NurikabeType.WHITE - || curr.getType() == NurikabeType.NUMBER) { - adj.add(curr); // adds cells to adj only if they are white or number blocks - } - } - } - List numberedCells = new ArrayList<>(); // number value of number cells - for (NurikabeCell c : adj) { // loops through adjacent cells - Set disRow = regions.getSet(c); // set of white spaces - for (NurikabeCell d : disRow) { // loops through white spaces - if (d.getType() == NurikabeType.NUMBER) { // if the white space is a number - numberedCells.add(d); // add that number to numberedCells - } - } - } - for (NurikabeCell number : numberedCells) { // loops through numberedCells - if (regions.getSet(number).size() - == number.getData()) { // if that cells white area is the exact - return null; // size of the number of one of the number cells within that set - } - } + if (cell.getType() == NurikabeType.BLACK) { + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adj = new HashSet<>(); // set to hold adjacent cells + Point loc = cell.getLocation(); // position of placed cell + List directions = + Arrays.asList(new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); + for (Point direction : directions) { + NurikabeCell curr = destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); + if (curr != null) { + if (curr.getType() == NurikabeType.WHITE || curr.getType() == NurikabeType.NUMBER) { + adj.add(curr); // adds cells to adj only if they are white or number blocks + } } - return "Does not follow from this rule at this index"; + } + List numberedCells = new ArrayList<>(); // number value of number cells + for (NurikabeCell c : adj) { // loops through adjacent cells + Set disRow = regions.getSet(c); // set of white spaces + for (NurikabeCell d : disRow) { // loops through white spaces + if (d.getType() == NurikabeType.NUMBER) { // if the white space is a number + numberedCells.add(d); // add that number to numberedCells + } + } + } + for (NurikabeCell number : numberedCells) { // loops through numberedCells + if (regions.getSet(number).size() + == number.getData()) { // if that cells white area is the exact + return null; // size of the number of one of the number cells within that set + } + } } + return "Does not follow from this rule at this index"; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java index e7995165b..e05b72b7c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java @@ -12,53 +12,51 @@ public class TooFewSpacesContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; - - public TooFewSpacesContradictionRule() { - super( - "NURI-CONT-0006", - "Too Few Spaces", - "A region cannot contain less spaces than its number.", - "edu/rpi/legup/images/nurikabe/contradictions/TooFewSpaces.png"); + private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; + + public TooFewSpacesContradictionRule() { + super( + "NURI-CONT-0006", + "Too Few Spaces", + "A region cannot contain less spaces than its number.", + "edu/rpi/legup/images/nurikabe/contradictions/TooFewSpaces.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } - - DisjointSets regions = - NurikabeUtilities.getPossibleWhiteRegions(nurikabeBoard); - Set whiteRegion = regions.getSet(cell); - NurikabeCell numberedCell = null; - for (NurikabeCell c : whiteRegion) { - if (c.getType() == NurikabeType.NUMBER) { - numberedCell = c; - break; - } - } + DisjointSets regions = NurikabeUtilities.getPossibleWhiteRegions(nurikabeBoard); + Set whiteRegion = regions.getSet(cell); + NurikabeCell numberedCell = null; + for (NurikabeCell c : whiteRegion) { + if (c.getType() == NurikabeType.NUMBER) { + numberedCell = c; + break; + } + } - if (numberedCell != null && whiteRegion.size() < numberedCell.getData()) { - // System.err.println("Cell Value: " + numberedCell.getData() + ", Loc: " + - // cell.getLocation() - // + ", region: " + whiteRegion.size()); - return null; - } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + if (numberedCell != null && whiteRegion.size() < numberedCell.getData()) { + // System.err.println("Cell Value: " + numberedCell.getData() + ", Loc: " + + // cell.getLocation() + // + ", region: " + whiteRegion.size()); + return null; } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java index 7bd0883ef..550c07f57 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java @@ -13,50 +13,49 @@ public class TooManySpacesContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; - - public TooManySpacesContradictionRule() { - super( - "NURI-CONT-0007", - "Too Many Spaces", - "A region cannot contain more spaces than its number.", - "edu/rpi/legup/images/nurikabe/contradictions/TooManySpaces.png"); + private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; + + public TooManySpacesContradictionRule() { + super( + "NURI-CONT-0007", + "Too Many Spaces", + "A region cannot contain more spaces than its number.", + "edu/rpi/legup/images/nurikabe/contradictions/TooManySpaces.png"); + } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } - - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); - Set whiteRegion = regions.getSet(cell); - ArrayList numberedCells = new ArrayList<>(); - for (NurikabeCell c : whiteRegion) { - if (c.getType() == NurikabeType.NUMBER) { - numberedCells.add(c); - } - } - - for (NurikabeCell number : numberedCells) { - if (whiteRegion.size() > number.getData()) { - return null; - } - } - return super.getNoContradictionMessage() + ":" + this.NO_CONTRADICTION_MESSAGE; + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); + Set whiteRegion = regions.getSet(cell); + ArrayList numberedCells = new ArrayList<>(); + for (NurikabeCell c : whiteRegion) { + if (c.getType() == NurikabeType.NUMBER) { + numberedCells.add(c); + } } + + for (NurikabeCell number : numberedCells) { + if (whiteRegion.size() > number.getData()) { + return null; + } + } + return super.getNoContradictionMessage() + ":" + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java index c578d317f..92b6f8d3e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java @@ -12,97 +12,94 @@ public class UnreachableWhiteCellContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Cell at this index can be reached"; - private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; + private final String NO_CONTRADICTION_MESSAGE = "Cell at this index can be reached"; + private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - public UnreachableWhiteCellContradictionRule() { - super( - "NURI-CONT-0002", - "Unreachable White Cell", - "A white cell must be able to reach a white region", - "edu/rpi/legup/images/nurikabe/contradictions/CantReach.png"); - } + public UnreachableWhiteCellContradictionRule() { + super( + "NURI-CONT-0002", + "Unreachable White Cell", + "A white cell must be able to reach a white region", + "edu/rpi/legup/images/nurikabe/contradictions/CantReach.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - int height = nurikabeBoard.getHeight(); - int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); - // Get regions - HashMap whiteRegionMap = - NurikabeUtilities.getWhiteRegionMap(nurikabeBoard); - if (whiteRegionMap.containsKey(cell)) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - // BFS to a region - - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Get regions + HashMap whiteRegionMap = + NurikabeUtilities.getWhiteRegionMap(nurikabeBoard); + if (whiteRegionMap.containsKey(cell)) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } + // BFS to a region - // Mark the current node as visited and enqueue it - HashMap visited = new HashMap<>(); - visited.put(cell, true); - queue.add(cell); - int pathLength = 1; - while (queue.size() != 0) { - // Set of adjacent squares - Set adj = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - NurikabeCell s = queue.poll(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(nurikabeBoard.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(nurikabeBoard.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(nurikabeBoard.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(nurikabeBoard.getCell(loc.x, loc.y + 1)); - } + // Mark the current node as visited and enqueue it + HashMap visited = new HashMap<>(); + visited.put(cell, true); + queue.add(cell); + int pathLength = 1; + while (queue.size() != 0) { + // Set of adjacent squares + Set adj = new HashSet<>(); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + NurikabeCell s = queue.poll(); - for (NurikabeCell n : adj) { - int regionNeed = whiteRegionMap.getOrDefault(n, -1); - if (pathLength <= regionNeed) { - return super.getNoContradictionMessage() - + ": " - + this.NO_CONTRADICTION_MESSAGE; - } - } - } + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(nurikabeBoard.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(nurikabeBoard.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(nurikabeBoard.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(nurikabeBoard.getCell(loc.x, loc.y + 1)); + } - for (NurikabeCell n : adj) { - if (!visited.getOrDefault(n, false) - && (n.getType() == NurikabeType.UNKNOWN - || n.getType() == NurikabeType.WHITE)) { - visited.put(n, true); - queue.add(n); - } - } - ++pathLength; + for (NurikabeCell n : adj) { + int regionNeed = whiteRegionMap.getOrDefault(n, -1); + if (pathLength <= regionNeed) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } + } - return null; + for (NurikabeCell n : adj) { + if (!visited.getOrDefault(n, false) + && (n.getType() == NurikabeType.UNKNOWN || n.getType() == NurikabeType.WHITE)) { + visited.put(n, true); + queue.add(n); + } + } + ++pathLength; } + + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java index 434e7ccde..2299b4c46 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java @@ -14,59 +14,58 @@ public class WhiteBottleNeckDirectRule extends DirectRule { - public WhiteBottleNeckDirectRule() { - super( - "NURI-BASC-0009", - "White Bottle Neck", - "If a region needs more whites and there is only one path for the region to expand," - + " then those unknowns must be white.", - "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new NoNumberContradictionRule()); - contras.add(new TooFewSpacesContradictionRule()); + public WhiteBottleNeckDirectRule() { + super( + "NURI-BASC-0009", + "White Bottle Neck", + "If a region needs more whites and there is only one path for the region to expand," + + " then those unknowns must be white.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); + } - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new NoNumberContradictionRule()); + contras.add(new TooFewSpacesContradictionRule()); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - for (ContradictionRule contraRule : contras) { - if (contraRule.checkContradiction(modified) == null) { - return null; - } - } - return "This is not the only way for white to escape!"; + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + for (ContradictionRule contraRule : contras) { + if (contraRule.checkContradiction(modified) == null) { return null; + } } + return "This is not the only way for white to escape!"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java index 8b0b8e6d5..4e6f25cba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java @@ -7,104 +7,104 @@ public class ShortTruthTable extends Puzzle { - public ShortTruthTable() { - super(); - - this.name = "ShortTruthTable"; - - this.importer = new ShortTruthTableImporter(this); - this.exporter = new ShortTruthTableExporter(this); - - this.factory = new ShortTruthTableCellFactory(); - } - - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) currentBoard; - boardView = new ShortTruthTableView(sttBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); + public ShortTruthTable() { + super(); + + this.name = "ShortTruthTable"; + + this.importer = new ShortTruthTableImporter(this); + this.exporter = new ShortTruthTableExporter(this); + + this.factory = new ShortTruthTableCellFactory(); + } + + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) currentBoard; + boardView = new ShortTruthTableView(sttBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } + + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } + + @Override + /** + * Determines if the given dimensions are valid for Short Truth Table + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Short Truth Table, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // Number of rows must be odd to allow for proper spacing between the statements + if (rows % 2 != 1) { + return false; } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; + return true; + } + + /** + * Determines if the given statements are valid for Short Truth Table + * + * @param statements + * @return true if the statements are valid for Short Truth Table, false otherwise + */ + public boolean isValidTextInput(String[] statements) { + if (statements.length == 0) { + return false; } - @Override - /** - * Determines if the given dimensions are valid for Short Truth Table - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Short Truth Table, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // Number of rows must be odd to allow for proper spacing between the statements - if (rows % 2 != 1) { - return false; - } - - return true; + ShortTruthTableImporter importer = (ShortTruthTableImporter) this.getImporter(); + for (String s : statements) { + if (!importer.validGrammar(s)) { + return false; + } } - - /** - * Determines if the given statements are valid for Short Truth Table - * - * @param statements - * @return true if the statements are valid for Short Truth Table, false otherwise - */ - public boolean isValidTextInput(String[] statements) { - if (statements.length == 0) { - return false; - } - - ShortTruthTableImporter importer = (ShortTruthTableImporter) this.getImporter(); - for (String s : statements) { - if (!importer.validGrammar(s)) { - return false; - } - } - return true; + return true; + } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + + ShortTruthTableBoard sttboard = (ShortTruthTableBoard) board; + + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(sttboard) == null) { + return false; + } } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - - ShortTruthTableBoard sttboard = (ShortTruthTableBoard) board; - - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(sttboard) == null) { - return false; - } - } - for (PuzzleElement data : sttboard.getPuzzleElements()) { - ShortTruthTableCell cell = (ShortTruthTableCell) data; - if (cell.getType() == ShortTruthTableCellType.UNKNOWN) { - return false; - } - } - return true; + for (PuzzleElement data : sttboard.getPuzzleElements()) { + ShortTruthTableCell cell = (ShortTruthTableCell) data; + if (cell.getType() == ShortTruthTableCellType.UNKNOWN) { + return false; + } } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java index 519a61974..2876523f8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java @@ -10,115 +10,115 @@ public class ShortTruthTableBoard extends GridBoard { - private ShortTruthTableStatement[] statements; + private ShortTruthTableStatement[] statements; - public ShortTruthTableBoard(int width, int height, ShortTruthTableStatement[] statements) { + public ShortTruthTableBoard(int width, int height, ShortTruthTableStatement[] statements) { - super(width, height); + super(width, height); - this.statements = statements; - } + this.statements = statements; + } - public Set getCellsWithSymbol(char symbol) { - Set cells = new HashSet(); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - ShortTruthTableCell cell = (ShortTruthTableCell) getCell(x, y); - if (cell.getSymbol() == symbol) { - cells.add(cell); - } - } + public Set getCellsWithSymbol(char symbol) { + Set cells = new HashSet(); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + ShortTruthTableCell cell = (ShortTruthTableCell) getCell(x, y); + if (cell.getSymbol() == symbol) { + cells.add(cell); } - return cells; - } - - public ShortTruthTableCell getCellFromElement(PuzzleElement element) { - return (ShortTruthTableCell) getPuzzleElement(element); + } } - - @Override - public ShortTruthTableCell getCell(int x, int y) { - return (ShortTruthTableCell) super.getCell(x, y); + return cells; + } + + public ShortTruthTableCell getCellFromElement(PuzzleElement element) { + return (ShortTruthTableCell) getPuzzleElement(element); + } + + @Override + public ShortTruthTableCell getCell(int x, int y) { + return (ShortTruthTableCell) super.getCell(x, y); + } + + @Override + public ShortTruthTableBoard copy() { + + // Copy the statements + ShortTruthTableStatement[] statementsCopy = + new ShortTruthTableStatement[this.statements.length]; + for (int i = 0; i < statements.length; i++) { + statementsCopy[i] = this.statements[i].copy(); } - - @Override - public ShortTruthTableBoard copy() { - - // Copy the statements - ShortTruthTableStatement[] statementsCopy = - new ShortTruthTableStatement[this.statements.length]; - for (int i = 0; i < statements.length; i++) { - statementsCopy[i] = this.statements[i].copy(); - } - // copy the board and set the cells - ShortTruthTableBoard boardCopy = - new ShortTruthTableBoard(getWidth(), getHeight(), statementsCopy); - for (int r = 0; r < this.dimension.height; r++) { - for (int c = 0; c < this.dimension.width; c++) { - if (r % 2 == 0 && c < statementsCopy[r / 2].getLength()) { - boardCopy.setCell(c, r, statementsCopy[r / 2].getCell(c)); - } else { - boardCopy.setCell(c, r, getCell(c, r).copy()); - } - } - } - for (PuzzleElement e : modifiedData) { - boardCopy.getPuzzleElement(e).setModifiable(false); + // copy the board and set the cells + ShortTruthTableBoard boardCopy = + new ShortTruthTableBoard(getWidth(), getHeight(), statementsCopy); + for (int r = 0; r < this.dimension.height; r++) { + for (int c = 0; c < this.dimension.width; c++) { + if (r % 2 == 0 && c < statementsCopy[r / 2].getLength()) { + boardCopy.setCell(c, r, statementsCopy[r / 2].getCell(c)); + } else { + boardCopy.setCell(c, r, getCell(c, r).copy()); } - System.out.println("Board.copy()"); - System.out.println("original:\n" + this); - System.out.println("copy:\n" + boardCopy); - return boardCopy; + } } - - public ShortTruthTableStatement[] getStatements() { - return statements; + for (PuzzleElement e : modifiedData) { + boardCopy.getPuzzleElement(e).setModifiable(false); } - - public static List copyStatementList( - List statements) { - List copy = new ArrayList(); - for (int i = 0; i < statements.size(); i++) { - copy.add(statements.get(i).copy()); - } - return copy; + System.out.println("Board.copy()"); + System.out.println("original:\n" + this); + System.out.println("copy:\n" + boardCopy); + return boardCopy; + } + + public ShortTruthTableStatement[] getStatements() { + return statements; + } + + public static List copyStatementList( + List statements) { + List copy = new ArrayList(); + for (int i = 0; i < statements.size(); i++) { + copy.add(statements.get(i).copy()); } - - // @Override - // public void setPuzzleElement(int index, PuzzleElement element){ - // ShortTruthTableCell cellElement = (ShortTruthTableCell) element; - // ShortTruthTableCell cell = getCell(cellElement.getX(), cellElement.getY()); - // cell.setType(cellElement.getType()); - // } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - int r = cell.getY(); - int c = cell.getX(); - if (r % 2 == 0 && c < statements[r / 2].getLength()) { - statements[r / 2] = statements[r / 2].replace(c, cell); - setCell(c, r, statements[r / 2].getCell(c)); - } - super.notifyChange(cell); + return copy; + } + + // @Override + // public void setPuzzleElement(int index, PuzzleElement element){ + // ShortTruthTableCell cellElement = (ShortTruthTableCell) element; + // ShortTruthTableCell cell = getCell(cellElement.getX(), cellElement.getY()); + // cell.setType(cellElement.getType()); + // } + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + int r = cell.getY(); + int c = cell.getX(); + if (r % 2 == 0 && c < statements[r / 2].getLength()) { + statements[r / 2] = statements[r / 2].replace(c, cell); + setCell(c, r, statements[r / 2].getCell(c)); } - - @Override - public String toString() { - System.out.println("ShortTruthTableBoard toString() called"); - StringBuilder str = new StringBuilder(); - for (int i = 0; i < dimension.height; i += 2) { - for (int j = 0; j < dimension.width; j++) { - ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); - str.append(c.getSymbol()); - } - str.append(" "); - for (int j = 0; j < dimension.width; j++) { - ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); - str.append(ShortTruthTableCellType.toChar(c.getType())); - } - str.append('\n'); - } - return str.toString(); + super.notifyChange(cell); + } + + @Override + public String toString() { + System.out.println("ShortTruthTableBoard toString() called"); + StringBuilder str = new StringBuilder(); + for (int i = 0; i < dimension.height; i += 2) { + for (int j = 0; j < dimension.width; j++) { + ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); + str.append(c.getSymbol()); + } + str.append(" "); + for (int j = 0; j < dimension.width; j++) { + ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); + str.append(ShortTruthTableCellType.toChar(c.getType())); + } + str.append('\n'); } + return str.toString(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java index 75bba369f..a432fe5e4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java @@ -7,211 +7,210 @@ public class ShortTruthTableCell extends GridCell { - // The symbol on the cell - private char symbol; - - // This is a reference to the statement that contains this cell - private ShortTruthTableStatement statement; - - // Constructors - - public ShortTruthTableCell(char symbol, ShortTruthTableCellType cellType, Point location) { - super(cellType, location); - this.symbol = symbol; - } - - /** - * Constructs a new NOT_IN_PLAY Cell - * - * @param location the location of this cell on the board - */ - public ShortTruthTableCell(Point location) { - this(' ', ShortTruthTableCellType.NOT_IN_PLAY, location); - } - - // Getters - - public ShortTruthTableStatement getStatementReference() { - return statement; - } - - public ShortTruthTableCellType getType() { - return data; - } - - public char getSymbol() { - return symbol; - } - - /** - * Returns true if this cell is a letter; false if it is an operation, paren, unused, etc - * - * @return true if cell is a variable; false otherwise - */ - public boolean isVariable() { - return Character.isLetter(symbol); - } - - public int getX() { - return (int) location.getX(); - } - - public int getY() { - return (int) location.getY(); - } - - public boolean isAssigned() { - return getType() == ShortTruthTableCellType.TRUE - || getType() == ShortTruthTableCellType.FALSE; - } - - // Setters - - void setStatementReference(ShortTruthTableStatement statement) { - this.statement = statement; - } - - public void setType(ShortTruthTableCellType type) { - data = type; - } - - public void setGiven(ShortTruthTableCellType type) { - setType(type); - setModifiable(false); - setGiven(true); - } - - // Modifiers - - public void cycleTypeForward() { - switch (data) { - case UNKNOWN: - data = ShortTruthTableCellType.TRUE; - break; - case TRUE: - data = ShortTruthTableCellType.FALSE; - break; - case FALSE: - data = ShortTruthTableCellType.UNKNOWN; - break; - default: - break; - } - } - - public void cycleTypeBackward() { - cycleTypeForward(); - cycleTypeForward(); - } - - // TO STRING - - @Override - public String toString() { - return String.format("STTCell: %c %2d %-11s %s", symbol, index, data, location.toString()); - } - - // Copy function - - @Override - public ShortTruthTableCell copy() { - ShortTruthTableCell copy = new ShortTruthTableCell(symbol, data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } - - /** - * Sets the type of this ShortTruthTableCell - * - * @param e element to set the type of this Short Truth Table cell to - */ - @Override - public void setType(Element e, MouseEvent m) { - // Do not allow odd rows to be modified since they are spacer rows - if (this.getLocation().getY() % 2 == 1) { - return; - } - - // Red Element - if (e.getElementID().equals("STTT-PLAC-0002")) { - this.data = ShortTruthTableCellType.FALSE; + // The symbol on the cell + private char symbol; + + // This is a reference to the statement that contains this cell + private ShortTruthTableStatement statement; + + // Constructors + + public ShortTruthTableCell(char symbol, ShortTruthTableCellType cellType, Point location) { + super(cellType, location); + this.symbol = symbol; + } + + /** + * Constructs a new NOT_IN_PLAY Cell + * + * @param location the location of this cell on the board + */ + public ShortTruthTableCell(Point location) { + this(' ', ShortTruthTableCellType.NOT_IN_PLAY, location); + } + + // Getters + + public ShortTruthTableStatement getStatementReference() { + return statement; + } + + public ShortTruthTableCellType getType() { + return data; + } + + public char getSymbol() { + return symbol; + } + + /** + * Returns true if this cell is a letter; false if it is an operation, paren, unused, etc + * + * @return true if cell is a variable; false otherwise + */ + public boolean isVariable() { + return Character.isLetter(symbol); + } + + public int getX() { + return (int) location.getX(); + } + + public int getY() { + return (int) location.getY(); + } + + public boolean isAssigned() { + return getType() == ShortTruthTableCellType.TRUE || getType() == ShortTruthTableCellType.FALSE; + } + + // Setters + + void setStatementReference(ShortTruthTableStatement statement) { + this.statement = statement; + } + + public void setType(ShortTruthTableCellType type) { + data = type; + } + + public void setGiven(ShortTruthTableCellType type) { + setType(type); + setModifiable(false); + setGiven(true); + } + + // Modifiers + + public void cycleTypeForward() { + switch (data) { + case UNKNOWN: + data = ShortTruthTableCellType.TRUE; + break; + case TRUE: + data = ShortTruthTableCellType.FALSE; + break; + case FALSE: + data = ShortTruthTableCellType.UNKNOWN; + break; + default: + break; + } + } + + public void cycleTypeBackward() { + cycleTypeForward(); + cycleTypeForward(); + } + + // TO STRING + + @Override + public String toString() { + return String.format("STTCell: %c %2d %-11s %s", symbol, index, data, location.toString()); + } + + // Copy function + + @Override + public ShortTruthTableCell copy() { + ShortTruthTableCell copy = new ShortTruthTableCell(symbol, data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } + + /** + * Sets the type of this ShortTruthTableCell + * + * @param e element to set the type of this Short Truth Table cell to + */ + @Override + public void setType(Element e, MouseEvent m) { + // Do not allow odd rows to be modified since they are spacer rows + if (this.getLocation().getY() % 2 == 1) { + return; + } + + // Red Element + if (e.getElementID().equals("STTT-PLAC-0002")) { + this.data = ShortTruthTableCellType.FALSE; + } + // Green Element + else { + if (e.getElementID().equals("STTT-PLAC-0001")) { + this.data = ShortTruthTableCellType.TRUE; + } + // Unknown Element + else { + if (e.getElementID().equals("STTT-PLAC-0003")) { + this.data = ShortTruthTableCellType.UNKNOWN; } - // Green Element + // Argument Element else { - if (e.getElementID().equals("STTT-PLAC-0001")) { - this.data = ShortTruthTableCellType.TRUE; + if (e.getElementID().equals("STTT-UNPL-0001")) { + // Prevents non-argument symbols from being changed + if (!(this.symbol >= 'A' && this.symbol <= 'Z')) { + return; } - // Unknown Element - else { - if (e.getElementID().equals("STTT-PLAC-0003")) { - this.data = ShortTruthTableCellType.UNKNOWN; - } - // Argument Element - else { - if (e.getElementID().equals("STTT-UNPL-0001")) { - // Prevents non-argument symbols from being changed - if (!(this.symbol >= 'A' && this.symbol <= 'Z')) { - return; - } - if (m.getButton() == MouseEvent.BUTTON1) { - this.symbol += 1; - if (this.symbol > 'Z') { - this.symbol = 'A'; - } - } else { - if (m.getButton() == MouseEvent.BUTTON3) { - this.symbol -= 1; - if (this.symbol < 'A') { - this.symbol = 'Z'; - } - } - } + if (m.getButton() == MouseEvent.BUTTON1) { + this.symbol += 1; + if (this.symbol > 'Z') { + this.symbol = 'A'; + } + } else { + if (m.getButton() == MouseEvent.BUTTON3) { + this.symbol -= 1; + if (this.symbol < 'A') { + this.symbol = 'Z'; + } + } + } + } + // And/Or Element + else { + if (e.getElementID().equals("STTT-UNPL-0002")) { + if (m.getButton() == MouseEvent.BUTTON1) { + if (this.symbol == '^') { + this.symbol = '|'; + } else { + if (this.symbol == '|') { + this.symbol = '>'; + } else { + if (this.symbol == '>') { + this.symbol = '-'; + } else { + if (this.symbol == '-') { + this.symbol = '^'; + } } - // And/Or Element - else { - if (e.getElementID().equals("STTT-UNPL-0002")) { - if (m.getButton() == MouseEvent.BUTTON1) { - if (this.symbol == '^') { - this.symbol = '|'; - } else { - if (this.symbol == '|') { - this.symbol = '>'; - } else { - if (this.symbol == '>') { - this.symbol = '-'; - } else { - if (this.symbol == '-') { - this.symbol = '^'; - } - } - } - } - } else { - if (m.getButton() == MouseEvent.BUTTON3) { - if (this.symbol == '^') { - this.symbol = '-'; - } else { - if (this.symbol == '|') { - this.symbol = '^'; - } else { - if (this.symbol == '>') { - this.symbol = '|'; - } else { - if (this.symbol == '-') { - this.symbol = '>'; - } - } - } - } - } - } + } + } + } else { + if (m.getButton() == MouseEvent.BUTTON3) { + if (this.symbol == '^') { + this.symbol = '-'; + } else { + if (this.symbol == '|') { + this.symbol = '^'; + } else { + if (this.symbol == '>') { + this.symbol = '|'; + } else { + if (this.symbol == '-') { + this.symbol = '>'; } + } } + } } + } } + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java index df74afdc9..288fd11f9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java @@ -10,64 +10,61 @@ import org.w3c.dom.Node; public class ShortTruthTableCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public ShortTruthTableCell importCell(Node node, Board board) - throws InvalidFileFormatException { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public ShortTruthTableCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "ShortTruthTable Factory: unknown puzzleElement puzzleElement"); - } + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "ShortTruthTable Factory: unknown puzzleElement puzzleElement"); + } - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board; + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board; - // get the attributes for the cell - NamedNodeMap attributeList = node.getAttributes(); - int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); - int charIndex = - Integer.valueOf(attributeList.getNamedItem("char_index").getNodeValue()); - String cellType = attributeList.getNamedItem("type").getNodeValue(); + // get the attributes for the cell + NamedNodeMap attributeList = node.getAttributes(); + int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); + int charIndex = Integer.valueOf(attributeList.getNamedItem("char_index").getNodeValue()); + String cellType = attributeList.getNamedItem("type").getNodeValue(); - // modify the appropriate cell - ShortTruthTableCell cell = - (ShortTruthTableCell) sttBoard.getCell(charIndex, rowIndex * 2); - cell.setData(ShortTruthTableCellType.valueOf(cellType)); + // modify the appropriate cell + ShortTruthTableCell cell = (ShortTruthTableCell) sttBoard.getCell(charIndex, rowIndex * 2); + cell.setData(ShortTruthTableCellType.valueOf(cellType)); - return cell; + return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); - } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - org.w3c.dom.Element cellElement = document.createElement("cell"); - cellElement.setAttribute("row_index", String.valueOf(cell.getY() / 2)); - cellElement.setAttribute("char_index", String.valueOf(cell.getX())); - cellElement.setAttribute("type", String.valueOf(cell.getType())); + org.w3c.dom.Element cellElement = document.createElement("cell"); + cellElement.setAttribute("row_index", String.valueOf(cell.getY() / 2)); + cellElement.setAttribute("char_index", String.valueOf(cell.getX())); + cellElement.setAttribute("type", String.valueOf(cell.getType())); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java index d5a8292a2..fde55ee3c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java @@ -4,64 +4,64 @@ import java.util.Map; public enum ShortTruthTableCellType { - FALSE(0), - TRUE(1), - UNKNOWN(-1), - NOT_IN_PLAY(-2), - PARENTHESIS(-3); + FALSE(0), + TRUE(1), + UNKNOWN(-1), + NOT_IN_PLAY(-2), + PARENTHESIS(-3); - public int value; - private static Map map = new HashMap<>(); + public int value; + private static Map map = new HashMap<>(); - ShortTruthTableCellType(int value) { - this.value = value; - } + ShortTruthTableCellType(int value) { + this.value = value; + } - static { - for (ShortTruthTableCellType cellType : ShortTruthTableCellType.values()) { - map.put(cellType.value, cellType); - } + static { + for (ShortTruthTableCellType cellType : ShortTruthTableCellType.values()) { + map.put(cellType.value, cellType); } + } - public static ShortTruthTableCellType valueOf(int cellType) { - return (ShortTruthTableCellType) map.get(cellType); - } + public static ShortTruthTableCellType valueOf(int cellType) { + return (ShortTruthTableCellType) map.get(cellType); + } - /** - * Gets the char value of a cell, Used for debugging - * - * @param type cell type input - * @return true if value is 1, false if value is 0, ? if value is -1, or blank otherwise - */ - public static char toChar(ShortTruthTableCellType type) { - if (type == TRUE) return 'T'; - if (type == FALSE) return 'F'; - if (type == UNKNOWN) return '?'; - return ' '; - } + /** + * Gets the char value of a cell, Used for debugging + * + * @param type cell type input + * @return true if value is 1, false if value is 0, ? if value is -1, or blank otherwise + */ + public static char toChar(ShortTruthTableCellType type) { + if (type == TRUE) return 'T'; + if (type == FALSE) return 'F'; + if (type == UNKNOWN) return '?'; + return ' '; + } - /** - * Returns true if this cell holds the value either TRUE or FALSE - * - * @return true if this cell holds the value either TRUE or FALSE - */ - public boolean isTrueOrFalse() { - return value == 0 || value == 1; - } + /** + * Returns true if this cell holds the value either TRUE or FALSE + * + * @return true if this cell holds the value either TRUE or FALSE + */ + public boolean isTrueOrFalse() { + return value == 0 || value == 1; + } - public ShortTruthTableCellType getNegation() { - switch (value) { - case 1: - return ShortTruthTableCellType.FALSE; - case 0: - return ShortTruthTableCellType.TRUE; - default: - throw new RuntimeException("Trying to negate a cell not assigned to true or false"); - } + public ShortTruthTableCellType getNegation() { + switch (value) { + case 1: + return ShortTruthTableCellType.FALSE; + case 0: + return ShortTruthTableCellType.TRUE; + default: + throw new RuntimeException("Trying to negate a cell not assigned to true or false"); } + } - public static ShortTruthTableCellType getDefaultType(char c) { - if (c == '(' || c == ')') return PARENTHESIS; - return UNKNOWN; - } + public static ShortTruthTableCellType getDefaultType(char c) { + if (c == '(' || c == ')') return PARENTHESIS; + return UNKNOWN; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java index 172867f5a..e83c7b358 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java @@ -6,29 +6,29 @@ public class ShortTruthTableController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { - System.out.println("STTController: Cell change"); + System.out.println("STTController: Cell change"); - // cast the data to a short truth table cell - ShortTruthTableCell cell = (ShortTruthTableCell) data; + // cast the data to a short truth table cell + ShortTruthTableCell cell = (ShortTruthTableCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - cell.cycleTypeForward(); - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - cell.cycleTypeBackward(); - } - } + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + cell.cycleTypeForward(); + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + cell.cycleTypeBackward(); + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java index 43e1d2299..af6e412ba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java @@ -6,74 +6,73 @@ public class ShortTruthTableElementView extends GridElementView { - // Font - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; + // Font + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; - // Square Colors - private static final Color TRUE_COLOR = new Color(0, 130, 0); // green - private static final Color TRUE_COLOR_COLORBLIND = new Color(0, 0, 255); - private static final Color FALSE_COLOR = new Color(200, 0, 0); // red + // Square Colors + private static final Color TRUE_COLOR = new Color(0, 130, 0); // green + private static final Color TRUE_COLOR_COLORBLIND = new Color(0, 0, 255); + private static final Color FALSE_COLOR = new Color(200, 0, 0); // red - private static final Color FALSE_COLOR_COLORBLIND = new Color(255, 0, 0); - private static final Color UNKNOWN_COLOR = Color.WHITE; + private static final Color FALSE_COLOR_COLORBLIND = new Color(255, 0, 0); + private static final Color UNKNOWN_COLOR = Color.WHITE; - public ShortTruthTableElementView(ShortTruthTableCell cell) { - super(cell); - } + public ShortTruthTableElementView(ShortTruthTableCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public ShortTruthTableCell getPuzzleElement() { - return (ShortTruthTableCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public ShortTruthTableCell getPuzzleElement() { + return (ShortTruthTableCell) super.getPuzzleElement(); + } - @Override - public void drawElement(Graphics2D graphics2D) { + @Override + public void drawElement(Graphics2D graphics2D) { - // get information about the cell - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - ShortTruthTableCellType type = cell.getData(); + // get information about the cell + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + ShortTruthTableCellType type = cell.getData(); - // do not draw the cell if it is not in play - if (type == ShortTruthTableCellType.NOT_IN_PLAY) return; + // do not draw the cell if it is not in play + if (type == ShortTruthTableCellType.NOT_IN_PLAY) return; - // fill in background color of the cell - graphics2D.setStroke(new BasicStroke(1)); - LegupPreferences prefs = LegupPreferences.getInstance(); - switch (type) { - case TRUE: - if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - graphics2D.setColor(TRUE_COLOR_COLORBLIND); - break; - } - graphics2D.setColor(TRUE_COLOR); - break; - case FALSE: - if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - graphics2D.setColor(FALSE_COLOR_COLORBLIND); - break; - } - graphics2D.setColor(FALSE_COLOR); - break; - default: - graphics2D.setColor(UNKNOWN_COLOR); - break; + // fill in background color of the cell + graphics2D.setStroke(new BasicStroke(1)); + LegupPreferences prefs = LegupPreferences.getInstance(); + switch (type) { + case TRUE: + if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + graphics2D.setColor(TRUE_COLOR_COLORBLIND); + break; } - graphics2D.fillRect(location.x, location.y, size.width, size.height); - - // Draw the symbol on the cell - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getSymbol()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString( - ShortTruthTableOperation.getLogicSymbol(cell.getSymbol()), xText, yText); + graphics2D.setColor(TRUE_COLOR); + break; + case FALSE: + if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + graphics2D.setColor(FALSE_COLOR_COLORBLIND); + break; + } + graphics2D.setColor(FALSE_COLOR); + break; + default: + graphics2D.setColor(UNKNOWN_COLOR); + break; } + graphics2D.fillRect(location.x, location.y, size.width, size.height); + + // Draw the symbol on the cell + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getSymbol()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(ShortTruthTableOperation.getLogicSymbol(cell.getSymbol()), xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java index 0914c159a..a3c2c6918 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java @@ -6,41 +6,40 @@ public class ShortTruthTableExporter extends PuzzleExporter { - public ShortTruthTableExporter(ShortTruthTable stt) { - super(stt); + public ShortTruthTableExporter(ShortTruthTable stt) { + super(stt); + } + + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + ShortTruthTableBoard board; + if (puzzle.getTree() != null) { + board = (ShortTruthTableBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (ShortTruthTableBoard) puzzle.getBoardView().getBoard(); } - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - ShortTruthTableBoard board; - if (puzzle.getTree() != null) { - board = (ShortTruthTableBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (ShortTruthTableBoard) puzzle.getBoardView().getBoard(); - } - - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - - org.w3c.dom.Element dataElement = newDocument.createElement("data"); - - ShortTruthTableStatement[] statements = board.getStatements(); - for (int i = 0; i < statements.length; i++) { - org.w3c.dom.Element statementElement = newDocument.createElement("statement"); - statementElement.setAttribute("representation", statements[i].getStringRep()); - statementElement.setAttribute("row_index", String.valueOf(i)); - dataElement.appendChild(statementElement); - } - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - ShortTruthTableCell cell = board.getCellFromElement(puzzleElement); - if (!cell.getType().isTrueOrFalse()) continue; - - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - dataElement.appendChild(cellElement); - } - - boardElement.appendChild(dataElement); - return boardElement; + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + + org.w3c.dom.Element dataElement = newDocument.createElement("data"); + + ShortTruthTableStatement[] statements = board.getStatements(); + for (int i = 0; i < statements.length; i++) { + org.w3c.dom.Element statementElement = newDocument.createElement("statement"); + statementElement.setAttribute("representation", statements[i].getStringRep()); + statementElement.setAttribute("row_index", String.valueOf(i)); + dataElement.appendChild(statementElement); + } + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + ShortTruthTableCell cell = board.getCellFromElement(puzzleElement); + if (!cell.getType().isTrueOrFalse()) continue; + + org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); + dataElement.appendChild(cellElement); } + + boardElement.appendChild(dataElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java index 396668380..979bd8d30 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java @@ -14,347 +14,335 @@ class ShortTruthTableImporter extends PuzzleImporter { - public ShortTruthTableImporter(ShortTruthTable stt) { - super(stt); + public ShortTruthTableImporter(ShortTruthTable stt) { + super(stt); + } + + /** + * Parse a string into all the cells, the y position of the statement is passed so the y position + * can be set + * + * @param statement + * @param y + * @return + */ + private List getCells(String statement, int y) { + List cells = new ArrayList(); + // go through each char in the statement and make a cell for it + for (int i = 0; i < statement.length(); i++) { + char c = statement.charAt(i); + ShortTruthTableCell cell = + new ShortTruthTableCell(c, ShortTruthTableCellType.getDefaultType(c), new Point(i, y)); + // it is modifiable if the type is unknown + cell.setModifiable(cell.getType() == ShortTruthTableCellType.UNKNOWN); + cells.add(cell); } - - /** - * Parse a string into all the cells, the y position of the statement is passed so the y - * position can be set - * - * @param statement - * @param y - * @return - */ - private List getCells(String statement, int y) { - List cells = new ArrayList(); - // go through each char in the statement and make a cell for it - for (int i = 0; i < statement.length(); i++) { - char c = statement.charAt(i); - ShortTruthTableCell cell = - new ShortTruthTableCell( - c, ShortTruthTableCellType.getDefaultType(c), new Point(i, y)); - // it is modifiable if the type is unknown - cell.setModifiable(cell.getType() == ShortTruthTableCellType.UNKNOWN); - cells.add(cell); - } - return cells; + return cells; + } + + /** + * Parses the statementData into all the cells (with symbols) and statements for the puzzle. All + * cells are set to UNKNWON, it their value is given, it will be set later in the import process. + * + *

Both allCells and statements act as returns, They should be passed as empty arrays + * + * @param statementData The data to be imported + * @param allCells returns all the cells as a jagged 2d array + * @param statements returns all the statements + * @return the length, in chars, of the longest statement + */ + private int parseAllStatementsAndCells( + final NodeList statementData, + List> allCells, + List statements) + throws InvalidFileFormatException { + + int maxStatementLength = 0; + + // get a 2D arraylist of all the cells + for (int i = 0; i < statementData.getLength(); i++) { + + // Get the atributes from the statement i in the file + NamedNodeMap attributeList = statementData.item(i).getAttributes(); + + String statementRep = attributeList.getNamedItem("representation").getNodeValue(); + System.out.println("STATEMENT REP: " + statementRep); + System.out.println("ROW INDEX: " + attributeList.getNamedItem("row_index").getNodeValue()); + // parser time (on statementRep) + // if (!validGrammar(statementRep)) throw some error + if (!validGrammar(statementRep)) { + JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); + throw new InvalidFileFormatException("shorttruthtable importer: invalid sentence syntax"); + } + int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); + + // get the cells for the statement + List rowOfCells = getCells(statementRep, rowIndex * 2); + allCells.add(rowOfCells); + statements.add(new ShortTruthTableStatement(statementRep, rowOfCells)); + + // keep track of the length of the longest statement + maxStatementLength = Math.max(maxStatementLength, statementRep.length()); } - /** - * Parses the statementData into all the cells (with symbols) and statements for the puzzle. All - * cells are set to UNKNWON, it their value is given, it will be set later in the import - * process. - * - *

Both allCells and statements act as returns, They should be passed as empty arrays - * - * @param statementData The data to be imported - * @param allCells returns all the cells as a jagged 2d array - * @param statements returns all the statements - * @return the length, in chars, of the longest statement - */ - private int parseAllStatementsAndCells( - final NodeList statementData, - List> allCells, - List statements) - throws InvalidFileFormatException { - - int maxStatementLength = 0; - - // get a 2D arraylist of all the cells - for (int i = 0; i < statementData.getLength(); i++) { - - // Get the atributes from the statement i in the file - NamedNodeMap attributeList = statementData.item(i).getAttributes(); - - String statementRep = attributeList.getNamedItem("representation").getNodeValue(); - System.out.println("STATEMENT REP: " + statementRep); - System.out.println( - "ROW INDEX: " + attributeList.getNamedItem("row_index").getNodeValue()); - // parser time (on statementRep) - // if (!validGrammar(statementRep)) throw some error - if (!validGrammar(statementRep)) { - JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); - throw new InvalidFileFormatException( - "shorttruthtable importer: invalid sentence syntax"); - } - int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); - - // get the cells for the statement - List rowOfCells = getCells(statementRep, rowIndex * 2); - allCells.add(rowOfCells); - statements.add(new ShortTruthTableStatement(statementRep, rowOfCells)); - - // keep track of the length of the longest statement - maxStatementLength = Math.max(maxStatementLength, statementRep.length()); - } - - return maxStatementLength; + return maxStatementLength; + } + + private int parseAllStatementsAndCells( + String[] statementData, + List> allCells, + List statements) + throws IllegalArgumentException { + int maxStatementLength = 0; + + for (int i = 0; i < statementData.length; i++) { + if (!validGrammar(statementData[i])) { + JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); + throw new IllegalArgumentException("shorttruthtable importer: invalid sentence syntax"); + } + + // get the cells for the statement + List rowOfCells = getCells(statementData[i], i * 2); + allCells.add(rowOfCells); + statements.add(new ShortTruthTableStatement(statementData[i], rowOfCells)); + + // keep track of the length of the longest statement + maxStatementLength = Math.max(maxStatementLength, statementData[i].length()); } - private int parseAllStatementsAndCells( - String[] statementData, - List> allCells, - List statements) - throws IllegalArgumentException { - int maxStatementLength = 0; - - for (int i = 0; i < statementData.length; i++) { - if (!validGrammar(statementData[i])) { - JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); - throw new IllegalArgumentException( - "shorttruthtable importer: invalid sentence syntax"); - } - - // get the cells for the statement - List rowOfCells = getCells(statementData[i], i * 2); - allCells.add(rowOfCells); - statements.add(new ShortTruthTableStatement(statementData[i], rowOfCells)); - - // keep track of the length of the longest statement - maxStatementLength = Math.max(maxStatementLength, statementData[i].length()); + return maxStatementLength; + } + + protected boolean validGrammar(String sentence) { + int open = 0; + int close = 0; + char[] valid_characters = new char[] {'^', 'v', '!', '>', '-', '&', '|', '~', '$', '%'}; + for (int i = 0; i < sentence.length(); i++) { + char s = sentence.charAt(i); + if (s == '(' || s == ')') { + switch (s) { + case ')': + close++; + break; + case '(': + open++; + break; } - - return maxStatementLength; - } - - protected boolean validGrammar(String sentence) { - int open = 0; - int close = 0; - char[] valid_characters = new char[] {'^', 'v', '!', '>', '-', '&', '|', '~', '$', '%'}; - for (int i = 0; i < sentence.length(); i++) { - char s = sentence.charAt(i); - if (s == '(' || s == ')') { - switch (s) { - case ')': - close++; - break; - case '(': - open++; - break; - } - continue; - } - if (!Character.isLetter(s)) { - boolean valid = false; - for (char c : valid_characters) { - if (c == s) { - valid = true; - break; - } - } - if (!valid) { - System.out.println("Invalid character"); - System.out.println(s); - return false; - } - if (i != sentence.length() - 1) { - char next = sentence.charAt(i + 1); - if (next != '!' && next != '~') { - for (char c : valid_characters) { - if (c == next) { - System.out.println("Invalid next character"); - System.out.println(s); - System.out.println(next); - return false; - } - } - } - } - } else { - if (i != sentence.length() - 1) { - if (Character.isLetter(sentence.charAt(i + 1))) { - System.out.println("Invalid next character"); - System.out.println(s); - System.out.println(sentence.charAt(i + 1)); - return false; - } - } - } + continue; + } + if (!Character.isLetter(s)) { + boolean valid = false; + for (char c : valid_characters) { + if (c == s) { + valid = true; + break; + } } - return open == close; - } - - private ShortTruthTableBoard generateBoard( - List> allCells, - List statements, - int width) { - - // calculate the height for the board - int height = statements.size() * 2 - 1; - - // instantiate the board with the correct width and height - ShortTruthTableBoard sttBoard = - new ShortTruthTableBoard( - width, - height, - statements.toArray(new ShortTruthTableStatement[statements.size()])); - - // set the cells in the board. create not_in_play cells where needed - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - - // get the statement index for this row of the table - int statementIndex = y / 2; - - // get the cell at this location; or create a not_in_play one if necessary - ShortTruthTableCell cell = null; - - // for a cell to exist at (x, y), it must be a valid row and within the statement - // length - if (y % 2 == 0 && x < statements.get(statementIndex).getLength()) { - cell = allCells.get(statementIndex).get(x); - System.out.println( - "Importer: check cell statement ref: " + cell.getStatementReference()); - } else { - // if it is not a valid cell space, add a NOT_IN_PLAY cell - cell = - new ShortTruthTableCell( - ' ', ShortTruthTableCellType.NOT_IN_PLAY, new Point(x, y)); - cell.setModifiable(false); - } - - // add the cell to the table - cell.setIndex(y * width + x); - sttBoard.setCell(x, y, cell); - } + if (!valid) { + System.out.println("Invalid character"); + System.out.println(s); + return false; } - - return sttBoard; - } - - private void setGivenCells( - ShortTruthTableBoard sttBoard, - Element dataElement, - NodeList cellData, - List statements) - throws InvalidFileFormatException { - - // if it is normal, set all predicates to true and the conclusion to false - if (dataElement.getAttribute("normal").equalsIgnoreCase("true")) { - // set all predicates to true (all but the last one) - for (int i = 0; i < statements.size() - 1; i++) { - statements.get(i).getCell().setGiven(ShortTruthTableCellType.TRUE); + if (i != sentence.length() - 1) { + char next = sentence.charAt(i + 1); + if (next != '!' && next != '~') { + for (char c : valid_characters) { + if (c == next) { + System.out.println("Invalid next character"); + System.out.println(s); + System.out.println(next); + return false; + } } - // set the conclusion to false (the last one) - statements.get(statements.size() - 1).getCell().setGiven(ShortTruthTableCellType.FALSE); + } } - - // set the given cell values - for (int i = 0; i < cellData.getLength(); i++) { - // set the value with the factory importer - ShortTruthTableCell cell = - (ShortTruthTableCell) - puzzle.getFactory().importCell(cellData.item(i), sttBoard); - // set the modifiable and given flags - cell.setModifiable(false); - cell.setGiven(true); + } else { + if (i != sentence.length() - 1) { + if (Character.isLetter(sentence.charAt(i + 1))) { + System.out.println("Invalid next character"); + System.out.println(s); + System.out.println(sentence.charAt(i + 1)); + return false; + } } + } } + return open == close; + } + + private ShortTruthTableBoard generateBoard( + List> allCells, + List statements, + int width) { + + // calculate the height for the board + int height = statements.size() * 2 - 1; + + // instantiate the board with the correct width and height + ShortTruthTableBoard sttBoard = + new ShortTruthTableBoard( + width, height, statements.toArray(new ShortTruthTableStatement[statements.size()])); + + // set the cells in the board. create not_in_play cells where needed + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + + // get the statement index for this row of the table + int statementIndex = y / 2; + + // get the cell at this location; or create a not_in_play one if necessary + ShortTruthTableCell cell = null; + + // for a cell to exist at (x, y), it must be a valid row and within the statement + // length + if (y % 2 == 0 && x < statements.get(statementIndex).getLength()) { + cell = allCells.get(statementIndex).get(x); + System.out.println("Importer: check cell statement ref: " + cell.getStatementReference()); + } else { + // if it is not a valid cell space, add a NOT_IN_PLAY cell + cell = new ShortTruthTableCell(' ', ShortTruthTableCellType.NOT_IN_PLAY, new Point(x, y)); + cell.setModifiable(false); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return false; + // add the cell to the table + cell.setIndex(y * width + x); + sttBoard.setCell(x, y, cell); + } } - @Override - public boolean acceptsTextInput() { - return true; + return sttBoard; + } + + private void setGivenCells( + ShortTruthTableBoard sttBoard, + Element dataElement, + NodeList cellData, + List statements) + throws InvalidFileFormatException { + + // if it is normal, set all predicates to true and the conclusion to false + if (dataElement.getAttribute("normal").equalsIgnoreCase("true")) { + // set all predicates to true (all but the last one) + for (int i = 0; i < statements.size() - 1; i++) { + statements.get(i).getCell().setGiven(ShortTruthTableCellType.TRUE); + } + // set the conclusion to false (the last one) + statements.get(statements.size() - 1).getCell().setGiven(ShortTruthTableCellType.FALSE); } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException - */ - @Override - public void initializeBoard(int rows, int columns) {} - - // STATEMENT IMPORTER - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - - try { - - // Check File formatting - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "short truth table Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("data").getLength() == 0) { - throw new InvalidFileFormatException( - "short truth table Importer: no statements found for board"); - } - - // get all the cells in a 2D arraylist - List> allCells = new ArrayList>(); - // store the statement data structors - List statements = new ArrayList(); - - // get the elements from the file - Element dataElement = (Element) boardElement.getElementsByTagName("data").item(0); - NodeList statementData = dataElement.getElementsByTagName("statement"); - NodeList cellData = dataElement.getElementsByTagName("cell"); - - // Parse the data - int maxStatementLength = - parseAllStatementsAndCells(statementData, allCells, statements); - - // generate the board - ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); - - // set the given cell values - setGivenCells(sttBoard, dataElement, cellData, statements); - - puzzle.setCurrentBoard(sttBoard); - - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "short truth table Importer: unknown value where integer expected"); - } + // set the given cell values + for (int i = 0; i < cellData.getLength(); i++) { + // set the value with the factory importer + ShortTruthTableCell cell = + (ShortTruthTableCell) puzzle.getFactory().importCell(cellData.item(i), sttBoard); + // set the modifiable and given flags + cell.setModifiable(false); + cell.setGiven(true); } + } + + @Override + public boolean acceptsRowsAndColumnsInput() { + return false; + } + + @Override + public boolean acceptsTextInput() { + return true; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException + */ + @Override + public void initializeBoard(int rows, int columns) {} + + // STATEMENT IMPORTER + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + + try { + + // Check File formatting + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "short truth table Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("data").getLength() == 0) { + throw new InvalidFileFormatException( + "short truth table Importer: no statements found for board"); + } + + // get all the cells in a 2D arraylist + List> allCells = new ArrayList>(); + // store the statement data structors + List statements = new ArrayList(); + + // get the elements from the file + Element dataElement = (Element) boardElement.getElementsByTagName("data").item(0); + NodeList statementData = dataElement.getElementsByTagName("statement"); + NodeList cellData = dataElement.getElementsByTagName("cell"); + + // Parse the data + int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); + + // generate the board + ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); + + // set the given cell values + setGivenCells(sttBoard, dataElement, cellData, statements); + + puzzle.setCurrentBoard(sttBoard); + + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "short truth table Importer: unknown value where integer expected"); + } + } + + /** + * Creates the board for building using statements + * + * @param statementInput + * @throws UnsupportedOperationException + * @throws IllegalArgumentException + */ + public void initializeBoard(String[] statementInput) + throws UnsupportedOperationException, IllegalArgumentException { + List statementsList = new LinkedList<>(); + for (String s : statementInput) { + if (s.strip().length() > 0) { + statementsList.add(s); + } + } + String[] statementData = statementsList.toArray(new String[statementsList.size()]); - /** - * Creates the board for building using statements - * - * @param statementInput - * @throws UnsupportedOperationException - * @throws IllegalArgumentException - */ - public void initializeBoard(String[] statementInput) - throws UnsupportedOperationException, IllegalArgumentException { - List statementsList = new LinkedList<>(); - for (String s : statementInput) { - if (s.strip().length() > 0) { - statementsList.add(s); - } - } - String[] statementData = statementsList.toArray(new String[statementsList.size()]); - - if (statementData.length == 0) { - throw new IllegalArgumentException( - "short truth table Importer: no statements found for board"); - } + if (statementData.length == 0) { + throw new IllegalArgumentException( + "short truth table Importer: no statements found for board"); + } - // Store all cells and statements - List> allCells = new ArrayList<>(); - List statements = new ArrayList<>(); + // Store all cells and statements + List> allCells = new ArrayList<>(); + List statements = new ArrayList<>(); - // Parse the data - int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); + // Parse the data + int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); - // Generate and set the board - don't set given cell values since none are given - ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); - puzzle.setCurrentBoard(sttBoard); - } + // Generate and set the board - don't set given cell values since none are given + ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); + puzzle.setCurrentBoard(sttBoard); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java index 8284474da..1a5fd3a12 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java @@ -2,47 +2,47 @@ public class ShortTruthTableOperation { - public static final char AND = '^'; - public static final char OR = '|'; - public static final char NOT = '~'; - public static final char CONDITIONAL = '>'; - public static final char BICONDITIONAL = '-'; + public static final char AND = '^'; + public static final char OR = '|'; + public static final char NOT = '~'; + public static final char CONDITIONAL = '>'; + public static final char BICONDITIONAL = '-'; - private ShortTruthTableOperation() {} + private ShortTruthTableOperation() {} - public static String getLogicSymbol(char c) { - switch (c) { - case AND: - return "\u2227"; - case OR: - return "\u2228"; - case NOT: - return "\u00AC"; - case CONDITIONAL: - return "\u2192"; - case BICONDITIONAL: - return "\u2194"; - } - return "" + c; + public static String getLogicSymbol(char c) { + switch (c) { + case AND: + return "\u2227"; + case OR: + return "\u2228"; + case NOT: + return "\u00AC"; + case CONDITIONAL: + return "\u2192"; + case BICONDITIONAL: + return "\u2194"; } + return "" + c; + } - public static String getRuleName(char operation) { - switch (operation) { - case AND: - return "And"; - case OR: - return "Or"; - case NOT: - return "Not"; - case CONDITIONAL: - return "Conditional"; - case BICONDITIONAL: - return "Biconditional"; - } - return null; + public static String getRuleName(char operation) { + switch (operation) { + case AND: + return "And"; + case OR: + return "Or"; + case NOT: + return "Not"; + case CONDITIONAL: + return "Conditional"; + case BICONDITIONAL: + return "Biconditional"; } + return null; + } - public static boolean isOperation(char c) { - return c == AND || c == OR || c == NOT || c == CONDITIONAL || c == BICONDITIONAL; - } + public static boolean isOperation(char c) { + return c == AND || c == OR || c == NOT || c == CONDITIONAL || c == BICONDITIONAL; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java index 2059e3ca5..2733b07ee 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java @@ -9,292 +9,292 @@ public class ShortTruthTableStatement extends PuzzleElement { - // the cell that this statement holds - private final ShortTruthTableCell cell; - - // child nodes of the tree - private final ShortTruthTableStatement parentStatement; - private final ShortTruthTableStatement leftStatement; - private final ShortTruthTableStatement rightStatement; - - // the representation string for this statement - private final String stringRep; - private final List cells; - - // constructor for root statement, sets parent to null - public ShortTruthTableStatement(String statement, List cells) { - this(statement, null, cells); + // the cell that this statement holds + private final ShortTruthTableCell cell; + + // child nodes of the tree + private final ShortTruthTableStatement parentStatement; + private final ShortTruthTableStatement leftStatement; + private final ShortTruthTableStatement rightStatement; + + // the representation string for this statement + private final String stringRep; + private final List cells; + + // constructor for root statement, sets parent to null + public ShortTruthTableStatement(String statement, List cells) { + this(statement, null, cells); + } + + // recursive constructor; constructs child statement nodes if necessary + private ShortTruthTableStatement( + String statement, ShortTruthTableStatement parent, List cells) { + + this.parentStatement = parent; + + // set the string rep to the statement (include parens in case this is a sub statement) + this.stringRep = statement; + this.cells = new ArrayList(cells); + + // remove the parens for parsing the statement + statement = removeParens(statement); + removeParens(cells); + + // get the index of the char that this statement represents + int index = parse(statement); + + // construct the cell for this node in the tree + cell = cells.get(index); + // give the cell a reference back to this statement + cell.setStatementReference(this); + + // get the strings on either side of this char in the string rep + String left = statement.substring(0, index); + String right = statement.substring(index + 1); + + List leftCells = + new ArrayList(cells.subList(0, index)); + List rightCells = + new ArrayList(cells.subList(index + 1, cells.size())); + + // construct sub-statements if necessary + if (left.length() > 0) { + leftStatement = new ShortTruthTableStatement(left, this, leftCells); + } else { + leftStatement = null; } - // recursive constructor; constructs child statement nodes if necessary - private ShortTruthTableStatement( - String statement, ShortTruthTableStatement parent, List cells) { - - this.parentStatement = parent; - - // set the string rep to the statement (include parens in case this is a sub statement) - this.stringRep = statement; - this.cells = new ArrayList(cells); - - // remove the parens for parsing the statement - statement = removeParens(statement); - removeParens(cells); - - // get the index of the char that this statement represents - int index = parse(statement); - - // construct the cell for this node in the tree - cell = cells.get(index); - // give the cell a reference back to this statement - cell.setStatementReference(this); - - // get the strings on either side of this char in the string rep - String left = statement.substring(0, index); - String right = statement.substring(index + 1); - - List leftCells = - new ArrayList(cells.subList(0, index)); - List rightCells = - new ArrayList(cells.subList(index + 1, cells.size())); - - // construct sub-statements if necessary - if (left.length() > 0) { - leftStatement = new ShortTruthTableStatement(left, this, leftCells); - } else { - leftStatement = null; - } - - if (right.length() > 0) { - rightStatement = new ShortTruthTableStatement(right, this, rightCells); - } else { - rightStatement = null; - } + if (right.length() > 0) { + rightStatement = new ShortTruthTableStatement(right, this, rightCells); + } else { + rightStatement = null; } + } - // parsing for the constructor - static String removeParens(String statement) { + // parsing for the constructor + static String removeParens(String statement) { - if (statement.charAt(0) != '(') { - return statement; - } - - // if the statement does start with a paren, check that it matches with the last paren - int openParenCount = 1; - int i = 1; - while (i < statement.length() - 1) { - char c = statement.charAt(i); - if (c == '(') { - openParenCount++; - } else { - if (c == ')') openParenCount--; - } - - // if the first paren has been closed, and it is not the end of the string, - // then there is no whole statement parens to remove - if (openParenCount == 0 && i != statement.length() - 1) { - return statement; - } - - i++; - } - // if the while loop made it through the entire statement, there are parens around the whole - // thing - return statement.substring(1, statement.length() - 1); + if (statement.charAt(0) != '(') { + return statement; } - int parse(String statement) { - - // Split by and, or, CONDITIONAL, or biconditional - // keep track of the parens, it must be equal to zero to split - int openParenCount = 0; - // index for stepping through the string - int i = 0; - // step through each char in the statement - while (i < statement.length()) { - // get the char - char c = statement.charAt(i); - // keep track of the open parens - if (c == '(') { - openParenCount++; - } else { - if (c == ')') { - openParenCount--; - } - // if the char is an operator, and there are no open parens, split the statement - // here - else { - if (openParenCount == 0 - && ShortTruthTableOperation.isOperation(c) - && c != ShortTruthTableOperation.NOT) { - return i; - } - } - } - // increment the index - i++; - } - - // if it made it through the while loop: - // this is an atomic statement or a negation - // either way, the important char is the first character in the string - return 0; + // if the statement does start with a paren, check that it matches with the last paren + int openParenCount = 1; + int i = 1; + while (i < statement.length() - 1) { + char c = statement.charAt(i); + if (c == '(') { + openParenCount++; + } else { + if (c == ')') openParenCount--; + } + + // if the first paren has been closed, and it is not the end of the string, + // then there is no whole statement parens to remove + if (openParenCount == 0 && i != statement.length() - 1) { + return statement; + } + + i++; } - - static void removeParens(List cells) { - - if (cells.get(0).getSymbol() != '(') { - return; + // if the while loop made it through the entire statement, there are parens around the whole + // thing + return statement.substring(1, statement.length() - 1); + } + + int parse(String statement) { + + // Split by and, or, CONDITIONAL, or biconditional + // keep track of the parens, it must be equal to zero to split + int openParenCount = 0; + // index for stepping through the string + int i = 0; + // step through each char in the statement + while (i < statement.length()) { + // get the char + char c = statement.charAt(i); + // keep track of the open parens + if (c == '(') { + openParenCount++; + } else { + if (c == ')') { + openParenCount--; } - - // if the statement does start with a paren, check that it matches with the last paren - int openParenCount = 1; - int i = 1; - while (i < cells.size() - 1) { - char c = cells.get(i).getSymbol(); - if (c == '(') { - openParenCount++; - } else { - if (c == ')') openParenCount--; - } - - // if the first paren has been closed, and it is not the end of the string, - // then there is no whole statement parens to remove - if (openParenCount == 0 && i != cells.size() - 1) { - return; - } - - i++; + // if the char is an operator, and there are no open parens, split the statement + // here + else { + if (openParenCount == 0 + && ShortTruthTableOperation.isOperation(c) + && c != ShortTruthTableOperation.NOT) { + return i; + } } - - // if the while loop made it through the entire statement, there are parens around the whole - // thing - cells.remove(cells.size() - 1); - cells.remove(0); + } + // increment the index + i++; } - // Getters + // if it made it through the while loop: + // this is an atomic statement or a negation + // either way, the important char is the first character in the string + return 0; + } - public ShortTruthTableCell getCell() { - return cell; - } + static void removeParens(List cells) { - public ShortTruthTableStatement getLeftStatement() { - return leftStatement; + if (cells.get(0).getSymbol() != '(') { + return; } - public ShortTruthTableStatement getRightStatement() { - return rightStatement; + // if the statement does start with a paren, check that it matches with the last paren + int openParenCount = 1; + int i = 1; + while (i < cells.size() - 1) { + char c = cells.get(i).getSymbol(); + if (c == '(') { + openParenCount++; + } else { + if (c == ')') openParenCount--; + } + + // if the first paren has been closed, and it is not the end of the string, + // then there is no whole statement parens to remove + if (openParenCount == 0 && i != cells.size() - 1) { + return; + } + + i++; } - public ShortTruthTableStatement getParentStatement() { - return parentStatement; - } + // if the while loop made it through the entire statement, there are parens around the whole + // thing + cells.remove(cells.size() - 1); + cells.remove(0); + } - @Override - public String toString() { - if (this.parentStatement == null) { - return "SST_Statement: " + stringRep + " parent: null"; - } - return "SST_Statement: " + stringRep + " parent: " + parentStatement.stringRep; - } + // Getters - public String getStringRep() { - return this.stringRep; - } + public ShortTruthTableCell getCell() { + return cell; + } - /** - * Returns the length of the statement in cells. This includes all cells used for parenthesis - * - * @return the number of cells contained in this statement - */ - public int getLength() { - return stringRep.length(); - } + public ShortTruthTableStatement getLeftStatement() { + return leftStatement; + } - public ShortTruthTableCell getCell(int i) { - return cells.get(i); - } + public ShortTruthTableStatement getRightStatement() { + return rightStatement; + } - // Getters (recursive) - - // returns all cells in this statement with the symbol 'symbol'; runs recursively on both sides - // of - // the tree - public Set getCellsWithSymbol(char symbol) { - Set set = new HashSet(getLength()); - if (cell.getSymbol() == symbol) set.add(cell); - if (leftStatement != null) set.addAll(leftStatement.getCellsWithSymbol(symbol)); - if (rightStatement != null) set.addAll(rightStatement.getCellsWithSymbol(symbol)); - return set; - } + public ShortTruthTableStatement getParentStatement() { + return parentStatement; + } - /** - * Returns an array of three elements where [0] is the left statement type, [1] is this - * statement type, and [2] is the right statement type. null means either the statement doesn't - * exist or is an unknown value. - * - * @return the assigned values to this statement and its sub-statements - */ - public ShortTruthTableCellType[] getCellTypePattern() { - // get this type and the right type, they will always be used - ShortTruthTableCellType type = this.cell.getType(); - System.out.println("Right statement: " + rightStatement.getCell()); - ShortTruthTableCellType rightType = this.rightStatement.getCell().getType(); - System.out.println("Right type: " + rightType); - // if this is a not statement, there is no left side - if (cell.getSymbol() == ShortTruthTableOperation.NOT) { - return new ShortTruthTableCellType[] {null, type, rightType}; - } - // if it is any other operation, get the left side too and return it - ShortTruthTableCellType leftType = this.leftStatement.getCell().getType(); - return new ShortTruthTableCellType[] {leftType, type, rightType}; + @Override + public String toString() { + if (this.parentStatement == null) { + return "SST_Statement: " + stringRep + " parent: null"; } - - // Setters - - private void setCellLocations(int rowIndex, int offset) { - // set the location of this cell - int xLoc = offset; - if (leftStatement != null) { - xLoc += leftStatement.getLength(); - } - cell.setLocation(new Point(xLoc, rowIndex)); - // recurse on both sides of the tree - if (leftStatement != null) { - leftStatement.setCellLocations(rowIndex, offset); - } - if (rightStatement != null) { - rightStatement.setCellLocations(rowIndex, xLoc + 1); - } + return "SST_Statement: " + stringRep + " parent: " + parentStatement.stringRep; + } + + public String getStringRep() { + return this.stringRep; + } + + /** + * Returns the length of the statement in cells. This includes all cells used for parenthesis + * + * @return the number of cells contained in this statement + */ + public int getLength() { + return stringRep.length(); + } + + public ShortTruthTableCell getCell(int i) { + return cells.get(i); + } + + // Getters (recursive) + + // returns all cells in this statement with the symbol 'symbol'; runs recursively on both sides + // of + // the tree + public Set getCellsWithSymbol(char symbol) { + Set set = new HashSet(getLength()); + if (cell.getSymbol() == symbol) set.add(cell); + if (leftStatement != null) set.addAll(leftStatement.getCellsWithSymbol(symbol)); + if (rightStatement != null) set.addAll(rightStatement.getCellsWithSymbol(symbol)); + return set; + } + + /** + * Returns an array of three elements where [0] is the left statement type, [1] is this statement + * type, and [2] is the right statement type. null means either the statement doesn't exist or is + * an unknown value. + * + * @return the assigned values to this statement and its sub-statements + */ + public ShortTruthTableCellType[] getCellTypePattern() { + // get this type and the right type, they will always be used + ShortTruthTableCellType type = this.cell.getType(); + System.out.println("Right statement: " + rightStatement.getCell()); + ShortTruthTableCellType rightType = this.rightStatement.getCell().getType(); + System.out.println("Right type: " + rightType); + // if this is a not statement, there is no left side + if (cell.getSymbol() == ShortTruthTableOperation.NOT) { + return new ShortTruthTableCellType[] {null, type, rightType}; } - - public void setCellLocations(int rowIndex) { - setCellLocations(rowIndex, 0); + // if it is any other operation, get the left side too and return it + ShortTruthTableCellType leftType = this.leftStatement.getCell().getType(); + return new ShortTruthTableCellType[] {leftType, type, rightType}; + } + + // Setters + + private void setCellLocations(int rowIndex, int offset) { + // set the location of this cell + int xLoc = offset; + if (leftStatement != null) { + xLoc += leftStatement.getLength(); } - - public ShortTruthTableStatement copy() { - // copy all the cells - List cellsCopy = new ArrayList<>(); - for (ShortTruthTableCell c : cells) { - cellsCopy.add(c.copy()); - } - // make a copy of the statement with all the copied cells - // return the new statement - return new ShortTruthTableStatement(stringRep, cellsCopy); + cell.setLocation(new Point(xLoc, rowIndex)); + // recurse on both sides of the tree + if (leftStatement != null) { + leftStatement.setCellLocations(rowIndex, offset); + } + if (rightStatement != null) { + rightStatement.setCellLocations(rowIndex, xLoc + 1); } + } - public ShortTruthTableStatement replace(int column, ShortTruthTableCell cell) { - // copy all the cells (replacing one) - List cellsCopy = new ArrayList<>(); - for (ShortTruthTableCell c : cells) { - if (c.getX() == column) { - cellsCopy.add(cell); - } else { - cellsCopy.add(c); - } - } - // make a copy of the statement with all the copied cells - // return the new statement - return new ShortTruthTableStatement(stringRep, cellsCopy); + public void setCellLocations(int rowIndex) { + setCellLocations(rowIndex, 0); + } + + public ShortTruthTableStatement copy() { + // copy all the cells + List cellsCopy = new ArrayList<>(); + for (ShortTruthTableCell c : cells) { + cellsCopy.add(c.copy()); + } + // make a copy of the statement with all the copied cells + // return the new statement + return new ShortTruthTableStatement(stringRep, cellsCopy); + } + + public ShortTruthTableStatement replace(int column, ShortTruthTableCell cell) { + // copy all the cells (replacing one) + List cellsCopy = new ArrayList<>(); + for (ShortTruthTableCell c : cells) { + if (c.getX() == column) { + cellsCopy.add(cell); + } else { + cellsCopy.add(c); + } } + // make a copy of the statement with all the copied cells + // return the new statement + return new ShortTruthTableStatement(stringRep, cellsCopy); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java index 15becf443..e15f5b928 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java @@ -7,19 +7,18 @@ public class ShortTruthTableView extends GridBoardView { - public ShortTruthTableView(ShortTruthTableBoard board) { - super(new BoardController(), new ShortTruthTableController(), board.getDimension()); + public ShortTruthTableView(ShortTruthTableBoard board) { + super(new BoardController(), new ShortTruthTableController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - // System.out.println("STTView :"+cell); - Point loc = cell.getLocation(); - ShortTruthTableElementView elementView = new ShortTruthTableElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - } + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + // System.out.println("STTView :"+cell); + Point loc = cell.getLocation(); + ShortTruthTableElementView elementView = new ShortTruthTableElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java index 9294fba4e..ed53dc3bf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class ArgumentElement extends NonPlaceableElement { - public ArgumentElement() { - super( - "STTT-UNPL-0001", - "Argument Element", - "Argument of logic statement element", - "edu/rpi/legup/images/shorttruthtable/tiles/LetterTile.png"); - } + public ArgumentElement() { + super( + "STTT-UNPL-0001", + "Argument Element", + "Argument of logic statement element", + "edu/rpi/legup/images/shorttruthtable/tiles/LetterTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java index 783186baa..eb6b9996c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class GreenElement extends PlaceableElement { - public GreenElement() { - super( - "STTT-PLAC-0001", - "Green Element", - "A green tile to set certain tiles to true", - "edu/rpi/legup/images/shorttruthtable/tiles/GreenTile.png"); - } + public GreenElement() { + super( + "STTT-PLAC-0001", + "Green Element", + "A green tile to set certain tiles to true", + "edu/rpi/legup/images/shorttruthtable/tiles/GreenTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java index 5fed4b1df..8336e0a41 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class LogicSymbolElement extends NonPlaceableElement { - public LogicSymbolElement() { - super( - "STTT-UNPL-0002", - "Logic Symbol Element", - "Logic symbol element", - "edu/rpi/legup/images/shorttruthtable/tiles/ConditionalBiconditionalTile.png"); - } + public LogicSymbolElement() { + super( + "STTT-UNPL-0002", + "Logic Symbol Element", + "Logic symbol element", + "edu/rpi/legup/images/shorttruthtable/tiles/ConditionalBiconditionalTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java index e2a589b65..c9e0472ae 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class RedElement extends PlaceableElement { - public RedElement() { - super( - "STTT-PLAC-0002", - "Red Element", - "A red tile to set certain tiles to false", - "edu/rpi/legup/images/shorttruthtable/tiles/RedTile.png"); - } + public RedElement() { + super( + "STTT-PLAC-0002", + "Red Element", + "A red tile to set certain tiles to false", + "edu/rpi/legup/images/shorttruthtable/tiles/RedTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java index d475bc05d..87feed9ed 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class UnknownElement extends PlaceableElement { - public UnknownElement() { - super( - "STTT-PLAC-0003", - "Unknown Element", - "A blank tile", - "edu/rpi/legup/images/shorttruthtable/tiles/UnknownTile.png"); - } + public UnknownElement() { + super( + "STTT-PLAC-0003", + "Unknown Element", + "A blank tile", + "edu/rpi/legup/images/shorttruthtable/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java index 38048b5b0..f8421da08 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java @@ -4,13 +4,13 @@ public class DirectRuleAtomic extends DirectRule_Generic { - public DirectRuleAtomic() { - super( - "STTT-BASC-0001", - "Atomic Rule", - "All identical atoms have the same T/F value", - "Atomic", - new ContradictionRuleAtomic(), - false); - } + public DirectRuleAtomic() { + super( + "STTT-BASC-0001", + "Atomic Rule", + "All identical atoms have the same T/F value", + "Atomic", + new ContradictionRuleAtomic(), + false); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java index 470ba7c29..84b49d135 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java @@ -11,82 +11,79 @@ public abstract class DirectRule_Generic extends DirectRule { - final ContradictionRule CORRESPONDING_CONTRADICTION_RULE; - final boolean ELIMINATION_RULE; + final ContradictionRule CORRESPONDING_CONTRADICTION_RULE; + final boolean ELIMINATION_RULE; - public DirectRule_Generic( - String ruleID, - String ruleName, - String description, - String imageName, - ContradictionRule contraRule, - boolean eliminationRule) { - super( - ruleID, - ruleName, - description, - "edu/rpi/legup/images/shorttruthtable/ruleimages/basic/" + imageName + ".png"); - this.CORRESPONDING_CONTRADICTION_RULE = contraRule; - this.ELIMINATION_RULE = eliminationRule; - } - - public String checkRuleRawAt(TreeTransition transition, PuzzleElement element) { - // Rule must have cell to evaluate on - if (element == null) return super.getInvalidUseOfRuleMessage() + ": Must have painted cell"; + public DirectRule_Generic( + String ruleID, + String ruleName, + String description, + String imageName, + ContradictionRule contraRule, + boolean eliminationRule) { + super( + ruleID, + ruleName, + description, + "edu/rpi/legup/images/shorttruthtable/ruleimages/basic/" + imageName + ".png"); + this.CORRESPONDING_CONTRADICTION_RULE = contraRule; + this.ELIMINATION_RULE = eliminationRule; + } - // Check that the puzzle element is not unknown - ShortTruthTableBoard parentBoard = - (ShortTruthTableBoard) transition.getParents().get(0).getBoard(); - ShortTruthTableBoard finalBoard = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell parentCell = - (ShortTruthTableCell) parentBoard.getPuzzleElement(element); - ShortTruthTableCell finalCell = (ShortTruthTableCell) finalBoard.getPuzzleElement(element); + public String checkRuleRawAt(TreeTransition transition, PuzzleElement element) { + // Rule must have cell to evaluate on + if (element == null) return super.getInvalidUseOfRuleMessage() + ": Must have painted cell"; - if (!finalCell.isAssigned()) { - return super.getInvalidUseOfRuleMessage() - + ": Only assigned cells are allowed for basic rules"; - } + // Check that the puzzle element is not unknown + ShortTruthTableBoard parentBoard = + (ShortTruthTableBoard) transition.getParents().get(0).getBoard(); + ShortTruthTableBoard finalBoard = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell parentCell = (ShortTruthTableCell) parentBoard.getPuzzleElement(element); + ShortTruthTableCell finalCell = (ShortTruthTableCell) finalBoard.getPuzzleElement(element); - // Strategy: Negate the modified cell and check if there is a contradiction. If there is - // one, - // then the - // original statement must be true. If there isn't one, then the original statement must be - // false. + if (!finalCell.isAssigned()) { + return super.getInvalidUseOfRuleMessage() + + ": Only assigned cells are allowed for basic rules"; + } - ShortTruthTableBoard modifiedBoard = parentBoard.copy(); + // Strategy: Negate the modified cell and check if there is a contradiction. If there is + // one, + // then the + // original statement must be true. If there isn't one, then the original statement must be + // false. - PuzzleElement checkElement = - this.ELIMINATION_RULE - ? parentCell.getStatementReference().getParentStatement().getCell() - : element; + ShortTruthTableBoard modifiedBoard = parentBoard.copy(); - ShortTruthTableCell checkCell = - this.ELIMINATION_RULE - ? (ShortTruthTableCell) - modifiedBoard.getCell(parentCell.getX(), parentCell.getY()) - : (ShortTruthTableCell) modifiedBoard.getPuzzleElement(element); + PuzzleElement checkElement = + this.ELIMINATION_RULE + ? parentCell.getStatementReference().getParentStatement().getCell() + : element; - checkCell.setType(finalCell.getType().getNegation()); + ShortTruthTableCell checkCell = + this.ELIMINATION_RULE + ? (ShortTruthTableCell) modifiedBoard.getCell(parentCell.getX(), parentCell.getY()) + : (ShortTruthTableCell) modifiedBoard.getPuzzleElement(element); - String contradictionMessage = - CORRESPONDING_CONTRADICTION_RULE.checkContradictionAt(modifiedBoard, checkElement); - if (contradictionMessage - == null) { // A contradiction exists in the modified statement; this is good! - return null; - } + checkCell.setType(finalCell.getType().getNegation()); - return super.getInvalidUseOfRuleMessage(); + String contradictionMessage = + CORRESPONDING_CONTRADICTION_RULE.checkContradictionAt(modifiedBoard, checkElement); + if (contradictionMessage + == null) { // A contradiction exists in the modified statement; this is good! + return null; } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node short truth table board used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + return super.getInvalidUseOfRuleMessage(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node short truth table board used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java index 6f48784a3..b6e88fa65 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java @@ -4,7 +4,7 @@ public class DirectRuleAndElimination extends DirectRule_GenericElimination { - public DirectRuleAndElimination() { - super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); - } + public DirectRuleAndElimination() { + super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java index 168877ca6..8c12882a7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java @@ -4,7 +4,7 @@ public class DirectRuleBiconditionalElimination extends DirectRule_GenericElimination { - public DirectRuleBiconditionalElimination() { - super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); - } + public DirectRuleBiconditionalElimination() { + super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java index 4a287b195..a316b4566 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java @@ -4,7 +4,7 @@ public class DirectRuleConditionalElimination extends DirectRule_GenericElimination { - public DirectRuleConditionalElimination() { - super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); - } + public DirectRuleConditionalElimination() { + super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java index 5acff5837..f15a4d2b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java @@ -4,7 +4,7 @@ public class DirectRuleNotElimination extends DirectRule_GenericElimination { - public DirectRuleNotElimination() { - super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); - } + public DirectRuleNotElimination() { + super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java index fba43762a..77d507764 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java @@ -4,7 +4,7 @@ public class DirectRuleOrElimination extends DirectRule_GenericElimination { - public DirectRuleOrElimination() { - super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); - } + public DirectRuleOrElimination() { + super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java index 1f85e5b79..b741f47b9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java @@ -5,15 +5,15 @@ public abstract class DirectRule_GenericElimination extends DirectRule_Generic { - public DirectRule_GenericElimination( - String ruleID, String ruleName, ContradictionRule contradictionRule) { + public DirectRule_GenericElimination( + String ruleID, String ruleName, ContradictionRule contradictionRule) { - super( - ruleID, - ruleName + " Elimination", - ruleName + " statements must have a valid pattern", - "elimination/" + ruleName, - contradictionRule, - true); - } + super( + ruleID, + ruleName + " Elimination", + ruleName + " statements must have a valid pattern", + "elimination/" + ruleName, + contradictionRule, + true); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java index 667b97a0f..838f28e4c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleAndIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleAndIntroduction() { - super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); - } + public DirectRuleAndIntroduction() { + super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java index c2dfeebba..5e332c355 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleBiconditionalIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleBiconditionalIntroduction() { - super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); - } + public DirectRuleBiconditionalIntroduction() { + super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java index 728d7f244..7b3843fde 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleConditionalIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleConditionalIntroduction() { - super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); - } + public DirectRuleConditionalIntroduction() { + super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java index 80b963a56..be6926915 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleNotIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleNotIntroduction() { - super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); - } + public DirectRuleNotIntroduction() { + super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java index 66a569655..887b1bff0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleOrIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleOrIntroduction() { - super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); - } + public DirectRuleOrIntroduction() { + super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java index 8469ff0b9..5b6803dc2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java @@ -5,15 +5,15 @@ public abstract class DirectRule_GenericIntroduction extends DirectRule_Generic { - protected DirectRule_GenericIntroduction( - String ruleID, String ruleName, ContradictionRule contradictionRule) { + protected DirectRule_GenericIntroduction( + String ruleID, String ruleName, ContradictionRule contradictionRule) { - super( - ruleID, - ruleName + " Introduction", - ruleName + " statements must have a valid pattern", - "introduction/" + ruleName, - contradictionRule, - false); - } + super( + ruleID, + ruleName + " Introduction", + ruleName + " statements must have a valid pattern", + "introduction/" + ruleName, + contradictionRule, + false); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java index 9b589f14e..60c9ab49e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java @@ -5,13 +5,13 @@ public class CaseRuleAnd extends CaseRule_GenericStatement { - public CaseRuleAnd() { - super("STTT-CASE-0001", ShortTruthTableOperation.AND, "And", trueCases, falseCases); - } + public CaseRuleAnd() { + super("STTT-CASE-0001", ShortTruthTableOperation.AND, "And", trueCases, falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = {{T, T}}; - private static final ShortTruthTableCellType[][] falseCases = { - {F, U}, - {U, F} - }; + private static final ShortTruthTableCellType[][] trueCases = {{T, T}}; + private static final ShortTruthTableCellType[][] falseCases = { + {F, U}, + {U, F} + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java index 58d2068b2..46975b7df 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java @@ -11,57 +11,57 @@ public class CaseRuleAtomic extends CaseRule_Generic { - public CaseRuleAtomic() { - super( - "STTT-CASE-0002", - "Atomic", - "True or False", - "Each unknown cell must either be true or false"); - } + public CaseRuleAtomic() { + super( + "STTT-CASE-0002", + "Atomic", + "True or False", + "Each unknown cell must either be true or false"); + } - // Adds all elements that can be selected for this case rule - @Override - public CaseBoard getCaseBoard(Board board) { - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); - sttBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(sttBoard, this); - for (PuzzleElement element : sttBoard.getPuzzleElements()) { - if (((ShortTruthTableCell) element).getType() == ShortTruthTableCellType.UNKNOWN) { - caseBoard.addPickableElement(element); - } - } - return caseBoard; + // Adds all elements that can be selected for this case rule + @Override + public CaseBoard getCaseBoard(Board board) { + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); + sttBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(sttBoard, this); + for (PuzzleElement element : sttBoard.getPuzzleElements()) { + if (((ShortTruthTableCell) element).getType() == ShortTruthTableCellType.UNKNOWN) { + caseBoard.addPickableElement(element); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(ShortTruthTableCellType.TRUE); - case1.addModifiedData(data1); - cases.add(case1); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(ShortTruthTableCellType.TRUE); + case1.addModifiedData(data1); + cases.add(case1); - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(ShortTruthTableCellType.FALSE); - case2.addModifiedData(data2); - cases.add(case2); + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(ShortTruthTableCellType.FALSE); + case2.addModifiedData(data2); + cases.add(case2); - return cases; - } + return cases; + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java index 1bb5f0332..52058a6f5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java @@ -5,21 +5,21 @@ public class CaseRuleBiconditional extends CaseRule_GenericStatement { - public CaseRuleBiconditional() { - super( - "STTT-CASE-0003", - ShortTruthTableOperation.BICONDITIONAL, - "Biconditional", - trueCases, - falseCases); - } + public CaseRuleBiconditional() { + super( + "STTT-CASE-0003", + ShortTruthTableOperation.BICONDITIONAL, + "Biconditional", + trueCases, + falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {T, T}, - {F, F} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - {F, T} - }; + private static final ShortTruthTableCellType[][] trueCases = { + {T, T}, + {F, F} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + {F, T} + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java index 397341f0e..ea1f78408 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java @@ -5,20 +5,20 @@ public class CaseRuleConditional extends CaseRule_GenericStatement { - public CaseRuleConditional() { - super( - "STTT-CASE-0004", - ShortTruthTableOperation.CONDITIONAL, - "Conditional", - trueCases, - falseCases); - } + public CaseRuleConditional() { + super( + "STTT-CASE-0004", + ShortTruthTableOperation.CONDITIONAL, + "Conditional", + trueCases, + falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {U, T}, - {F, U} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - }; + private static final ShortTruthTableCellType[][] trueCases = { + {U, T}, + {F, U} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java index 36f4e6f87..a9b2abb65 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java @@ -5,15 +5,15 @@ public class CaseRuleOr extends CaseRule_GenericStatement { - public CaseRuleOr() { - super("STTT-CASE-0005", ShortTruthTableOperation.OR, "Or", trueCases, falseCases); - } + public CaseRuleOr() { + super("STTT-CASE-0005", ShortTruthTableOperation.OR, "Or", trueCases, falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {T, U}, - {U, T} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {F, F}, - }; + private static final ShortTruthTableCellType[][] trueCases = { + {T, U}, + {U, T} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {F, F}, + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java index 5885f98f8..09eca7d8e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java @@ -7,57 +7,57 @@ public abstract class CaseRule_Generic extends CaseRule { - public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { - super( - ruleID, - title, - description, - "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - // Validate that two children are generated - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "ERROR: This case rule must spawn at least 1 child."; - } + public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { + super( + ruleID, + title, + description, + "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); + } - // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE - // List cases = Arrays.asList(childTransitions.get(0), - // childTransitions.get(1)); - // for (TreeTransition c : cases) { - // ShortTruthTableCell mod1 = - // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // ShortTruthTableCell mod2 = - // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == - // ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && - // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == - // ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { - // return "ERROR: This case rule must be an unknown, true, or false cell."; - // } - // } - return null; + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + // Validate that two children are generated + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "ERROR: This case rule must spawn at least 1 child."; } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE + // List cases = Arrays.asList(childTransitions.get(0), + // childTransitions.get(1)); + // for (TreeTransition c : cases) { + // ShortTruthTableCell mod1 = + // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // ShortTruthTableCell mod2 = + // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == + // ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && + // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == + // ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { + // return "ERROR: This case rule must be an unknown, true, or false cell."; + // } + // } + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java index 99f771246..68dd33b16 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java @@ -13,140 +13,133 @@ public abstract class CaseRule_GenericStatement extends CaseRule_Generic { - public CaseRule_GenericStatement( - String ruleID, - char operation, - String title, - ShortTruthTableCellType[][] trueCases, - ShortTruthTableCellType[][] falseCases) { - super( - ruleID, - ShortTruthTableOperation.getRuleName(operation), - title + " case", - "A known " + title.toUpperCase() + " statement can have multiple forms"); - - this.operation = operation; - - this.trueCases = trueCases; - this.falseCases = falseCases; + public CaseRule_GenericStatement( + String ruleID, + char operation, + String title, + ShortTruthTableCellType[][] trueCases, + ShortTruthTableCellType[][] falseCases) { + super( + ruleID, + ShortTruthTableOperation.getRuleName(operation), + title + " case", + "A known " + title.toUpperCase() + " statement can have multiple forms"); + + this.operation = operation; + + this.trueCases = trueCases; + this.falseCases = falseCases; + } + + private final char operation; + + private final ShortTruthTableCellType[][] trueCases; + private final ShortTruthTableCellType[][] falseCases; + + protected static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; + protected static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; + protected static final ShortTruthTableCellType U = ShortTruthTableCellType.UNKNOWN; + + // Adds all elements that can be selected for this caserule + @Override + public CaseBoard getCaseBoard(Board board) { + // copy the board and add all elements that can be selected + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); + sttBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(sttBoard, this); + + // add all elements that can be selected for the case rule statement + for (PuzzleElement element : sttBoard.getPuzzleElements()) { + // get the cell object + ShortTruthTableCell cell = sttBoard.getCellFromElement(element); + // the cell must match the symbol + if (cell.getSymbol() != this.operation) continue; + // the statement must be assigned with unassigned sub-statements + if (!cell.getType().isTrueOrFalse()) continue; + if (cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) + continue; + if (this.operation != ShortTruthTableOperation.NOT + && cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) { + continue; + } + // if the element has passed all the checks, it can be selected + caseBoard.addPickableElement(element); } - - private final char operation; - - private final ShortTruthTableCellType[][] trueCases; - private final ShortTruthTableCellType[][] falseCases; - - protected static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; - protected static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; - protected static final ShortTruthTableCellType U = ShortTruthTableCellType.UNKNOWN; - - // Adds all elements that can be selected for this caserule - @Override - public CaseBoard getCaseBoard(Board board) { - // copy the board and add all elements that can be selected - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); - sttBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(sttBoard, this); - - // add all elements that can be selected for the case rule statement - for (PuzzleElement element : sttBoard.getPuzzleElements()) { - // get the cell object - ShortTruthTableCell cell = sttBoard.getCellFromElement(element); - // the cell must match the symbol - if (cell.getSymbol() != this.operation) continue; - // the statement must be assigned with unassigned sub-statements - if (!cell.getType().isTrueOrFalse()) continue; - if (cell.getStatementReference() - .getRightStatement() - .getCell() - .getType() - .isTrueOrFalse()) continue; - if (this.operation != ShortTruthTableOperation.NOT - && cell.getStatementReference() - .getRightStatement() - .getCell() - .getType() - .isTrueOrFalse()) { - continue; - } - // if the element has passed all the checks, it can be selected - caseBoard.addPickableElement(element); - } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ShortTruthTableBoard sttBoard = ((ShortTruthTableBoard) board); - ShortTruthTableCell cell = sttBoard.getCellFromElement(puzzleElement); - - // If the statement is set to true, collect true cases. Otherwise, collect the false cases - if (cell.getType() == ShortTruthTableCellType.TRUE) { - return getCasesFromCell(sttBoard, puzzleElement, trueCases); - } - return getCasesFromCell(sttBoard, puzzleElement, falseCases); + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ShortTruthTableBoard sttBoard = ((ShortTruthTableBoard) board); + ShortTruthTableCell cell = sttBoard.getCellFromElement(puzzleElement); + + // If the statement is set to true, collect true cases. Otherwise, collect the false cases + if (cell.getType() == ShortTruthTableCellType.TRUE) { + return getCasesFromCell(sttBoard, puzzleElement, trueCases); } - - /** - * Collects a list of boards for each possible outcome of case-rule application - * - * @param board current board state - * @param puzzleElement case rule operator - * @param possibilities list of possibilities for operator state - * @return ArrayList of Boards - */ - private ArrayList getCasesFromCell( - ShortTruthTableBoard board, - PuzzleElement puzzleElement, - ShortTruthTableCellType[][] possibilities) { - // Create branch case for each possibility - ArrayList cases = new ArrayList<>(); - for (int i = 0; i < possibilities.length; i++) { - // Create a new board to modify and get statement of selected square - ShortTruthTableBoard b = board.copy(); - ShortTruthTableCell cell = b.getCellFromElement(puzzleElement); - ShortTruthTableStatement statement = cell.getStatementReference(); - - // Modify neighboring cells of case-rule application by the provided logical cases - if (possibilities[i][0] != ShortTruthTableCellType.UNKNOWN) { - ShortTruthTableCell leftCell = statement.getLeftStatement().getCell(); - leftCell.setData(possibilities[i][0]); - b.addModifiedData(leftCell); - } - if (possibilities[i][1] != ShortTruthTableCellType.UNKNOWN) { - ShortTruthTableCell rightCell = statement.getRightStatement().getCell(); - rightCell.setData(possibilities[i][1]); - b.addModifiedData(rightCell); - } - - cases.add(b); - } - return cases; - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = super.dependentElements(board, puzzleElement); - - elements.add(board.getPuzzleElement(puzzleElement)); - - return elements; + return getCasesFromCell(sttBoard, puzzleElement, falseCases); + } + + /** + * Collects a list of boards for each possible outcome of case-rule application + * + * @param board current board state + * @param puzzleElement case rule operator + * @param possibilities list of possibilities for operator state + * @return ArrayList of Boards + */ + private ArrayList getCasesFromCell( + ShortTruthTableBoard board, + PuzzleElement puzzleElement, + ShortTruthTableCellType[][] possibilities) { + // Create branch case for each possibility + ArrayList cases = new ArrayList<>(); + for (int i = 0; i < possibilities.length; i++) { + // Create a new board to modify and get statement of selected square + ShortTruthTableBoard b = board.copy(); + ShortTruthTableCell cell = b.getCellFromElement(puzzleElement); + ShortTruthTableStatement statement = cell.getStatementReference(); + + // Modify neighboring cells of case-rule application by the provided logical cases + if (possibilities[i][0] != ShortTruthTableCellType.UNKNOWN) { + ShortTruthTableCell leftCell = statement.getLeftStatement().getCell(); + leftCell.setData(possibilities[i][0]); + b.addModifiedData(leftCell); + } + if (possibilities[i][1] != ShortTruthTableCellType.UNKNOWN) { + ShortTruthTableCell rightCell = statement.getRightStatement().getCell(); + rightCell.setData(possibilities[i][1]); + b.addModifiedData(rightCell); + } + + cases.add(b); } + return cases; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = super.dependentElements(board, puzzleElement); + + elements.add(board.getPuzzleElement(puzzleElement)); + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java index 595dd0cb2..0549b5f99 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java @@ -5,18 +5,18 @@ public class ContradictionRuleAnd extends ContradictionRule_GenericStatement { - public ContradictionRuleAnd() { - super( - "STTT-CONT-0001", - "Contradicting And", - "An AND statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/And.png", - ShortTruthTableOperation.AND, - new ShortTruthTableCellType[][] { - {n, T, F}, - {F, T, n}, - // {F, T, F}, - {T, F, T}, - }); - } + public ContradictionRuleAnd() { + super( + "STTT-CONT-0001", + "Contradicting And", + "An AND statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/And.png", + ShortTruthTableOperation.AND, + new ShortTruthTableCellType[][] { + {n, T, F}, + {F, T, n}, + // {F, T, F}, + {T, F, T}, + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java index 879b7c9a5..16256ec6a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java @@ -11,49 +11,49 @@ public class ContradictionRuleAtomic extends ContradictionRule { - public ContradictionRuleAtomic() { - super( - "STTT-CONT-0002", - "Contradicting Variable", - "A single variable can not be both True and False", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Atomic.png"); + public ContradictionRuleAtomic() { + super( + "STTT-CONT-0002", + "Contradicting Variable", + "A single variable can not be both True and False", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Atomic.png"); + } + + @Override + public String checkContradictionAt(Board puzzleBoard, PuzzleElement puzzleElement) { + + // cast the board toa shortTruthTableBoard + ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; + + // get the cell that contradicts another cell in the board + ShortTruthTableCell cell = (ShortTruthTableCell) board.getPuzzleElement(puzzleElement); + + if (!cell.isVariable()) { + System.out.println(" Not Var"); + return "Can not check for contradiction on a non-variable element"; } - @Override - public String checkContradictionAt(Board puzzleBoard, PuzzleElement puzzleElement) { - - // cast the board toa shortTruthTableBoard - ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - - // get the cell that contradicts another cell in the board - ShortTruthTableCell cell = (ShortTruthTableCell) board.getPuzzleElement(puzzleElement); - - if (!cell.isVariable()) { - System.out.println(" Not Var"); - return "Can not check for contradiction on a non-variable element"; - } - - ShortTruthTableCellType cellType = cell.getType(); - if (!cellType.isTrueOrFalse()) { - return "Can only check for a contradiction against a cell that is assigned a value of" - + " True or False"; - } - - // get all the cells with the same value - Set varCells = board.getCellsWithSymbol(cell.getSymbol()); - - // check if there are any contradictions - Iterator itr = varCells.iterator(); - while (itr.hasNext()) { - ShortTruthTableCell checkCell = itr.next(); - ShortTruthTableCellType checkCellType = checkCell.getType(); - // if there is an assigned contradiction, return null - if (checkCellType.isTrueOrFalse() && checkCellType != cellType) { - return null; - } - } - - // if it made it through the while loop, thene there is no contradiction - return "There is no contradiction for the variable " + cell.getSymbol(); + ShortTruthTableCellType cellType = cell.getType(); + if (!cellType.isTrueOrFalse()) { + return "Can only check for a contradiction against a cell that is assigned a value of" + + " True or False"; } + + // get all the cells with the same value + Set varCells = board.getCellsWithSymbol(cell.getSymbol()); + + // check if there are any contradictions + Iterator itr = varCells.iterator(); + while (itr.hasNext()) { + ShortTruthTableCell checkCell = itr.next(); + ShortTruthTableCellType checkCellType = checkCell.getType(); + // if there is an assigned contradiction, return null + if (checkCellType.isTrueOrFalse() && checkCellType != cellType) { + return null; + } + } + + // if it made it through the while loop, thene there is no contradiction + return "There is no contradiction for the variable " + cell.getSymbol(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java index bae07acce..2be92ffb1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java @@ -5,18 +5,18 @@ public class ContradictionRuleBiconditional extends ContradictionRule_GenericStatement { - public ContradictionRuleBiconditional() { - super( - "STTT-CONT-0003", - "Contradicting Biconditional", - "A Biconditional statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Biconditional.png", - ShortTruthTableOperation.BICONDITIONAL, - new ShortTruthTableCellType[][] { - {T, T, F}, - {F, T, T}, - {T, F, T}, - {F, F, F} - }); - } + public ContradictionRuleBiconditional() { + super( + "STTT-CONT-0003", + "Contradicting Biconditional", + "A Biconditional statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Biconditional.png", + ShortTruthTableOperation.BICONDITIONAL, + new ShortTruthTableCellType[][] { + {T, T, F}, + {F, T, T}, + {T, F, T}, + {F, F, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java index e3a51a00e..b9ce9b74e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java @@ -5,17 +5,17 @@ public class ContradictionRuleConditional extends ContradictionRule_GenericStatement { - public ContradictionRuleConditional() { - super( - "STTT-CONT-0004", - "Contradicting Conditional", - "A Conditional statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Conditional.png", - ShortTruthTableOperation.CONDITIONAL, - new ShortTruthTableCellType[][] { - {n, F, T}, - {F, F, n}, - {T, T, F} - }); - } + public ContradictionRuleConditional() { + super( + "STTT-CONT-0004", + "Contradicting Conditional", + "A Conditional statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Conditional.png", + ShortTruthTableOperation.CONDITIONAL, + new ShortTruthTableCellType[][] { + {n, F, T}, + {F, F, n}, + {T, T, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java index 4e20485bc..6c4bb40e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java @@ -5,16 +5,16 @@ public class ContradictionRuleNot extends ContradictionRule_GenericStatement { - public ContradictionRuleNot() { - super( - "STTT-CONT-0005", - "Contradicting Negation", - "A negation and its following statement can not have the same truth value", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Not.png", - ShortTruthTableOperation.NOT, - new ShortTruthTableCellType[][] { - {n, T, T}, - {n, F, F} - }); - } + public ContradictionRuleNot() { + super( + "STTT-CONT-0005", + "Contradicting Negation", + "A negation and its following statement can not have the same truth value", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Not.png", + ShortTruthTableOperation.NOT, + new ShortTruthTableCellType[][] { + {n, T, T}, + {n, F, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java index 2ab197dad..85f29ca3f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java @@ -5,17 +5,17 @@ public class ContradictionRuleOr extends ContradictionRule_GenericStatement { - public ContradictionRuleOr() { - super( - "STTT-CONT-0006", - "Contradicting Or", - "An OR statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Or.png", - ShortTruthTableOperation.OR, - new ShortTruthTableCellType[][] { - {n, F, T}, - {T, F, n}, - {F, T, F} - }); - } + public ContradictionRuleOr() { + super( + "STTT-CONT-0006", + "Contradicting Or", + "An OR statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Or.png", + ShortTruthTableOperation.OR, + new ShortTruthTableCellType[][] { + {n, F, T}, + {T, F, n}, + {F, T, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java index 87b1ba628..7ddc053ca 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java @@ -10,79 +10,76 @@ public abstract class ContradictionRule_GenericStatement extends ContradictionRule { - private final char operationSymbol; - - private final ShortTruthTableCellType[][] contradictionPatterns; - - static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; - static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; - static final ShortTruthTableCellType n = null; - - private final String NOT_RIGHT_OPERATOR_ERROR_MESSAGE = - "This cell does not contain the correct operation"; - private final String NOT_TRUE_FALSE_ERROR_MESSAGE = - "Can only check for a contradiction on a cell that is assigned a value of True or" - + " False"; - - public ContradictionRule_GenericStatement( - String ruleID, - String ruleName, - String description, - String imageName, - char operationSymbol, - ShortTruthTableCellType[][] contradictionPatterns) { - super(ruleID, ruleName, description, imageName); - this.operationSymbol = operationSymbol; - this.contradictionPatterns = contradictionPatterns; + private final char operationSymbol; + + private final ShortTruthTableCellType[][] contradictionPatterns; + + static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; + static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; + static final ShortTruthTableCellType n = null; + + private final String NOT_RIGHT_OPERATOR_ERROR_MESSAGE = + "This cell does not contain the correct operation"; + private final String NOT_TRUE_FALSE_ERROR_MESSAGE = + "Can only check for a contradiction on a cell that is assigned a value of True or" + " False"; + + public ContradictionRule_GenericStatement( + String ruleID, + String ruleName, + String description, + String imageName, + char operationSymbol, + ShortTruthTableCellType[][] contradictionPatterns) { + super(ruleID, ruleName, description, imageName); + this.operationSymbol = operationSymbol; + this.contradictionPatterns = contradictionPatterns; + } + + @Override + public String checkContradictionAt(Board puzzleBoard, PuzzleElement operatorPuzzleElement) { + + // cast the board to a shortTruthTableBoard + ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; + + // get the cell that contradicts another cell in the board + ShortTruthTableCell cell = board.getCellFromElement(operatorPuzzleElement); + ShortTruthTableStatement statement = cell.getStatementReference(); + + if (cell.getSymbol() != this.operationSymbol) { + return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_RIGHT_OPERATOR_ERROR_MESSAGE; } - @Override - public String checkContradictionAt(Board puzzleBoard, PuzzleElement operatorPuzzleElement) { + // check that the initial statement is assigned + ShortTruthTableCellType cellType = cell.getType(); - // cast the board to a shortTruthTableBoard - ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; + if (!cellType.isTrueOrFalse()) { + return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_TRUE_FALSE_ERROR_MESSAGE; + } - // get the cell that contradicts another cell in the board - ShortTruthTableCell cell = board.getCellFromElement(operatorPuzzleElement); - ShortTruthTableStatement statement = cell.getStatementReference(); + // get the pattern for this sub-statement + ShortTruthTableCellType[] testPattern = statement.getCellTypePattern(); - if (cell.getSymbol() != this.operationSymbol) { - return super.getInvalidUseOfRuleMessage() - + ": " - + this.NOT_RIGHT_OPERATOR_ERROR_MESSAGE; + // if the board pattern matches any contradiction pattern, it is a valid contradiction + for (ShortTruthTableCellType[] pattern : contradictionPatterns) { + boolean matches = true; + for (int i = 0; i < 3; i++) { + // ull means that part does not affect the statement + if (pattern[i] == null) { + continue; } - - // check that the initial statement is assigned - ShortTruthTableCellType cellType = cell.getType(); - - if (!cellType.isTrueOrFalse()) { - return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_TRUE_FALSE_ERROR_MESSAGE; + // if it is not null, it must match the test pattern + if (pattern[i] != testPattern[i]) { + matches = false; + break; } - - // get the pattern for this sub-statement - ShortTruthTableCellType[] testPattern = statement.getCellTypePattern(); - - // if the board pattern matches any contradiction pattern, it is a valid contradiction - for (ShortTruthTableCellType[] pattern : contradictionPatterns) { - boolean matches = true; - for (int i = 0; i < 3; i++) { - // ull means that part does not affect the statement - if (pattern[i] == null) { - continue; - } - // if it is not null, it must match the test pattern - if (pattern[i] != testPattern[i]) { - matches = false; - break; - } - } - // if testPattern matches one of the valid contradiction patterns, the contradiction is - // correct - if (matches) { - return null; - } - } - - return super.getNoContradictionMessage(); + } + // if testPattern matches one of the valid contradiction patterns, the contradiction is + // correct + if (matches) { + return null; + } } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java index df5ba78a3..4dd2781e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java @@ -7,78 +7,78 @@ public class Skyscrapers extends Puzzle { - public Skyscrapers() { - super(); + public Skyscrapers() { + super(); - this.name = "Skyscrapers"; + this.name = "Skyscrapers"; - this.importer = new SkyscrapersImporter(this); - this.exporter = new SkyscrapersExporter(this); + this.importer = new SkyscrapersImporter(this); + this.exporter = new SkyscrapersExporter(this); - this.factory = new SkyscrapersCellFactory(); - } + this.factory = new SkyscrapersCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new SkyscrapersView((SkyscrapersBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new SkyscrapersView((SkyscrapersBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Skyscrapers - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Skyscrapers, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows >= 4 && rows == columns; - } + @Override + /** + * Determines if the given dimensions are valid for Skyscrapers + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Skyscrapers, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows >= 4 && rows == columns; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - SkyscrapersBoard SkyscraperBoard = (SkyscrapersBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + SkyscrapersBoard SkyscraperBoard = (SkyscrapersBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(SkyscraperBoard) == null) { - System.out.println(rule.getRuleName()); - return false; - } - } - for (PuzzleElement data : SkyscraperBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) data; - if (cell.getType() == SkyscrapersType.UNKNOWN) { - return false; - } - } - return true; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(SkyscraperBoard) == null) { + System.out.println(rule.getRuleName()); + return false; + } + } + for (PuzzleElement data : SkyscraperBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) data; + if (cell.getType() == SkyscrapersType.UNKNOWN) { + return false; + } } + return true; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java index 4cd09b254..7bc754cb4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java @@ -10,264 +10,264 @@ public class SkyscrapersBoard extends GridBoard { - private ArrayList eastClues; - // EAST clues - private ArrayList southClues; - // SOUTH clues - private ArrayList westClues; - // WEST clues - private ArrayList northClues; - // NORTH clues + private ArrayList eastClues; + // EAST clues + private ArrayList southClues; + // SOUTH clues + private ArrayList westClues; + // WEST clues + private ArrayList northClues; + // NORTH clues - private boolean viewFlag = false; - private boolean dupeFlag = false; + private boolean viewFlag = false; + private boolean dupeFlag = false; - public SkyscrapersBoard(int size) { - super(size, size); + public SkyscrapersBoard(int size) { + super(size, size); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + this.northClues = new ArrayList<>(); - for (int i = 0; i < size; i++) { - eastClues.add(null); - southClues.add(null); - westClues.add(null); - northClues.add(null); - } + for (int i = 0; i < size; i++) { + eastClues.add(null); + southClues.add(null); + westClues.add(null); + northClues.add(null); } + } - /** - * @return eastClues a list of the eastern clues ordered from loc.y = 0 to max - */ - public ArrayList getEastClues() { - return eastClues; - } + /** + * @return eastClues a list of the eastern clues ordered from loc.y = 0 to max + */ + public ArrayList getEastClues() { + return eastClues; + } - /** - * @return southClues a list of the southern clues ordered from loc.x = 0 to max - */ - public ArrayList getSouthClues() { - return southClues; - } + /** + * @return southClues a list of the southern clues ordered from loc.x = 0 to max + */ + public ArrayList getSouthClues() { + return southClues; + } - /** - * @return westClues a list of the western clues ordered from loc.y = 0 to max - */ - public ArrayList getWestClues() { - return westClues; - } + /** + * @return westClues a list of the western clues ordered from loc.y = 0 to max + */ + public ArrayList getWestClues() { + return westClues; + } - /** - * @return northClues a list of the northern clues ordered from loc.x = 0 to max - */ - public ArrayList getNorthClues() { - return northClues; - } + /** + * @return northClues a list of the northern clues ordered from loc.x = 0 to max + */ + public ArrayList getNorthClues() { + return northClues; + } - public boolean getDupeFlag() { - return dupeFlag; - } + public boolean getDupeFlag() { + return dupeFlag; + } - public boolean getViewFlag() { - return viewFlag; - } + public boolean getViewFlag() { + return viewFlag; + } - public void setDupeFlag(boolean newFlag) { - dupeFlag = newFlag; - } + public void setDupeFlag(boolean newFlag) { + dupeFlag = newFlag; + } - public void setViewFlag(boolean newFlag) { - viewFlag = newFlag; - } + public void setViewFlag(boolean newFlag) { + viewFlag = newFlag; + } - @Override - public SkyscrapersCell getCell(int x, int y) { - return (SkyscrapersCell) super.getCell(x, y); - } + @Override + public SkyscrapersCell getCell(int x, int y) { + return (SkyscrapersCell) super.getCell(x, y); + } - public int getSize() { - return this.getWidth(); - } + public int getSize() { + return this.getWidth(); + } - @Override - public PuzzleElement getPuzzleElement(PuzzleElement element) { - // If the element index is -2, it is a clue and should be returned separately - if (element.getIndex() == -2) { - return element; - } - return super.getPuzzleElement(element); + @Override + public PuzzleElement getPuzzleElement(PuzzleElement element) { + // If the element index is -2, it is a clue and should be returned separately + if (element.getIndex() == -2) { + return element; } + return super.getPuzzleElement(element); + } - /** - * Gets the cells of a certain type directly adjacent to a given cell - * - * @param cell at the center, - * @param type of cell to collect - * @return list of cells of the given type - */ - public List getAdjacent(SkyscrapersCell cell, SkyscrapersType type) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - SkyscrapersCell up = getCell(loc.x, loc.y - 1); - SkyscrapersCell right = getCell(loc.x + 1, loc.y); - SkyscrapersCell down = getCell(loc.x, loc.y + 1); - SkyscrapersCell left = getCell(loc.x - 1, loc.y); - if (up != null && (up.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(up); - } - if (right != null && (right.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(right); - } - if (down != null && (down.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(down); - } - if (left != null && (left.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(left); - } - return adj; + /** + * Gets the cells of a certain type directly adjacent to a given cell + * + * @param cell at the center, + * @param type of cell to collect + * @return list of cells of the given type + */ + public List getAdjacent(SkyscrapersCell cell, SkyscrapersType type) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + SkyscrapersCell up = getCell(loc.x, loc.y - 1); + SkyscrapersCell right = getCell(loc.x + 1, loc.y); + SkyscrapersCell down = getCell(loc.x, loc.y + 1); + SkyscrapersCell left = getCell(loc.x - 1, loc.y); + if (up != null && (up.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(up); + } + if (right != null && (right.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(right); + } + if (down != null && (down.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(down); } + if (left != null && (left.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(left); + } + return adj; + } - /** - * Gets the cells of a certain type directly diagonal to a given cell - * - * @param cell at the center, - * @param type of cell to collect - * @return list of cells of the given type - */ - public List getDiagonals(SkyscrapersCell cell, SkyscrapersType type) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - SkyscrapersCell upRight = getCell(loc.x + 1, loc.y - 1); - SkyscrapersCell downRight = getCell(loc.x + 1, loc.y + 1); - SkyscrapersCell downLeft = getCell(loc.x - 1, loc.y + 1); - SkyscrapersCell upLeft = getCell(loc.x - 1, loc.y - 1); - if (upRight != null && (upRight.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(upRight); - } - if (downLeft != null && (downLeft.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(downLeft); - } - if (downRight != null && (downRight.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(downRight); - } - if (upLeft != null && (upLeft.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(upLeft); - } - return dia; + /** + * Gets the cells of a certain type directly diagonal to a given cell + * + * @param cell at the center, + * @param type of cell to collect + * @return list of cells of the given type + */ + public List getDiagonals(SkyscrapersCell cell, SkyscrapersType type) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + SkyscrapersCell upRight = getCell(loc.x + 1, loc.y - 1); + SkyscrapersCell downRight = getCell(loc.x + 1, loc.y + 1); + SkyscrapersCell downLeft = getCell(loc.x - 1, loc.y + 1); + SkyscrapersCell upLeft = getCell(loc.x - 1, loc.y - 1); + if (upRight != null && (upRight.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(upRight); } + if (downLeft != null && (downLeft.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(downLeft); + } + if (downRight != null && (downRight.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(downRight); + } + if (upLeft != null && (upLeft.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(upLeft); + } + return dia; + } - /** - * Gets the cells of a certain type in a given row/column - * - * @param index: y pos of row or x pos of col, - * @param type of cell to collect, - * @param isRow true if row, false if col - * @return list of cells of the given type, ordered west to east or north to south - */ - public List getRowCol(int index, SkyscrapersType type, boolean isRow) { - List list = new ArrayList<>(); - for (int i = 0; i < dimension.height; i++) { - SkyscrapersCell cell; - if (isRow) { - cell = getCell(i, index); - } else { - cell = getCell(index, i); - } + /** + * Gets the cells of a certain type in a given row/column + * + * @param index: y pos of row or x pos of col, + * @param type of cell to collect, + * @param isRow true if row, false if col + * @return list of cells of the given type, ordered west to east or north to south + */ + public List getRowCol(int index, SkyscrapersType type, boolean isRow) { + List list = new ArrayList<>(); + for (int i = 0; i < dimension.height; i++) { + SkyscrapersCell cell; + if (isRow) { + cell = getCell(i, index); + } else { + cell = getCell(index, i); + } - if (cell.getType() == type || type == SkyscrapersType.ANY) { - list.add(cell); - } - } - return list; + if (cell.getType() == type || type == SkyscrapersType.ANY) { + list.add(cell); + } } + return list; + } - /** Prints a semblance of the board to console (helps in debugging) */ - public void printBoard() { - for (int i = 0; i < this.dimension.height; i++) { - for (SkyscrapersCell cell : this.getRowCol(i, SkyscrapersType.ANY, true)) { - if (cell.getType() == SkyscrapersType.Number) { - System.out.print(cell.getData() + " "); - } else { - System.out.print(0 + " "); - } - } - System.out.println(); + /** Prints a semblance of the board to console (helps in debugging) */ + public void printBoard() { + for (int i = 0; i < this.dimension.height; i++) { + for (SkyscrapersCell cell : this.getRowCol(i, SkyscrapersType.ANY, true)) { + if (cell.getType() == SkyscrapersType.Number) { + System.out.print(cell.getData() + " "); + } else { + System.out.print(0 + " "); } + } + System.out.println(); } + } - /** - * @param x position of cell - * @param y position of cell - * @param e Element to be placed (null if nothing selected) - * @param m MouseEvent Increases clue values if in editor mode. Currently allows for presetting - * tile values, though they will not be saved. - */ - @Override - public void setCell(int x, int y, Element e, MouseEvent m) { - SkyscrapersClue clue = this.getClue(x, y); - if (e == null) return; - if (clue != null) { - if (!e.getElementID().equals("SKYS-UNPL-0003")) { - return; - } + /** + * @param x position of cell + * @param y position of cell + * @param e Element to be placed (null if nothing selected) + * @param m MouseEvent Increases clue values if in editor mode. Currently allows for presetting + * tile values, though they will not be saved. + */ + @Override + public void setCell(int x, int y, Element e, MouseEvent m) { + SkyscrapersClue clue = this.getClue(x, y); + if (e == null) return; + if (clue != null) { + if (!e.getElementID().equals("SKYS-UNPL-0003")) { + return; + } - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.height) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } - } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } else { - clue.setData(dimension.height); - } - } + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.height) { + clue.setData(clue.getData() + 1); } else { - super.setCell(x - 1, y - 1, e, m); + clue.setData(0); } - } - - /** - * @param x position of element on boardView - * @param y position of element on boardView - * @return The clue at the given position - */ - public SkyscrapersClue getClue(int x, int y) { - int viewIndex = getSize() + 1; - if (x == 0 && y > 0 && y < viewIndex) { - return westClues.get(y - 1); - } else if (x == viewIndex && y > 0 && y < viewIndex) { - return eastClues.get(y - 1); - } else if (y == 0 && x > 0 && x < viewIndex) { - return northClues.get(x - 1); - } else if (y == viewIndex && x > 0 && x < viewIndex) { - return southClues.get(x - 1); + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.height); } - return null; + } + } else { + super.setCell(x - 1, y - 1, e, m); } + } - @Override - public SkyscrapersBoard copy() { - SkyscrapersBoard copy = new SkyscrapersBoard(dimension.width); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.eastClues = eastClues; - copy.southClues = southClues; - copy.westClues = westClues; - copy.northClues = northClues; + /** + * @param x position of element on boardView + * @param y position of element on boardView + * @return The clue at the given position + */ + public SkyscrapersClue getClue(int x, int y) { + int viewIndex = getSize() + 1; + if (x == 0 && y > 0 && y < viewIndex) { + return westClues.get(y - 1); + } else if (x == viewIndex && y > 0 && y < viewIndex) { + return eastClues.get(y - 1); + } else if (y == 0 && x > 0 && x < viewIndex) { + return northClues.get(x - 1); + } else if (y == viewIndex && x > 0 && x < viewIndex) { + return southClues.get(x - 1); + } + return null; + } - copy.dupeFlag = dupeFlag; - copy.viewFlag = viewFlag; - return copy; + @Override + public SkyscrapersBoard copy() { + SkyscrapersBoard copy = new SkyscrapersBoard(dimension.width); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.eastClues = eastClues; + copy.southClues = southClues; + copy.westClues = westClues; + copy.northClues = northClues; + + copy.dupeFlag = dupeFlag; + copy.viewFlag = viewFlag; + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java index 1cf9a357b..a315ac788 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java @@ -8,59 +8,59 @@ import java.awt.event.MouseEvent; public class SkyscrapersCell extends GridCell { - private int max; + private int max; - public SkyscrapersCell(Integer value, Point location, int size) { - super(value, location); - this.max = size; - } + public SkyscrapersCell(Integer value, Point location, int size) { + super(value, location); + this.max = size; + } - public SkyscrapersType getType() { - switch (convertToSkyType(data)) { - case UNKNOWN: - return SkyscrapersType.UNKNOWN; - default: - return SkyscrapersType.Number; - } + public SkyscrapersType getType() { + switch (convertToSkyType(data)) { + case UNKNOWN: + return SkyscrapersType.UNKNOWN; + default: + return SkyscrapersType.Number; } + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "SKYS-UNPL-0001": - this.data = 0; - break; - case "SKYS-UNPL-0002": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data <= 0 || this.data >= this.max) { - this.data = 1; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 1) { - this.data = this.data - 1; - } else { - this.data = this.max; - } - break; - } - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "SKYS-UNPL-0001": + this.data = 0; + break; + case "SKYS-UNPL-0002": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data <= 0 || this.data >= this.max) { + this.data = 1; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 1) { + this.data = this.data - 1; + } else { + this.data = this.max; + } + break; } + break; } + } - public int getMax() { - return max; - } + public int getMax() { + return max; + } - @Override - public SkyscrapersCell copy() { - SkyscrapersCell copy = new SkyscrapersCell(data, (Point) location.clone(), max); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public SkyscrapersCell copy() { + SkyscrapersCell copy = new SkyscrapersCell(data, (Point) location.clone(), max); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java index 03572b816..1f10b31d3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java @@ -10,67 +10,65 @@ import org.w3c.dom.Node; public class SkyscrapersCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if input is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Skyscrapers Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if input is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: unknown puzzleElement puzzleElement"); + } - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - int size = skyscrapersBoard.getSize(); - NamedNodeMap attributeList = node.getAttributes(); + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + int size = skyscrapersBoard.getSize(); + NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= size || y >= size) { - throw new InvalidFileFormatException( - "Skyscrapers Factory: cell location out of bounds"); - } - if (value < 0 || value > size) { - throw new InvalidFileFormatException("Skyscrapers Factory: cell unknown value"); - } + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= size || y >= size) { + throw new InvalidFileFormatException("Skyscrapers Factory: cell location out of bounds"); + } + if (value < 0 || value > size) { + throw new InvalidFileFormatException("Skyscrapers Factory: cell unknown value"); + } - SkyscrapersCell cell = new SkyscrapersCell(value, new Point(x, y), size); - cell.setIndex(y * size + x); + SkyscrapersCell cell = new SkyscrapersCell(value, new Point(x, y), size); + cell.setIndex(y * size + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Skyscrapers Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException( - "Skyscrapers Factory: could not find attribute(s)"); - } + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Skyscrapers Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java index 7b8bf635b..dd2bc5412 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java @@ -3,53 +3,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class SkyscrapersClue extends PuzzleElement { - private SkyscrapersType type; - private int clueIndex; - - public SkyscrapersClue(int value, int clueIndex, SkyscrapersType type) { - super(value); - this.index = -2; - this.clueIndex = clueIndex; // index in list - this.type = type; - this.setModifiable(false); + private SkyscrapersType type; + private int clueIndex; + + public SkyscrapersClue(int value, int clueIndex, SkyscrapersType type) { + super(value); + this.index = -2; + this.clueIndex = clueIndex; // index in list + this.type = type; + this.setModifiable(false); + } + + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; } - - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; - } - return sb.reverse().toString(); - } - - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; - } - return result; - } - - public int getClueIndex() { - return clueIndex; - } - - public SkyscrapersType getType() { - return type; - } - - public void setType(SkyscrapersType type) { - this.type = type; - } - - public SkyscrapersClue copy() { - SkyscrapersClue copy = new SkyscrapersClue(data, clueIndex, type); - copy.setIndex(index); - copy.setModifiable(isModifiable); - return copy; + return sb.reverse().toString(); + } + + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; } + return result; + } + + public int getClueIndex() { + return clueIndex; + } + + public SkyscrapersType getType() { + return type; + } + + public void setType(SkyscrapersType type) { + this.type = type; + } + + public SkyscrapersClue copy() { + SkyscrapersClue copy = new SkyscrapersClue(data, clueIndex, type); + copy.setIndex(index); + copy.setModifiable(isModifiable); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java index 5a49a1476..bd9abc162 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java @@ -5,55 +5,55 @@ public class SkyscrapersClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public SkyscrapersClueView(SkyscrapersClue clue) { - super(clue); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public SkyscrapersClueView(SkyscrapersClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public SkyscrapersClue getPuzzleElement() { + return (SkyscrapersClue) super.getPuzzleElement(); + } + + @Override + public void draw(Graphics2D graphics2D) { + drawElement(graphics2D); + if (this.isShowCasePicker() && this.isCaseRulePickable()) { + drawCase(graphics2D); + if (this.isHover()) { + drawHover(graphics2D); + } } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public SkyscrapersClue getPuzzleElement() { - return (SkyscrapersClue) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + SkyscrapersClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + case CLUE_EAST: + case CLUE_SOUTH: + case CLUE_WEST: + value = String.valueOf(clue.getData()); + break; + default: + value = ""; } - @Override - public void draw(Graphics2D graphics2D) { - drawElement(graphics2D); - if (this.isShowCasePicker() && this.isCaseRulePickable()) { - drawCase(graphics2D); - if (this.isHover()) { - drawHover(graphics2D); - } - } - } - - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - SkyscrapersClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - case CLUE_EAST: - case CLUE_SOUTH: - case CLUE_WEST: - value = String.valueOf(clue.getData()); - break; - default: - value = ""; - } - - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java index f78774e35..e0503382e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java @@ -6,29 +6,29 @@ public class SkyscrapersController extends ElementController { - public SkyscrapersController() { - super(); - } + public SkyscrapersController() { + super(); + } - @Override - public void changeCell(MouseEvent e, PuzzleElement element) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (e.getButton() == MouseEvent.BUTTON1) { - if (cell.getData() < cell.getMax()) { - int num = cell.getData() + 1; - cell.setData(num); - } else { - cell.setData(SkyscrapersType.UNKNOWN.toValue()); - } + @Override + public void changeCell(MouseEvent e, PuzzleElement element) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (e.getButton() == MouseEvent.BUTTON1) { + if (cell.getData() < cell.getMax()) { + int num = cell.getData() + 1; + cell.setData(num); + } else { + cell.setData(SkyscrapersType.UNKNOWN.toValue()); + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() > 0) { + int num = cell.getData() - 1; + cell.setData(num); } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() > 0) { - int num = cell.getData() - 1; - cell.setData(num); - } else { - cell.setData(cell.getMax()); - } - } + cell.setData(cell.getMax()); } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java index 2f33017c3..397ab5a93 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java @@ -4,34 +4,33 @@ import java.awt.*; public class SkyscrapersElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = new Color(0x212121); - private static final Color BORDER_COLOR = new Color(0x424242); - private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = new Color(0x212121); + private static final Color BORDER_COLOR = new Color(0x424242); + private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); - public SkyscrapersElementView(SkyscrapersCell cell) { - super(cell); - } + public SkyscrapersElementView(SkyscrapersCell cell) { + super(cell); + } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BACKGROUND_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BORDER_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BACKGROUND_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BORDER_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - int val = cell.getData(); - if (val != 0) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(val); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = - location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + int val = cell.getData(); + if (val != 0) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(val); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java index 75d2bd04f..5d85d950e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java @@ -6,62 +6,58 @@ public class SkyscrapersExporter extends PuzzleExporter { - public SkyscrapersExporter(Skyscrapers skyscrapers) { - super(skyscrapers); + public SkyscrapersExporter(Skyscrapers skyscrapers) { + super(skyscrapers); + } + + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + SkyscrapersBoard board; + if (puzzle.getTree() != null) { + board = (SkyscrapersBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (SkyscrapersBoard) puzzle.getBoardView().getBoard(); } - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - SkyscrapersBoard board; - if (puzzle.getTree() != null) { - board = (SkyscrapersBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (SkyscrapersBoard) puzzle.getBoardView().getBoard(); - } - - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("size", String.valueOf(board.getWidth())); - - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - if (cell.getData() != 0) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); - - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (int i = 0; i < board.getWidth(); i++) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute( - "value", String.valueOf(board.getEastClues().get(i).getData())); - clueElement.setAttribute( - "index", String.valueOf(board.getWestClues().get(i).getData())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); - - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (int i = 0; i < board.getWidth(); i++) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute( - "value", String.valueOf(board.getSouthClues().get(i).getData())); - clueElement.setAttribute( - "index", String.valueOf(board.getNorthClues().get(i).getData())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("size", String.valueOf(board.getWidth())); + + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + if (cell.getData() != 0) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); + + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (int i = 0; i < board.getWidth(); i++) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(board.getEastClues().get(i).getData())); + clueElement.setAttribute("index", String.valueOf(board.getWestClues().get(i).getData())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); + + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (int i = 0; i < board.getWidth(); i++) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(board.getSouthClues().get(i).getData())); + clueElement.setAttribute("index", String.valueOf(board.getNorthClues().get(i).getData())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); - org.w3c.dom.Element flagsElement = newDocument.createElement("flags"); - flagsElement.setAttribute("dupe", String.valueOf(board.getDupeFlag())); - flagsElement.setAttribute("view", String.valueOf(board.getViewFlag())); - boardElement.appendChild(flagsElement); + org.w3c.dom.Element flagsElement = newDocument.createElement("flags"); + flagsElement.setAttribute("dupe", String.valueOf(board.getDupeFlag())); + flagsElement.setAttribute("view", String.valueOf(board.getViewFlag())); + boardElement.appendChild(flagsElement); - return boardElement; - } + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java index 0fc7e6c39..23b9a03a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java @@ -8,217 +8,205 @@ import org.w3c.dom.NodeList; public class SkyscrapersImporter extends PuzzleImporter { - public SkyscrapersImporter(Skyscrapers skyscrapers) { - super(skyscrapers); + public SkyscrapersImporter(Skyscrapers skyscrapers) { + super(skyscrapers); + } + + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } + + @Override + public boolean acceptsTextInput() { + return false; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + // assert(rows == columns); + int size = rows; + SkyscrapersBoard skyscrapersBoard = new SkyscrapersBoard(size); + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + SkyscrapersCell cell = + new SkyscrapersCell(SkyscrapersType.UNKNOWN.toValue(), new Point(x, y), size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + skyscrapersBoard.setCell(x, y, cell); + } } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; + for (int i = 0; i < size; i++) { + skyscrapersBoard + .getWestClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_WEST)); + skyscrapersBoard + .getEastClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_EAST)); } - @Override - public boolean acceptsTextInput() { - return false; + for (int i = 0; i < size; i++) { + skyscrapersBoard + .getNorthClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_NORTH)); + skyscrapersBoard + .getSouthClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_SOUTH)); } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - // assert(rows == columns); - int size = rows; - SkyscrapersBoard skyscrapersBoard = new SkyscrapersBoard(size); - - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - SkyscrapersCell cell = - new SkyscrapersCell( - SkyscrapersType.UNKNOWN.toValue(), new Point(x, y), size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - skyscrapersBoard.setCell(x, y, cell); - } + puzzle.setCurrentBoard(skyscrapersBoard); + } + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Skyscrapers Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + + SkyscrapersBoard skyscrapersBoard = null; + + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + skyscrapersBoard = new SkyscrapersBoard(size); + } + + if (skyscrapersBoard == null) { + throw new InvalidFileFormatException("Skyscraper Importer: invalid board dimensions"); + } + + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Skyscrapers Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + int size = skyscrapersBoard.getSize(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + SkyscrapersCell cell = + (SkyscrapersCell) + puzzle.getFactory().importCell(elementDataList.item(i), skyscrapersBoard); + Point loc = cell.getLocation(); + if (cell.getData() != 0) { + cell.setModifiable(false); + cell.setGiven(true); } - - for (int i = 0; i < size; i++) { - skyscrapersBoard - .getWestClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_WEST)); - skyscrapersBoard - .getEastClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_EAST)); + skyscrapersBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + if (skyscrapersBoard.getCell(x, y) == null) { + SkyscrapersCell cell = + new SkyscrapersCell(SkyscrapersType.UNKNOWN.value, new Point(x, y), size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + skyscrapersBoard.setCell(x, y, cell); + } } - - for (int i = 0; i < size; i++) { - skyscrapersBoard - .getNorthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_NORTH)); - skyscrapersBoard - .getSouthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_SOUTH)); + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("Skyscraper Importer: cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { + throw new InvalidFileFormatException( + "Skyscraper Importer: side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "Skyscraper Importer: axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != skyscrapersBoard.getHeight() + || southClues.getLength() != skyscrapersBoard.getWidth()) { + throw new InvalidFileFormatException( + "Skyscraper Importer: there must be same number of clues as the dimension" + + " of the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + skyscrapersBoard + .getWestClues() + .set(/*index - 1*/ i, new SkyscrapersClue(index, i, SkyscrapersType.CLUE_WEST)); + skyscrapersBoard + .getEastClues() + .set(/*index - 1*/ i, new SkyscrapersClue(value, i, SkyscrapersType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + skyscrapersBoard + .getNorthClues() + .set(/*index - 1*/ i, new SkyscrapersClue(index, i, SkyscrapersType.CLUE_NORTH)); + skyscrapersBoard + .getSouthClues() + .set(/*index - 1*/ i, new SkyscrapersClue(value, i, SkyscrapersType.CLUE_SOUTH)); + } + + NodeList flagList = boardElement.getElementsByTagName("flags"); + if (flagList.getLength() == 1) { + Element flags = (Element) flagList.item(0); + if (flags.hasAttribute("dupe")) { + skyscrapersBoard.setDupeFlag(Boolean.parseBoolean(flags.getAttribute("dupe"))); } - - puzzle.setCurrentBoard(skyscrapersBoard); - } - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "Skyscrapers Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - - SkyscrapersBoard skyscrapersBoard = null; - - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - skyscrapersBoard = new SkyscrapersBoard(size); - } - - if (skyscrapersBoard == null) { - throw new InvalidFileFormatException( - "Skyscraper Importer: invalid board dimensions"); - } - - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "Skyscrapers Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - int size = skyscrapersBoard.getSize(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - SkyscrapersCell cell = - (SkyscrapersCell) - puzzle.getFactory() - .importCell(elementDataList.item(i), skyscrapersBoard); - Point loc = cell.getLocation(); - if (cell.getData() != 0) { - cell.setModifiable(false); - cell.setGiven(true); - } - skyscrapersBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - if (skyscrapersBoard.getCell(x, y) == null) { - SkyscrapersCell cell = - new SkyscrapersCell( - SkyscrapersType.UNKNOWN.value, new Point(x, y), size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - skyscrapersBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("Skyscraper Importer: cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { - throw new InvalidFileFormatException( - "Skyscraper Importer: side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "Skyscraper Importer: axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != skyscrapersBoard.getHeight() - || southClues.getLength() != skyscrapersBoard.getWidth()) { - throw new InvalidFileFormatException( - "Skyscraper Importer: there must be same number of clues as the dimension" - + " of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - skyscrapersBoard - .getWestClues() - .set( - /*index - 1*/ i, - new SkyscrapersClue(index, i, SkyscrapersType.CLUE_WEST)); - skyscrapersBoard - .getEastClues() - .set( - /*index - 1*/ i, - new SkyscrapersClue(value, i, SkyscrapersType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - skyscrapersBoard - .getNorthClues() - .set( - /*index - 1*/ i, - new SkyscrapersClue(index, i, SkyscrapersType.CLUE_NORTH)); - skyscrapersBoard - .getSouthClues() - .set( - /*index - 1*/ i, - new SkyscrapersClue(value, i, SkyscrapersType.CLUE_SOUTH)); - } - - NodeList flagList = boardElement.getElementsByTagName("flags"); - if (flagList.getLength() == 1) { - Element flags = (Element) flagList.item(0); - if (flags.hasAttribute("dupe")) { - skyscrapersBoard.setDupeFlag(Boolean.parseBoolean(flags.getAttribute("dupe"))); - } - if (flags.hasAttribute("view")) { - skyscrapersBoard.setViewFlag(Boolean.parseBoolean(flags.getAttribute("view"))); - } - } - - puzzle.setCurrentBoard(skyscrapersBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Skyscraper Importer: unknown value where integer expected"); + if (flags.hasAttribute("view")) { + skyscrapersBoard.setViewFlag(Boolean.parseBoolean(flags.getAttribute("view"))); } - } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Skyscrapers cannot accept text input"); + puzzle.setCurrentBoard(skyscrapersBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Skyscraper Importer: unknown value where integer expected"); } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Skyscrapers cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java index 4c150e8ae..e9feeed47 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java @@ -1,40 +1,40 @@ package edu.rpi.legup.puzzle.skyscrapers; public enum SkyscrapersType { - UNKNOWN(0), - Number(1), - CLUE_NORTH(-1), - CLUE_EAST(-2), - CLUE_SOUTH(-3), - CLUE_WEST(-4), - ANY(-5); + UNKNOWN(0), + Number(1), + CLUE_NORTH(-1), + CLUE_EAST(-2), + CLUE_SOUTH(-3), + CLUE_WEST(-4), + ANY(-5); - public int value; + public int value; - SkyscrapersType(int value) { - this.value = value; - } + SkyscrapersType(int value) { + this.value = value; + } - public int toValue() { - return value; - } + public int toValue() { + return value; + } - public static SkyscrapersType convertToSkyType(int num) { - switch (num) { - case 0: - return UNKNOWN; - case -1: - return CLUE_NORTH; - case -2: - return CLUE_EAST; - case -3: - return CLUE_SOUTH; - case -4: - return CLUE_WEST; - case -5: - return ANY; - default: - return Number; - } + public static SkyscrapersType convertToSkyType(int num) { + switch (num) { + case 0: + return UNKNOWN; + case -1: + return CLUE_NORTH; + case -2: + return CLUE_EAST; + case -3: + return CLUE_SOUTH; + case -4: + return CLUE_WEST; + case -5: + return ANY; + default: + return Number; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java index edd2cdbf5..b922c808a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java @@ -12,195 +12,188 @@ import org.apache.logging.log4j.Logger; public class SkyscrapersView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(SkyscrapersView.class.getName()); - - private ArrayList northClues; - private ArrayList eastClues; - private ArrayList southClues; - private ArrayList westClues; - - public SkyscrapersView(SkyscrapersBoard board) { - super(new BoardController(), new SkyscrapersController(), board.getDimension()); - - this.northClues = new ArrayList<>(); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); - SkyscrapersElementView elementView = new SkyscrapersElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); - elementViews.add(elementView); - } + private static final Logger LOGGER = LogManager.getLogger(SkyscrapersView.class.getName()); + + private ArrayList northClues; + private ArrayList eastClues; + private ArrayList southClues; + private ArrayList westClues; + + public SkyscrapersView(SkyscrapersBoard board) { + super(new BoardController(), new SkyscrapersController(), board.getDimension()); + + this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); + SkyscrapersElementView elementView = new SkyscrapersElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); + elementViews.add(elementView); + } - for (int i = 0; i < gridSize.height; i++) { - SkyscrapersClueView row = new SkyscrapersClueView(board.getWestClues().get(i)); - row.setLocation(new Point(0, (i + 1) * elementSize.height)); - row.setSize(elementSize); + for (int i = 0; i < gridSize.height; i++) { + SkyscrapersClueView row = new SkyscrapersClueView(board.getWestClues().get(i)); + row.setLocation(new Point(0, (i + 1) * elementSize.height)); + row.setSize(elementSize); - SkyscrapersClueView clue = new SkyscrapersClueView(board.getEastClues().get(i)); - clue.setLocation( - new Point( - (gridSize.height + 1) * elementSize.height, - (i + 1) * elementSize.height)); - clue.setSize(elementSize); + SkyscrapersClueView clue = new SkyscrapersClueView(board.getEastClues().get(i)); + clue.setLocation( + new Point((gridSize.height + 1) * elementSize.height, (i + 1) * elementSize.height)); + clue.setSize(elementSize); - westClues.add(row); - eastClues.add(clue); - } + westClues.add(row); + eastClues.add(clue); + } - for (int i = 0; i < gridSize.width; i++) { - SkyscrapersClueView col = new SkyscrapersClueView(board.getNorthClues().get(i)); - col.setLocation(new Point((i + 1) * elementSize.width, 0)); - col.setSize(elementSize); + for (int i = 0; i < gridSize.width; i++) { + SkyscrapersClueView col = new SkyscrapersClueView(board.getNorthClues().get(i)); + col.setLocation(new Point((i + 1) * elementSize.width, 0)); + col.setSize(elementSize); - SkyscrapersClueView clue = new SkyscrapersClueView(board.getSouthClues().get(i)); - clue.setLocation( - new Point( - (i + 1) * elementSize.width, (gridSize.width + 1) * elementSize.width)); - clue.setSize(elementSize); + SkyscrapersClueView clue = new SkyscrapersClueView(board.getSouthClues().get(i)); + clue.setLocation( + new Point((i + 1) * elementSize.width, (gridSize.width + 1) * elementSize.width)); + clue.setSize(elementSize); - northClues.add(col); - southClues.add(clue); - } + northClues.add(col); + southClues.add(clue); } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - @Override - public ElementView getElement(Point point) { - Point scaledPoint = - new Point( - (int) Math.round(point.x / getScale()), - (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - for (SkyscrapersClueView clueView : northClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : eastClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : southClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : westClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - return null; - } - - public ArrayList getNorthClues() { - return northClues; - } - - public ArrayList getWestClues() { - return westClues; - } - - @Override - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = (gridSize.width + 2) * elementSize.width; - boardViewSize.height = (gridSize.height + 2) * elementSize.height; - return boardViewSize; - } - - /** - * Sets the board associated with this view - * - * @param board board - */ - @Override - public void setBoard(Board board) { - if (this.board != board) { - this.board = board; - - if (board instanceof CaseBoard) { - setCasePickable(); - } else { - for (ElementView elementView : elementViews) { - elementView.setPuzzleElement( - board.getPuzzleElement(elementView.getPuzzleElement())); - elementView.setShowCasePicker(false); - } - for (SkyscrapersClueView clueView : northClues) { - clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); - clueView.setShowCasePicker(false); - } - for (SkyscrapersClueView clueView : westClues) { - clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); - clueView.setShowCasePicker(false); - } - } - } + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + @Override + public ElementView getElement(Point point) { + Point scaledPoint = + new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } } - - @Override - protected void setCasePickable() { - CaseBoard caseBoard = (CaseBoard) board; - Board baseBoard = caseBoard.getBaseBoard(); - + for (SkyscrapersClueView clueView : northClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : eastClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : southClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : westClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + return null; + } + + public ArrayList getNorthClues() { + return northClues; + } + + public ArrayList getWestClues() { + return westClues; + } + + @Override + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = (gridSize.width + 2) * elementSize.width; + boardViewSize.height = (gridSize.height + 2) * elementSize.height; + return boardViewSize; + } + + /** + * Sets the board associated with this view + * + * @param board board + */ + @Override + public void setBoard(Board board) { + if (this.board != board) { + this.board = board; + + if (board instanceof CaseBoard) { + setCasePickable(); + } else { for (ElementView elementView : elementViews) { - PuzzleElement puzzleElement = - baseBoard.getPuzzleElement(elementView.getPuzzleElement()); - elementView.setPuzzleElement(puzzleElement); - elementView.setShowCasePicker(true); - elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); + elementView.setShowCasePicker(false); } for (SkyscrapersClueView clueView : northClues) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); - clueView.setPuzzleElement(puzzleElement); - clueView.setShowCasePicker(true); - clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); + clueView.setShowCasePicker(false); } for (SkyscrapersClueView clueView : westClues) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); - clueView.setPuzzleElement(puzzleElement); - clueView.setShowCasePicker(true); - clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); + clueView.setShowCasePicker(false); } + } } + } + + @Override + protected void setCasePickable() { + CaseBoard caseBoard = (CaseBoard) board; + Board baseBoard = caseBoard.getBaseBoard(); + + for (ElementView elementView : elementViews) { + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); + elementView.setPuzzleElement(puzzleElement); + elementView.setShowCasePicker(true); + elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + for (SkyscrapersClueView clueView : northClues) { + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); + clueView.setPuzzleElement(puzzleElement); + clueView.setShowCasePicker(true); + clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + for (SkyscrapersClueView clueView : westClues) { + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); + clueView.setPuzzleElement(puzzleElement); + clueView.setShowCasePicker(true); + clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + } - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); - for (SkyscrapersClueView clueView : northClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : northClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : eastClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : eastClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : southClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : southClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : westClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : westClues) { + clueView.draw(graphics2D); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java index 64c9033e6..e66e67f1c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java @@ -4,11 +4,11 @@ public class ClueTile extends NonPlaceableElement { - public ClueTile() { - super( - "SKYS-UNPL-0003", - "Clue Tile", - "Clue Updater", - "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); - } + public ClueTile() { + super( + "SKYS-UNPL-0003", + "Clue Tile", + "Clue Updater", + "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java index 4d6b37c9a..6df519c96 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - public NumberTile() { - super( - "SKYS-UNPL-0002", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); - } + public NumberTile() { + super( + "SKYS-UNPL-0002", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java index 2fb21193a..ee25f38c0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "SKYS-UNPL-0001", - "Unknown", - "A blank tile", - "edu/rpi/legup/images/skyscrapers/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "SKYS-UNPL-0001", + "Unknown", + "A blank tile", + "edu/rpi/legup/images/skyscrapers/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java index 45bdadea3..0889b0c25 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java @@ -12,189 +12,184 @@ import javax.swing.*; public class CellForNumberCaseRule extends CaseRule { - public CellForNumberCaseRule() { - super( - "SKYS-CASE-0002", - "Cell For Number", - "A number (1-n) must appear in any given row/column", - "edu/rpi/legup/images/skyscrapers/cases/CellForNumber.png"); + public CellForNumberCaseRule() { + super( + "SKYS-CASE-0002", + "Cell For Number", + "A number (1-n) must appear in any given row/column", + "edu/rpi/legup/images/skyscrapers/cases/CellForNumber.png"); + } + + private Integer selectedNumber; + + @Override + public CaseBoard getCaseBoard(Board board) { + SkyscrapersBoard currentBoard = (SkyscrapersBoard) board.copy(); + currentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(currentBoard, this); + for (SkyscrapersClue data : currentBoard.getWestClues()) { + // System.out.println(data.getType()); + caseBoard.addPickableElement(data); } - - private Integer selectedNumber; - - @Override - public CaseBoard getCaseBoard(Board board) { - SkyscrapersBoard currentBoard = (SkyscrapersBoard) board.copy(); - currentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(currentBoard, this); - for (SkyscrapersClue data : currentBoard.getWestClues()) { - // System.out.println(data.getType()); - caseBoard.addPickableElement(data); - } - for (SkyscrapersClue data : currentBoard.getNorthClues()) { - // System.out.println(data.getType()); - caseBoard.addPickableElement(data); - } - - // selects integer before checking Command.canExecute for use in Command.getErrorString - int size = ((SkyscrapersBoard) board).getWidth(); - Object[] possibleValues = new Object[size]; - for (int i = 0; i < size; i++) { - possibleValues[i] = i + 1; - } - Object selectedValue; - do { - selectedValue = - JOptionPane.showInputDialog( - null, - "Pick the number to be added", - "Cell For Number", - JOptionPane.INFORMATION_MESSAGE, - null, - possibleValues, - possibleValues[0]); - } while (selectedValue == null); - selectedNumber = (Integer) selectedValue; - - return caseBoard; + for (SkyscrapersClue data : currentBoard.getNorthClues()) { + // System.out.println(data.getType()); + caseBoard.addPickableElement(data); } - public ArrayList getCasesFor(Board board, PuzzleElement puzzleElement, Integer number) { - ArrayList cases = new ArrayList<>(); - - SkyscrapersClue clue = (SkyscrapersClue) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - - List openCells = - skyscrapersboard.getRowCol( - clue.getClueIndex(), - SkyscrapersType.UNKNOWN, - clue.getType() == SkyscrapersType.CLUE_WEST); - for (SkyscrapersCell cell : openCells) { - SkyscrapersBoard newCase = skyscrapersboard.copy(); - PuzzleElement newCell = newCase.getPuzzleElement(cell); - newCell.setData(number); - newCase.addModifiedData(newCell); - - // if flags - boolean passed = true; - if (skyscrapersboard.getDupeFlag()) { - DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); - passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; - } - if (skyscrapersboard.getViewFlag()) { - PreemptiveVisibilityContradictionRule ViewRule = - new PreemptiveVisibilityContradictionRule(); - passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; - } - if (passed) { - cases.add(newCase); - } - } - return cases; + // selects integer before checking Command.canExecute for use in Command.getErrorString + int size = ((SkyscrapersBoard) board).getWidth(); + Object[] possibleValues = new Object[size]; + for (int i = 0; i < size; i++) { + possibleValues[i] = i + 1; } - - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - return getCasesFor(board, puzzleElement, selectedNumber); + Object selectedValue; + do { + selectedValue = + JOptionPane.showInputDialog( + null, + "Pick the number to be added", + "Cell For Number", + JOptionPane.INFORMATION_MESSAGE, + null, + possibleValues, + possibleValues[0]); + } while (selectedValue == null); + selectedNumber = (Integer) selectedValue; + + return caseBoard; + } + + public ArrayList getCasesFor(Board board, PuzzleElement puzzleElement, Integer number) { + ArrayList cases = new ArrayList<>(); + + SkyscrapersClue clue = (SkyscrapersClue) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + + List openCells = + skyscrapersboard.getRowCol( + clue.getClueIndex(), + SkyscrapersType.UNKNOWN, + clue.getType() == SkyscrapersType.CLUE_WEST); + for (SkyscrapersCell cell : openCells) { + SkyscrapersBoard newCase = skyscrapersboard.copy(); + PuzzleElement newCell = newCase.getPuzzleElement(cell); + newCell.setData(number); + newCase.addModifiedData(newCell); + + // if flags + boolean passed = true; + if (skyscrapersboard.getDupeFlag()) { + DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); + passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; + } + if (skyscrapersboard.getViewFlag()) { + PreemptiveVisibilityContradictionRule ViewRule = + new PreemptiveVisibilityContradictionRule(); + passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; + } + if (passed) { + cases.add(newCase); + } } - - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - SkyscrapersBoard oldBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - if (childTransitions.size() == 0) { - return "This case rule must have at least one child."; - } - - if (childTransitions.size() - != getCasesFor( - oldBoard, - oldBoard.getPuzzleElement(transition.getSelection()), - (Integer) - childTransitions - .get(0) - .getBoard() - .getModifiedData() - .iterator() - .next() - .getData()) - .size()) { - // System.out.println("Wrong number of cases."); - return "Wrong number of cases."; - } - - for (TreeTransition newTree : childTransitions) { - SkyscrapersBoard newBoard = (SkyscrapersBoard) newTree.getBoard(); - if (newBoard.getModifiedData().size() != 1) { - // System.out.println("Only one cell should be modified."); - return "Only one cell should be modified."; - } - SkyscrapersCell newCell = - (SkyscrapersCell) newBoard.getModifiedData().iterator().next(); - if (newCell.getType() != SkyscrapersType.Number) { - // System.out.println("Changed value should be a number."); - return "Changed value should be a number."; - } - } - return null; + return cases; + } + + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + return getCasesFor(board, puzzleElement, selectedNumber); + } + + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + SkyscrapersBoard oldBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + if (childTransitions.size() == 0) { + return "This case rule must have at least one child."; } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + if (childTransitions.size() + != getCasesFor( + oldBoard, + oldBoard.getPuzzleElement(transition.getSelection()), + (Integer) + childTransitions + .get(0) + .getBoard() + .getModifiedData() + .iterator() + .next() + .getData()) + .size()) { + // System.out.println("Wrong number of cases."); + return "Wrong number of cases."; } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; - SkyscrapersClue clue = (SkyscrapersClue) puzzleBoard.getPuzzleElement(puzzleElement); - - // check each point in modified row/col - List data = - puzzleBoard.getRowCol( - clue.getClueIndex(), - SkyscrapersType.ANY, - clue.getType() == SkyscrapersType.CLUE_WEST); - for (SkyscrapersCell point : data) { - List cells = new ArrayList<>(List.of(point)); - - // if dependent on row/col - if ((puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) - && point.getType() == SkyscrapersType.UNKNOWN) { - // get perpendicular row/col intersecting this point - int index; - if (clue.getType() == SkyscrapersType.CLUE_WEST) { - index = point.getLocation().x; - } else { - index = point.getLocation().y; - } - cells.addAll( - puzzleBoard.getRowCol( - index, - SkyscrapersType.ANY, - clue.getType() != SkyscrapersType.CLUE_WEST)); - } - - // add all to result - for (SkyscrapersCell cell : cells) { - if (!elements.contains(board.getPuzzleElement(cell))) { - elements.add(board.getPuzzleElement(cell)); - } - } + for (TreeTransition newTree : childTransitions) { + SkyscrapersBoard newBoard = (SkyscrapersBoard) newTree.getBoard(); + if (newBoard.getModifiedData().size() != 1) { + // System.out.println("Only one cell should be modified."); + return "Only one cell should be modified."; + } + SkyscrapersCell newCell = (SkyscrapersCell) newBoard.getModifiedData().iterator().next(); + if (newCell.getType() != SkyscrapersType.Number) { + // System.out.println("Changed value should be a number."); + return "Changed value should be a number."; + } + } + return null; + } + + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; + SkyscrapersClue clue = (SkyscrapersClue) puzzleBoard.getPuzzleElement(puzzleElement); + + // check each point in modified row/col + List data = + puzzleBoard.getRowCol( + clue.getClueIndex(), SkyscrapersType.ANY, clue.getType() == SkyscrapersType.CLUE_WEST); + for (SkyscrapersCell point : data) { + List cells = new ArrayList<>(List.of(point)); + + // if dependent on row/col + if ((puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) + && point.getType() == SkyscrapersType.UNKNOWN) { + // get perpendicular row/col intersecting this point + int index; + if (clue.getType() == SkyscrapersType.CLUE_WEST) { + index = point.getLocation().x; + } else { + index = point.getLocation().y; } - - return elements; + cells.addAll( + puzzleBoard.getRowCol( + index, SkyscrapersType.ANY, clue.getType() != SkyscrapersType.CLUE_WEST)); + } + + // add all to result + for (SkyscrapersCell cell : cells) { + if (!elements.contains(board.getPuzzleElement(cell))) { + elements.add(board.getPuzzleElement(cell)); + } + } } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java index b13a62bc6..194bb905b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java @@ -12,57 +12,57 @@ public class DuplicateNumberContradictionRule extends ContradictionRule { - public DuplicateNumberContradictionRule() { - super( - "SKYS-CONT-0001", - "Duplicate Number", - "Skyscrapers of same height cannot be placed in the same row or column.", - "edu/rpi/legup/images/skyscrapers/contradictions/DuplicateNumber.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + public DuplicateNumberContradictionRule() { + super( + "SKYS-CONT-0001", + "Duplicate Number", + "Skyscrapers of same height cannot be placed in the same row or column.", + "edu/rpi/legup/images/skyscrapers/contradictions/DuplicateNumber.png"); + } - Set candidates = new HashSet(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - // check row - for (int i = 0; i < skyscrapersboard.getWidth(); i++) { - SkyscrapersCell c = skyscrapersboard.getCell(i, loc.y); - if (i != loc.x - && cell.getType() == SkyscrapersType.Number - && c.getType() == SkyscrapersType.Number - && c.getData() == cell.getData()) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - return null; - } - } + Set candidates = new HashSet(); - // check column - for (int i = 0; i < skyscrapersboard.getHeight(); i++) { - SkyscrapersCell c = skyscrapersboard.getCell(loc.x, i); - if (i != loc.y - && cell.getType() == SkyscrapersType.Number - && c.getType() == SkyscrapersType.Number - && c.getData() == cell.getData()) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - return null; - } - } + // check row + for (int i = 0; i < skyscrapersboard.getWidth(); i++) { + SkyscrapersCell c = skyscrapersboard.getCell(i, loc.y); + if (i != loc.x + && cell.getType() == SkyscrapersType.Number + && c.getType() == SkyscrapersType.Number + && c.getData() == cell.getData()) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + return null; + } + } - return super.getNoContradictionMessage(); + // check column + for (int i = 0; i < skyscrapersboard.getHeight(); i++) { + SkyscrapersCell c = skyscrapersboard.getCell(loc.x, i); + if (i != loc.y + && cell.getType() == SkyscrapersType.Number + && c.getType() == SkyscrapersType.Number + && c.getData() == cell.getData()) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + return null; + } } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java index 742bdb253..08929e856 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java @@ -12,128 +12,127 @@ public class ExceedingVisibilityContradictionRule extends ContradictionRule { - public ExceedingVisibilityContradictionRule() { - super( - "SKYS-CONT-0002", - "Exceeding Visibility", - "More skyscrapers are visible than there should be.", - "edu/rpi/legup/images/skyscrapers/contradictions/ExceedingVisibility.png"); - } + public ExceedingVisibilityContradictionRule() { + super( + "SKYS-CONT-0002", + "Exceeding Visibility", + "More skyscrapers are visible than there should be.", + "edu/rpi/legup/images/skyscrapers/contradictions/ExceedingVisibility.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - // get borders - int west = skyscrapersboard.getWestClues().get(loc.y).getData(); - int east = skyscrapersboard.getEastClues().get(loc.y).getData(); - int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); - int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); + // get borders + int west = skyscrapersboard.getWestClues().get(loc.y).getData(); + int east = skyscrapersboard.getEastClues().get(loc.y).getData(); + int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); + int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); - // check row - int max = 0; - int count = 0; - List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); - if (row.size() == skyscrapersboard.getWidth()) { - // from west border - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > west) { - return null; - } + // check row + int max = 0; + int count = 0; + List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); + if (row.size() == skyscrapersboard.getWidth()) { + // from west border + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > west) { + return null; + } - max = 0; - count = 0; - // from east border - Collections.reverse(row); - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > east) { - return null; - } + max = 0; + count = 0; + // from east border + Collections.reverse(row); + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; } + } + if (count > east) { + return null; + } + } - // check column - List col = - skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); - if (col.size() == skyscrapersboard.getHeight()) { - // from north border - max = 0; - count = 0; - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // check column + List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); + if (col.size() == skyscrapersboard.getHeight()) { + // from north border + max = 0; + count = 0; + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > north) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > north) { + return null; + } - // from south border - max = 0; - count = 0; - Collections.reverse(col); - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // from south border + max = 0; + count = 0; + Collections.reverse(col); + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > south) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; } - - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); + } + if (count > south) { + return null; + } } - /** - * Checks whether the Skyscraper cell has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the Skyscraper cell contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } - } - return "No instance of the contradiction " + this.ruleName + " here"; + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } + + /** + * Checks whether the Skyscraper cell has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the Skyscraper cell contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } } + return "No instance of the contradiction " + this.ruleName + " here"; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java index fa7c9074e..d969a3415 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java @@ -12,129 +12,128 @@ public class InsufficientVisibilityContradictionRule extends ContradictionRule { - public InsufficientVisibilityContradictionRule() { - super( - "SKYS-CONT-0003", - "Insufficient Visibility", - "Less skyscrapers are visible than there should be.", - "edu/rpi/legup/images/skyscrapers/contradictions/InsufficientVisibility.png"); - } + public InsufficientVisibilityContradictionRule() { + super( + "SKYS-CONT-0003", + "Insufficient Visibility", + "Less skyscrapers are visible than there should be.", + "edu/rpi/legup/images/skyscrapers/contradictions/InsufficientVisibility.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - // get borders - int west = skyscrapersboard.getWestClues().get(loc.y).getData(); - int east = skyscrapersboard.getEastClues().get(loc.y).getData(); - int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); - int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); + // get borders + int west = skyscrapersboard.getWestClues().get(loc.y).getData(); + int east = skyscrapersboard.getEastClues().get(loc.y).getData(); + int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); + int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); - // check row - int max = 0; - int count = 0; - java.util.List row = - skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); - if (row.size() == skyscrapersboard.getWidth()) { - // from west border - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < west) { - return null; - } + // check row + int max = 0; + int count = 0; + java.util.List row = + skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); + if (row.size() == skyscrapersboard.getWidth()) { + // from west border + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < west) { + return null; + } - max = 0; - count = 0; - // from east border - Collections.reverse(row); - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < east) { - return null; - } + max = 0; + count = 0; + // from east border + Collections.reverse(row); + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; } + } + if (count < east) { + return null; + } + } - // check column - List col = - skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); - if (col.size() == skyscrapersboard.getHeight()) { - // from north border - max = 0; - count = 0; - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // check column + List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); + if (col.size() == skyscrapersboard.getHeight()) { + // from north border + max = 0; + count = 0; + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < north) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < north) { + return null; + } - // from south border - max = 0; - count = 0; - Collections.reverse(col); - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // from south border + max = 0; + count = 0; + Collections.reverse(col); + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < south) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; } - - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); + } + if (count < south) { + return null; + } } - /** - * Checks whether the Skyscraper cell has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the Skyscraper cell contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } - } - return "No instance of the contradiction " + this.ruleName + " here"; + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } + + /** + * Checks whether the Skyscraper cell has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the Skyscraper cell contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } } + return "No instance of the contradiction " + this.ruleName + " here"; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java index 391448781..3d8649290 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java @@ -12,118 +12,115 @@ public class LastSingularCellDirectRule extends DirectRule { - public LastSingularCellDirectRule() { - super( - "SKYS-BASC-0002", - "Last Cell for Number", - "There is only one cell on this row/col for this number that does not create a" - + " duplicate contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); - } + public LastSingularCellDirectRule() { + super( + "SKYS-BASC-0002", + "Last Cell for Number", + "There is only one cell on this row/col for this number that does not create a" + + " duplicate contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = - (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN - && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN + && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getWestClues().get(finalCell.getLocation().y), - (Integer) finalCell.getData()); - ArrayList YCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getNorthClues().get(finalCell.getLocation().x), - (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getWestClues().get(finalCell.getLocation().y), + (Integer) finalCell.getData()); + ArrayList YCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getNorthClues().get(finalCell.getLocation().x), + (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - // System.out.println(XCandidates.size()); - // System.out.println(YCandidates.size()); + // System.out.println(XCandidates.size()); + // System.out.println(YCandidates.size()); - // return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + // return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; } + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + } - // helper to check if candidate list is valid - private String candidateCheck( - ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() - == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() - == finalCell.getData()) { - return null; - } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; + // helper to check if candidate list is valid + private String candidateCheck( + ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() + == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; } - return ": This cell is not forced."; + return ": Wrong number in the cell."; + } + return ": No case for this cell."; } + return ": This cell is not forced."; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java index fceee0cd1..f95c1ace2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java @@ -12,92 +12,89 @@ public class LastSingularNumberDirectRule extends DirectRule { - public LastSingularNumberDirectRule() { - super( - "SKYS-BASC-0003", - "Last Number for Cell", - "There is only one number for this cell that does not create a duplicate" - + " contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); - } + public LastSingularNumberDirectRule() { + super( + "SKYS-BASC-0003", + "Last Number for Cell", + "There is only one number for this cell that does not create a duplicate" + + " contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = - (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - // check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() - == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + // check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java index a853c657d..8658942e2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java @@ -12,121 +12,118 @@ public class LastVisibleCellDirectRule extends DirectRule { - public LastVisibleCellDirectRule() { - super( - "SKYS-BASC-0001", - "Last Visible Cell", - "There is only one cell on this row/col for this number that does not create a" - + " visibility contradiction", - "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); - } + public LastVisibleCellDirectRule() { + super( + "SKYS-BASC-0001", + "Last Visible Cell", + "There is only one cell on this row/col for this number that does not create a" + + " visibility contradiction", + "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - // last cell for number based on preemptive visibility rules - SkyscrapersBoard initialBoard = - (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + // last cell for number based on preemptive visibility rules + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getWestClues().get(finalCell.getLocation().y), - (Integer) finalCell.getData()); - ArrayList YCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getNorthClues().get(finalCell.getLocation().x), - (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getWestClues().get(finalCell.getLocation().y), + (Integer) finalCell.getData()); + ArrayList YCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getNorthClues().get(finalCell.getLocation().x), + (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - // System.out.println(XCandidates.size()); - // System.out.println(YCandidates.size()); + // System.out.println(XCandidates.size()); + // System.out.println(YCandidates.size()); - // return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + // return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; } + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; + } - // helper to check if candidate list is valid - private String candidateCheck( - ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() - == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() - == finalCell.getData()) { - return null; - } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; + // helper to check if candidate list is valid + private String candidateCheck( + ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() + == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; } - return ": This cell is not forced."; + return ": Wrong number in the cell."; + } + return ": No case for this cell."; } + return ": This cell is not forced."; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(modBoard.getPuzzleElements().size()); - for (PuzzleElement element : modBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - modBoard.addModifiedData(cell); - } - } - // System.out.println(modBoard.getModifiedData().isEmpty()); - if (modBoard.getModifiedData().isEmpty()) { - return null; - } else { - return modBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(modBoard.getPuzzleElements().size()); + for (PuzzleElement element : modBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + modBoard.addModifiedData(cell); + } + } + // System.out.println(modBoard.getModifiedData().isEmpty()); + if (modBoard.getModifiedData().isEmpty()) { + return null; + } else { + return modBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java index da1057b56..199c6f0f9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java @@ -12,93 +12,90 @@ public class LastVisibleNumberDirectRule extends DirectRule { - public LastVisibleNumberDirectRule() { - super( - "SKYS-BASC-0005", - "Last Visible Number", - "There is only one number for this cell that does not create a visibility" - + " contradiction", - "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); - } + public LastVisibleNumberDirectRule() { + super( + "SKYS-BASC-0005", + "Last Visible Number", + "There is only one number for this cell that does not create a visibility" + + " contradiction", + "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - // last number for cell based upon preemptive visibility rules - SkyscrapersBoard initialBoard = - (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + // last number for cell based upon preemptive visibility rules + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - // check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() - == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + // check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java index bbc202e72..2ddb588cd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java @@ -12,95 +12,93 @@ public class NEdgeDirectRule extends DirectRule { - public NEdgeDirectRule() { - super( - "SKYS-BASC-0004", - "N Edge", - "If the maximum number appears on an edge, the row or column's numbers appear in" - + " ascending order, starting at that edge.", - "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); + public NEdgeDirectRule() { + super( + "SKYS-BASC-0004", + "N Edge", + "If the maximum number appears on an edge, the row or column's numbers appear in" + + " ascending order, starting at that edge.", + "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN + && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = - (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN - && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; - } + SkyscrapersBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); + Point loc = finalCell.getLocation(); + int max = initialBoard.getHeight(); - SkyscrapersBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); - Point loc = finalCell.getLocation(); - int max = initialBoard.getHeight(); + if (initialBoard.getWestClues().get(loc.y).getData() == max + && finalCell.getData() == loc.x + 1) { + return null; + } + if (initialBoard.getEastClues().get(loc.y).getData() == max + && finalCell.getData() == max - loc.x) { + return null; + } + if (initialBoard.getNorthClues().get(loc.x).getData() == max + && finalCell.getData() == loc.y + 1) { + return null; + } + if (initialBoard.getSouthClues().get(loc.x).getData() == max + && finalCell.getData() == max - loc.y) { + return null; + } - if (initialBoard.getWestClues().get(loc.y).getData() == max - && finalCell.getData() == loc.x + 1) { - return null; - } - if (initialBoard.getEastClues().get(loc.y).getData() == max - && finalCell.getData() == max - loc.x) { - return null; - } - if (initialBoard.getNorthClues().get(loc.x).getData() == max - && finalCell.getData() == loc.y + 1) { - return null; - } - if (initialBoard.getSouthClues().get(loc.x).getData() == max - && finalCell.getData() == max - loc.y) { - return null; - } + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; + } - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; } + return false; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; - } - return false; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; - } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java index 145dd6ee2..9b6f67ca0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java @@ -16,166 +16,158 @@ public class NumberForCellCaseRule extends CaseRule { - public NumberForCellCaseRule() { - super( - "SKYS-CASE-0001", - "Number For Cell", - "A blank cell must have height of 1 to n.", - "edu/rpi/legup/images/skyscrapers/cases/NumberForCell.png"); + public NumberForCellCaseRule() { + super( + "SKYS-CASE-0001", + "Number For Cell", + "A blank cell must have height of 1 to n.", + "edu/rpi/legup/images/skyscrapers/cases/NumberForCell.png"); + } + + @Override + public CaseBoard getCaseBoard(Board board) { + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) board.copy(); + lightUpBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((SkyscrapersCell) data).getType() == SkyscrapersType.UNKNOWN) { + caseBoard.addPickableElement(data); + } } - - @Override - public CaseBoard getCaseBoard(Board board) { - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) board.copy(); - lightUpBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((SkyscrapersCell) data).getType() == SkyscrapersType.UNKNOWN) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); + + Set candidates = new HashSet(); + for (int i = 1; i <= skyscrapersboard.getWidth(); i++) { + Board newCase = board.copy(); + PuzzleElement newCell = newCase.getPuzzleElement(puzzleElement); + newCell.setData(i); + newCase.addModifiedData(newCell); + + // if flags + boolean passed = true; + if (skyscrapersboard.getDupeFlag()) { + DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); + passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; + } + if (skyscrapersboard.getViewFlag()) { + PreemptiveVisibilityContradictionRule ViewRule = + new PreemptiveVisibilityContradictionRule(); + passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; + } + // how should unresolved be handled? should it be? + if (passed) { + cases.add(newCase); + } } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); - - Set candidates = new HashSet(); - for (int i = 1; i <= skyscrapersboard.getWidth(); i++) { - Board newCase = board.copy(); - PuzzleElement newCell = newCase.getPuzzleElement(puzzleElement); - newCell.setData(i); - newCase.addModifiedData(newCell); - - // if flags - boolean passed = true; - if (skyscrapersboard.getDupeFlag()) { - DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); - passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; - } - if (skyscrapersboard.getViewFlag()) { - PreemptiveVisibilityContradictionRule ViewRule = - new PreemptiveVisibilityContradictionRule(); - passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; - } - // how should unresolved be handled? should it be? - if (passed) { - cases.add(newCase); - } - } - - return cases; + return cases; + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "This case rule must have at least one child."; + } else { + if (childTransitions.size() + != getCases( + transition.getBoard(), + childTransitions.get(0).getBoard().getModifiedData().iterator().next()) + .size()) { + return "Wrong number of children."; + } } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "This case rule must have at least one child."; - } else { - if (childTransitions.size() - != getCases( - transition.getBoard(), - childTransitions - .get(0) - .getBoard() - .getModifiedData() - .iterator() - .next()) - .size()) { - return "Wrong number of children."; - } - } - - // TreeTransition case1 = childTransitions.get(0); - // TreeTransition case2 = childTransitions.get(1); - TreeTransition case1 = childTransitions.get(0); - SkyscrapersCell mod1 = - (SkyscrapersCell) case1.getBoard().getModifiedData().iterator().next(); - for (int i = 0; i < childTransitions.size(); i++) { - TreeTransition case2 = childTransitions.get(i); - if (case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } - SkyscrapersCell mod2 = - (SkyscrapersCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } - if (!(mod2.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must assign a number."; - } - } - // System.out.println("no contradiction"); - return null; + // TreeTransition case1 = childTransitions.get(0); + // TreeTransition case2 = childTransitions.get(1); + TreeTransition case1 = childTransitions.get(0); + SkyscrapersCell mod1 = (SkyscrapersCell) case1.getBoard().getModifiedData().iterator().next(); + for (int i = 0; i < childTransitions.size(); i++) { + TreeTransition case2 = childTransitions.get(i); + if (case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } + SkyscrapersCell mod2 = (SkyscrapersCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } + if (!(mod2.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must assign a number."; + } } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + // System.out.println("no contradiction"); + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; + SkyscrapersCell point = (SkyscrapersCell) puzzleBoard.getPuzzleElement(puzzleElement); + + List cells = new ArrayList<>(List.of(point)); + + // if dependent on row/col + if (puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) { + // add all cells in row/col intersecting given point + cells.addAll(puzzleBoard.getRowCol(point.getLocation().x, SkyscrapersType.ANY, false)); + cells.addAll(puzzleBoard.getRowCol(point.getLocation().y, SkyscrapersType.ANY, true)); } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; - SkyscrapersCell point = (SkyscrapersCell) puzzleBoard.getPuzzleElement(puzzleElement); - - List cells = new ArrayList<>(List.of(point)); - - // if dependent on row/col - if (puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) { - // add all cells in row/col intersecting given point - cells.addAll(puzzleBoard.getRowCol(point.getLocation().x, SkyscrapersType.ANY, false)); - cells.addAll(puzzleBoard.getRowCol(point.getLocation().y, SkyscrapersType.ANY, true)); - } - - for (SkyscrapersCell cell : cells) { - if (!elements.contains(board.getPuzzleElement(cell))) { - elements.add(board.getPuzzleElement(cell)); - } - } - - return elements; + for (SkyscrapersCell cell : cells) { + if (!elements.contains(board.getPuzzleElement(cell))) { + elements.add(board.getPuzzleElement(cell)); + } } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java index dc274eb15..3b1537917 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java @@ -13,191 +13,185 @@ public class PreemptiveVisibilityContradictionRule extends ContradictionRule { - public PreemptiveVisibilityContradictionRule() { - super( - "SKYS-CONT-0006", - "Preemptive Visibility", - "Visibility constraints are not met given an incomplete row/col", - "edu/rpi/legup/images/skyscrapers/contradictions/PreemptiveVisibility.png"); - } + public PreemptiveVisibilityContradictionRule() { + super( + "SKYS-CONT-0006", + "Preemptive Visibility", + "Visibility constraints are not met given an incomplete row/col", + "edu/rpi/legup/images/skyscrapers/contradictions/PreemptiveVisibility.png"); + } + + /** + * Checks whether there is an instance of a visibility contradiction in every possible row/col + * based on the specific puzzleElement index using this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the all possible rows/cols contain a contradiction at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); + + // Initialize instances of necessary contradiction and case rules + InsufficientVisibilityContradictionRule tooFew = new InsufficientVisibilityContradictionRule(); + ExceedingVisibilityContradictionRule tooMany = new ExceedingVisibilityContradictionRule(); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + + // Initialize skyscraperBoard queues for rows and cols + Queue rowQ = new LinkedList<>(); + rowQ.add(skyscrapersBoard); + Queue colQ = new LinkedList<>(); + colQ.add(skyscrapersBoard); + + // find all cases for the corresponding row and column for each possible skyscraper height + + // Add every possible case for all heights for each corresponding row and column + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + int num = i + 1; + + // check row west clue + List rows; + + int size = rowQ.size(); + for (int j = 0; j < size; j++) { + SkyscrapersBoard temp = rowQ.poll(); // get row from the top of the stack + + // don't do anything if already in row + boolean exists = false; + for (SkyscrapersCell c : temp.getRowCol(loc.y, SkyscrapersType.Number, true)) { + if (c.getData() == num) { + exists = true; + break; + } + } - /** - * Checks whether there is an instance of a visibility contradiction in every possible row/col - * based on the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the all possible rows/cols contain a contradiction at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); - - // Initialize instances of necessary contradiction and case rules - InsufficientVisibilityContradictionRule tooFew = - new InsufficientVisibilityContradictionRule(); - ExceedingVisibilityContradictionRule tooMany = new ExceedingVisibilityContradictionRule(); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - - // Initialize skyscraperBoard queues for rows and cols - Queue rowQ = new LinkedList<>(); - rowQ.add(skyscrapersBoard); - Queue colQ = new LinkedList<>(); - colQ.add(skyscrapersBoard); - - // find all cases for the corresponding row and column for each possible skyscraper height - - // Add every possible case for all heights for each corresponding row and column - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - int num = i + 1; - - // check row west clue - List rows; - - int size = rowQ.size(); - for (int j = 0; j < size; j++) { - SkyscrapersBoard temp = rowQ.poll(); // get row from the top of the stack - - // don't do anything if already in row - boolean exists = false; - for (SkyscrapersCell c : temp.getRowCol(loc.y, SkyscrapersType.Number, true)) { - if (c.getData() == num) { - exists = true; - break; - } - } - - if (exists) { - rowQ.add(temp); - } else { - // set flags - boolean dupeTemp = temp.getDupeFlag(); - boolean viewTemp = temp.getViewFlag(); - temp.setDupeFlag(false); - temp.setViewFlag(false); - - // get all cases for corresponding row based on west clue - rows = - caseRule.getCasesFor( - temp, skyscrapersBoard.getWestClues().get(loc.y), num); - - // reset flags - temp.setDupeFlag(dupeTemp); - temp.setViewFlag(viewTemp); - - // add all row cases to row queue - for (Board k : rows) { - rowQ.add((SkyscrapersBoard) k); - } - } - } - - // check col north clue - List cols; - - size = colQ.size(); - for (int j = 0; j < size; j++) { - SkyscrapersBoard temp = colQ.poll(); // get row from the top of the stack - - // don't do anything if already in col - boolean exists = false; - for (SkyscrapersCell c : temp.getRowCol(loc.x, SkyscrapersType.Number, false)) { - if (c.getData() == num) { - exists = true; - break; - } - } - - if (exists) { - colQ.add(temp); - } else { - // set flags - boolean dupeTemp = temp.getDupeFlag(); - boolean viewTemp = temp.getViewFlag(); - temp.setDupeFlag(false); - temp.setViewFlag(false); - - // get all cases for corresponding col based on north clue - cols = - caseRule.getCasesFor( - temp, skyscrapersBoard.getNorthClues().get(loc.x), num); - - // reset flags - temp.setDupeFlag(dupeTemp); - temp.setViewFlag(viewTemp); - - // add all row cases to row queue - for (Board k : cols) { - colQ.add((SkyscrapersBoard) k); - } - } - } + if (exists) { + rowQ.add(temp); + } else { + // set flags + boolean dupeTemp = temp.getDupeFlag(); + boolean viewTemp = temp.getViewFlag(); + temp.setDupeFlag(false); + temp.setViewFlag(false); + + // get all cases for corresponding row based on west clue + rows = caseRule.getCasesFor(temp, skyscrapersBoard.getWestClues().get(loc.y), num); + + // reset flags + temp.setDupeFlag(dupeTemp); + temp.setViewFlag(viewTemp); + + // add all row cases to row queue + for (Board k : rows) { + rowQ.add((SkyscrapersBoard) k); + } + } + } + + // check col north clue + List cols; + + size = colQ.size(); + for (int j = 0; j < size; j++) { + SkyscrapersBoard temp = colQ.poll(); // get row from the top of the stack + + // don't do anything if already in col + boolean exists = false; + for (SkyscrapersCell c : temp.getRowCol(loc.x, SkyscrapersType.Number, false)) { + if (c.getData() == num) { + exists = true; + break; + } } - String rowTooFew; - String rowTooMany; - boolean rowContradiction = true; - // check if each case board has a contradiction - while (rowQ.size() > 0) { - SkyscrapersBoard fullRow = rowQ.poll(); - - // checks if there is a contradiction given the row based on the west clue - rowTooFew = - tooFew.checkContradictionAt( - fullRow, cell); // is cell the correct puzzle element to check? - rowTooMany = tooMany.checkContradictionAt(fullRow, cell); - - // boolean that checks if there is a contradiction within all rows - rowContradiction = - rowContradiction - && (rowTooFew == null - || rowTooMany - == null); // !null means there isn't a contradiction, so - // there must be a valid - // permutation of the array + if (exists) { + colQ.add(temp); + } else { + // set flags + boolean dupeTemp = temp.getDupeFlag(); + boolean viewTemp = temp.getViewFlag(); + temp.setDupeFlag(false); + temp.setViewFlag(false); + + // get all cases for corresponding col based on north clue + cols = caseRule.getCasesFor(temp, skyscrapersBoard.getNorthClues().get(loc.x), num); + + // reset flags + temp.setDupeFlag(dupeTemp); + temp.setViewFlag(viewTemp); + + // add all row cases to row queue + for (Board k : cols) { + colQ.add((SkyscrapersBoard) k); + } } + } + } - String colTooFew; - String colTooMany; - boolean colContradiction = true; - while (colQ.size() > 0) { - SkyscrapersBoard fullCol = colQ.poll(); + String rowTooFew; + String rowTooMany; + boolean rowContradiction = true; + // check if each case board has a contradiction + while (rowQ.size() > 0) { + SkyscrapersBoard fullRow = rowQ.poll(); + + // checks if there is a contradiction given the row based on the west clue + rowTooFew = + tooFew.checkContradictionAt( + fullRow, cell); // is cell the correct puzzle element to check? + rowTooMany = tooMany.checkContradictionAt(fullRow, cell); + + // boolean that checks if there is a contradiction within all rows + rowContradiction = + rowContradiction + && (rowTooFew == null + || rowTooMany == null); // !null means there isn't a contradiction, so + // there must be a valid + // permutation of the array + } - // checks if there is a contradiction given the col baesd on the north clue - colTooFew = tooFew.checkContradictionAt(fullCol, cell); - colTooMany = tooMany.checkContradictionAt(fullCol, cell); + String colTooFew; + String colTooMany; + boolean colContradiction = true; + while (colQ.size() > 0) { + SkyscrapersBoard fullCol = colQ.poll(); - // boolean that checks if there is a contradiction within all the cols - colContradiction = colContradiction && (colTooFew == null || colTooMany == null); - } + // checks if there is a contradiction given the col baesd on the north clue + colTooFew = tooFew.checkContradictionAt(fullCol, cell); + colTooMany = tooMany.checkContradictionAt(fullCol, cell); - // if every possible permutation results in contradictions return null, else no - // contradiction - if (rowContradiction || colContradiction) { - return null; - } - return super.getNoContradictionMessage(); + // boolean that checks if there is a contradiction within all the cols + colContradiction = colContradiction && (colTooFew == null || colTooMany == null); } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } - } - return "No instance of the contradiction " + this.ruleName + " here"; + // if every possible permutation results in contradictions return null, else no + // contradiction + if (rowContradiction || colContradiction) { + return null; + } + return super.getNoContradictionMessage(); + } + + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } } + return "No instance of the contradiction " + this.ruleName + " here"; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java index d4a3d0486..a34fe0730 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java @@ -8,33 +8,33 @@ public class UnresolvedCellContradictionRule extends ContradictionRule { - public UnresolvedCellContradictionRule() { - super( - "SKYS-CONT-0004", - "Unresolved Cell", - "Elimination leaves no possible number for a cell.", - "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedCell.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + public UnresolvedCellContradictionRule() { + super( + "SKYS-CONT-0004", + "Unresolved Cell", + "Elimination leaves no possible number for a cell.", + "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedCell.png"); + } - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList cases = caseRule.getCases(board, puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - if (cases.size() == 0) { - return null; - } + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList cases = caseRule.getCases(board, puzzleElement); - return super.getNoContradictionMessage(); + if (cases.size() == 0) { + return null; } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java index fed429988..e4e1152e9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java @@ -10,92 +10,90 @@ public class UnresolvedNumberContradictionRule extends ContradictionRule { - public UnresolvedNumberContradictionRule() { - super( - "SKYS-CONT-0005", - "Unresolved Number", - "No possible cell for a number without a duplicate contradiction.", - // specify a number? defaulting to every number for now. expand to more than - // duplicate? - "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedNumber.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); + public UnresolvedNumberContradictionRule() { + super( + "SKYS-CONT-0005", + "Unresolved Number", + "No possible cell for a number without a duplicate contradiction.", + // specify a number? defaulting to every number for now. expand to more than + // duplicate? + "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedNumber.png"); + } - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - int num = i + 1; - // check row - // isn't already present - boolean exists = false; - for (SkyscrapersCell presentCell : - skyscrapersBoard.getRowCol(loc.y, SkyscrapersType.Number, true)) { - if (presentCell.getData() == num) { - exists = true; - break; - } - } - if (!exists) { - // and no possible cases - if (caseRule.getCasesFor(board, skyscrapersBoard.getWestClues().get(loc.y), num) - .size() - == 0) { - return null; - } - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); - // check col - // same process as for row - exists = false; - for (SkyscrapersCell presentCell : - skyscrapersBoard.getRowCol(loc.x, SkyscrapersType.Number, false)) { - if (presentCell.getData() == num) { - exists = true; - break; - } - } - if (!exists) { - if (caseRule.getCasesFor(board, skyscrapersBoard.getNorthClues().get(loc.x), num) - .size() - == 0) { - return null; - } - } + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + int num = i + 1; + // check row + // isn't already present + boolean exists = false; + for (SkyscrapersCell presentCell : + skyscrapersBoard.getRowCol(loc.y, SkyscrapersType.Number, true)) { + if (presentCell.getData() == num) { + exists = true; + break; } + } + if (!exists) { + // and no possible cases + if (caseRule.getCasesFor(board, skyscrapersBoard.getWestClues().get(loc.y), num).size() + == 0) { + return null; + } + } - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); + // check col + // same process as for row + exists = false; + for (SkyscrapersCell presentCell : + skyscrapersBoard.getRowCol(loc.x, SkyscrapersType.Number, false)) { + if (presentCell.getData() == num) { + exists = true; + break; + } + } + if (!exists) { + if (caseRule.getCasesFor(board, skyscrapersBoard.getNorthClues().get(loc.x), num).size() + == 0) { + return null; + } + } } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return null; - } - } - return "No instance of the contradiction " + this.ruleName + " here"; + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } + + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return null; + } } + return "No instance of the contradiction " + this.ruleName + " here"; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java index a7cd9ac12..e0583a13b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.sudoku; public enum GroupType { - REGION, - ROW, - COLUMN + REGION, + ROW, + COLUMN } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java index 0b6971235..e81bc909e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java @@ -9,76 +9,76 @@ public class PossibleNumberCaseBoard extends CaseBoard { - private SudokuCell cell; - private Set pickableRegions; - private Set pickableRows; - private Set pickableCols; + private SudokuCell cell; + private Set pickableRegions; + private Set pickableRows; + private Set pickableCols; - public PossibleNumberCaseBoard( - SudokuBoard baseBoard, PossibleNumberCaseRule caseRule, SudokuCell cell) { - super(baseBoard, caseRule); - this.cell = cell; - this.pickableRegions = new HashSet<>(); - this.pickableRows = new HashSet<>(); - this.pickableCols = new HashSet<>(); + public PossibleNumberCaseBoard( + SudokuBoard baseBoard, PossibleNumberCaseRule caseRule, SudokuCell cell) { + super(baseBoard, caseRule); + this.cell = cell; + this.pickableRegions = new HashSet<>(); + this.pickableRows = new HashSet<>(); + this.pickableCols = new HashSet<>(); + } + + @Override + public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { + if (e == null) { + return false; } - @Override - public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { - if (e == null) { - return false; + SudokuCell sudokuCell = (SudokuCell) puzzleElement; + if (e.isShiftDown()) { + for (int r : pickableRows) { + if (r == sudokuCell.getLocation().y) { + return true; } - - SudokuCell sudokuCell = (SudokuCell) puzzleElement; - if (e.isShiftDown()) { - for (int r : pickableRows) { - if (r == sudokuCell.getLocation().y) { - return true; - } - } - } else { - if (e.isControlDown()) { - for (int c : pickableCols) { - if (c == sudokuCell.getLocation().x) { - return true; - } - } - } else { - for (int r : pickableRegions) { - if (r == sudokuCell.getGroupIndex()) { - return true; - } - } - } + } + } else { + if (e.isControlDown()) { + for (int c : pickableCols) { + if (c == sudokuCell.getLocation().x) { + return true; + } + } + } else { + for (int r : pickableRegions) { + if (r == sudokuCell.getGroupIndex()) { + return true; + } } - return false; + } } + return false; + } - public void addPickableRegion(int region) { - this.pickableRegions.add(region); - } + public void addPickableRegion(int region) { + this.pickableRegions.add(region); + } - public void addPickableRow(int row) { - this.pickableRows.add(row); - } + public void addPickableRow(int row) { + this.pickableRows.add(row); + } - public void addPickableCol(int col) { - this.pickableCols.add(col); - } + public void addPickableCol(int col) { + this.pickableCols.add(col); + } - public SudokuCell getCell() { - return cell; - } + public SudokuCell getCell() { + return cell; + } - public Set getPickableRegions() { - return pickableRegions; - } + public Set getPickableRegions() { + return pickableRegions; + } - public Set getPickableRows() { - return pickableRows; - } + public Set getPickableRows() { + return pickableRows; + } - public Set getPickableCols() { - return pickableCols; - } + public Set getPickableCols() { + return pickableCols; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java index 877c92665..30aa78aac 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java @@ -7,102 +7,102 @@ import edu.rpi.legup.ui.boardview.BoardView; public class Sudoku extends Puzzle { - private SudokuView boardView; - - /** Sudoku Constructor */ - public Sudoku() { - super(); - - this.name = "Sudoku"; - - this.importer = new SudokuImporter(this); - this.exporter = new SudokuExporter(this); - - this.factory = new SudokuCellFactory(); + private SudokuView boardView; + + /** Sudoku Constructor */ + public Sudoku() { + super(); + + this.name = "Sudoku"; + + this.importer = new SudokuImporter(this); + this.exporter = new SudokuExporter(this); + + this.factory = new SudokuCellFactory(); + } + + public BoardView getBoardView() { + return boardView; + } + + /** Initializes the game board */ + @Override + public void initializeView() { + boardView = new SudokuView((SudokuBoard) currentBoard); + } + + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } + + @Override + /** + * Determines if the given dimensions are valid for Sudoku + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Sudoku, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // The number of rows and columns must be greater than 1 + if (rows <= 1 || columns <= 1) { + return false; } - public BoardView getBoardView() { - return boardView; + // The number of rows and columns must be equal + if (rows != columns) { + return false; } - /** Initializes the game board */ - @Override - public void initializeView() { - boardView = new SudokuView((SudokuBoard) currentBoard); + // For Sudoku, the number of rows and columns must be a perfect square + // Note: we don't need to check the columns since by this point, we have verified that the + // number of rows + // equals the number of columns + double sqrtRows = Math.sqrt(rows); + if (sqrtRows - Math.floor(sqrtRows) != 0) { + return false; } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; + return true; + } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(sudokuBoard) == null) { + return false; + } } - @Override - /** - * Determines if the given dimensions are valid for Sudoku - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Sudoku, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // The number of rows and columns must be greater than 1 - if (rows <= 1 || columns <= 1) { - return false; - } - - // The number of rows and columns must be equal - if (rows != columns) { - return false; - } - - // For Sudoku, the number of rows and columns must be a perfect square - // Note: we don't need to check the columns since by this point, we have verified that the - // number of rows - // equals the number of columns - double sqrtRows = Math.sqrt(rows); - if (sqrtRows - Math.floor(sqrtRows) != 0) { - return false; - } - - return true; + for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { + SudokuCell cell = (SudokuCell) puzzleElement; + if (cell.getData() == 0) { + return false; + } } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(sudokuBoard) == null) { - return false; - } - } - - for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { - SudokuCell cell = (SudokuCell) puzzleElement; - if (cell.getData() == 0) { - return false; - } - } - return true; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java index 46e6020bb..095dbf64c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java @@ -7,166 +7,166 @@ import java.util.Set; public class SudokuBoard extends GridBoard { - private int size; - private int groupSize; - - /** - * SudokuBoard Constructor - create a new Sudoku board - * - * @param size size of one side of the sudoku board, must be an integer square root - */ - public SudokuBoard(int size) { - super(size, size); - this.size = size; - this.groupSize = (int) Math.sqrt(dimension.width); + private int size; + private int groupSize; + + /** + * SudokuBoard Constructor - create a new Sudoku board + * + * @param size size of one side of the sudoku board, must be an integer square root + */ + public SudokuBoard(int size) { + super(size, size); + this.size = size; + this.groupSize = (int) Math.sqrt(dimension.width); + } + + /** + * Gets a SudokuCell from the board + * + * @param x x location of the cell + * @param y y location of the cell + * @return SudokuCell at location (x, y) + */ + @Override + public SudokuCell getCell(int x, int y) { + return (SudokuCell) super.getCell(x, y); + } + + /** + * Gets the SudokuCell in the specified group index at the x and y location given The group index + * must be by less than the width (or height) of the board and the x and y location is relative to + * the group. This means the x and y values must be less the square root of the width (or height) + * of the board. + * + * @param groupIndex group index of the cell + * @param x x location relative to the group + * @param y y location relative to the group + * @return cell in the specified group index at the given x and y location + */ + public SudokuCell getCell(int groupIndex, int x, int y) { + return getCell( + x + (groupIndex % groupSize) * groupSize, y + (groupIndex / groupSize) * groupSize); + } + + /** + * Gets the size of the sudoku board Standard board is 9x9 + * + * @return size of the board + */ + public int getSize() { + return size; + } + + /** + * Gets the minor group size of the sudoku board Standard board is 3x3x3x3 + * + * @return minor group size + */ + public int getGroupSize() { + return groupSize; + } + + /** + * Gets all the cells in the specified row + * + * @param rowNum row index + * @return list of all the cells in the row + */ + public Set getRow(int rowNum) { + Set row = new HashSet<>(); + for (int i = 0; i < size; i++) { + row.add(getCell(i, rowNum)); } - - /** - * Gets a SudokuCell from the board - * - * @param x x location of the cell - * @param y y location of the cell - * @return SudokuCell at location (x, y) - */ - @Override - public SudokuCell getCell(int x, int y) { - return (SudokuCell) super.getCell(x, y); + return row; + } + + /** + * Gets all the cells in the specified column + * + * @param colNum column index + * @return list of all the cells in the column + */ + public Set getCol(int colNum) { + Set col = new HashSet<>(); + for (int i = 0; i < size; i++) { + col.add(getCell(colNum, i)); } - - /** - * Gets the SudokuCell in the specified group index at the x and y location given The group - * index must be by less than the width (or height) of the board and the x and y location is - * relative to the group. This means the x and y values must be less the square root of the - * width (or height) of the board. - * - * @param groupIndex group index of the cell - * @param x x location relative to the group - * @param y y location relative to the group - * @return cell in the specified group index at the given x and y location - */ - public SudokuCell getCell(int groupIndex, int x, int y) { - return getCell( - x + (groupIndex % groupSize) * groupSize, y + (groupIndex / groupSize) * groupSize); + return col; + } + + /** + * Gets all the cells in the specified region + * + * @param regionNum region index + * @return list of all the cells in the region + */ + public Set getRegion(int regionNum) { + Set region = new HashSet<>(); + for (int i = 0; i < size; i++) { + region.add(getCell(regionNum, i % groupSize, i / groupSize)); } - - /** - * Gets the size of the sudoku board Standard board is 9x9 - * - * @return size of the board - */ - public int getSize() { - return size; + return region; + } + + public Set getAffected(SudokuCell cell) { + Point loc = cell.getLocation(); + cell = getCell(loc.x, loc.y); + Set affected = new HashSet<>(); + affected.addAll(getRegion(cell.getGroupIndex())); + affected.addAll(getRow(loc.y)); + affected.addAll(getCol(loc.x)); + + return affected; + } + + public Set getPossibleValues(SudokuCell cell) { + Point loc = cell.getLocation(); + cell = getCell(loc.x, loc.y); + Set possible = getAffected(cell); + + Set possibleValues = new HashSet<>(); + for (int i = 0; i < size; i++) { + possibleValues.add(i); } - - /** - * Gets the minor group size of the sudoku board Standard board is 3x3x3x3 - * - * @return minor group size - */ - public int getGroupSize() { - return groupSize; + for (SudokuCell c : possible) { + possibleValues.remove(c.getData()); } - /** - * Gets all the cells in the specified row - * - * @param rowNum row index - * @return list of all the cells in the row - */ - public Set getRow(int rowNum) { - Set row = new HashSet<>(); - for (int i = 0; i < size; i++) { - row.add(getCell(i, rowNum)); - } - return row; + return possibleValues; + } + + /** + * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent + * puzzle element with the new data. + * + * @param puzzleElement equivalent puzzle element with the new data. + */ + @Override + public void notifyChange(PuzzleElement puzzleElement) { + super.notifyChange(puzzleElement); + Set affected = getAffected((SudokuCell) puzzleElement); + for (SudokuCell c : affected) { + c.setAnnotations(getPossibleValues(c)); } - - /** - * Gets all the cells in the specified column - * - * @param colNum column index - * @return list of all the cells in the column - */ - public Set getCol(int colNum) { - Set col = new HashSet<>(); - for (int i = 0; i < size; i++) { - col.add(getCell(colNum, i)); - } - return col; + } + + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + @Override + public SudokuBoard copy() { + SudokuBoard copy = new SudokuBoard(size); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } - - /** - * Gets all the cells in the specified region - * - * @param regionNum region index - * @return list of all the cells in the region - */ - public Set getRegion(int regionNum) { - Set region = new HashSet<>(); - for (int i = 0; i < size; i++) { - region.add(getCell(regionNum, i % groupSize, i / groupSize)); - } - return region; - } - - public Set getAffected(SudokuCell cell) { - Point loc = cell.getLocation(); - cell = getCell(loc.x, loc.y); - Set affected = new HashSet<>(); - affected.addAll(getRegion(cell.getGroupIndex())); - affected.addAll(getRow(loc.y)); - affected.addAll(getCol(loc.x)); - - return affected; - } - - public Set getPossibleValues(SudokuCell cell) { - Point loc = cell.getLocation(); - cell = getCell(loc.x, loc.y); - Set possible = getAffected(cell); - - Set possibleValues = new HashSet<>(); - for (int i = 0; i < size; i++) { - possibleValues.add(i); - } - for (SudokuCell c : possible) { - possibleValues.remove(c.getData()); - } - - return possibleValues; - } - - /** - * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent - * puzzle element with the new data. - * - * @param puzzleElement equivalent puzzle element with the new data. - */ - @Override - public void notifyChange(PuzzleElement puzzleElement) { - super.notifyChange(puzzleElement); - Set affected = getAffected((SudokuCell) puzzleElement); - for (SudokuCell c : affected) { - c.setAnnotations(getPossibleValues(c)); - } - } - - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - @Override - public SudokuBoard copy() { - SudokuBoard copy = new SudokuBoard(size); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - return copy; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java index 006e6c0a5..4b9ea2b4c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java @@ -6,57 +6,57 @@ import java.util.Set; public class SudokuCell extends GridCell { - private int groupIndex; - private Set annotations; - private int max; - - /** - * SudokuCell Constructor - creates a new Sudoku cell to hold the puzzleElement - * - * @param value value of the sudoku cell - * @param location location of the cell on the board - * @param groupIndex index of the group the cell is in on the board - * @param size size of the sudoku cell - */ - public SudokuCell(int value, Point location, int groupIndex, int size) { - super(value, location); - this.groupIndex = groupIndex; - this.annotations = new HashSet<>(); - this.max = size; - } - - /** - * Gets the group index of the cell - * - * @return group index of the cell - */ - public int getGroupIndex() { - return groupIndex; - } - - public int getMax() { - return max; - } - - public Set getAnnotations() { - return annotations; - } - - public void setAnnotations(Set annotations) { - this.annotations = annotations; - } - - /** - * Performs a deep copy on the SudokuCell - * - * @return a new copy of the SudokuCell that is independent of this one - */ - @Override - public SudokuCell copy() { - SudokuCell copy = new SudokuCell(data, (Point) location.clone(), groupIndex, max); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + private int groupIndex; + private Set annotations; + private int max; + + /** + * SudokuCell Constructor - creates a new Sudoku cell to hold the puzzleElement + * + * @param value value of the sudoku cell + * @param location location of the cell on the board + * @param groupIndex index of the group the cell is in on the board + * @param size size of the sudoku cell + */ + public SudokuCell(int value, Point location, int groupIndex, int size) { + super(value, location); + this.groupIndex = groupIndex; + this.annotations = new HashSet<>(); + this.max = size; + } + + /** + * Gets the group index of the cell + * + * @return group index of the cell + */ + public int getGroupIndex() { + return groupIndex; + } + + public int getMax() { + return max; + } + + public Set getAnnotations() { + return annotations; + } + + public void setAnnotations(Set annotations) { + this.annotations = annotations; + } + + /** + * Performs a deep copy on the SudokuCell + * + * @return a new copy of the SudokuCell that is independent of this one + */ + @Override + public SudokuCell copy() { + SudokuCell copy = new SudokuCell(data, (Point) location.clone(), groupIndex, max); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java index 9b24f13da..edb095519 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java @@ -5,33 +5,33 @@ import java.awt.event.MouseEvent; public class SudokuCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - SudokuCell cell = (SudokuCell) data; - System.out.print(111); - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() < cell.getMax()) { - data.setData(cell.getData() + 1); - } else { - data.setData(0); - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + SudokuCell cell = (SudokuCell) data; + System.out.print(111); + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() < cell.getMax()) { + data.setData(cell.getData() + 1); } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() > 0) { - data.setData(cell.getData() - 1); - } else { - data.setData(cell.getMax()); - } - } + data.setData(0); } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() > 0) { + data.setData(cell.getData() - 1); + } else { + data.setData(cell.getMax()); + } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java index 1ef24ea59..7214193be 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java @@ -10,65 +10,63 @@ import org.w3c.dom.Node; public class SudokuCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public SudokuCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Sudoku Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public SudokuCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException("Sudoku Factory: unknown puzzleElement puzzleElement"); + } - SudokuBoard sudokuBoard = (SudokuBoard) board; - int size = sudokuBoard.getSize(); - int minorSize = (int) Math.sqrt(size); + SudokuBoard sudokuBoard = (SudokuBoard) board; + int size = sudokuBoard.getSize(); + int minorSize = (int) Math.sqrt(size); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= size || y >= size) { - throw new InvalidFileFormatException("Sudoku Factory: cell location out of bounds"); - } - if (value < 0 || value > 9) { - throw new InvalidFileFormatException("Sudoku Factory: cell unknown value"); - } - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(value, new Point(x, y), groupIndex, size); - cell.setIndex(y * size + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Sudoku Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Sudoku Factory: could not find attribute(s)"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= size || y >= size) { + throw new InvalidFileFormatException("Sudoku Factory: cell location out of bounds"); + } + if (value < 0 || value > 9) { + throw new InvalidFileFormatException("Sudoku Factory: cell unknown value"); + } + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(value, new Point(x, y), groupIndex, size); + cell.setIndex(y * size + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("Sudoku Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Sudoku Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - SudokuCell cell = (SudokuCell) puzzleElement; - Point loc = cell.getLocation(); + SudokuCell cell = (SudokuCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java index c3d236b53..142cf8f88 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java @@ -6,69 +6,65 @@ import java.awt.*; public class SudokuElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Font ANNOTATE_FONT = new Font("TimesRoman", Font.BOLD, 8); - private static final Color FONT_COLOR = new Color(0x212121); - private static final Color BORDER_COLOR = new Color(0x424242); - private static final Color GIVEN_COLOR = new Color(0x75, 0x75, 0x75, 0x80); - private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Font ANNOTATE_FONT = new Font("TimesRoman", Font.BOLD, 8); + private static final Color FONT_COLOR = new Color(0x212121); + private static final Color BORDER_COLOR = new Color(0x424242); + private static final Color GIVEN_COLOR = new Color(0x75, 0x75, 0x75, 0x80); + private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); - public SudokuElementView(GridCell cell) { - super(cell); - } + public SudokuElementView(GridCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public SudokuCell getPuzzleElement() { - return (SudokuCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public SudokuCell getPuzzleElement() { + return (SudokuCell) super.getPuzzleElement(); + } - @Override - public void drawGiven(Graphics2D graphics2D) { - graphics2D.setColor(GIVEN_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } + @Override + public void drawGiven(Graphics2D graphics2D) { + graphics2D.setColor(GIVEN_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BACKGROUND_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BORDER_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BACKGROUND_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BORDER_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - SudokuCell cell = (SudokuCell) puzzleElement; - int val = cell.getData(); - if (val != 0) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(val); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = - location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } else { - boolean annotate = - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.SHOW_ANNOTATIONS) - .equalsIgnoreCase(Boolean.toString(true)); - if (annotate) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(ANNOTATE_FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getAnnotations()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = - location.y - + ((size.height - metrics.getHeight()) / 2) - + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } - } + SudokuCell cell = (SudokuCell) puzzleElement; + int val = cell.getData(); + if (val != 0) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(val); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } else { + boolean annotate = + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.SHOW_ANNOTATIONS) + .equalsIgnoreCase(Boolean.toString(true)); + if (annotate) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(ANNOTATE_FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getAnnotations()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java index f10aabae1..3bb78e9e9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java @@ -6,33 +6,33 @@ public class SudokuExporter extends PuzzleExporter { - public SudokuExporter(Sudoku sudoku) { - super(sudoku); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - SudokuBoard board; - if (puzzle.getTree() != null) { - board = (SudokuBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (SudokuBoard) puzzle.getBoardView().getBoard(); - } + public SudokuExporter(Sudoku sudoku) { + super(sudoku); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("size", String.valueOf(board.getSize())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + SudokuBoard board; + if (puzzle.getTree() != null) { + board = (SudokuBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (SudokuBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SudokuCell cell = (SudokuCell) puzzleElement; - if (cell.getData() != 0) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("size", String.valueOf(board.getSize())); - boardElement.appendChild(cellsElement); - return boardElement; + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SudokuCell cell = (SudokuCell) puzzleElement; + if (cell.getData() != 0) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java index 68bf1e795..5ad32efbc 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java @@ -8,128 +8,122 @@ import org.w3c.dom.NodeList; public class SudokuImporter extends PuzzleImporter { - public SudokuImporter(Sudoku sudoku) { - super(sudoku); - } + public SudokuImporter(Sudoku sudoku) { + super(sudoku); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - SudokuBoard sudokuBoard; - int minorSize = (int) Math.sqrt(rows); - sudokuBoard = new SudokuBoard(rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + SudokuBoard sudokuBoard; + int minorSize = (int) Math.sqrt(rows); + sudokuBoard = new SudokuBoard(rows); - for (int y = 0; y < columns; y++) { - for (int x = 0; x < rows; x++) { - if (sudokuBoard.getCell(x, y) == null) { - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, rows); - cell.setIndex(y * rows + x); - cell.setModifiable(true); - sudokuBoard.setCell(x, y, cell); - } - } + for (int y = 0; y < columns; y++) { + for (int x = 0; x < rows; x++) { + if (sudokuBoard.getCell(x, y) == null) { + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, rows); + cell.setIndex(y * rows + x); + cell.setModifiable(true); + sudokuBoard.setCell(x, y, cell); } - - puzzle.setCurrentBoard(sudokuBoard); + } } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "Sudoku Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "Sudoku Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + puzzle.setCurrentBoard(sudokuBoard); + } - SudokuBoard sudokuBoard; - int size; - int minorSize; - if (!boardElement.getAttribute("size").isEmpty()) { - size = Integer.valueOf(boardElement.getAttribute("size")); - minorSize = (int) Math.sqrt(size); - if (minorSize * minorSize != size) { - throw new InvalidFileFormatException( - "Sudoku Importer: invalid board dimensions"); - } - sudokuBoard = new SudokuBoard(size); - } else { - throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("Sudoku Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("Sudoku Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - for (int i = 0; i < elementDataList.getLength(); i++) { - SudokuCell cell = - (SudokuCell) - puzzle.getFactory() - .importCell(elementDataList.item(i), sudokuBoard); - Point loc = cell.getLocation(); - if (cell.getData() != 0) { - cell.setModifiable(false); - cell.setGiven(true); - } - sudokuBoard.setCell(loc.x, loc.y, cell); - } + SudokuBoard sudokuBoard; + int size; + int minorSize; + if (!boardElement.getAttribute("size").isEmpty()) { + size = Integer.valueOf(boardElement.getAttribute("size")); + minorSize = (int) Math.sqrt(size); + if (minorSize * minorSize != size) { + throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); + } + sudokuBoard = new SudokuBoard(size); + } else { + throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); + } - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - if (sudokuBoard.getCell(x, y) == null) { - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - sudokuBoard.setCell(x, y, cell); - } - } - } - // - // for(int y = 0; y < size; y++) - // { - // for(int x = 0; x < size; x++) - // { - // SudokuCell cell = sudokuBoard.getCell(x, y); - // System.err.println("(" + x + ", " + y + ") - " + - // cell.getGroupIndex()); - // } - // } + for (int i = 0; i < elementDataList.getLength(); i++) { + SudokuCell cell = + (SudokuCell) puzzle.getFactory().importCell(elementDataList.item(i), sudokuBoard); + Point loc = cell.getLocation(); + if (cell.getData() != 0) { + cell.setModifiable(false); + cell.setGiven(true); + } + sudokuBoard.setCell(loc.x, loc.y, cell); + } - puzzle.setCurrentBoard(sudokuBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Sudoku Importer: unknown value where integer expected"); + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + if (sudokuBoard.getCell(x, y) == null) { + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + sudokuBoard.setCell(x, y, cell); + } } - } + } + // + // for(int y = 0; y < size; y++) + // { + // for(int x = 0; x < size; x++) + // { + // SudokuCell cell = sudokuBoard.getCell(x, y); + // System.err.println("(" + x + ", " + y + ") - " + + // cell.getGroupIndex()); + // } + // } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Sudoku cannot accept text input"); + puzzle.setCurrentBoard(sudokuBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException("Sudoku Importer: unknown value where integer expected"); } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Sudoku cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java index aa58f9a23..43939bbd4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java @@ -10,162 +10,160 @@ import javax.swing.*; public class SudokuView extends GridBoardView { - private static final Color STROKE_COLOR = new Color(0, 0, 0); - private static final Stroke MINOR_STOKE = new BasicStroke(1); - private static final Stroke MAJOR_STOKE = new BasicStroke(4); - - public SudokuView(SudokuBoard board) { - super(new BoardController(), new SudokuCellController(), board.getDimension()); - - int minorSize = (int) Math.sqrt(gridSize.width); - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - Point location = - new Point( - k * elementSize.width + (k / minorSize) * 4 + 5, - i * elementSize.height + (i / minorSize) * 4 + 5); - SudokuElementView element = new SudokuElementView(board.getCell(k, i)); - element.setIndex(i * gridSize.width + k); - element.setSize(elementSize); - element.setLocation(location); - elementViews.add(element); - } - } + private static final Color STROKE_COLOR = new Color(0, 0, 0); + private static final Stroke MINOR_STOKE = new BasicStroke(1); + private static final Stroke MAJOR_STOKE = new BasicStroke(4); + + public SudokuView(SudokuBoard board) { + super(new BoardController(), new SudokuCellController(), board.getDimension()); + + int minorSize = (int) Math.sqrt(gridSize.width); + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + Point location = + new Point( + k * elementSize.width + (k / minorSize) * 4 + 5, + i * elementSize.height + (i / minorSize) * 4 + 5); + SudokuElementView element = new SudokuElementView(board.getCell(k, i)); + element.setIndex(i * gridSize.width + k); + element.setSize(elementSize); + element.setLocation(location); + elementViews.add(element); + } } - - /** - * Gets the SudokuElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return SudokuElementView at the specified index - */ - @Override - public SudokuElementView getElement(int index) { - return (SudokuElementView) super.getElement(index); + } + + /** + * Gets the SudokuElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return SudokuElementView at the specified index + */ + @Override + public SudokuElementView getElement(int index) { + return (SudokuElementView) super.getElement(index); + } + + public void drawGrid(Graphics2D graphics2D) { + int minorSize = (int) Math.sqrt(gridSize.width); + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MAJOR_STOKE); + graphics2D.drawRect( + 3, + 3, + gridSize.width * (elementSize.width + 1) + 3, + gridSize.height * (elementSize.height + 1) + 3); + + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MAJOR_STOKE); + for (int i = 1; i < minorSize; i++) { + int x = i * minorSize * elementSize.width + i * ((minorSize + 1)) + 3; + graphics2D.drawLine(x, 3, x, gridSize.height * (elementSize.height + 1) + 6); } - - public void drawGrid(Graphics2D graphics2D) { - int minorSize = (int) Math.sqrt(gridSize.width); - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MAJOR_STOKE); - graphics2D.drawRect( - 3, - 3, - gridSize.width * (elementSize.width + 1) + 3, - gridSize.height * (elementSize.height + 1) + 3); - - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MAJOR_STOKE); - for (int i = 1; i < minorSize; i++) { - int x = i * minorSize * elementSize.width + i * ((minorSize + 1)) + 3; - graphics2D.drawLine(x, 3, x, gridSize.height * (elementSize.height + 1) + 6); - } - for (int i = 1; i < minorSize; i++) { - int y = i * minorSize * elementSize.height + i * ((minorSize + 1)) + 3; - graphics2D.drawLine(3, y, gridSize.width * (elementSize.width + 1) + 6, y); - } + for (int i = 1; i < minorSize; i++) { + int y = i * minorSize * elementSize.height + i * ((minorSize + 1)) + 3; + graphics2D.drawLine(3, y, gridSize.width * (elementSize.width + 1) + 6, y); } + } - @Override - public void drawBoard(Graphics2D graphics2D) { - drawGrid(graphics2D); - - if (board instanceof PossibleNumberCaseBoard) { - drawCaseBoard(graphics2D); - return; - } - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MINOR_STOKE); - ElementView hover = null; - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - ElementView element = elementViews.get(i * gridSize.height + k); - if (!element.isHover()) { - element.draw(graphics2D); - } else { - hover = element; - } - } - } + @Override + public void drawBoard(Graphics2D graphics2D) { + drawGrid(graphics2D); - if (hover != null) { - hover.draw(graphics2D); - } + if (board instanceof PossibleNumberCaseBoard) { + drawCaseBoard(graphics2D); + return; } - - public void drawCaseBoard(Graphics2D graphics2D) { - drawGrid(graphics2D); - - PossibleNumberCaseBoard caseBoard = (PossibleNumberCaseBoard) board; - SudokuBoard sudokuBoard = (SudokuBoard) caseBoard.getBaseBoard(); - - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MINOR_STOKE); - ElementView hover = null; - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - ElementView element = elementViews.get(i * gridSize.height + k); - if (!element.isHover()) { - element.draw(graphics2D); - } else { - hover = element; - } - } + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MINOR_STOKE); + ElementView hover = null; + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + ElementView element = elementViews.get(i * gridSize.height + k); + if (!element.isHover()) { + element.draw(graphics2D); + } else { + hover = element; } + } + } - graphics2D.setColor(new Color(0x1A, 0x23, 0x7E, 200)); - for (int r : caseBoard.getPickableRegions()) { - Set region = sudokuBoard.getRegion(r); - int x = Integer.MAX_VALUE, - y = Integer.MAX_VALUE, - w = Integer.MIN_VALUE, - h = Integer.MIN_VALUE; - for (SudokuCell c : region) { - x = Math.min(x, c.getLocation().x); - y = Math.min(y, c.getLocation().y); - w = Math.max(w, c.getLocation().x); - h = Math.max(h, c.getLocation().y); - } - - SudokuElementView firstElement = getElement(y * gridSize.width + x); - SudokuElementView lastElement = getElement(h * gridSize.width + w); - x = firstElement.getLocation().x; - y = firstElement.getLocation().y; - w = (lastElement.getLocation().x + elementSize.width) - x; - h = (lastElement.getLocation().y + elementSize.height) - y; - graphics2D.fillRect(x + 4, y + 4, w - 8, h - 8); + if (hover != null) { + hover.draw(graphics2D); + } + } + + public void drawCaseBoard(Graphics2D graphics2D) { + drawGrid(graphics2D); + + PossibleNumberCaseBoard caseBoard = (PossibleNumberCaseBoard) board; + SudokuBoard sudokuBoard = (SudokuBoard) caseBoard.getBaseBoard(); + + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MINOR_STOKE); + ElementView hover = null; + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + ElementView element = elementViews.get(i * gridSize.height + k); + if (!element.isHover()) { + element.draw(graphics2D); + } else { + hover = element; } - - // if(hover != null) - // hover.draw(graphics2D); + } } - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = gridSize.width * (elementSize.width + 1) + 9; - boardViewSize.height = gridSize.height * (elementSize.height + 1) + 9; - return boardViewSize; + graphics2D.setColor(new Color(0x1A, 0x23, 0x7E, 200)); + for (int r : caseBoard.getPickableRegions()) { + Set region = sudokuBoard.getRegion(r); + int x = Integer.MAX_VALUE, + y = Integer.MAX_VALUE, + w = Integer.MIN_VALUE, + h = Integer.MIN_VALUE; + for (SudokuCell c : region) { + x = Math.min(x, c.getLocation().x); + y = Math.min(y, c.getLocation().y); + w = Math.max(w, c.getLocation().x); + h = Math.max(h, c.getLocation().y); + } + + SudokuElementView firstElement = getElement(y * gridSize.width + x); + SudokuElementView lastElement = getElement(h * gridSize.width + w); + x = firstElement.getLocation().x; + y = firstElement.getLocation().y; + w = (lastElement.getLocation().x + elementSize.width) - x; + h = (lastElement.getLocation().y + elementSize.height) - y; + graphics2D.fillRect(x + 4, y + 4, w - 8, h - 8); } - public DataSelectionView getSelectionPopupMenu() { - DataSelectionView selectionView = new DataSelectionView(elementController); - GridLayout layout = new GridLayout(3, 3); - selectionView.setLayout(layout); - for (int r = 1; r <= 3; r++) { - for (int c = 1; c <= 3; c++) { - SudokuElementView element = - new SudokuElementView( - new SudokuCell((r - 1) * 3 + c, null, 0, gridSize.width)); - element.setSize(new Dimension(32, 32)); - element.setLocation(new Point(0, 0)); - SelectionItemView item = - new SelectionItemView( - element.getPuzzleElement(), new ImageIcon(element.getImage())); - item.addActionListener(elementController); - item.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item); - } - } - return selectionView; + // if(hover != null) + // hover.draw(graphics2D); + } + + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = gridSize.width * (elementSize.width + 1) + 9; + boardViewSize.height = gridSize.height * (elementSize.height + 1) + 9; + return boardViewSize; + } + + public DataSelectionView getSelectionPopupMenu() { + DataSelectionView selectionView = new DataSelectionView(elementController); + GridLayout layout = new GridLayout(3, 3); + selectionView.setLayout(layout); + for (int r = 1; r <= 3; r++) { + for (int c = 1; c <= 3; c++) { + SudokuElementView element = + new SudokuElementView(new SudokuCell((r - 1) * 3 + c, null, 0, gridSize.width)); + element.setSize(new Dimension(32, 32)); + element.setLocation(new Point(0, 0)); + SelectionItemView item = + new SelectionItemView(element.getPuzzleElement(), new ImageIcon(element.getImage())); + item.addActionListener(elementController); + item.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item); + } } + return selectionView; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java index 12183d70d..4a122dbcf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java @@ -3,24 +3,24 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class NumberTile extends PlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super("SUDO-PLAC-0001", "Number Tile", "A numbered tile", null); - object_num = 0; - } + public NumberTile() { + super("SUDO-PLAC-0001", "Number Tile", "A numbered tile", null); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java index 190679b41..bde33119a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java @@ -10,90 +10,89 @@ public class AdvancedDeductionDirectRule extends DirectRule { - public AdvancedDeductionDirectRule() { - super( - "SUDO-BASC-0001", - "Advanced Deduction", - "Use of group logic deduces more answers by means of forced by Location and forced" - + " by Deduction", - "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); - } + public AdvancedDeductionDirectRule() { + super( + "SUDO-BASC-0001", + "Advanced Deduction", + "Use of group logic deduces more answers by means of forced by Location and forced" + + " by Deduction", + "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - int index = cell.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int relX = rowIndex / groupDim; - int relY = colIndex % groupDim; - int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; - boolean[][] possible = new boolean[groupDim][groupDim]; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - SudokuCell c = initialBoard.getCell(groupNum, x, y); - if (c.getData() == cell.getData() && x != relX && y != relY) { - return super.getRuleName() + ": Duplicate value in sub-region"; - } - possible[y][x] = c.getData() == 0; - } + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + int index = cell.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int relX = rowIndex / groupDim; + int relY = colIndex % groupDim; + int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; + boolean[][] possible = new boolean[groupDim][groupDim]; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + SudokuCell c = initialBoard.getCell(groupNum, x, y); + if (c.getData() == cell.getData() && x != relX && y != relY) { + return super.getRuleName() + ": Duplicate value in sub-region"; } - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupSize; x++) { - SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); - SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); - if (r.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[y][i] = false; - } - } - if (c.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[i][y] = false; - } - } - } + possible[y][x] = c.getData() == 0; + } + } + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupSize; x++) { + SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); + SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); + if (r.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[y][i] = false; + } } - boolean isForced = false; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - if (possible[y][x] && !isForced) { - isForced = true; - } else { - if (possible[y][x]) { - return super.getInvalidUseOfRuleMessage() + ": Not forced"; - } - } - } + if (c.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[i][y] = false; + } } - if (!isForced) { + } + } + boolean isForced = false; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + if (possible[y][x] && !isForced) { + isForced = true; + } else { + if (possible[y][x]) { return super.getInvalidUseOfRuleMessage() + ": Not forced"; + } } - return null; + } } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + if (!isForced) { + return super.getInvalidUseOfRuleMessage() + ": Not forced"; } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java index fd03ef36c..fe32fc450 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java @@ -10,86 +10,85 @@ import java.util.Set; public class LastCellForNumberDirectRule extends DirectRule { - public LastCellForNumberDirectRule() { - super( - "SUDO-BASC-0002", - "Last Cell for Number", - "This is the only cell open in its group for some number.", - "edu/rpi/legup/images/sudoku/forcedByElimination.png"); - } + public LastCellForNumberDirectRule() { + super( + "SUDO-BASC-0002", + "Last Cell for Number", + "This is the only cell open in its group for some number.", + "edu/rpi/legup/images/sudoku/forcedByElimination.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; - } + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } - int size = initialBoard.getSize(); + int size = initialBoard.getSize(); - Set region = initialBoard.getRegion(cell.getGroupIndex()); - Set row = initialBoard.getRow(cell.getLocation().y); - Set col = initialBoard.getCol(cell.getLocation().x); + Set region = initialBoard.getRegion(cell.getGroupIndex()); + Set row = initialBoard.getRow(cell.getLocation().y); + Set col = initialBoard.getCol(cell.getLocation().x); - boolean contains = false; - if (region.size() == size - 1) { - for (SudokuCell c : region) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } + boolean contains = false; + if (region.size() == size - 1) { + for (SudokuCell c : region) { + if (cell.getData() == c.getData()) { + contains = true; + break; } - if (row.size() == size - 1) { - contains = false; - for (SudokuCell c : row) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } - } - if (col.size() == size - 1) { - contains = false; - for (SudokuCell c : col) { - if (cell.getData() == c.getData()) { - contains = true; - break; - } - } - if (!contains) { - return null; - } + } + if (!contains) { + return null; + } + } + if (row.size() == size - 1) { + contains = false; + for (SudokuCell c : row) { + if (cell.getData() == c.getData()) { + contains = true; + break; } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } + if (!contains) { + return null; + } } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { + if (col.size() == size - 1) { + contains = false; + for (SudokuCell c : col) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { return null; + } } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java index ca0ac3023..881df8455 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java @@ -11,71 +11,69 @@ public class LastNumberForCellDirectRule extends DirectRule { - public LastNumberForCellDirectRule() { - super( - "SUDO-BASC-0003", - "Last Number for Cell", - "This is the only number left that can fit in the cell of a group.", - "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); - } + public LastNumberForCellDirectRule() { + super( + "SUDO-BASC-0003", + "Last Number for Cell", + "This is the only number left that can fit in the cell of a group.", + "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - int index = puzzleElement.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; - HashSet numbers = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - numbers.add(i); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); - numbers.remove(cell.getData()); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(i, colIndex); - numbers.remove(cell.getData()); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(rowIndex, i); - numbers.remove(cell.getData()); - } - if (numbers.size() > 1) { - return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; - } else { - if (numbers.size() == 1 - && numbers.iterator().next() - != finalBoard.getPuzzleElement(puzzleElement).getData()) { - return super.getInvalidUseOfRuleMessage() - + ": The number at the index is forced but not correct"; - } - } - return null; + int index = puzzleElement.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; + HashSet numbers = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + numbers.add(i); } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); + numbers.remove(cell.getData()); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(i, colIndex); + numbers.remove(cell.getData()); } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(rowIndex, i); + numbers.remove(cell.getData()); + } + if (numbers.size() > 1) { + return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; + } else { + if (numbers.size() == 1 + && numbers.iterator().next() != finalBoard.getPuzzleElement(puzzleElement).getData()) { + return super.getInvalidUseOfRuleMessage() + + ": The number at the index is forced but not correct"; + } + } + return null; + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java index e44728d3e..e87b77492 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java @@ -10,55 +10,55 @@ public class NoSolutionContradictionRule extends ContradictionRule { - public NoSolutionContradictionRule() { - super( - "SUDO-CONT-0001", - "No Solution for Cell", - "Process of elimination yields no valid numbers for an empty cell.", - "edu/rpi/legup/images/sudoku/NoSolution.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); - if (cell.getData() != 0) { - return super.getNoContradictionMessage(); - } + public NoSolutionContradictionRule() { + super( + "SUDO-CONT-0001", + "No Solution for Cell", + "Process of elimination yields no valid numbers for an empty cell.", + "edu/rpi/legup/images/sudoku/NoSolution.png"); + } - int groupSize = sudokuBoard.getSize(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); + if (cell.getData() != 0) { + return super.getNoContradictionMessage(); + } - Set region = sudokuBoard.getRegion(cell.getGroupIndex()); - Set row = sudokuBoard.getRow(cell.getLocation().y); - Set col = sudokuBoard.getCol(cell.getLocation().x); - Set solution = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - solution.add(i); - } + int groupSize = sudokuBoard.getSize(); - for (SudokuCell c : region) { - solution.remove(c.getData()); - } - for (SudokuCell c : row) { - solution.remove(c.getData()); - } - for (SudokuCell c : col) { - solution.remove(c.getData()); - } + Set region = sudokuBoard.getRegion(cell.getGroupIndex()); + Set row = sudokuBoard.getRow(cell.getLocation().y); + Set col = sudokuBoard.getCol(cell.getLocation().x); + Set solution = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + solution.add(i); + } - if (solution.isEmpty()) { - return null; - } + for (SudokuCell c : region) { + solution.remove(c.getData()); + } + for (SudokuCell c : row) { + solution.remove(c.getData()); + } + for (SudokuCell c : col) { + solution.remove(c.getData()); + } - return super.getNoContradictionMessage(); + if (solution.isEmpty()) { + return null; } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java index fb6da62d4..be1875c90 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java @@ -12,99 +12,99 @@ import java.util.Set; public class PossibleCellCaseRule extends CaseRule { - public PossibleCellCaseRule() { - super( - "SUDO-CASE-0001", - "Possible Cells for Number", - "A number has a limited set of cells in which it can be placed.", - "edu/rpi/legup/images/sudoku/possible_cells_number.png"); - } + public PossibleCellCaseRule() { + super( + "SUDO-CASE-0001", + "Possible Cells for Number", + "A number has a limited set of cells in which it can be placed.", + "edu/rpi/legup/images/sudoku/possible_cells_number.png"); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - @Override - public CaseBoard getCaseBoard(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(sudokuBoard, this); - for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { - if (((SudokuCell) puzzleElement).getData() == 0) { - caseBoard.addPickableElement(puzzleElement); - } - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(sudokuBoard, this); + for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { + if (((SudokuCell) puzzleElement).getData() == 0) { + caseBoard.addPickableElement(puzzleElement); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) puzzleElement; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) puzzleElement; - Set possibleValue = new HashSet<>(); - for (int i = 1; i <= sudokuBoard.getSize(); i++) { - possibleValue.add(i); - } - - int groupNum = cell.getGroupIndex(); - for (SudokuCell c : sudokuBoard.getRegion(groupNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + Set possibleValue = new HashSet<>(); + for (int i = 1; i <= sudokuBoard.getSize(); i++) { + possibleValue.add(i); + } - int rowNum = cell.getLocation().y; - for (SudokuCell c : sudokuBoard.getRegion(rowNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int groupNum = cell.getGroupIndex(); + for (SudokuCell c : sudokuBoard.getRegion(groupNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - int colNum = cell.getLocation().x; - for (SudokuCell c : sudokuBoard.getRegion(colNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int rowNum = cell.getLocation().y; + for (SudokuCell c : sudokuBoard.getRegion(rowNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - for (Integer i : possibleValue) { - SudokuBoard newCase = sudokuBoard.copy(); + int colNum = cell.getLocation().x; + for (SudokuCell c : sudokuBoard.getRegion(colNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - PuzzleElement newCasePuzzleElement = newCase.getPuzzleElement(puzzleElement); - newCasePuzzleElement.setData(i); - newCase.addModifiedData(newCasePuzzleElement); - cases.add(newCase); - } + for (Integer i : possibleValue) { + SudokuBoard newCase = sudokuBoard.copy(); - return cases; + PuzzleElement newCasePuzzleElement = newCase.getPuzzleElement(puzzleElement); + newCasePuzzleElement.setData(i); + newCase.addModifiedData(newCasePuzzleElement); + cases.add(newCase); } + + return cases; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java index e6ab0e64c..f638fbbb6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java @@ -15,117 +15,117 @@ public class PossibleNumberCaseRule extends CaseRule { - public PossibleNumberCaseRule() { - super( - "SUDO-CASE-0002", - "Possible Numbers for Cell", - "An empty cell has a limited set of possible numbers that can fill it.", - "edu/rpi/legup/images/sudoku/PossibleValues.png"); - } + public PossibleNumberCaseRule() { + super( + "SUDO-CASE-0002", + "Possible Numbers for Cell", + "An empty cell has a limited set of possible numbers that can fill it.", + "edu/rpi/legup/images/sudoku/PossibleValues.png"); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - @Override - public CaseBoard getCaseBoard(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - PossibleNumberCaseBoard caseBoard = new PossibleNumberCaseBoard(sudokuBoard, this, null); - for (int i = 0; i < sudokuBoard.getSize(); i++) { - caseBoard.addPickableRegion(i); - caseBoard.addPickableRow(i); - caseBoard.addPickableCol(i); - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + PossibleNumberCaseBoard caseBoard = new PossibleNumberCaseBoard(sudokuBoard, this, null); + for (int i = 0; i < sudokuBoard.getSize(); i++) { + caseBoard.addPickableRegion(i); + caseBoard.addPickableRow(i); + caseBoard.addPickableCol(i); } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - return getCases(board, puzzleElement, 1, GroupType.REGION); - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + return getCases(board, puzzleElement, 1, GroupType.REGION); + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @param value value that the rule will be applied from - * @param groupType group type - * @return a list of elements the specified could be - */ - public ArrayList getCases( - Board board, PuzzleElement puzzleElement, int value, GroupType groupType) { - ArrayList cases = new ArrayList<>(); - SudokuBoard sudokuBoard = (SudokuBoard) board; - List caseCells = new ArrayList<>(); - SudokuCell cell = (SudokuCell) puzzleElement; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @param value value that the rule will be applied from + * @param groupType group type + * @return a list of elements the specified could be + */ + public ArrayList getCases( + Board board, PuzzleElement puzzleElement, int value, GroupType groupType) { + ArrayList cases = new ArrayList<>(); + SudokuBoard sudokuBoard = (SudokuBoard) board; + List caseCells = new ArrayList<>(); + SudokuCell cell = (SudokuCell) puzzleElement; - Set group; - if (groupType == GroupType.REGION) { - group = sudokuBoard.getRegion(cell.getGroupIndex()); - } else { - if (groupType == GroupType.ROW) { - group = sudokuBoard.getRow(cell.getLocation().y); - } else { - group = sudokuBoard.getCol(cell.getLocation().x); - } - } + Set group; + if (groupType == GroupType.REGION) { + group = sudokuBoard.getRegion(cell.getGroupIndex()); + } else { + if (groupType == GroupType.ROW) { + group = sudokuBoard.getRow(cell.getLocation().y); + } else { + group = sudokuBoard.getCol(cell.getLocation().x); + } + } - for (SudokuCell c : group) { - if (c.getData() == 0) { - Set blockableCells = sudokuBoard.getRegion(c.getGroupIndex()); - blockableCells.addAll(sudokuBoard.getRow(c.getLocation().y)); - blockableCells.addAll(sudokuBoard.getCol(c.getLocation().x)); + for (SudokuCell c : group) { + if (c.getData() == 0) { + Set blockableCells = sudokuBoard.getRegion(c.getGroupIndex()); + blockableCells.addAll(sudokuBoard.getRow(c.getLocation().y)); + blockableCells.addAll(sudokuBoard.getCol(c.getLocation().x)); - boolean repeat = false; - for (SudokuCell bc : blockableCells) { - if (bc.getData() == value) { - repeat = true; - break; - } - } - if (!repeat) { - caseCells.add(c); - } - } + boolean repeat = false; + for (SudokuCell bc : blockableCells) { + if (bc.getData() == value) { + repeat = true; + break; + } } - - for (SudokuCell c : caseCells) { - Board newCase = sudokuBoard.copy(); - PuzzleElement element = newCase.getPuzzleElement(c); - element.setData(value); - newCase.addModifiedData(element); - cases.add(newCase); + if (!repeat) { + caseCells.add(c); } + } + } - return cases; + for (SudokuCell c : caseCells) { + Board newCase = sudokuBoard.copy(); + PuzzleElement element = newCase.getPuzzleElement(c); + element.setData(value); + newCase.addModifiedData(element); + cases.add(newCase); } + + return cases; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java index 955414e8e..cf0bfa600 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java @@ -10,60 +10,60 @@ public class RepeatedNumberContradictionRule extends ContradictionRule { - public RepeatedNumberContradictionRule() { - super( - "SUDO-CONT-0002", - "Repeated Numbers", - "Two identical numbers are placed in the same group.", - "edu/rpi/legup/images/sudoku/RepeatedNumber.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getNoContradictionMessage(); - } + public RepeatedNumberContradictionRule() { + super( + "SUDO-CONT-0002", + "Repeated Numbers", + "Two identical numbers are placed in the same group.", + "edu/rpi/legup/images/sudoku/RepeatedNumber.png"); + } - Set region = sudokuBoard.getRegion(cell.getGroupIndex()); - Set row = sudokuBoard.getRow(cell.getLocation().y); - Set col = sudokuBoard.getCol(cell.getLocation().x); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getNoContradictionMessage(); + } - Set regionDup = new HashSet<>(); - Set rowDup = new HashSet<>(); - Set colDup = new HashSet<>(); + Set region = sudokuBoard.getRegion(cell.getGroupIndex()); + Set row = sudokuBoard.getRow(cell.getLocation().y); + Set col = sudokuBoard.getCol(cell.getLocation().x); - for (SudokuCell c : region) { - if (regionDup.contains(c.getData())) { - return null; - } - regionDup.add(c.getData()); - } + Set regionDup = new HashSet<>(); + Set rowDup = new HashSet<>(); + Set colDup = new HashSet<>(); - for (SudokuCell c : row) { - if (rowDup.contains(c.getData())) { - return null; - } - rowDup.add(c.getData()); - } + for (SudokuCell c : region) { + if (regionDup.contains(c.getData())) { + return null; + } + regionDup.add(c.getData()); + } - for (SudokuCell c : col) { - if (colDup.contains(c.getData())) { - return null; - } - colDup.add(c.getData()); - } + for (SudokuCell c : row) { + if (rowDup.contains(c.getData())) { + return null; + } + rowDup.add(c.getData()); + } - return super.getNoContradictionMessage(); + for (SudokuCell c : col) { + if (colDup.contains(c.getData())) { + return null; + } + colDup.add(c.getData()); } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java b/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java index a11f5f05b..fa66fcb1b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java @@ -15,170 +15,169 @@ import java.util.Map; public class ClueCommand extends PuzzleCommand { - private TreeViewSelection selection; - private TreeTentClueView clueView; - private Map addTran; - private List> emptyCells; - - public ClueCommand(TreeViewSelection selection, TreeTentClueView clueView) { - this.selection = selection; - this.clueView = clueView; - this.addTran = new HashMap<>(); - this.emptyCells = new ArrayList<>(); - } - - /** Executes a command */ - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - - final TreeViewSelection newSelection = new TreeViewSelection(); - for (int i = 0; i < selection.getSelectedViews().size(); i++) { - TreeElementView selectedView = selection.getSelectedViews().get(i); - TreeElement treeElement = selectedView.getTreeElement(); - - final TreeTransition finalTran; - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - List tempList = emptyCells.get(i); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - TreeTransition transition = addTran.get(treeNode); - if (transition == null) { - transition = tree.addNewTransition(treeNode); - addTran.put(treeNode, transition); - } else { - treeNode.addChild(transition); - } - - finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(finalTran)); - board = (TreeTentBoard) finalTran.getBoard(); - } else { - finalTran = (TreeTransition) treeElement; - newSelection.addToSelection(treeView.getElementView(treeElement)); - } - - for (TreeTentCell cell : tempList) { - cell = (TreeTentCell) board.getPuzzleElement(cell); - cell.setData(TreeTentType.GRASS); - board.addModifiedData(cell); - finalTran.propagateChange(cell); - - final TreeTentCell finalCell = cell; - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); - } - if (i == 0) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); - } + private TreeViewSelection selection; + private TreeTentClueView clueView; + private Map addTran; + private List> emptyCells; + + public ClueCommand(TreeViewSelection selection, TreeTentClueView clueView) { + this.selection = selection; + this.clueView = clueView; + this.addTran = new HashMap<>(); + this.emptyCells = new ArrayList<>(); + } + + /** Executes a command */ + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + + final TreeViewSelection newSelection = new TreeViewSelection(); + for (int i = 0; i < selection.getSelectedViews().size(); i++) { + TreeElementView selectedView = selection.getSelectedViews().get(i); + TreeElement treeElement = selectedView.getTreeElement(); + + final TreeTransition finalTran; + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + List tempList = emptyCells.get(i); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + TreeTransition transition = addTran.get(treeNode); + if (transition == null) { + transition = tree.addNewTransition(treeNode); + addTran.put(treeNode, transition); + } else { + treeNode.addChild(transition); } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + + finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(finalTran)); + board = (TreeTentBoard) finalTran.getBoard(); + } else { + finalTran = (TreeTransition) treeElement; + newSelection.addToSelection(treeView.getElementView(treeElement)); + } + + for (TreeTentCell cell : tempList) { + cell = (TreeTentCell) board.getPuzzleElement(cell); + cell.setData(TreeTentType.GRASS); + board.addModifiedData(cell); + finalTran.propagateChange(cell); + + final TreeTentCell finalCell = cell; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); + } + if (i == 0) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); + } + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + if (selection.getSelectedViews().isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - if (selection.getSelectedViews().isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + emptyCells.clear(); + for (TreeElementView view : selection.getSelectedViews()) { + TreeElement treeElement = view.getTreeElement(); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) treeElement; + if (!node.getChildren().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); } - - emptyCells.clear(); - for (TreeElementView view : selection.getSelectedViews()) { - TreeElement treeElement = view.getTreeElement(); - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) treeElement; - if (!node.getChildren().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } else { - if (!board.isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - - List tempList = new ArrayList<>(); - TreeTentClue clue = clueView.getPuzzleElement(); - if (clue.getType() == TreeTentType.CLUE_NORTH - || clue.getType() == TreeTentType.CLUE_SOUTH) { - int col = - clue.getType() == TreeTentType.CLUE_NORTH - ? clue.getClueIndex() - : clue.getClueIndex() - 1; - for (int i = 0; i < board.getWidth(); i++) { - TreeTentCell cell = board.getCell(col, i); - if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { - tempList.add(cell); - } - } - } else { - int row = - clue.getType() == TreeTentType.CLUE_WEST - ? clue.getClueIndex() - : clue.getClueIndex() - 1; - for (int i = 0; i < board.getWidth(); i++) { - TreeTentCell cell = board.getCell(i, row); - if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { - tempList.add(cell); - } - } - } - if (tempList.isEmpty()) { - return "There are no modifiable unknown cells in every selected tree element."; - } - emptyCells.add(tempList); + } else { + if (!board.isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); } - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - - for (int i = 0; i < selection.getSelectedViews().size(); i++) { - TreeElementView selectedView = selection.getSelectedViews().get(i); - TreeElement treeElement = selectedView.getTreeElement(); - - final TreeTransition finalTran; - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - List tempList = emptyCells.get(i); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - finalTran = treeNode.getChildren().get(0); - tree.removeTreeElement(finalTran); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); - - board = (TreeTentBoard) finalTran.getBoard(); - } else { - finalTran = (TreeTransition) treeElement; - } - - for (TreeTentCell cell : tempList) { - cell = (TreeTentCell) board.getPuzzleElement(cell); - cell.setData(TreeTentType.UNKNOWN); - board.removeModifiedData(cell); - - final TreeTentCell finalCell = cell; - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); - } - - if (i == 0) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); - } + } + + List tempList = new ArrayList<>(); + TreeTentClue clue = clueView.getPuzzleElement(); + if (clue.getType() == TreeTentType.CLUE_NORTH || clue.getType() == TreeTentType.CLUE_SOUTH) { + int col = + clue.getType() == TreeTentType.CLUE_NORTH + ? clue.getClueIndex() + : clue.getClueIndex() - 1; + for (int i = 0; i < board.getWidth(); i++) { + TreeTentCell cell = board.getCell(col, i); + if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { + tempList.add(cell); + } } - final TreeViewSelection newSelection = selection; - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } else { + int row = + clue.getType() == TreeTentType.CLUE_WEST + ? clue.getClueIndex() + : clue.getClueIndex() - 1; + for (int i = 0; i < board.getWidth(); i++) { + TreeTentCell cell = board.getCell(i, row); + if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { + tempList.add(cell); + } + } + } + if (tempList.isEmpty()) { + return "There are no modifiable unknown cells in every selected tree element."; + } + emptyCells.add(tempList); + } + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + + for (int i = 0; i < selection.getSelectedViews().size(); i++) { + TreeElementView selectedView = selection.getSelectedViews().get(i); + TreeElement treeElement = selectedView.getTreeElement(); + + final TreeTransition finalTran; + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + List tempList = emptyCells.get(i); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + finalTran = treeNode.getChildren().get(0); + tree.removeTreeElement(finalTran); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); + + board = (TreeTentBoard) finalTran.getBoard(); + } else { + finalTran = (TreeTransition) treeElement; + } + + for (TreeTentCell cell : tempList) { + cell = (TreeTentCell) board.getPuzzleElement(cell); + cell.setData(TreeTentType.UNKNOWN); + board.removeModifiedData(cell); + + final TreeTentCell finalCell = cell; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); + } + + if (i == 0) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); + } } + final TreeViewSelection newSelection = selection; + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java b/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java index feece58a9..4420d791e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java @@ -14,214 +14,212 @@ import java.util.List; public class EditLineCommand extends PuzzleCommand { - private TreeTentElementView start; - private TreeTentElementView end; - - private TreeViewSelection selection; - - public EditLineCommand( - TreeViewSelection selection, TreeTentElementView start, ElementView endDrag) { - this.selection = selection; - this.start = start; - this.end = getViewInDirection(endDrag); + private TreeTentElementView start; + private TreeTentElementView end; + + private TreeViewSelection selection; + + public EditLineCommand( + TreeViewSelection selection, TreeTentElementView start, ElementView endDrag) { + this.selection = selection; + this.start = start; + this.end = getViewInDirection(endDrag); + } + + /** Executes a command */ + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + TreeTentCell startCell; + TreeTentCell endCell; + + final TreeTransition transition; + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + transition = tree.addNewTransition(treeNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + + board = (TreeTentBoard) transition.getBoard(); + } else { + transition = (TreeTransition) treeElement; } - /** Executes a command */ - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - TreeTentCell startCell; - TreeTentCell endCell; - - final TreeTransition transition; - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - transition = tree.addNewTransition(treeNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); + endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); - board = (TreeTentBoard) transition.getBoard(); - } else { - transition = (TreeTransition) treeElement; - } - - startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); - endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + TreeTentLine line = new TreeTentLine(startCell, endCell); - TreeTentLine line = new TreeTentLine(startCell, endCell); - - TreeTentLine dupLine = null; - for (TreeTentLine l : board.getLines()) { - if (line.compare(l)) { - dupLine = l; - break; - } - } - - final TreeTentLine notifyLine; - if (dupLine == null) { - board.addModifiedData(line); - board.getLines().add(line); - notifyLine = line; - transition.propagateAddition(notifyLine); - } else { - board.removeModifiedData(dupLine); - board.getLines().remove(dupLine); - notifyLine = dupLine; - transition.propagateDeletion(notifyLine); - } - - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); - - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(transition)); - - final TreeViewSelection newSelection = - new TreeViewSelection(treeView.getElementView(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + TreeTentLine dupLine = null; + for (TreeTentLine l : board.getLines()) { + if (line.compare(l)) { + dupLine = l; + break; + } } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); - } - - if (start == null || end == null) { - return "The line must connect a tree to a tent."; - } - - TreeElementView view = selection.getFirstSelection(); - TreeElement treeElement = view.getTreeElement(); - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) treeElement; - if (!node.getChildren().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } else { - if (!board.isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - TreeTentLine line = - new TreeTentLine( - (TreeTentCell) start.getPuzzleElement(), - (TreeTentCell) end.getPuzzleElement()); - for (TreeTentLine l : board.getLines()) { - if (line.compare(l) && !l.isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); - } - } - - TreeTentCell startCell = (TreeTentCell) start.getPuzzleElement(); - TreeTentCell endCell = (TreeTentCell) end.getPuzzleElement(); - if (!((startCell.getType() == TreeTentType.TENT && endCell.getType() == TreeTentType.TREE) - || (endCell.getType() == TreeTentType.TENT - && startCell.getType() == TreeTentType.TREE))) { - return "The line must connect a tree to a tent."; - } + final TreeTentLine notifyLine; + if (dupLine == null) { + board.addModifiedData(line); + board.getLines().add(line); + notifyLine = line; + transition.propagateAddition(notifyLine); + } else { + board.removeModifiedData(dupLine); + board.getLines().remove(dupLine); + notifyLine = dupLine; + transition.propagateDeletion(notifyLine); + } - return null; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(transition)); + + final TreeViewSelection newSelection = + new TreeViewSelection(treeView.getElementView(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); } - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - TreeTentCell startCell; - TreeTentCell endCell; - TreeTransition transition; - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - transition = treeNode.getChildren().get(0); - - tree.removeTreeElement(transition); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - - board = (TreeTentBoard) transition.getBoard(); - } else { - transition = (TreeTransition) treeElement; - } + if (start == null || end == null) { + return "The line must connect a tree to a tent."; + } - startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); - endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + TreeElementView view = selection.getFirstSelection(); + TreeElement treeElement = view.getTreeElement(); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) treeElement; + if (!node.getChildren().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } else { + if (!board.isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } + TreeTentLine line = + new TreeTentLine( + (TreeTentCell) start.getPuzzleElement(), (TreeTentCell) end.getPuzzleElement()); + for (TreeTentLine l : board.getLines()) { + if (line.compare(l) && !l.isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); + } + } - TreeTentLine line = new TreeTentLine(startCell, endCell); + TreeTentCell startCell = (TreeTentCell) start.getPuzzleElement(); + TreeTentCell endCell = (TreeTentCell) end.getPuzzleElement(); + if (!((startCell.getType() == TreeTentType.TENT && endCell.getType() == TreeTentType.TREE) + || (endCell.getType() == TreeTentType.TENT && startCell.getType() == TreeTentType.TREE))) { + return "The line must connect a tree to a tent."; + } - TreeTentLine dupLine = null; - for (TreeTentLine l : board.getLines()) { - if (line.compare(l)) { - dupLine = l; - break; - } - } + return null; + } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + TreeTentCell startCell; + TreeTentCell endCell; + TreeTransition transition; + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + transition = treeNode.getChildren().get(0); + + tree.removeTreeElement(transition); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + + board = (TreeTentBoard) transition.getBoard(); + } else { + transition = (TreeTransition) treeElement; + } - final TreeTentLine notifyLine; - if (dupLine == null) { - board.addModifiedData(line); - board.getLines().add(line); - notifyLine = line; - } else { - board.removeModifiedData(dupLine); - board.getLines().remove(dupLine); - notifyLine = dupLine; - } - transition.propagateChange(notifyLine); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); + endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + TreeTentLine line = new TreeTentLine(startCell, endCell); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + TreeTentLine dupLine = null; + for (TreeTentLine l : board.getLines()) { + if (line.compare(l)) { + dupLine = l; + break; + } } - private TreeTentElementView getViewInDirection(ElementView endDrag) { - TreeTentView boardView = (TreeTentView) getInstance().getLegupUI().getBoardView(); - Dimension size = boardView.getElementSize(); - int xIndex, yIndex; - - Point startLoc = start.getLocation(); - Point endLoc = endDrag.getLocation(); - double radians = Math.atan2(startLoc.y - endLoc.y, endLoc.x - startLoc.x); - if (radians >= Math.PI / 4 && radians < 3 * Math.PI / 4) { - // up - xIndex = startLoc.x / size.width; - yIndex = (startLoc.y / size.height) - 1; + final TreeTentLine notifyLine; + if (dupLine == null) { + board.addModifiedData(line); + board.getLines().add(line); + notifyLine = line; + } else { + board.removeModifiedData(dupLine); + board.getLines().remove(dupLine); + notifyLine = dupLine; + } + transition.propagateChange(notifyLine); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } + + private TreeTentElementView getViewInDirection(ElementView endDrag) { + TreeTentView boardView = (TreeTentView) getInstance().getLegupUI().getBoardView(); + Dimension size = boardView.getElementSize(); + int xIndex, yIndex; + + Point startLoc = start.getLocation(); + Point endLoc = endDrag.getLocation(); + double radians = Math.atan2(startLoc.y - endLoc.y, endLoc.x - startLoc.x); + if (radians >= Math.PI / 4 && radians < 3 * Math.PI / 4) { + // up + xIndex = startLoc.x / size.width; + yIndex = (startLoc.y / size.height) - 1; + } else { + if (radians >= -Math.PI / 4 && radians < Math.PI / 4) { + // right + xIndex = (startLoc.x / size.width) + 1; + yIndex = startLoc.y / size.height; + } else { + if (radians >= -3 * Math.PI / 4 && radians < -Math.PI / 4) { + // down + xIndex = startLoc.x / size.width; + yIndex = (startLoc.y / size.height) + 1; } else { - if (radians >= -Math.PI / 4 && radians < Math.PI / 4) { - // right - xIndex = (startLoc.x / size.width) + 1; - yIndex = startLoc.y / size.height; - } else { - if (radians >= -3 * Math.PI / 4 && radians < -Math.PI / 4) { - // down - xIndex = startLoc.x / size.width; - yIndex = (startLoc.y / size.height) + 1; - } else { - // left - xIndex = (startLoc.x / size.width) - 1; - yIndex = startLoc.y / size.height; - } - } + // left + xIndex = (startLoc.x / size.width) - 1; + yIndex = startLoc.y / size.height; } - return (TreeTentElementView) boardView.getElement(xIndex - 1, yIndex - 1); + } } + return (TreeTentElementView) boardView.getElement(xIndex - 1, yIndex - 1); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java index 68c97865d..94381b031 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java @@ -7,82 +7,82 @@ public class TreeTent extends Puzzle { - public TreeTent() { - super(); + public TreeTent() { + super(); - this.name = "TreeTent"; + this.name = "TreeTent"; - this.importer = new TreeTentImporter(this); - this.exporter = new TreeTentExporter(this); + this.importer = new TreeTentImporter(this); + this.exporter = new TreeTentExporter(this); - this.factory = new TreeTentCellFactory(); - } + this.factory = new TreeTentCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - TreeTentBoard board = (TreeTentBoard) currentBoard; - boardView = new TreeTentView((TreeTentBoard) currentBoard); - boardView.setBoard(board); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + TreeTentBoard board = (TreeTentBoard) currentBoard; + boardView = new TreeTentView((TreeTentBoard) currentBoard); + boardView.setBoard(board); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Tree Tent - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Tree Tent, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - return rows > 0 && columns > 0; - } + @Override + /** + * Determines if the given dimensions are valid for Tree Tent + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Tree Tent, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + return rows > 0 && columns > 0; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} - /** - * @return if it is valid TreeTent puzzle must have same number of clues as the dimension size - */ - @Override - public boolean checkValidity() { - TreeTentBoard b = (TreeTentBoard) this.getBoardView().getBoard(); - List elements = b.getPuzzleElements(); - int treeCount = 0; - for (PuzzleElement element : elements) { - TreeTentCell c = (TreeTentCell) element; - if (c.getType() == TreeTentType.TREE) { - treeCount++; - } - } - return treeCount != 0; + /** + * @return if it is valid TreeTent puzzle must have same number of clues as the dimension size + */ + @Override + public boolean checkValidity() { + TreeTentBoard b = (TreeTentBoard) this.getBoardView().getBoard(); + List elements = b.getPuzzleElements(); + int treeCount = 0; + for (PuzzleElement element : elements) { + TreeTentCell c = (TreeTentCell) element; + if (c.getType() == TreeTentType.TREE) { + treeCount++; + } } + return treeCount != 0; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java index 09706f92a..ac1dcca38 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java @@ -9,234 +9,234 @@ public class TreeTentBoard extends GridBoard { - private ArrayList lines; + private ArrayList lines; - private ArrayList rowClues; - private ArrayList colClues; + private ArrayList rowClues; + private ArrayList colClues; - public TreeTentBoard(int width, int height) { - super(width, height); + public TreeTentBoard(int width, int height) { + super(width, height); - this.lines = new ArrayList<>(); + this.lines = new ArrayList<>(); - this.rowClues = new ArrayList<>(); - this.colClues = new ArrayList<>(); + this.rowClues = new ArrayList<>(); + this.colClues = new ArrayList<>(); - for (int i = 0; i < height; i++) { - rowClues.add(null); - } - for (int i = 0; i < width; i++) { - colClues.add(null); - } + for (int i = 0; i < height; i++) { + rowClues.add(null); } - - public TreeTentBoard(int size) { - this(size, size); + for (int i = 0; i < width; i++) { + colClues.add(null); } - - public ArrayList getLines() { - return lines; + } + + public TreeTentBoard(int size) { + this(size, size); + } + + public ArrayList getLines() { + return lines; + } + + public ArrayList getRowClues() { + return rowClues; + } + + public ArrayList getColClues() { + return colClues; + } + + @Override + public TreeTentCell getCell(int x, int y) { + return (TreeTentCell) super.getCell(x, y); + } + + @Override + public PuzzleElement getPuzzleElement(PuzzleElement element) { + switch (element.getIndex()) { + case -2: + return element; + case -1: + TreeTentLine line = (TreeTentLine) element; + TreeTentLine thisLine = null; + for (TreeTentLine l : lines) { + if (line.compare(l)) { + thisLine = l; + break; + } + } + return thisLine; + default: + return super.getPuzzleElement(element); } - - public ArrayList getRowClues() { - return rowClues; + } + + public TreeTentClue getClue(int x, int y) { + if (x == getWidth() && 0 <= y && y < getHeight()) { + return rowClues.get(y); + } else { + if (y == getHeight() && 0 <= x && x < getWidth()) { + return colClues.get(x); + } } - - public ArrayList getColClues() { - return colClues; + return null; + } + + /** + * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element + * with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + @Override + public void notifyAddition(PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + lines.add((TreeTentLine) puzzleElement); } - - @Override - public TreeTentCell getCell(int x, int y) { - return (TreeTentCell) super.getCell(x, y); + } + + /** + * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + @Override + public void notifyDeletion(PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + for (TreeTentLine line : lines) { + if (line.compare((TreeTentLine) puzzleElement)) { + lines.remove(line); + break; + } + } } - - @Override - public PuzzleElement getPuzzleElement(PuzzleElement element) { - switch (element.getIndex()) { - case -2: - return element; - case -1: - TreeTentLine line = (TreeTentLine) element; - TreeTentLine thisLine = null; - for (TreeTentLine l : lines) { - if (line.compare(l)) { - thisLine = l; - break; - } - } - return thisLine; - default: - return super.getPuzzleElement(element); - } + } + + /** + * Get a list of all orthogonally adjacent cells. + * + * @param cell The cell to get adjacent cells from. + * @param type The cell types to get. + * @return List of adjacent cells in the form { up, right, down, left }. If an adjacent cell is + * null, it will not be added to the list. + */ + public List getAdjacent(TreeTentCell cell, TreeTentType type) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + for (int i = -2; i < 2; i++) { + TreeTentCell adjCell = getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); + if (adjCell != null && adjCell.getType() == type) { + adj.add(adjCell); + } } - - public TreeTentClue getClue(int x, int y) { - if (x == getWidth() && 0 <= y && y < getHeight()) { - return rowClues.get(y); - } else { - if (y == getHeight() && 0 <= x && x < getWidth()) { - return colClues.get(x); - } - } - return null; - } - - /** - * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle - * element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - @Override - public void notifyAddition(PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - lines.add((TreeTentLine) puzzleElement); - } + return adj; + } + + /** + * Gets all cells of a specified type that are diagonals of a specified cell + * + * @param cell the base cell + * @param type the type to look for + * @return a list of TreeTentCells that are diagonals of the given TreeTentCell and are of the + * given TreeTentType + */ + public List getDiagonals(TreeTentCell cell, TreeTentType type) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + TreeTentCell upRight = getCell(loc.x + 1, loc.y - 1); + TreeTentCell downRight = getCell(loc.x + 1, loc.y + 1); + TreeTentCell downLeft = getCell(loc.x - 1, loc.y + 1); + TreeTentCell upLeft = getCell(loc.x - 1, loc.y - 1); + if (upRight != null && upRight.getType() == type) { + dia.add(upRight); } - - /** - * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle - * element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - @Override - public void notifyDeletion(PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - for (TreeTentLine line : lines) { - if (line.compare((TreeTentLine) puzzleElement)) { - lines.remove(line); - break; - } - } - } + if (downLeft != null && downLeft.getType() == type) { + dia.add(downLeft); } - - /** - * Get a list of all orthogonally adjacent cells. - * - * @param cell The cell to get adjacent cells from. - * @param type The cell types to get. - * @return List of adjacent cells in the form { up, right, down, left }. If an adjacent cell is - * null, it will not be added to the list. - */ - public List getAdjacent(TreeTentCell cell, TreeTentType type) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - for (int i = -2; i < 2; i++) { - TreeTentCell adjCell = getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); - if (adjCell != null && adjCell.getType() == type) { - adj.add(adjCell); - } - } - return adj; - } - - /** - * Gets all cells of a specified type that are diagonals of a specified cell - * - * @param cell the base cell - * @param type the type to look for - * @return a list of TreeTentCells that are diagonals of the given TreeTentCell and are of the - * given TreeTentType - */ - public List getDiagonals(TreeTentCell cell, TreeTentType type) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - TreeTentCell upRight = getCell(loc.x + 1, loc.y - 1); - TreeTentCell downRight = getCell(loc.x + 1, loc.y + 1); - TreeTentCell downLeft = getCell(loc.x - 1, loc.y + 1); - TreeTentCell upLeft = getCell(loc.x - 1, loc.y - 1); - if (upRight != null && upRight.getType() == type) { - dia.add(upRight); - } - if (downLeft != null && downLeft.getType() == type) { - dia.add(downLeft); - } - if (downRight != null && downRight.getType() == type) { - dia.add(downRight); - } - if (upLeft != null && upLeft.getType() == type) { - dia.add(upLeft); - } - return dia; - } - - /** - * Creates and returns a list of TreeTentCells that match the given TreeTentType - * - * @param index the row or column number - * @param type type of TreeTent element - * @param isRow boolean value beased on whether a row of column is being checked - * @return List of TreeTentCells that match the given TreeTentType - */ - public List getRowCol(int index, TreeTentType type, boolean isRow) { - List list = new ArrayList<>(); - if (isRow) { - for (int i = 0; i < dimension.height; i++) { - TreeTentCell cell = getCell(i, index); - if (cell.getType() == type) { - list.add(cell); - } - } - } else { - for (int i = 0; i < dimension.width; i++) { - TreeTentCell cell = getCell(index, i); - if (cell.getType() == type) { - list.add(cell); - } - } - } - return list; - } - - /** - * Determines if this board contains the equivalent puzzle elements as the one specified - * - * @param board board to check equivalence - * @return true if the boards are equivalent, false otherwise - */ - @Override - public boolean equalsBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - for (TreeTentLine l1 : lines) { - boolean hasLine = false; - for (TreeTentLine l2 : treeTentBoard.lines) { - if (l1.compare(l2)) { - hasLine = true; - } - } - if (!hasLine) { - return false; - } - } - return super.equalsBoard(treeTentBoard); - } - - /** - * Performs a deep copy of the TreeTentBoard - * - * @return a TreeTentBoard object that is a deep copy of the current TreeTentBoard - */ - @Override - public TreeTentBoard copy() { - TreeTentBoard copy = new TreeTentBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (TreeTentLine line : lines) { - TreeTentLine lineCpy = line.copy(); - lineCpy.setModifiable(false); - copy.getLines().add(lineCpy); - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.rowClues = rowClues; - copy.colClues = colClues; - return copy; + if (downRight != null && downRight.getType() == type) { + dia.add(downRight); + } + if (upLeft != null && upLeft.getType() == type) { + dia.add(upLeft); + } + return dia; + } + + /** + * Creates and returns a list of TreeTentCells that match the given TreeTentType + * + * @param index the row or column number + * @param type type of TreeTent element + * @param isRow boolean value beased on whether a row of column is being checked + * @return List of TreeTentCells that match the given TreeTentType + */ + public List getRowCol(int index, TreeTentType type, boolean isRow) { + List list = new ArrayList<>(); + if (isRow) { + for (int i = 0; i < dimension.height; i++) { + TreeTentCell cell = getCell(i, index); + if (cell.getType() == type) { + list.add(cell); + } + } + } else { + for (int i = 0; i < dimension.width; i++) { + TreeTentCell cell = getCell(index, i); + if (cell.getType() == type) { + list.add(cell); + } + } + } + return list; + } + + /** + * Determines if this board contains the equivalent puzzle elements as the one specified + * + * @param board board to check equivalence + * @return true if the boards are equivalent, false otherwise + */ + @Override + public boolean equalsBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + for (TreeTentLine l1 : lines) { + boolean hasLine = false; + for (TreeTentLine l2 : treeTentBoard.lines) { + if (l1.compare(l2)) { + hasLine = true; + } + } + if (!hasLine) { + return false; + } + } + return super.equalsBoard(treeTentBoard); + } + + /** + * Performs a deep copy of the TreeTentBoard + * + * @return a TreeTentBoard object that is a deep copy of the current TreeTentBoard + */ + @Override + public TreeTentBoard copy() { + TreeTentBoard copy = new TreeTentBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (TreeTentLine line : lines) { + TreeTentLine lineCpy = line.copy(); + lineCpy.setModifiable(false); + copy.getLines().add(lineCpy); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } + copy.rowClues = rowClues; + copy.colClues = colClues; + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java index c7c9f0d21..e19c8b3a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java @@ -7,50 +7,50 @@ public class TreeTentCell extends GridCell { - public TreeTentCell(TreeTentType value, Point location) { - super(value, location); - } + public TreeTentCell(TreeTentType value, Point location) { + super(value, location); + } - public TreeTentType getType() { - return data; - } + public TreeTentType getType() { + return data; + } - public int getValue() { - switch (data) { - case TREE: - return 1; - case GRASS: - return 2; - case TENT: - return 3; - default: - return 0; - } + public int getValue() { + switch (data) { + case TREE: + return 1; + case GRASS: + return 2; + case TENT: + return 3; + default: + return 0; } + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementName()) { - case "Unknown Tile": - this.data = TreeTentType.UNKNOWN; - break; - case "Tree Tile": - this.data = TreeTentType.TREE; - break; - case "Grass Tile": - this.data = TreeTentType.GRASS; - break; - case "Tent Tile": - this.data = TreeTentType.TENT; - } + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementName()) { + case "Unknown Tile": + this.data = TreeTentType.UNKNOWN; + break; + case "Tree Tile": + this.data = TreeTentType.TREE; + break; + case "Grass Tile": + this.data = TreeTentType.GRASS; + break; + case "Tent Tile": + this.data = TreeTentType.TENT; } + } - @Override - public TreeTentCell copy() { - TreeTentCell copy = new TreeTentCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public TreeTentCell copy() { + TreeTentCell copy = new TreeTentCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java index 1697b8bd5..10bcf77c7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java @@ -10,94 +10,92 @@ import org.w3c.dom.Node; public class TreeTentCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - int width = treeTentBoard.getWidth(); - int height = treeTentBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - if (node.getNodeName().equalsIgnoreCase("cell")) { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { + try { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + int width = treeTentBoard.getWidth(); + int height = treeTentBoard.getHeight(); + NamedNodeMap attributeList = node.getAttributes(); + if (node.getNodeName().equalsIgnoreCase("cell")) { - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException( - "TreeTent Factory: cell location out of bounds"); - } - if (value < 0 || value > 3) { - throw new InvalidFileFormatException("TreeTent Factory: cell unknown value"); - } + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("TreeTent Factory: cell location out of bounds"); + } + if (value < 0 || value > 3) { + throw new InvalidFileFormatException("TreeTent Factory: cell unknown value"); + } - TreeTentCell cell = new TreeTentCell(TreeTentType.valueOf(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } else { - if (node.getNodeName().equalsIgnoreCase("line")) { - int x1 = Integer.valueOf(attributeList.getNamedItem("x1").getNodeValue()); - int y1 = Integer.valueOf(attributeList.getNamedItem("y1").getNodeValue()); - int x2 = Integer.valueOf(attributeList.getNamedItem("x2").getNodeValue()); - int y2 = Integer.valueOf(attributeList.getNamedItem("y2").getNodeValue()); - if (x1 >= width || y1 >= height || x2 >= width || y2 >= height) { - throw new InvalidFileFormatException( - "TreeTent Factory: line location out of bounds"); - } + TreeTentCell cell = new TreeTentCell(TreeTentType.valueOf(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } else { + if (node.getNodeName().equalsIgnoreCase("line")) { + int x1 = Integer.valueOf(attributeList.getNamedItem("x1").getNodeValue()); + int y1 = Integer.valueOf(attributeList.getNamedItem("y1").getNodeValue()); + int x2 = Integer.valueOf(attributeList.getNamedItem("x2").getNodeValue()); + int y2 = Integer.valueOf(attributeList.getNamedItem("y2").getNodeValue()); + if (x1 >= width || y1 >= height || x2 >= width || y2 >= height) { + throw new InvalidFileFormatException("TreeTent Factory: line location out of bounds"); + } - TreeTentCell c1 = treeTentBoard.getCell(x1, y1); - TreeTentCell c2 = treeTentBoard.getCell(x2, y2); - return new TreeTentLine(c1, c2); - } else { - throw new InvalidFileFormatException( - "TreeTent Factory: unknown puzzleElement puzzleElement"); - } - } - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "TreeTent Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("TreeTent Factory: could not find attribute(s)"); + TreeTentCell c1 = treeTentBoard.getCell(x1, y1); + TreeTentCell c2 = treeTentBoard.getCell(x2, y2); + return new TreeTentLine(c1, c2); + } else { + throw new InvalidFileFormatException( + "TreeTent Factory: unknown puzzleElement puzzleElement"); } + } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "TreeTent Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("TreeTent Factory: could not find attribute(s)"); } + } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentCell) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentCell) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); + TreeTentCell cell = (TreeTentCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getValue())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getValue())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } else { - org.w3c.dom.Element lineElement = document.createElement("line"); + return cellElement; + } else { + org.w3c.dom.Element lineElement = document.createElement("line"); - TreeTentLine line = (TreeTentLine) puzzleElement; + TreeTentLine line = (TreeTentLine) puzzleElement; - lineElement.setAttribute("x1", String.valueOf(line.getC1().getLocation().x)); - lineElement.setAttribute("y1", String.valueOf(line.getC1().getLocation().y)); - lineElement.setAttribute("x2", String.valueOf(line.getC2().getLocation().x)); - lineElement.setAttribute("y2", String.valueOf(line.getC2().getLocation().y)); + lineElement.setAttribute("x1", String.valueOf(line.getC1().getLocation().x)); + lineElement.setAttribute("y1", String.valueOf(line.getC1().getLocation().y)); + lineElement.setAttribute("x2", String.valueOf(line.getC2().getLocation().x)); + lineElement.setAttribute("y2", String.valueOf(line.getC2().getLocation().y)); - return lineElement; - } + return lineElement; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java index bcba7dc94..df9e7eed2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java @@ -3,53 +3,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class TreeTentClue extends PuzzleElement { - private TreeTentType type; - private int clueIndex; - - public TreeTentClue(int value, int clueIndex, TreeTentType type) { - super(value); - this.index = -2; - this.clueIndex = clueIndex; - this.type = type; - } - - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; - } - return sb.reverse().toString(); - } - - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; - } - return result; - } - - public int getClueIndex() { - return clueIndex; - } - - public void setClueIndex(int clueIndex) { - this.clueIndex = clueIndex; - } - - public TreeTentType getType() { - return type; - } - - public void setType(TreeTentType type) { - this.type = type; - } - - public TreeTentClue copy() { - return null; - } + private TreeTentType type; + private int clueIndex; + + public TreeTentClue(int value, int clueIndex, TreeTentType type) { + super(value); + this.index = -2; + this.clueIndex = clueIndex; + this.type = type; + } + + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; + } + return sb.reverse().toString(); + } + + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; + } + return result; + } + + public int getClueIndex() { + return clueIndex; + } + + public void setClueIndex(int clueIndex) { + this.clueIndex = clueIndex; + } + + public TreeTentType getType() { + return type; + } + + public void setType(TreeTentType type) { + this.type = type; + } + + public TreeTentClue copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java index d1b230d20..e59c86f62 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java @@ -5,50 +5,50 @@ public class TreeTentClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public TreeTentClueView(TreeTentClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public TreeTentClue getPuzzleElement() { - return (TreeTentClue) super.getPuzzleElement(); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public TreeTentClueView(TreeTentClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public TreeTentClue getPuzzleElement() { + return (TreeTentClue) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + TreeTentClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + value = String.valueOf(clue.getData() + 1); + break; + case CLUE_EAST: + value = String.valueOf(clue.getData()); + break; + case CLUE_SOUTH: + value = String.valueOf(clue.getData()); + break; + case CLUE_WEST: + value = TreeTentClue.colNumToString(clue.getData() + 1); + break; + default: + value = ""; } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - TreeTentClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - value = String.valueOf(clue.getData() + 1); - break; - case CLUE_EAST: - value = String.valueOf(clue.getData()); - break; - case CLUE_SOUTH: - value = String.valueOf(clue.getData()); - break; - case CLUE_WEST: - value = TreeTentClue.colNumToString(clue.getData() + 1); - break; - default: - value = ""; - } - - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java index 79e074657..d3a4b3d26 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java @@ -19,120 +19,115 @@ public class TreeTentController extends ElementController { - private ElementView lastCellPressed; - private ElementView dragStart; + private ElementView lastCellPressed; + private ElementView dragStart; - public TreeTentController() { - super(); - this.dragStart = null; - this.lastCellPressed = null; - } + public TreeTentController() { + super(); + this.dragStart = null; + this.lastCellPressed = null; + } - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() != MouseEvent.BUTTON2) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - dragStart = boardView.getElement(e.getPoint()); - lastCellPressed = boardView.getElement(e.getPoint()); - } + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() != MouseEvent.BUTTON2) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + dragStart = boardView.getElement(e.getPoint()); + lastCellPressed = boardView.getElement(e.getPoint()); } + } - @Override - public void mouseReleased(MouseEvent e) { - if (GameBoardFacade.getInstance().getLegupUI().getTreePanel() != null - && e.getButton() != MouseEvent.BUTTON2) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = - GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - lastCellPressed = boardView.getElement(e.getPoint()); - Board board = boardView.getBoard(); - TreeViewSelection selection = treeView.getSelection(); + @Override + public void mouseReleased(MouseEvent e) { + if (GameBoardFacade.getInstance().getLegupUI().getTreePanel() != null + && e.getButton() != MouseEvent.BUTTON2) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + lastCellPressed = boardView.getElement(e.getPoint()); + Board board = boardView.getBoard(); + TreeViewSelection selection = treeView.getSelection(); - if (dragStart != null) { - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - AutoCaseRuleCommand autoCaseRuleCommand = - new AutoCaseRuleCommand( - dragStart, selection, caseBoard.getCaseRule(), caseBoard, e); - if (autoCaseRuleCommand.canExecute()) { - autoCaseRuleCommand.execute(); - getInstance().getHistory().pushChange(autoCaseRuleCommand); - treePanel.updateError(""); - } else { - treePanel.updateError(autoCaseRuleCommand.getError()); - } + if (dragStart != null) { + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + AutoCaseRuleCommand autoCaseRuleCommand = + new AutoCaseRuleCommand(dragStart, selection, caseBoard.getCaseRule(), caseBoard, e); + if (autoCaseRuleCommand.canExecute()) { + autoCaseRuleCommand.execute(); + getInstance().getHistory().pushChange(autoCaseRuleCommand); + treePanel.updateError(""); + } else { + treePanel.updateError(autoCaseRuleCommand.getError()); + } + } else { + if (dragStart == lastCellPressed) { + if (dragStart.getPuzzleElement().getIndex() >= 0) { + ICommand edit = new EditDataCommand(lastCellPressed, selection, e); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + treePanel.updateError(""); + } else { + treePanel.updateError(edit.getError()); + } + } else { + ClueCommand edit = new ClueCommand(selection, (TreeTentClueView) dragStart); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + treePanel.updateError(""); + } else { + treePanel.updateError(edit.getError()); + } + } + } else { + if (lastCellPressed != null) { + if (dragStart instanceof TreeTentElementView) { + ICommand editLine = + new EditLineCommand( + selection, (TreeTentElementView) dragStart, lastCellPressed); + if (editLine.canExecute()) { + editLine.execute(); + getInstance().getHistory().pushChange(editLine); } else { - if (dragStart == lastCellPressed) { - if (dragStart.getPuzzleElement().getIndex() >= 0) { - ICommand edit = new EditDataCommand(lastCellPressed, selection, e); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - treePanel.updateError(""); - } else { - treePanel.updateError(edit.getError()); - } - } else { - ClueCommand edit = - new ClueCommand(selection, (TreeTentClueView) dragStart); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - treePanel.updateError(""); - } else { - treePanel.updateError(edit.getError()); - } - } - } else { - if (lastCellPressed != null) { - if (dragStart instanceof TreeTentElementView) { - ICommand editLine = - new EditLineCommand( - selection, - (TreeTentElementView) dragStart, - lastCellPressed); - if (editLine.canExecute()) { - editLine.execute(); - getInstance().getHistory().pushChange(editLine); - } else { - treePanel.updateError(editLine.getError()); - } - } - } - } + treePanel.updateError(editLine.getError()); } + } } - dragStart = null; - lastCellPressed = null; + } } + } + dragStart = null; + lastCellPressed = null; } + } - @Override - public void changeCell(MouseEvent e, PuzzleElement element) { - TreeTentCell cell = (TreeTentCell) element; - if (e.getButton() == MouseEvent.BUTTON1) { - if (cell.getData() == TreeTentType.UNKNOWN) { - element.setData(TreeTentType.GRASS); - } else { - if (cell.getData() == TreeTentType.GRASS) { - element.setData(TreeTentType.TENT); - } else { - element.setData(TreeTentType.UNKNOWN); - } - } + @Override + public void changeCell(MouseEvent e, PuzzleElement element) { + TreeTentCell cell = (TreeTentCell) element; + if (e.getButton() == MouseEvent.BUTTON1) { + if (cell.getData() == TreeTentType.UNKNOWN) { + element.setData(TreeTentType.GRASS); + } else { + if (cell.getData() == TreeTentType.GRASS) { + element.setData(TreeTentType.TENT); } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == TreeTentType.UNKNOWN) { - element.setData(TreeTentType.TENT); - } else { - if (cell.getData() == TreeTentType.GRASS) { - element.setData(TreeTentType.UNKNOWN); - } else { - element.setData(TreeTentType.GRASS); - } - } - } + element.setData(TreeTentType.UNKNOWN); + } + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == TreeTentType.UNKNOWN) { + element.setData(TreeTentType.TENT); + } else { + if (cell.getData() == TreeTentType.GRASS) { + element.setData(TreeTentType.UNKNOWN); + } else { + element.setData(TreeTentType.GRASS); + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java index 1196ab075..740ea5ea8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java @@ -5,69 +5,51 @@ import java.awt.geom.Rectangle2D; public class TreeTentElementView extends GridElementView { - public TreeTentElementView(TreeTentCell cell) { - super(cell); - } + public TreeTentElementView(TreeTentCell cell) { + super(cell); + } - /** - * Draws on the given frame based on the type of the cell of the current puzzleElement - * - * @param graphics2D the frame to be drawn on - */ - @Override - public void drawElement(Graphics2D graphics2D) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - TreeTentType type = cell.getType(); - graphics2D.setStroke(new BasicStroke(0)); - if (type == TreeTentType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fill( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); - graphics2D.setColor(Color.BLACK); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); + /** + * Draws on the given frame based on the type of the cell of the current puzzleElement + * + * @param graphics2D the frame to be drawn on + */ + @Override + public void drawElement(Graphics2D graphics2D) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + TreeTentType type = cell.getType(); + graphics2D.setStroke(new BasicStroke(0)); + if (type == TreeTentType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fill( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); + graphics2D.setColor(Color.BLACK); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); + } else { + if (type == TreeTentType.TREE) { + graphics2D.drawImage( + TreeTentView.TREE, location.x, location.y, size.width, size.height, null, null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == TreeTentType.GRASS) { + graphics2D.drawImage( + TreeTentView.GRASS, location.x, location.y, size.width, size.height, null, null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); } else { - if (type == TreeTentType.TREE) { - graphics2D.drawImage( - TreeTentView.TREE, - location.x, - location.y, - size.width, - size.height, - null, - null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == TreeTentType.GRASS) { - graphics2D.drawImage( - TreeTentView.GRASS, - location.x, - location.y, - size.width, - size.height, - null, - null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == TreeTentType.TENT) { - graphics2D.drawImage( - TreeTentView.TENT, - location.x, - location.y, - size.width, - size.height, - null, - null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } - } - } + if (type == TreeTentType.TENT) { + graphics2D.drawImage( + TreeTentView.TENT, location.x, location.y, size.width, size.height, null, null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java index 475aaab1e..621ea0a38 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java @@ -6,68 +6,68 @@ public class TreeTentExporter extends PuzzleExporter { - public TreeTentExporter(TreeTent treeTent) { - super(treeTent); - } + public TreeTentExporter(TreeTent treeTent) { + super(treeTent); + } - /** - * Creates and returns a new board element in the XML document specified - * - * @param newDocument the XML document to append to - * @return the new board element - */ - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - TreeTentBoard board; - if (puzzle.getTree() != null) { - board = (TreeTentBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (TreeTentBoard) puzzle.getBoardView().getBoard(); - } + /** + * Creates and returns a new board element in the XML document specified + * + * @param newDocument the XML document to append to + * @return the new board element + */ + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + TreeTentBoard board; + if (puzzle.getTree() != null) { + board = (TreeTentBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (TreeTentBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getData() != TreeTentType.UNKNOWN) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getData() != TreeTentType.UNKNOWN) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (TreeTentClue clue : board.getRowClues()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", TreeTentClue.colNumToString(clue.getClueIndex())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (TreeTentClue clue : board.getRowClues()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", TreeTentClue.colNumToString(clue.getClueIndex())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (TreeTentClue clue : board.getRowClues()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", String.valueOf(clue.getClueIndex())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (TreeTentClue clue : board.getRowClues()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", String.valueOf(clue.getClueIndex())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); - if (!board.getLines().isEmpty()) { - org.w3c.dom.Element linesElement = newDocument.createElement("lines"); - for (PuzzleElement data : board.getLines()) { - org.w3c.dom.Element lineElement = puzzle.getFactory().exportCell(newDocument, data); - linesElement.appendChild(lineElement); - } - boardElement.appendChild(linesElement); - } - return boardElement; + if (!board.getLines().isEmpty()) { + org.w3c.dom.Element linesElement = newDocument.createElement("lines"); + for (PuzzleElement data : board.getLines()) { + org.w3c.dom.Element lineElement = puzzle.getFactory().exportCell(newDocument, data); + linesElement.appendChild(lineElement); + } + boardElement.appendChild(linesElement); } + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java index 0117f41ce..ecb8eb664 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java @@ -8,212 +8,203 @@ import org.w3c.dom.NodeList; public class TreeTentImporter extends PuzzleImporter { - public TreeTentImporter(TreeTent treeTent) { - super(treeTent); + public TreeTentImporter(TreeTent treeTent) { + super(treeTent); + } + + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } + + @Override + public boolean acceptsTextInput() { + return false; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + TreeTentBoard treeTentBoard = new TreeTentBoard(columns, rows); + + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + if (treeTentBoard.getCell(x, y) == null) { + TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + treeTentBoard.setCell(x, y, cell); + } + } } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; + for (int i = 0; i < rows; i++) { + treeTentBoard.getRowClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_EAST)); } - @Override - public boolean acceptsTextInput() { - return false; + for (int i = 0; i < columns; i++) { + treeTentBoard.getColClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_SOUTH)); } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - TreeTentBoard treeTentBoard = new TreeTentBoard(columns, rows); - - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - if (treeTentBoard.getCell(x, y) == null) { - TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - treeTentBoard.setCell(x, y, cell); - } - } + puzzle.setCurrentBoard(treeTentBoard); + } + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException("TreeTent Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException("TreeTent Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + TreeTentBoard treeTentBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + treeTentBoard = new TreeTentBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + treeTentBoard = new TreeTentBoard(width, height); } - - for (int i = 0; i < rows; i++) { - treeTentBoard.getRowClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_EAST)); + } + + if (treeTentBoard == null) { + throw new InvalidFileFormatException("TreeTent Importer: invalid board dimensions"); + } + + int width = treeTentBoard.getWidth(); + int height = treeTentBoard.getHeight(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + TreeTentCell cell = + (TreeTentCell) puzzle.getFactory().importCell(elementDataList.item(i), treeTentBoard); + Point loc = cell.getLocation(); + if (cell.getData() != TreeTentType.UNKNOWN) { + cell.setModifiable(false); + cell.setGiven(true); } - - for (int i = 0; i < columns; i++) { - treeTentBoard.getColClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_SOUTH)); + treeTentBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (treeTentBoard.getCell(x, y) == null) { + TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + treeTentBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("TreeTent Importer: cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { + throw new InvalidFileFormatException( + "TreeTent Importer: side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "TreeTent Importer: axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != treeTentBoard.getHeight() + || southClues.getLength() != treeTentBoard.getWidth()) { + throw new InvalidFileFormatException( + "TreeTent Importer: there must be same number of clues as the dimension of" + + " the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = TreeTentClue.colStringToColNum(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > treeTentBoard.getHeight()) { + throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); } - puzzle.setCurrentBoard(treeTentBoard); - } + if (treeTentBoard.getRowClues().get(index - 1) != null) { + throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); + } + treeTentBoard + .getRowClues() + .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > treeTentBoard.getWidth()) { + throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); + } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "TreeTent Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "TreeTent Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - TreeTentBoard treeTentBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - treeTentBoard = new TreeTentBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - treeTentBoard = new TreeTentBoard(width, height); - } - } - - if (treeTentBoard == null) { - throw new InvalidFileFormatException("TreeTent Importer: invalid board dimensions"); - } - - int width = treeTentBoard.getWidth(); - int height = treeTentBoard.getHeight(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - TreeTentCell cell = - (TreeTentCell) - puzzle.getFactory() - .importCell(elementDataList.item(i), treeTentBoard); - Point loc = cell.getLocation(); - if (cell.getData() != TreeTentType.UNKNOWN) { - cell.setModifiable(false); - cell.setGiven(true); - } - treeTentBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (treeTentBoard.getCell(x, y) == null) { - TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - treeTentBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("TreeTent Importer: cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { - throw new InvalidFileFormatException( - "TreeTent Importer: side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "TreeTent Importer: axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != treeTentBoard.getHeight() - || southClues.getLength() != treeTentBoard.getWidth()) { - throw new InvalidFileFormatException( - "TreeTent Importer: there must be same number of clues as the dimension of" - + " the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = TreeTentClue.colStringToColNum(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > treeTentBoard.getHeight()) { - throw new InvalidFileFormatException( - "TreeTent Importer: clue index out of bounds"); - } - - if (treeTentBoard.getRowClues().get(index - 1) != null) { - throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); - } - treeTentBoard - .getRowClues() - .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > treeTentBoard.getWidth()) { - throw new InvalidFileFormatException( - "TreeTent Importer: clue index out of bounds"); - } - - if (treeTentBoard.getColClues().get(index - 1) != null) { - throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); - } - treeTentBoard - .getColClues() - .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_SOUTH)); - } - - if (boardElement.getElementsByTagName("lines").getLength() == 1) { - Element linesElement = (Element) boardElement.getElementsByTagName("lines").item(0); - NodeList linesList = linesElement.getElementsByTagName("line"); - for (int i = 0; i < linesList.getLength(); i++) { - treeTentBoard - .getLines() - .add( - (TreeTentLine) - puzzle.getFactory() - .importCell(linesList.item(i), treeTentBoard)); - } - } - - puzzle.setCurrentBoard(treeTentBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "TreeTent Importer: unknown value where integer expected"); + if (treeTentBoard.getColClues().get(index - 1) != null) { + throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); } - } + treeTentBoard + .getColClues() + .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_SOUTH)); + } + + if (boardElement.getElementsByTagName("lines").getLength() == 1) { + Element linesElement = (Element) boardElement.getElementsByTagName("lines").item(0); + NodeList linesList = linesElement.getElementsByTagName("line"); + for (int i = 0; i < linesList.getLength(); i++) { + treeTentBoard + .getLines() + .add((TreeTentLine) puzzle.getFactory().importCell(linesList.item(i), treeTentBoard)); + } + } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Tree Tent cannot accept text input"); + puzzle.setCurrentBoard(treeTentBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "TreeTent Importer: unknown value where integer expected"); } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Tree Tent cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java index dae10a1ae..bc252b0ba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java @@ -5,40 +5,40 @@ public class TreeTentLine extends PuzzleElement> { - public TreeTentLine(TreeTentCell c1, TreeTentCell c2) { - this.data = new Entry<>(c1, c2); - } - - public TreeTentCell getC1() { - return data.getKey(); - } - - public void setC1(TreeTentCell c1) { - this.data.setKey(c1); - } - - public TreeTentCell getC2() { - return data.getValue(); - } - - public void setC2(TreeTentCell c2) { - this.data.setValue(c2); - } - - public boolean compare(TreeTentLine line) { - return ((line.getC1().getLocation().equals(data.getKey().getLocation()) - && line.getC2().getLocation().equals(data.getValue().getLocation())) - || (line.getC1().getLocation().equals(data.getValue().getLocation()) - && line.getC2().getLocation().equals(data.getKey().getLocation()))); - } - - /** - * Copies this elements puzzleElement to a new PuzzleElement object - * - * @return copied PuzzleElement object - */ - @Override - public TreeTentLine copy() { - return new TreeTentLine(data.getKey().copy(), data.getValue().copy()); - } + public TreeTentLine(TreeTentCell c1, TreeTentCell c2) { + this.data = new Entry<>(c1, c2); + } + + public TreeTentCell getC1() { + return data.getKey(); + } + + public void setC1(TreeTentCell c1) { + this.data.setKey(c1); + } + + public TreeTentCell getC2() { + return data.getValue(); + } + + public void setC2(TreeTentCell c2) { + this.data.setValue(c2); + } + + public boolean compare(TreeTentLine line) { + return ((line.getC1().getLocation().equals(data.getKey().getLocation()) + && line.getC2().getLocation().equals(data.getValue().getLocation())) + || (line.getC1().getLocation().equals(data.getValue().getLocation()) + && line.getC2().getLocation().equals(data.getKey().getLocation()))); + } + + /** + * Copies this elements puzzleElement to a new PuzzleElement object + * + * @return copied PuzzleElement object + */ + @Override + public TreeTentLine copy() { + return new TreeTentLine(data.getKey().copy(), data.getValue().copy()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java index 6d478cff8..b2e6ed7b5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java @@ -4,28 +4,28 @@ import java.awt.*; public class TreeTentLineView extends ElementView { - private final Color LINE_COLOR = Color.GREEN; + private final Color LINE_COLOR = Color.GREEN; - private final Stroke LINE_STROKE = new BasicStroke(2); + private final Stroke LINE_STROKE = new BasicStroke(2); - public TreeTentLineView(TreeTentLine line) { - super(line); - } + public TreeTentLineView(TreeTentLine line) { + super(line); + } - @Override - public void draw(Graphics2D graphics2D) { + @Override + public void draw(Graphics2D graphics2D) { - TreeTentLine line = (TreeTentLine) puzzleElement; - Point p1 = line.getC1().getLocation(); - Point p2 = line.getC2().getLocation(); - int x1 = (p1.x + 1) * size.width + size.width / 2; - int y1 = (p1.y + 1) * size.height + size.height / 2; + TreeTentLine line = (TreeTentLine) puzzleElement; + Point p1 = line.getC1().getLocation(); + Point p2 = line.getC2().getLocation(); + int x1 = (p1.x + 1) * size.width + size.width / 2; + int y1 = (p1.y + 1) * size.height + size.height / 2; - int x2 = (p2.x + 1) * size.width + size.width / 2; - int y2 = (p2.y + 1) * size.height + size.height / 2; - // graphics2D.setColor(LINE_COLOR); - graphics2D.setColor(line.isModified() ? Color.GREEN : Color.WHITE); - graphics2D.setStroke(LINE_STROKE); - graphics2D.drawLine(x1, y1, x2, y2); - } + int x2 = (p2.x + 1) * size.width + size.width / 2; + int y2 = (p2.y + 1) * size.height + size.height / 2; + // graphics2D.setColor(LINE_COLOR); + graphics2D.setColor(line.isModified() ? Color.GREEN : Color.WHITE); + graphics2D.setStroke(LINE_STROKE); + graphics2D.drawLine(x1, y1, x2, y2); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java index 230283418..b1e480335 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java @@ -1,25 +1,25 @@ package edu.rpi.legup.puzzle.treetent; public enum TreeTentType { - UNKNOWN, - TREE, - GRASS, - TENT, - CLUE_NORTH, - CLUE_EAST, - CLUE_SOUTH, - CLUE_WEST; + UNKNOWN, + TREE, + GRASS, + TENT, + CLUE_NORTH, + CLUE_EAST, + CLUE_SOUTH, + CLUE_WEST; - public static TreeTentType valueOf(int num) { - switch (num) { - case 1: - return TREE; - case 2: - return GRASS; - case 3: - return TENT; - default: - return UNKNOWN; - } + public static TreeTentType valueOf(int num) { + switch (num) { + case 1: + return TREE; + case 2: + return GRASS; + case 3: + return TENT; + default: + return UNKNOWN; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java index 3b8cadad6..0973f9452 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java @@ -14,212 +14,201 @@ import org.apache.logging.log4j.Logger; public class TreeTentView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(TreeTentView.class.getName()); - - static Image TREE, GRASS, TENT; - - static { - try { - TREE = - ImageIO.read( - ClassLoader.getSystemResourceAsStream( - "edu/rpi/legup/images/treetent/tree.png")); - GRASS = - ImageIO.read( - ClassLoader.getSystemResourceAsStream( - "edu/rpi/legup/images/treetent/grass.png")); - TENT = - ImageIO.read( - ClassLoader.getSystemResourceAsStream( - "edu/rpi/legup/images/treetent/tent.png")); - } catch (IOException e) { - LOGGER.error("Failed to open TreeTent images"); - } - } - - private ArrayList lineViews; - - private ArrayList northClues; - private ArrayList eastClues; - private ArrayList southClues; - private ArrayList westClues; - - public TreeTentView(TreeTentBoard board) { - super(new BoardController(), new TreeTentController(), board.getDimension()); - - this.lineViews = new ArrayList<>(); - - this.northClues = new ArrayList<>(); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - TreeTentElementView elementView = new TreeTentElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); - elementViews.add(elementView); - } - - for (TreeTentLine line : board.getLines()) { - TreeTentLineView lineView = new TreeTentLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - - for (int i = 0; i < gridSize.height; i++) { - TreeTentClueView row = - new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_WEST)); - row.setLocation(new Point(0, (i + 1) * elementSize.height)); - row.setSize(elementSize); - - TreeTentClueView clue = new TreeTentClueView(board.getRowClues().get(i)); - clue.setLocation( - new Point( - (gridSize.width + 1) * elementSize.width, - (i + 1) * elementSize.height)); - clue.setSize(elementSize); - - westClues.add(row); - eastClues.add(clue); - } - - for (int i = 0; i < gridSize.width; i++) { - TreeTentClueView col = - new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_NORTH)); - col.setLocation(new Point((i + 1) * elementSize.width, 0)); - col.setSize(elementSize); - - TreeTentClueView clue = new TreeTentClueView(board.getColClues().get(i)); - clue.setLocation( - new Point( - (i + 1) * elementSize.width, - (gridSize.height + 1) * elementSize.height)); - clue.setSize(elementSize); - - northClues.add(col); - southClues.add(clue); - } - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - @Override - public ElementView getElement(Point point) { - Point scaledPoint = - new Point( - (int) Math.round(point.x / getScale()), - (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - for (TreeTentClueView clueView : northClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : eastClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : southClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : westClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - return null; - } - - public ArrayList getLineViews() { - return lineViews; - } - - public ArrayList getNorthClues() { - return northClues; - } - - public ArrayList getEastClues() { - return eastClues; - } - - public ArrayList getSouthClues() { - return southClues; - } - - public ArrayList getWestClues() { - return westClues; - } - - @Override - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = (gridSize.width + 2) * elementSize.width; - boardViewSize.height = (gridSize.height + 2) * elementSize.height; - return boardViewSize; - } - - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - super.onTreeElementChanged(treeElement); - TreeTentBoard treeTentBoard; - if (board instanceof CaseBoard) { - treeTentBoard = (TreeTentBoard) ((CaseBoard) board).getBaseBoard(); - } else { - treeTentBoard = (TreeTentBoard) board; - } - - lineViews.clear(); - for (TreeTentLine line : treeTentBoard.getLines()) { - TreeTentLineView lineView = new TreeTentLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - } - - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); - - for (TreeTentLineView view : lineViews) { - view.draw(graphics2D); - } - - for (TreeTentClueView clueView : northClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : eastClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : southClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : westClues) { - clueView.draw(graphics2D); - } + private static final Logger LOGGER = LogManager.getLogger(TreeTentView.class.getName()); + + static Image TREE, GRASS, TENT; + + static { + try { + TREE = + ImageIO.read( + ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tree.png")); + GRASS = + ImageIO.read( + ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/grass.png")); + TENT = + ImageIO.read( + ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tent.png")); + } catch (IOException e) { + LOGGER.error("Failed to open TreeTent images"); } + } + + private ArrayList lineViews; + + private ArrayList northClues; + private ArrayList eastClues; + private ArrayList southClues; + private ArrayList westClues; + + public TreeTentView(TreeTentBoard board) { + super(new BoardController(), new TreeTentController(), board.getDimension()); + + this.lineViews = new ArrayList<>(); + + this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + Point loc = cell.getLocation(); + TreeTentElementView elementView = new TreeTentElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); + elementViews.add(elementView); + } + + for (TreeTentLine line : board.getLines()) { + TreeTentLineView lineView = new TreeTentLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + + for (int i = 0; i < gridSize.height; i++) { + TreeTentClueView row = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_WEST)); + row.setLocation(new Point(0, (i + 1) * elementSize.height)); + row.setSize(elementSize); + + TreeTentClueView clue = new TreeTentClueView(board.getRowClues().get(i)); + clue.setLocation( + new Point((gridSize.width + 1) * elementSize.width, (i + 1) * elementSize.height)); + clue.setSize(elementSize); + + westClues.add(row); + eastClues.add(clue); + } + + for (int i = 0; i < gridSize.width; i++) { + TreeTentClueView col = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_NORTH)); + col.setLocation(new Point((i + 1) * elementSize.width, 0)); + col.setSize(elementSize); + + TreeTentClueView clue = new TreeTentClueView(board.getColClues().get(i)); + clue.setLocation( + new Point((i + 1) * elementSize.width, (gridSize.height + 1) * elementSize.height)); + clue.setSize(elementSize); + + northClues.add(col); + southClues.add(clue); + } + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + @Override + public ElementView getElement(Point point) { + Point scaledPoint = + new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + for (TreeTentClueView clueView : northClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : eastClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : southClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : westClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + return null; + } + + public ArrayList getLineViews() { + return lineViews; + } + + public ArrayList getNorthClues() { + return northClues; + } + + public ArrayList getEastClues() { + return eastClues; + } + + public ArrayList getSouthClues() { + return southClues; + } + + public ArrayList getWestClues() { + return westClues; + } + + @Override + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = (gridSize.width + 2) * elementSize.width; + boardViewSize.height = (gridSize.height + 2) * elementSize.height; + return boardViewSize; + } + + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + super.onTreeElementChanged(treeElement); + TreeTentBoard treeTentBoard; + if (board instanceof CaseBoard) { + treeTentBoard = (TreeTentBoard) ((CaseBoard) board).getBaseBoard(); + } else { + treeTentBoard = (TreeTentBoard) board; + } + + lineViews.clear(); + for (TreeTentLine line : treeTentBoard.getLines()) { + TreeTentLineView lineView = new TreeTentLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + } + + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); + + for (TreeTentLineView view : lineViews) { + view.draw(graphics2D); + } + + for (TreeTentClueView clueView : northClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : eastClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : southClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : westClues) { + clueView.draw(graphics2D); + } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java index 5356120a8..4d452f48d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java @@ -4,11 +4,11 @@ public class GrassTile extends PlaceableElement { - public GrassTile() { - super( - "TREE-PlAC-0002", - "Grass Tile", - "The grass crest tile", - "edu/rpi/legup/images/treetent/grass.png"); - } + public GrassTile() { + super( + "TREE-PlAC-0002", + "Grass Tile", + "The grass crest tile", + "edu/rpi/legup/images/treetent/grass.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java index 950aebfa7..249b22b04 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java @@ -4,11 +4,7 @@ public class TentTile extends PlaceableElement { - public TentTile() { - super( - "TREE-PLAC-0001", - "Tent Tile", - "The tent tile", - "edu/rpi/legup/images/treetent/tent.png"); - } + public TentTile() { + super("TREE-PLAC-0001", "Tent Tile", "The tent tile", "edu/rpi/legup/images/treetent/tent.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java index d04886ed5..eab34e0b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java @@ -4,11 +4,7 @@ public class TreeTile extends NonPlaceableElement { - public TreeTile() { - super( - "TREE-UNPL-0001", - "Tree Tile", - "The tree tile", - "edu/rpi/legup/images/treetent/tree.png"); - } + public TreeTile() { + super("TREE-UNPL-0001", "Tree Tile", "The tree tile", "edu/rpi/legup/images/treetent/tree.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java index a54240efd..589053d5a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "TREE-UNPL-0002", - "Unknown Tile", - "The blank tile", - "edu/rpi/legup/images/treetent/UnknownTile.png"); - } + public UnknownTile() { + super( + "TREE-UNPL-0002", + "Unknown Tile", + "The blank tile", + "edu/rpi/legup/images/treetent/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java index c91a60b1a..2e7b7a031 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java @@ -12,78 +12,77 @@ import java.util.List; public class EmptyFieldDirectRule extends DirectRule { - public EmptyFieldDirectRule() { - super( - "TREE-BASC-0001", - "Empty Field", - "Blank cells not adjacent to an unlinked tree are grass.", - "edu/rpi/legup/images/treetent/noTreesAround.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS - && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; - } + public EmptyFieldDirectRule() { + super( + "TREE-BASC-0001", + "Empty Field", + "Blank cells not adjacent to an unlinked tree are grass.", + "edu/rpi/legup/images/treetent/noTreesAround.png"); + } - if (isForced(finalBoard, finalCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS + && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; } - /** - * Returns a boolean value based on whether the specified cell has adjacent cells (true - no - * adjacent, false - has adjacent) - * - * @param board the TreeTent board - * @param cell the specified TreeTent cell - * @return true - no adjacent, false - has adjacent - */ - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjCells = board.getAdjacent(cell, TreeTentType.TREE); - return adjCells.isEmpty(); + if (isForced(finalBoard, finalCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; - } + /** + * Returns a boolean value based on whether the specified cell has adjacent cells (true - no + * adjacent, false - has adjacent) + * + * @param board the TreeTent board + * @param cell the specified TreeTent cell + * @return true - no adjacent, false - has adjacent + */ + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjCells = board.getAdjacent(cell, TreeTentType.TREE); + return adjCells.isEmpty(); + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java index 0116c0dcd..20b6628f0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java @@ -15,198 +15,192 @@ public class FillinRowCaseRule extends CaseRule { - public FillinRowCaseRule() { - super( - "TREE-CASE-0001", - "Fill In row", - "A row must have the number of tents of its clue.", - "edu/rpi/legup/images/treetent/case_rowcount.png"); + public FillinRowCaseRule() { + super( + "TREE-CASE-0001", + "Fill In row", + "A row must have the number of tents of its clue.", + "edu/rpi/legup/images/treetent/case_rowcount.png"); + } + + /** + * Gets the case board that indicates where this case rule can be applied on the given Board. + * + * @param board the given board + * @return the case board object + */ + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + ArrayList clues = treeTentBoard.getRowClues(); + clues.addAll(treeTentBoard.getColClues()); + for (PuzzleElement element : clues) { + // if ((((TreeTentCell) element).getType() == TreeTentType.CLUE_SOUTH && + // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().y, + // TreeTentType.UNKNOWN, + // true).size() != 0) || + // (((TreeTentCell) element).getType() == TreeTentType.CLUE_EAST && + // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().x, + // TreeTentType.UNKNOWN, + // false).size() != 0)) { + // caseBoard.addPickableElement(element); + // } + caseBoard.addPickableElement(element); } - - /** - * Gets the case board that indicates where this case rule can be applied on the given Board. - * - * @param board the given board - * @return the case board object - */ - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - ArrayList clues = treeTentBoard.getRowClues(); - clues.addAll(treeTentBoard.getColClues()); - for (PuzzleElement element : clues) { - // if ((((TreeTentCell) element).getType() == TreeTentType.CLUE_SOUTH && - // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().y, - // TreeTentType.UNKNOWN, - // true).size() != 0) || - // (((TreeTentCell) element).getType() == TreeTentType.CLUE_EAST && - // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().x, - // TreeTentType.UNKNOWN, - // false).size() != 0)) { - // caseBoard.addPickableElement(element); - // } - caseBoard.addPickableElement(element); - } - return caseBoard; + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + List group; + int tentsLeft; + TreeTentClue clue = ((TreeTentClue) puzzleElement); + int clueIndex = clue.getClueIndex() - 1; + TreeTentBoard tBoard = (TreeTentBoard) board; + if (clue.getType() == TreeTentType.CLUE_SOUTH) { + group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, false); + tentsLeft = + tBoard.getRowClues().get(clueIndex).getData() + - tBoard.getRowCol(clueIndex, TreeTentType.TENT, false).size(); + cases = genCombinations(tBoard, group, tentsLeft, clueIndex, false); + } else { + group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, true); + tentsLeft = + tBoard.getRowClues().get(clueIndex).getData() + - tBoard.getRowCol(clueIndex, TreeTentType.TENT, true).size(); + cases = genCombinations(tBoard, group, tentsLeft, clueIndex, true); } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - List group; - int tentsLeft; - TreeTentClue clue = ((TreeTentClue) puzzleElement); - int clueIndex = clue.getClueIndex() - 1; - TreeTentBoard tBoard = (TreeTentBoard) board; - if (clue.getType() == TreeTentType.CLUE_SOUTH) { - group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, false); - tentsLeft = - tBoard.getRowClues().get(clueIndex).getData() - - tBoard.getRowCol(clueIndex, TreeTentType.TENT, false).size(); - cases = genCombinations(tBoard, group, tentsLeft, clueIndex, false); + // generate every combination (nCr) + // call goodBoard for each generated combination + // alternitive would be to implement collision avoidance while generating instead of after + if (cases.size() > 0) { + return cases; + } + return null; + } + + private ArrayList genCombinations( + TreeTentBoard iBoard, List tiles, int target, Integer index, boolean isRow) { + return genCombRecursive( + iBoard, tiles, tiles, target, 0, new ArrayList(), index, isRow); + } + + private ArrayList genCombRecursive( + TreeTentBoard iBoard, + List original, + List tiles, + int target, + int current, + List selected, + Integer index, + boolean isRow) { + ArrayList b = new ArrayList<>(); + if (target == current) { + TreeTentBoard temp = iBoard.copy(); + for (TreeTentCell c : original) { + if (selected.contains(c)) { + PuzzleElement change = temp.getPuzzleElement(c); + change.setData(TreeTentType.TENT); + temp.addModifiedData(change); } else { - group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, true); - tentsLeft = - tBoard.getRowClues().get(clueIndex).getData() - - tBoard.getRowCol(clueIndex, TreeTentType.TENT, true).size(); - cases = genCombinations(tBoard, group, tentsLeft, clueIndex, true); - } - - // generate every combination (nCr) - // call goodBoard for each generated combination - // alternitive would be to implement collision avoidance while generating instead of after - if (cases.size() > 0) { - return cases; + PuzzleElement change = temp.getPuzzleElement(c); + change.setData(TreeTentType.GRASS); + temp.addModifiedData(change); } - return null; + } + if (goodBoard(temp, index, isRow)) { + b.add(temp); + } + return b; } - - private ArrayList genCombinations( - TreeTentBoard iBoard, - List tiles, - int target, - Integer index, - boolean isRow) { - return genCombRecursive( - iBoard, tiles, tiles, target, 0, new ArrayList(), index, isRow); + for (int i = 0; i < tiles.size(); ++i) { + List sub = tiles.subList(i + 1, tiles.size()); + List next = new ArrayList(selected); + next.add(tiles.get(i)); + b.addAll(genCombRecursive(iBoard, original, sub, target, current + 1, next, index, isRow)); } - - private ArrayList genCombRecursive( - TreeTentBoard iBoard, - List original, - List tiles, - int target, - int current, - List selected, - Integer index, - boolean isRow) { - ArrayList b = new ArrayList<>(); - if (target == current) { - TreeTentBoard temp = iBoard.copy(); - for (TreeTentCell c : original) { - if (selected.contains(c)) { - PuzzleElement change = temp.getPuzzleElement(c); - change.setData(TreeTentType.TENT); - temp.addModifiedData(change); - } else { - PuzzleElement change = temp.getPuzzleElement(c); - change.setData(TreeTentType.GRASS); - temp.addModifiedData(change); - } - } - if (goodBoard(temp, index, isRow)) { - b.add(temp); - } - return b; - } - for (int i = 0; i < tiles.size(); ++i) { - List sub = tiles.subList(i + 1, tiles.size()); - List next = new ArrayList(selected); - next.add(tiles.get(i)); - b.addAll( - genCombRecursive( - iBoard, original, sub, target, current + 1, next, index, isRow)); - } - return b; + return b; + } + + // Effectively runs TouchingTents check on all the added tents to make sure that the proposed + // board is valid. + // Could check more or less in the future depending on how "smart" this case rule should be. + private boolean goodBoard(TreeTentBoard board, Integer index, boolean isRow) { + List tents; + if (isRow) { + tents = board.getRowCol(index, TreeTentType.TENT, true); + } else { + tents = board.getRowCol(index, TreeTentType.TENT, false); } - // Effectively runs TouchingTents check on all the added tents to make sure that the proposed - // board is valid. - // Could check more or less in the future depending on how "smart" this case rule should be. - private boolean goodBoard(TreeTentBoard board, Integer index, boolean isRow) { - List tents; - if (isRow) { - tents = board.getRowCol(index, TreeTentType.TENT, true); - } else { - tents = board.getRowCol(index, TreeTentType.TENT, false); - } - - for (TreeTentCell t : tents) { - List adj = board.getAdjacent(t, TreeTentType.TENT); - List diag = board.getDiagonals(t, TreeTentType.TENT); - if (adj.size() > 0 || diag.size() > 0) { - return false; - } - } - return true; + for (TreeTentCell t : tents) { + List adj = board.getAdjacent(t, TreeTentType.TENT); + List diag = board.getDiagonals(t, TreeTentType.TENT); + if (adj.size() > 0 || diag.size() > 0) { + return false; + } } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; + return true; + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentClue clue = (TreeTentClue) puzzleElement; + + // add all elements of filled row + for (int i = 0; i < treeTentBoard.getWidth(); i++) { + TreeTentCell cell = treeTentBoard.getCell(i, clue.getClueIndex() - 1); + elements.add(board.getPuzzleElement((cell))); } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentClue clue = (TreeTentClue) puzzleElement; - - // add all elements of filled row - for (int i = 0; i < treeTentBoard.getWidth(); i++) { - TreeTentCell cell = treeTentBoard.getCell(i, clue.getClueIndex() - 1); - elements.add(board.getPuzzleElement((cell))); - } - - return elements; - } + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java index 838a3ca24..bb371c52b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java @@ -14,74 +14,73 @@ public class FinishWithGrassDirectRule extends DirectRule { - public FinishWithGrassDirectRule() { - super( - "TREE-BASC-0002", - "Finish with Grass", - "Grass can be added to finish a row or column that has reached its tent limit.", - "edu/rpi/legup/images/treetent/finishGrass.png"); - } + public FinishWithGrassDirectRule() { + super( + "TREE-BASC-0002", + "Finish with Grass", + "Grass can be added to finish a row or column that has reached its tent limit.", + "edu/rpi/legup/images/treetent/finishGrass.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS - && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS + && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; + } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; - } + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; } + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - return tentsRow.size() >= board.getRowClues().get(loc.y).getData() - || tentsCol.size() >= board.getColClues().get(loc.x).getData(); - } + return tentsRow.size() >= board.getRowClues().get(loc.y).getData() + || tentsCol.size() >= board.getColClues().get(loc.x).getData(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java index ae1a72e9d..1d1584353 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java @@ -14,77 +14,75 @@ public class FinishWithTentsDirectRule extends DirectRule { - public FinishWithTentsDirectRule() { - super( - "TREE-BASC-0003", - "Finish with Tents", - "Tents can be added to finish a row or column that has one open spot per required" - + " tent.", - "edu/rpi/legup/images/treetent/finishTent.png"); - } + public FinishWithTentsDirectRule() { + super( + "TREE-BASC-0003", + "Finish with Tents", + "Tents can be added to finish a row or column that has one open spot per required" + + " tent.", + "edu/rpi/legup/images/treetent/finishTent.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN - && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; } + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); - return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() - || unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); - } + return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() + || unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java index 53f7b9831..5d0ae5cd6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java @@ -13,92 +13,89 @@ public class LastCampingSpotDirectRule extends DirectRule { - public LastCampingSpotDirectRule() { - super( - "TREE-BASC-0004", - "Last Camping Spot", - "If an unlinked tree is adjacent to only one blank cell and not adjacent to any" - + " unlinked tents, the blank cell must be a tent.", - "edu/rpi/legup/images/treetent/oneTentPosition.png"); - } + public LastCampingSpotDirectRule() { + super( + "TREE-BASC-0004", + "Last Camping Spot", + "If an unlinked tree is adjacent to only one blank cell and not adjacent to any" + + " unlinked tents, the blank cell must be a tent.", + "edu/rpi/legup/images/treetent/oneTentPosition.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN - && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - if (isForced(finalBoard, finalCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } + if (isForced(finalBoard, finalCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; } + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); - for (TreeTentCell c : adjTrees) { - List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); - List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); - if (unkAroundTree.size() == 0) { - if (tntAroundTree.size() == 1) { - return true; - } else { - for (TreeTentCell t : tntAroundTree) { - if (t == cell) { - continue; - } - List treesAroundTents = - board.getAdjacent(t, TreeTentType.TREE); - if (treesAroundTents.size() == 1) { - return false; - } - } - return true; - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); + for (TreeTentCell c : adjTrees) { + List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); + List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); + if (unkAroundTree.size() == 0) { + if (tntAroundTree.size() == 1) { + return true; + } else { + for (TreeTentCell t : tntAroundTree) { + if (t == cell) { + continue; + } + List treesAroundTents = board.getAdjacent(t, TreeTentType.TREE); + if (treesAroundTents.size() == 1) { + return false; } + } + return true; } - return false; + } } + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java index bd303174a..fec820260 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java @@ -15,165 +15,163 @@ public class LinkTentCaseRule extends CaseRule { - public LinkTentCaseRule() { - super( - "TREE-CASE-0002", - "Links from tent", - "A tent must link to exactly one adjacent tree.", - "edu/rpi/legup/images/treetent/caseLinkTent.png"); - } + public LinkTentCaseRule() { + super( + "TREE-CASE-0002", + "Links from tent", + "A tent must link to exactly one adjacent tree.", + "edu/rpi/legup/images/treetent/caseLinkTent.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.TENT - && !getCases(board, element).isEmpty()) { - Boolean canAdd = true; - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) - || l.getC2() - .getLocation() - .equals(((TreeTentCell) element).getLocation())) { - canAdd = false; - break; - } - } - if (canAdd) { - caseBoard.addPickableElement(element); - } - } + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.TENT + && !getCases(board, element).isEmpty()) { + Boolean canAdd = true; + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) + || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { + canAdd = false; + break; + } + } + if (canAdd) { + caseBoard.addPickableElement(element); } - return caseBoard; + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - TreeTentCell cell = (TreeTentCell) puzzleElement; - List adj = ((TreeTentBoard) board).getAdjacent(cell, TreeTentType.TREE); - List lines = ((TreeTentBoard) board).getLines(); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + TreeTentCell cell = (TreeTentCell) puzzleElement; + List adj = ((TreeTentBoard) board).getAdjacent(cell, TreeTentType.TREE); + List lines = ((TreeTentBoard) board).getLines(); - for (TreeTentCell tree : adj) { - Boolean makeline = true; - for (TreeTentLine l : ((TreeTentBoard) board).getLines()) { - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - makeline = false; - } - } - if (makeline) { - TreeTentBoard temp = ((TreeTentBoard) board).copy(); - TreeTentLine l = - new TreeTentLine( - (TreeTentCell) temp.getPuzzleElement(cell), - (TreeTentCell) temp.getPuzzleElement(tree)); - temp.getLines().add(l); - temp.addModifiedData(l); - cases.add(temp); - } + for (TreeTentCell tree : adj) { + Boolean makeline = true; + for (TreeTentLine l : ((TreeTentBoard) board).getLines()) { + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + makeline = false; } - return cases; + } + if (makeline) { + TreeTentBoard temp = ((TreeTentBoard) board).copy(); + TreeTentLine l = + new TreeTentLine( + (TreeTentCell) temp.getPuzzleElement(cell), + (TreeTentCell) temp.getPuzzleElement(tree)); + temp.getLines().add(l); + temp.addModifiedData(l); + cases.add(temp); + } } + return cases; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } - PuzzleElement mod = modCells.iterator().next(); - TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; - if (line == null) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; - } - TreeTentCell tent = null; - if (line.getC1().getType() == TreeTentType.TENT) { - tent = line.getC1(); - } - if (line.getC2().getType() == TreeTentType.TENT) { - tent = line.getC2(); - } - if (tent == null) { - return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; + } + PuzzleElement mod = modCells.iterator().next(); + TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; + if (line == null) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; + } + TreeTentCell tent = null; + if (line.getC1().getType() == TreeTentType.TENT) { + tent = line.getC1(); + } + if (line.getC2().getType() == TreeTentType.TENT) { + tent = line.getC2(); + } + if (tent == null) { + return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; + } - TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - ArrayList cases = getCases(parentBoard, tent); - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != cases.size()) { - return super.getInvalidUseOfRuleMessage(); + TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + ArrayList cases = getCases(parentBoard, tent); + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != cases.size()) { + return super.getInvalidUseOfRuleMessage(); + } + for (Board caseBoard : cases) { + TreeTentBoard cBoard = (TreeTentBoard) caseBoard; + TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); + boolean hasLine = false; + for (TreeTransition tran : childTransitions) { + TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); + if (tBoard.getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage(); } - for (Board caseBoard : cases) { - TreeTentBoard cBoard = (TreeTentBoard) caseBoard; - TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); - boolean hasLine = false; - for (TreeTransition tran : childTransitions) { - TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); - if (tBoard.getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage(); - } - PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); - if (!(tElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; - } - if (cLine.compare((TreeTentLine) tElement)) { - hasLine = true; - break; - } - } - if (!hasLine) { - return super.getInvalidUseOfRuleMessage(); - } + PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); + if (!(tElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; } - - return null; + if (cLine.compare((TreeTentLine) tElement)) { + hasLine = true; + break; + } + } + if (!hasLine) { + return super.getInvalidUseOfRuleMessage(); + } } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + return null; + } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - return List.of(board.getPuzzleElement(puzzleElement)); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + return List.of(board.getPuzzleElement(puzzleElement)); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java index 03d039898..65bc52723 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java @@ -16,177 +16,174 @@ public class LinkTreeCaseRule extends CaseRule { - public LinkTreeCaseRule() { - super( - "TREE-CASE-0003", - "Links from tree", - "A tree must link to exactly one adjacent tent.", - "edu/rpi/legup/images/treetent/caseLinkTree.png"); - } + public LinkTreeCaseRule() { + super( + "TREE-CASE-0003", + "Links from tree", + "A tree must link to exactly one adjacent tent.", + "edu/rpi/legup/images/treetent/caseLinkTree.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.TREE - && !getCases(treeTentBoard, element).isEmpty()) { + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.TREE + && !getCases(treeTentBoard, element).isEmpty()) { - Boolean canAdd = true; - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) - || l.getC2() - .getLocation() - .equals(((TreeTentCell) element).getLocation())) { - canAdd = false; - break; - } - } - if (canAdd) { - caseBoard.addPickableElement(element); - } - } + Boolean canAdd = true; + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) + || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { + canAdd = false; + break; + } + } + if (canAdd) { + caseBoard.addPickableElement(element); } - return caseBoard; + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - List adjCells = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); - for (TreeTentCell c : adjCells) { - Boolean makeline = true; - for (TreeTentLine l : treeTentBoard.getLines()) { - if (l.getC1().getLocation().equals(c.getLocation()) - || l.getC2().getLocation().equals(c.getLocation())) { - makeline = false; - } - } - if (makeline) { - TreeTentBoard caseBoard = (TreeTentBoard) board.copy(); - TreeTentLine line = new TreeTentLine(cell, c); - caseBoard.getLines().add(line); - caseBoard.addModifiedData(line); - cases.add(caseBoard); - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + List adjCells = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); + for (TreeTentCell c : adjCells) { + Boolean makeline = true; + for (TreeTentLine l : treeTentBoard.getLines()) { + if (l.getC1().getLocation().equals(c.getLocation()) + || l.getC2().getLocation().equals(c.getLocation())) { + makeline = false; } - return cases; + } + if (makeline) { + TreeTentBoard caseBoard = (TreeTentBoard) board.copy(); + TreeTentLine line = new TreeTentLine(cell, c); + caseBoard.getLines().add(line); + caseBoard.addModifiedData(line); + cases.add(caseBoard); + } } + return cases; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } - PuzzleElement mod = modCells.iterator().next(); - TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; - if (line == null) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; - } - TreeTentCell tree = null; - if (line.getC1().getType() == TreeTentType.TREE) { - tree = line.getC1(); - } - if (line.getC2().getType() == TreeTentType.TREE) { - tree = line.getC2(); - } - if (tree == null) { - return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; + } + PuzzleElement mod = modCells.iterator().next(); + TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; + if (line == null) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; + } + TreeTentCell tree = null; + if (line.getC1().getType() == TreeTentType.TREE) { + tree = line.getC1(); + } + if (line.getC2().getType() == TreeTentType.TREE) { + tree = line.getC2(); + } + if (tree == null) { + return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; + } - TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - ArrayList cases = getCases(parentBoard, tree); - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != cases.size()) { - return super.getInvalidUseOfRuleMessage(); + TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + ArrayList cases = getCases(parentBoard, tree); + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != cases.size()) { + return super.getInvalidUseOfRuleMessage(); + } + for (Board caseBoard : cases) { + TreeTentBoard cBoard = (TreeTentBoard) caseBoard; + TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); + boolean hasLine = false; + for (TreeTransition tran : childTransitions) { + TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); + if (tBoard.getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage(); } - for (Board caseBoard : cases) { - TreeTentBoard cBoard = (TreeTentBoard) caseBoard; - TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); - boolean hasLine = false; - for (TreeTransition tran : childTransitions) { - TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); - if (tBoard.getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage(); - } - PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); - if (!(tElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; - } - if (cLine.compare((TreeTentLine) tElement)) { - hasLine = true; - break; - } - } - if (!hasLine) { - return super.getInvalidUseOfRuleMessage(); - } + PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); + if (!(tElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; } - - return null; + if (cLine.compare((TreeTentLine) tElement)) { + hasLine = true; + break; + } + } + if (!hasLine) { + return super.getInvalidUseOfRuleMessage(); + } } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + return null; + } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = - new ArrayList<>(List.of(board.getPuzzleElement(puzzleElement))); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell point = (TreeTentCell) puzzleElement; + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(List.of(board.getPuzzleElement(puzzleElement))); - // get all adjacent cells - Point loc = point.getLocation(); - for (int i = -2; i < 2; i++) { - TreeTentCell cell = treeTentBoard.getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); - if (cell != null) { - elements.add(board.getPuzzleElement(cell)); - } - } + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell point = (TreeTentCell) puzzleElement; - return elements; + // get all adjacent cells + Point loc = point.getLocation(); + for (int i = -2; i < 2; i++) { + TreeTentCell cell = treeTentBoard.getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); + if (cell != null) { + elements.add(board.getPuzzleElement(cell)); + } } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java index 912fa6d20..900c37d92 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java @@ -12,57 +12,57 @@ public class NoTentForTreeContradictionRule extends ContradictionRule { - public NoTentForTreeContradictionRule() { - super( - "TREE-CONT-0001", - "No Tent For Tree", - "Each tree must link to a tent.", - "edu/rpi/legup/images/treetent/contra_NoTentForTree.png"); - } + public NoTentForTreeContradictionRule() { + super( + "TREE-CONT-0001", + "No Tent For Tree", + "Each tree must link to a tent.", + "edu/rpi/legup/images/treetent/contra_NoTentForTree.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TREE) { - return super.getNoContradictionMessage(); - } - int adjTent = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); - int adjUnknown = treeTentBoard.getAdjacent(cell, TreeTentType.UNKNOWN).size(); - if (adjTent == 0 && adjUnknown == 0) { - return null; - } else { - if (adjTent != 0) { - List lines = treeTentBoard.getLines(); - List adjTents = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); - for (TreeTentLine l : lines) { - Iterator i = adjTents.iterator(); - while (i.hasNext()) { - TreeTentCell t = i.next(); - if (t.getLocation().equals(l.getC1().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - if (t.getLocation().equals(l.getC2().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - } - } - if (adjTents.size() == 0 && adjUnknown == 0) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TREE) { + return super.getNoContradictionMessage(); + } + int adjTent = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); + int adjUnknown = treeTentBoard.getAdjacent(cell, TreeTentType.UNKNOWN).size(); + if (adjTent == 0 && adjUnknown == 0) { + return null; + } else { + if (adjTent != 0) { + List lines = treeTentBoard.getLines(); + List adjTents = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); + for (TreeTentLine l : lines) { + Iterator i = adjTents.iterator(); + while (i.hasNext()) { + TreeTentCell t = i.next(); + if (t.getLocation().equals(l.getC1().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); } - return super.getNoContradictionMessage(); + if (t.getLocation().equals(l.getC2().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + } + } + if (adjTents.size() == 0 && adjUnknown == 0) { + return null; } + } + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java index 9bc3fddea..c6cf2fc35 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java @@ -12,51 +12,51 @@ public class NoTreeForTentContradictionRule extends ContradictionRule { - public NoTreeForTentContradictionRule() { - super( - "TREE-CONT-0002", - "No Tree For Tent", - "Each tent must link to a tree.", - "edu/rpi/legup/images/treetent/contra_NoTreeForTent.png"); - } + public NoTreeForTentContradictionRule() { + super( + "TREE-CONT-0002", + "No Tree For Tent", + "Each tent must link to a tree.", + "edu/rpi/legup/images/treetent/contra_NoTreeForTent.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TENT) { - return super.getNoContradictionMessage(); - } - List adjTrees = treeTentBoard.getAdjacent(cell, TreeTentType.TREE); - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - Iterator i = adjTrees.iterator(); - while (i.hasNext()) { - TreeTentCell t = i.next(); - if (t.getLocation().equals(l.getC1().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - if (t.getLocation().equals(l.getC2().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TENT) { + return super.getNoContradictionMessage(); + } + List adjTrees = treeTentBoard.getAdjacent(cell, TreeTentType.TREE); + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + Iterator i = adjTrees.iterator(); + while (i.hasNext()) { + TreeTentCell t = i.next(); + if (t.getLocation().equals(l.getC1().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); } - int adjTree = adjTrees.size(); - if (adjTree == 0) { - return null; - } else { - return super.getNoContradictionMessage(); + if (t.getLocation().equals(l.getC2().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); } + } + } + int adjTree = adjTrees.size(); + if (adjTree == 0) { + return null; + } else { + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java index e800dc416..447bbcde0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java @@ -13,74 +13,73 @@ public class SurroundTentWithGrassDirectRule extends DirectRule { - public SurroundTentWithGrassDirectRule() { - super( - "TREE-BASC-0005", - "Surround Tent with Grass", - "Blank cells adjacent or diagonal to a tent are grass.", - "edu/rpi/legup/images/treetent/aroundTent.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement == null) { - return null; - } - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN - && finalCell.getType() == TreeTentType.GRASS)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; - } + public SurroundTentWithGrassDirectRule() { + super( + "TREE-BASC-0005", + "Surround Tent with Grass", + "Blank cells adjacent or diagonal to a tent are grass.", + "edu/rpi/legup/images/treetent/aroundTent.png"); + } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement == null) { + return null; + } + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN + && finalCell.getType() == TreeTentType.GRASS)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List tents = board.getAdjacent(cell, TreeTentType.TENT); - tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); - return !tents.isEmpty(); + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; } + } + + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List tents = board.getAdjacent(cell, TreeTentType.TENT); + tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); + return !tents.isEmpty(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } - } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java index 8044faa0e..af44359fb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java @@ -14,112 +14,110 @@ public class TentForTreeDirectRule extends DirectRule { - public TentForTreeDirectRule() { - super( - "TREE-BASC-0006", - "Tent for Tree", - "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the" - + " unlinked tree must link to the unlinked tent.", - "edu/rpi/legup/images/treetent/NewTreeLink.png"); - } + public TentForTreeDirectRule() { + super( + "TREE-BASC-0006", + "Tent for Tree", + "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the" + + " unlinked tree must link to the unlinked tent.", + "edu/rpi/legup/images/treetent/NewTreeLink.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE - && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } else { - if (line.getC2().getType() == TreeTentType.TREE - && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } else { - return super.getInvalidUseOfRuleMessage() - + ": This line must connect a tree to a tent."; - } - } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE + && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); + } else { + if (line.getC2().getType() == TreeTentType.TREE + && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } else { + return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; } else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; - } else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; - } else { - return super.getInvalidUseOfRuleMessage() - + ": This tree and tent don't need to be linked."; - } - } + return super.getInvalidUseOfRuleMessage() + + ": This tree and tent don't need to be linked."; } + } } + } - private Integer isForced( - TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTents = board.getAdjacent(tree, TreeTentType.TENT); - adjTents.remove(tent); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTents) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tree.getLocation())) { - return -1; - } - toRemove.add(c); + private Integer isForced( + TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTents = board.getAdjacent(tree, TreeTentType.TENT); + adjTents.remove(tent); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTents) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); - } else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tree.getLocation())) { - return -1; - } - toRemove.add(c); - } - } - } - for (TreeTentCell c : toRemove) { - adjTents.remove(c); - } - toRemove.clear(); - } - if (adjTents.size() == 0) { - return 1; } else { - return 0; + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); + } } + } + for (TreeTentCell c : toRemove) { + adjTents.remove(c); + } + toRemove.clear(); } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + if (adjTents.size() == 0) { + return 1; + } else { + return 0; } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java index 63478f83e..2b6afd5d0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java @@ -13,101 +13,101 @@ public class TentOrGrassCaseRule extends CaseRule { - public TentOrGrassCaseRule() { - super( - "TREE-CASE-0004", - "Tent or Grass", - "Each blank cell is either a tent or grass.", - "edu/rpi/legup/images/treetent/caseTentOrGrass.png"); - } + public TentOrGrassCaseRule() { + super( + "TREE-CASE-0004", + "Tent or Grass", + "Each blank cell is either a tent or grass.", + "edu/rpi/legup/images/treetent/caseTentOrGrass.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.UNKNOWN) { - caseBoard.addPickableElement(element); - } - } - return caseBoard; + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.UNKNOWN) { + caseBoard.addPickableElement(element); + } } + return caseBoard; + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(TreeTentType.TENT); - case1.addModifiedData(data1); - cases.add(case1); - - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(TreeTentType.GRASS); - case2.addModifiedData(data2); - cases.add(case2); - - return cases; - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(TreeTentType.TENT); + case1.addModifiedData(data1); + cases.add(case1); - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; - } + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(TreeTentType.GRASS); + case2.addModifiedData(data2); + cases.add(case2); - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + return cases; + } - TreeTentCell mod1 = (TreeTentCell) case1.getBoard().getModifiedData().iterator().next(); - TreeTentCell mod2 = (TreeTentCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - if (!((mod1.getType() == TreeTentType.TENT && mod2.getType() == TreeTentType.GRASS) - || (mod2.getType() == TreeTentType.TENT && mod1.getType() == TreeTentType.GRASS))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have a tent and a grass cell."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - return null; + TreeTentCell mod1 = (TreeTentCell) case1.getBoard().getModifiedData().iterator().next(); + TreeTentCell mod2 = (TreeTentCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); + if (!((mod1.getType() == TreeTentType.TENT && mod2.getType() == TreeTentType.GRASS) + || (mod2.getType() == TreeTentType.TENT && mod1.getType() == TreeTentType.GRASS))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have a tent and a grass cell."; } + + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java index 7b3f43dbe..220a9aeb0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java @@ -10,39 +10,39 @@ public class TooFewTentsContradictionRule extends ContradictionRule { - public TooFewTentsContradictionRule() { - super( - "TREE-CONT-0003", - "Too Few Tents", - "Rows and columns cannot have fewer tents than their clue.", - "edu/rpi/legup/images/treetent/too_few_tents.png"); - } + public TooFewTentsContradictionRule() { + super( + "TREE-CONT-0003", + "Too Few Tents", + "Rows and columns cannot have fewer tents than their clue.", + "edu/rpi/legup/images/treetent/too_few_tents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); - int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); - int rowUnknowns = treeTentBoard.getRowCol(loc.y, TreeTentType.UNKNOWN, true).size(); - int colUnknowns = treeTentBoard.getRowCol(loc.x, TreeTentType.UNKNOWN, false).size(); + Point loc = cell.getLocation(); + int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); + int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); + int rowUnknowns = treeTentBoard.getRowCol(loc.y, TreeTentType.UNKNOWN, true).size(); + int colUnknowns = treeTentBoard.getRowCol(loc.x, TreeTentType.UNKNOWN, false).size(); - if (rowTents + rowUnknowns < treeTentBoard.getRowClues().get(loc.y).getData() - || colTents + colUnknowns < treeTentBoard.getColClues().get(loc.x).getData()) { - return null; - } else { - return super.getNoContradictionMessage(); - } + if (rowTents + rowUnknowns < treeTentBoard.getRowClues().get(loc.y).getData() + || colTents + colUnknowns < treeTentBoard.getColClues().get(loc.x).getData()) { + return null; + } else { + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java index dcc65feb6..da2a3964d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java @@ -10,37 +10,37 @@ public class TooManyTentsContradictionRule extends ContradictionRule { - public TooManyTentsContradictionRule() { - super( - "TREE-CONT-0004", - "Too Many Tents", - "Rows and columns cannot have more tents than their clue.", - "edu/rpi/legup/images/treetent/too_many_tents.png"); - } + public TooManyTentsContradictionRule() { + super( + "TREE-CONT-0004", + "Too Many Tents", + "Rows and columns cannot have more tents than their clue.", + "edu/rpi/legup/images/treetent/too_many_tents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); - int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); + Point loc = cell.getLocation(); + int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); + int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); - if (rowTents > treeTentBoard.getRowClues().get(loc.y).getData() - || colTents > treeTentBoard.getColClues().get(loc.x).getData()) { - return null; - } else { - return super.getNoContradictionMessage(); - } + if (rowTents > treeTentBoard.getRowClues().get(loc.y).getData() + || colTents > treeTentBoard.getColClues().get(loc.x).getData()) { + return null; + } else { + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java index d9dd36e12..075003130 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java @@ -9,36 +9,36 @@ public class TouchingTentsContradictionRule extends ContradictionRule { - public TouchingTentsContradictionRule() { - super( - "TREE-CONT-0005", - "Touching Tents", - "Tents cannot touch other tents.", - "edu/rpi/legup/images/treetent/contra_adjacentTents.png"); - } + public TouchingTentsContradictionRule() { + super( + "TREE-CONT-0005", + "Touching Tents", + "Tents cannot touch other tents.", + "edu/rpi/legup/images/treetent/contra_adjacentTents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent {@link PuzzleElement} - * @return null if the transition contains a contradiction at the specified - * puzzleElement, otherwise error message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TENT) { - return super.getNoContradictionMessage(); - } - int adjTree = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); - int diagTree = treeTentBoard.getDiagonals(cell, TreeTentType.TENT).size(); - if (adjTree > 0 || diagTree > 0) { - return null; - } else { - return super.getNoContradictionMessage(); - } + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent {@link PuzzleElement} + * @return null if the transition contains a contradiction at the specified + * puzzleElement, otherwise error message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TENT) { + return super.getNoContradictionMessage(); + } + int adjTree = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); + int diagTree = treeTentBoard.getDiagonals(cell, TreeTentType.TENT).size(); + if (adjTree > 0 || diagTree > 0) { + return null; + } else { + return super.getNoContradictionMessage(); } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java index d4360c7f6..1fd15dbc9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java @@ -13,112 +13,110 @@ import java.util.List; public class TreeForTentDirectRule extends DirectRule { - public TreeForTentDirectRule() { - super( - "TREE-BASC-0007", - "Tree for Tent", - "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must" - + " link to the unlinked tree.", - "edu/rpi/legup/images/treetent/NewTentLink.png"); - } + public TreeForTentDirectRule() { + super( + "TREE-BASC-0007", + "Tree for Tent", + "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must" + + " link to the unlinked tree.", + "edu/rpi/legup/images/treetent/NewTentLink.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE - && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } else { - if (line.getC2().getType() == TreeTentType.TREE - && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } else { - return super.getInvalidUseOfRuleMessage() - + ": This line must connect a tree to a tent."; - } - } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE + && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); + } else { + if (line.getC2().getType() == TreeTentType.TREE + && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } else { + return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; } else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; - } else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; - } else { - return super.getInvalidUseOfRuleMessage() - + ": This tree and tent don't need to be linked."; - } - } + return super.getInvalidUseOfRuleMessage() + + ": This tree and tent don't need to be linked."; } + } } + } - private Integer isForced( - TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); - adjTrees.remove(tree); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTrees) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tent.getLocation())) { - return -1; - } - toRemove.add(c); + private Integer isForced( + TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); + adjTrees.remove(tree); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTrees) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); - } else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tent.getLocation())) { - return -1; - } - toRemove.add(c); - } - } - } - for (TreeTentCell c : toRemove) { - adjTrees.remove(c); - } - toRemove.clear(); - } - if (adjTrees.size() == 0) { - return 1; } else { - return 0; + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); + } } + } + for (TreeTentCell c : toRemove) { + adjTrees.remove(c); + } + toRemove.clear(); } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link - * TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; + if (adjTrees.size() == 0) { + return 1; + } else { + return 0; } + } + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/save/ExportFileException.java b/src/main/java/edu/rpi/legup/save/ExportFileException.java index 9def1f392..70eec7868 100644 --- a/src/main/java/edu/rpi/legup/save/ExportFileException.java +++ b/src/main/java/edu/rpi/legup/save/ExportFileException.java @@ -2,7 +2,7 @@ public class ExportFileException extends Exception { - public ExportFileException(String message) { - super("Export File Exception: " + message); - } + public ExportFileException(String message) { + super("Export File Exception: " + message); + } } diff --git a/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java b/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java index 1e24c5762..9207aeaa6 100644 --- a/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java +++ b/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java @@ -2,7 +2,7 @@ public class InvalidFileFormatException extends Exception { - public InvalidFileFormatException(String message) { - super("InvalidFileFormatException: " + message); - } + public InvalidFileFormatException(String message) { + super("InvalidFileFormatException: " + message); + } } diff --git a/src/main/java/edu/rpi/legup/save/SavableBoard.java b/src/main/java/edu/rpi/legup/save/SavableBoard.java index bd246303b..a0d141dea 100644 --- a/src/main/java/edu/rpi/legup/save/SavableBoard.java +++ b/src/main/java/edu/rpi/legup/save/SavableBoard.java @@ -4,13 +4,13 @@ import java.io.InputStream; public class SavableBoard { - private static final String LEGUP_HEADER = "edu.rpi.legup.Legup"; + private static final String LEGUP_HEADER = "edu.rpi.legup.Legup"; - private String filePath; - private InputStream inputStream; + private String filePath; + private InputStream inputStream; - public SavableBoard(String filePath) throws Exception { - this.filePath = filePath; - this.inputStream = new FileInputStream(filePath); - } + public SavableBoard(String filePath) throws Exception { + this.filePath = filePath; + this.inputStream = new FileInputStream(filePath); + } } diff --git a/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java b/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java index 70fbea033..dd56a3a72 100644 --- a/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java +++ b/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java @@ -11,216 +11,206 @@ import javax.swing.*; public class CreatePuzzleDialog extends JDialog { - private HomePanel homePanel; - - private String[] games; - private JComboBox gameBox; - private ActionListener gameBoxListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JComboBox comboBox = (JComboBox) e.getSource(); - String puzzleName = (String) comboBox.getSelectedItem(); - if (puzzleName.equals("ShortTruthTable")) { - textInputScrollPane.setVisible(true); - rowsLabel.setVisible(false); - rows.setVisible(false); - columnsLabel.setVisible(false); - columns.setVisible(false); - } else { - textInputScrollPane.setVisible(false); - rowsLabel.setVisible(true); - rows.setVisible(true); - columnsLabel.setVisible(true); - columns.setVisible(true); - } - } - }; - - private JLabel puzzleLabel; - private JLabel rowsLabel; - private JTextField rows; - private JLabel columnsLabel; - private JTextField columns; - - private JTextArea textArea; - private JScrollPane textInputScrollPane; - - private JButton ok = new JButton("Ok"); - private ActionListener okButtonListener = - new ActionListener() { - /** - * Attempts to open the puzzle editor interface for the given game with the given - * dimensions - * - * @param ae the event to be processed - */ - @Override - public void actionPerformed(ActionEvent ae) { - String game = - Config.convertDisplayNameToClassName( - (String) gameBox.getSelectedItem()); - - // Check if all 3 TextFields are filled - if (game.equals("ShortTruthTable") && textArea.getText().isEmpty()) { - System.out.println("Unfilled fields"); - return; - } - if (!game.equals("ShortTruthTable") - && (game.isEmpty() - || rows.getText().isEmpty() - || columns.getText().isEmpty())) { - System.out.println("Unfilled fields"); - return; - } - - try { - if (game.equals("ShortTruthTable")) { - homePanel.openEditorWithNewPuzzle( - "ShortTruthTable", textArea.getText().split("\n")); - } else { - homePanel.openEditorWithNewPuzzle( - game, - Integer.valueOf(rows.getText()), - Integer.valueOf(columns.getText())); - } - setVisible(false); - } catch (IllegalArgumentException e) { - System.out.println("Failed to open editor with new puzzle"); - e.printStackTrace(System.out); - } - } - }; - - private JButton cancel = new JButton("Cancel"); - private ActionListener cancelButtonListener = - new ActionListener() { - /** - * Dispose the puzzle creation dialog - * - * @param e the event to be processed - */ - @Override - public void actionPerformed(ActionEvent e) { - dispose(); - } - }; - - public CreatePuzzleDialog(JFrame parent, HomePanel homePanel) { - super(parent, true); - - this.homePanel = homePanel; - - initPuzzles(); - - Rectangle b = parent.getBounds(); - - setSize(350, 200); - setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); - - Container c = getContentPane(); - c.setLayout(null); - - puzzleLabel = new JLabel("Puzzle:"); - puzzleLabel.setBounds(10, 30, 70, 25); - gameBox.setBounds(80, 30, 190, 25); - - ok.setBounds(20, 130, 60, 25); - cancel.setBounds(170, 130, 90, 25); - - c.add(puzzleLabel); - c.add(gameBox); - - rows = new JTextField(); - columns = new JTextField(); - - rowsLabel = new JLabel("Rows:"); - columnsLabel = new JLabel("Columns:"); - - rowsLabel.setBounds(30, 70, 60, 25); - columnsLabel.setBounds(30, 95, 60, 25); - - rows.setBounds(100, 70, 60, 25); - columns.setBounds(100, 95, 60, 25); - - c.add(rowsLabel); - c.add(columnsLabel); - - c.add(rows); - c.add(columns); - - textArea = new JTextArea(); - textInputScrollPane = - new JScrollPane( - textArea, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - textInputScrollPane.setBounds(10, 70, this.getWidth() - 30, 50); - c.add(textInputScrollPane); - - c.add(ok); - c.add(cancel); - - if (Objects.equals(this.gameBox.getSelectedItem(), "ShortTruthTable")) { + private HomePanel homePanel; + + private String[] games; + private JComboBox gameBox; + private ActionListener gameBoxListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JComboBox comboBox = (JComboBox) e.getSource(); + String puzzleName = (String) comboBox.getSelectedItem(); + if (puzzleName.equals("ShortTruthTable")) { textInputScrollPane.setVisible(true); rowsLabel.setVisible(false); rows.setVisible(false); columnsLabel.setVisible(false); columns.setVisible(false); - } else { + } else { textInputScrollPane.setVisible(false); rowsLabel.setVisible(true); rows.setVisible(true); columnsLabel.setVisible(true); columns.setVisible(true); + } + } + }; + + private JLabel puzzleLabel; + private JLabel rowsLabel; + private JTextField rows; + private JLabel columnsLabel; + private JTextField columns; + + private JTextArea textArea; + private JScrollPane textInputScrollPane; + + private JButton ok = new JButton("Ok"); + private ActionListener okButtonListener = + new ActionListener() { + /** + * Attempts to open the puzzle editor interface for the given game with the given dimensions + * + * @param ae the event to be processed + */ + @Override + public void actionPerformed(ActionEvent ae) { + String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); + + // Check if all 3 TextFields are filled + if (game.equals("ShortTruthTable") && textArea.getText().isEmpty()) { + System.out.println("Unfilled fields"); + return; + } + if (!game.equals("ShortTruthTable") + && (game.isEmpty() || rows.getText().isEmpty() || columns.getText().isEmpty())) { + System.out.println("Unfilled fields"); + return; + } + + try { + if (game.equals("ShortTruthTable")) { + homePanel.openEditorWithNewPuzzle("ShortTruthTable", textArea.getText().split("\n")); + } else { + homePanel.openEditorWithNewPuzzle( + game, Integer.valueOf(rows.getText()), Integer.valueOf(columns.getText())); + } + setVisible(false); + } catch (IllegalArgumentException e) { + System.out.println("Failed to open editor with new puzzle"); + e.printStackTrace(System.out); + } } + }; + + private JButton cancel = new JButton("Cancel"); + private ActionListener cancelButtonListener = + new ActionListener() { + /** + * Dispose the puzzle creation dialog + * + * @param e the event to be processed + */ + @Override + public void actionPerformed(ActionEvent e) { + dispose(); + } + }; - ActionListener cursorSelectedGame = CursorController.createListener(this, gameBoxListener); - gameBox.addActionListener(cursorSelectedGame); - ActionListener cursorPressedOk = CursorController.createListener(this, okButtonListener); - ok.addActionListener(cursorPressedOk); - ActionListener cursorPressedCancel = - CursorController.createListener(this, cancelButtonListener); - cancel.addActionListener(cursorPressedCancel); - } + public CreatePuzzleDialog(JFrame parent, HomePanel homePanel) { + super(parent, true); + + this.homePanel = homePanel; + + initPuzzles(); + + Rectangle b = parent.getBounds(); + + setSize(350, 200); + setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); + + Container c = getContentPane(); + c.setLayout(null); + + puzzleLabel = new JLabel("Puzzle:"); + puzzleLabel.setBounds(10, 30, 70, 25); + gameBox.setBounds(80, 30, 190, 25); + + ok.setBounds(20, 130, 60, 25); + cancel.setBounds(170, 130, 90, 25); - public void initPuzzles() { - this.games = - GameBoardFacade.getInstance() - .getConfig() - .getFileCreationEnabledPuzzles() - .toArray(new String[0]); - Arrays.sort(this.games); - gameBox = new JComboBox(this.games); + c.add(puzzleLabel); + c.add(gameBox); + + rows = new JTextField(); + columns = new JTextField(); + + rowsLabel = new JLabel("Rows:"); + columnsLabel = new JLabel("Columns:"); + + rowsLabel.setBounds(30, 70, 60, 25); + columnsLabel.setBounds(30, 95, 60, 25); + + rows.setBounds(100, 70, 60, 25); + columns.setBounds(100, 95, 60, 25); + + c.add(rowsLabel); + c.add(columnsLabel); + + c.add(rows); + c.add(columns); + + textArea = new JTextArea(); + textInputScrollPane = + new JScrollPane( + textArea, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + textInputScrollPane.setBounds(10, 70, this.getWidth() - 30, 50); + c.add(textInputScrollPane); + + c.add(ok); + c.add(cancel); + + if (Objects.equals(this.gameBox.getSelectedItem(), "ShortTruthTable")) { + textInputScrollPane.setVisible(true); + rowsLabel.setVisible(false); + rows.setVisible(false); + columnsLabel.setVisible(false); + columns.setVisible(false); + } else { + textInputScrollPane.setVisible(false); + rowsLabel.setVisible(true); + rows.setVisible(true); + columnsLabel.setVisible(true); + columns.setVisible(true); } - // ^This method seems useless and never got covered - public void actionPerformed(ActionEvent e) { - if (e.getSource() == ok) { - String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); - - try { - if (game.equals("ShortTruthTable")) { - this.homePanel.openEditorWithNewPuzzle( - "ShortTruthTable", this.textArea.getText().split("\n")); - } else { - this.homePanel.openEditorWithNewPuzzle( - game, - Integer.valueOf(this.rows.getText()), - Integer.valueOf(this.columns.getText())); - } - this.setVisible(false); - } catch (IllegalArgumentException exception) { - // Don't do anything. This is here to prevent the dialog from closing if the - // dimensions are - // invalid. - } + ActionListener cursorSelectedGame = CursorController.createListener(this, gameBoxListener); + gameBox.addActionListener(cursorSelectedGame); + ActionListener cursorPressedOk = CursorController.createListener(this, okButtonListener); + ok.addActionListener(cursorPressedOk); + ActionListener cursorPressedCancel = + CursorController.createListener(this, cancelButtonListener); + cancel.addActionListener(cursorPressedCancel); + } + + public void initPuzzles() { + this.games = + GameBoardFacade.getInstance() + .getConfig() + .getFileCreationEnabledPuzzles() + .toArray(new String[0]); + Arrays.sort(this.games); + gameBox = new JComboBox(this.games); + } + + // ^This method seems useless and never got covered + public void actionPerformed(ActionEvent e) { + if (e.getSource() == ok) { + String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); + + try { + if (game.equals("ShortTruthTable")) { + this.homePanel.openEditorWithNewPuzzle( + "ShortTruthTable", this.textArea.getText().split("\n")); } else { - if (e.getSource() == cancel) { - this.setVisible(false); - } else { - // Unknown Action Event - } + this.homePanel.openEditorWithNewPuzzle( + game, Integer.valueOf(this.rows.getText()), Integer.valueOf(this.columns.getText())); } + this.setVisible(false); + } catch (IllegalArgumentException exception) { + // Don't do anything. This is here to prevent the dialog from closing if the + // dimensions are + // invalid. + } + } else { + if (e.getSource() == cancel) { + this.setVisible(false); + } else { + // Unknown Action Event + } } + } } diff --git a/src/main/java/edu/rpi/legup/ui/DynamicView.java b/src/main/java/edu/rpi/legup/ui/DynamicView.java index 8d3024c86..1dea7a905 100644 --- a/src/main/java/edu/rpi/legup/ui/DynamicView.java +++ b/src/main/java/edu/rpi/legup/ui/DynamicView.java @@ -18,210 +18,203 @@ public class DynamicView extends JPanel { - private ScrollView scrollView; - private JPanel zoomWrapper; - private JPanel zoomer; - private JLabel status; - - private static final Font ERROR_FONT = MaterialFonts.ITALIC; - private static final Color ERROR_COLOR = MaterialColors.RED_700; - - private static final Font INFO_FONT = MaterialFonts.REGULAR; - private static final Color INFO_COLOR = MaterialColors.GRAY_900; - - public DynamicView(ScrollView scrollView, DynamicViewType type) { - this.scrollView = scrollView; - - setLayout(new BorderLayout()); - - add(scrollView, CENTER); - add(setUpZoomer(type), SOUTH); + private ScrollView scrollView; + private JPanel zoomWrapper; + private JPanel zoomer; + private JLabel status; + + private static final Font ERROR_FONT = MaterialFonts.ITALIC; + private static final Color ERROR_COLOR = MaterialColors.RED_700; + + private static final Font INFO_FONT = MaterialFonts.REGULAR; + private static final Color INFO_COLOR = MaterialColors.GRAY_900; + + public DynamicView(ScrollView scrollView, DynamicViewType type) { + this.scrollView = scrollView; + + setLayout(new BorderLayout()); + + add(scrollView, CENTER); + add(setUpZoomer(type), SOUTH); + } + + /** + * Sets up the zoomer for the given DynamicViewType + * + * @param type The DynamicView that we are setting up the zoomer for (so the zoomer for the board + * view or the zoomer for the proof tree view) + * @return A JPanel containing the zoomer + */ + private JPanel setUpZoomer(DynamicViewType type) { + if (type == DynamicViewType.BOARD) { + return setUpBoardZoomer(); + } else { + if (type == DynamicViewType.PROOF_TREE) { + return setUpProofTreeZoomer(); + } } - /** - * Sets up the zoomer for the given DynamicViewType - * - * @param type The DynamicView that we are setting up the zoomer for (so the zoomer for the - * board view or the zoomer for the proof tree view) - * @return A JPanel containing the zoomer - */ - private JPanel setUpZoomer(DynamicViewType type) { - if (type == DynamicViewType.BOARD) { - return setUpBoardZoomer(); - } else { - if (type == DynamicViewType.PROOF_TREE) { - return setUpProofTreeZoomer(); + // Should never reach here; if you reach here, that's a problem! + return null; + } + + /** + * Sets up the zoomer for the board view + * + * @return A JPanel containing the zoomer + */ + private JPanel setUpBoardZoomer() { + final String label = "Resize Board"; + ActionListener listener = (ActionListener) -> this.fitBoardViewToScreen(); + return this.setUpZoomerHelper(label, listener); + } + + /** + * Sets up the zoomer for the proof tree view + * + * @return A JPanel containing the zoomer + */ + private JPanel setUpProofTreeZoomer() { + final String label = "Resize Proof"; + ActionListener listener = + (ActionListener) -> + GameBoardFacade.getInstance().getLegupUI().getProofEditor().fitTreeViewToScreen(); + return this.setUpZoomerHelper(label, listener); + } + + /** + * Creates the zoomer + * + * @param label A string containing the label to be displayed on the fit to screen button + * @param listener A listener that determines what the resize button will do + * @return A JPanel containing the zoomer + */ + private JPanel setUpZoomerHelper(final String label, ActionListener listener) { + zoomWrapper = new JPanel(); + try { + zoomer = new JPanel(); + + // Create and add the resize button to the zoomer + JButton resizeButton = new JButton(label); + resizeButton.setFocusPainted(false); + resizeButton.setFocusPainted(false); + resizeButton.setEnabled(true); + resizeButton.setSize(100, 50); + resizeButton.addActionListener(listener); + zoomer.add(resizeButton); + + JLabel zoomLabel = new JLabel("100%"); + zoomLabel.setFont(MaterialFonts.getRegularFont(16f)); + + JSlider zoomSlider = new JSlider(25, 400, 100); + + JButton plus = + new JButton( + new ImageIcon( + ImageIO.read( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/imgs/add.png"))))); + plus.setFocusPainted(false); + plus.setFont(MaterialFonts.getRegularFont(10f)); + plus.setPreferredSize(new Dimension(20, 20)); + plus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() + 25)); + + JButton minus = + new JButton( + new ImageIcon( + ImageIO.read( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/imgs/remove.png"))))); + minus.setFocusPainted(false); + minus.setPreferredSize(new Dimension(20, 20)); + minus.setFont(MaterialFonts.getRegularFont(10f)); + minus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() - 25)); + this.scrollView.setWheelScrollingEnabled(true); + + zoomSlider.setPreferredSize(new Dimension(160, 30)); + + scrollView.addComponentListener( + new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + zoomSlider.setValue(scrollView.getZoom()); + zoomLabel.setText(zoomSlider.getValue() + "%"); } - } - - // Should never reach here; if you reach here, that's a problem! - return null; - } - - /** - * Sets up the zoomer for the board view - * - * @return A JPanel containing the zoomer - */ - private JPanel setUpBoardZoomer() { - final String label = "Resize Board"; - ActionListener listener = (ActionListener) -> this.fitBoardViewToScreen(); - return this.setUpZoomerHelper(label, listener); - } - - /** - * Sets up the zoomer for the proof tree view - * - * @return A JPanel containing the zoomer - */ - private JPanel setUpProofTreeZoomer() { - final String label = "Resize Proof"; - ActionListener listener = - (ActionListener) -> - GameBoardFacade.getInstance() - .getLegupUI() - .getProofEditor() - .fitTreeViewToScreen(); - return this.setUpZoomerHelper(label, listener); - } - - /** - * Creates the zoomer - * - * @param label A string containing the label to be displayed on the fit to screen button - * @param listener A listener that determines what the resize button will do - * @return A JPanel containing the zoomer - */ - private JPanel setUpZoomerHelper(final String label, ActionListener listener) { - zoomWrapper = new JPanel(); - try { - zoomer = new JPanel(); - - // Create and add the resize button to the zoomer - JButton resizeButton = new JButton(label); - resizeButton.setFocusPainted(false); - resizeButton.setFocusPainted(false); - resizeButton.setEnabled(true); - resizeButton.setSize(100, 50); - resizeButton.addActionListener(listener); - zoomer.add(resizeButton); - - JLabel zoomLabel = new JLabel("100%"); - zoomLabel.setFont(MaterialFonts.getRegularFont(16f)); - - JSlider zoomSlider = new JSlider(25, 400, 100); - - JButton plus = - new JButton( - new ImageIcon( - ImageIO.read( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource( - "edu/rpi/legup/imgs/add.png"))))); - plus.setFocusPainted(false); - plus.setFont(MaterialFonts.getRegularFont(10f)); - plus.setPreferredSize(new Dimension(20, 20)); - plus.addActionListener( - (ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() + 25)); - - JButton minus = - new JButton( - new ImageIcon( - ImageIO.read( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource( - "edu/rpi/legup/imgs/remove.png"))))); - minus.setFocusPainted(false); - minus.setPreferredSize(new Dimension(20, 20)); - minus.setFont(MaterialFonts.getRegularFont(10f)); - minus.addActionListener( - (ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() - 25)); - this.scrollView.setWheelScrollingEnabled(true); - - zoomSlider.setPreferredSize(new Dimension(160, 30)); - - scrollView.addComponentListener( - new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - zoomSlider.setValue(scrollView.getZoom()); - zoomLabel.setText(zoomSlider.getValue() + "%"); - } - }); - - zoomSlider.addChangeListener( - (ChangeEvent e) -> { - scrollView.zoomTo(zoomSlider.getValue() / 100.0); - zoomLabel.setText(zoomSlider.getValue() + "%"); - }); - - zoomSlider.setMajorTickSpacing(100); - zoomSlider.setMinorTickSpacing(25); - zoomSlider.setPaintTicks(true); - - Hashtable labelTable = new Hashtable<>(); - labelTable.put(0, new JLabel("25%")); - labelTable.put(100, new JLabel("100%")); - labelTable.put(400, new JLabel("400%")); - zoomSlider.setLabelTable(labelTable); - - zoomer.setLayout(new FlowLayout()); - - zoomer.add(minus); - zoomer.add(zoomSlider); - zoomer.add(plus); - zoomer.add(zoomLabel); - - status = new JLabel(); - - zoomWrapper.setLayout(new BorderLayout()); - zoomWrapper.add(status, WEST); - zoomWrapper.add(zoomer, EAST); - } catch (IOException e) { - e.printStackTrace(); - } - return zoomWrapper; - } - - public ScrollView getScrollView() { - return this.scrollView; - } - - public JPanel getZoomWrapper() { - return this.zoomWrapper; - } - - public JPanel getZoomer() { - return this.zoomer; - } - - public void updateInfo(String message) { - status.setFont(INFO_FONT); - status.setForeground(INFO_COLOR); - status.setText(message); - } - - public void updateError(String message) { - status.setFont(ERROR_FONT); - status.setForeground(ERROR_COLOR); - status.setText(message); - } - - public void resetStatus() { - status.setText(""); - } - - public void reset() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - Board board1 = GameBoardFacade.getInstance().getBoard(); - board1.setModifiable(true); - Dimension bi = new Dimension(1200, 900); - this.getScrollView().zoomFit(); - } - - protected void fitBoardViewToScreen() { - scrollView.zoomFit(); + }); + + zoomSlider.addChangeListener( + (ChangeEvent e) -> { + scrollView.zoomTo(zoomSlider.getValue() / 100.0); + zoomLabel.setText(zoomSlider.getValue() + "%"); + }); + + zoomSlider.setMajorTickSpacing(100); + zoomSlider.setMinorTickSpacing(25); + zoomSlider.setPaintTicks(true); + + Hashtable labelTable = new Hashtable<>(); + labelTable.put(0, new JLabel("25%")); + labelTable.put(100, new JLabel("100%")); + labelTable.put(400, new JLabel("400%")); + zoomSlider.setLabelTable(labelTable); + + zoomer.setLayout(new FlowLayout()); + + zoomer.add(minus); + zoomer.add(zoomSlider); + zoomer.add(plus); + zoomer.add(zoomLabel); + + status = new JLabel(); + + zoomWrapper.setLayout(new BorderLayout()); + zoomWrapper.add(status, WEST); + zoomWrapper.add(zoomer, EAST); + } catch (IOException e) { + e.printStackTrace(); } + return zoomWrapper; + } + + public ScrollView getScrollView() { + return this.scrollView; + } + + public JPanel getZoomWrapper() { + return this.zoomWrapper; + } + + public JPanel getZoomer() { + return this.zoomer; + } + + public void updateInfo(String message) { + status.setFont(INFO_FONT); + status.setForeground(INFO_COLOR); + status.setText(message); + } + + public void updateError(String message) { + status.setFont(ERROR_FONT); + status.setForeground(ERROR_COLOR); + status.setText(message); + } + + public void resetStatus() { + status.setText(""); + } + + public void reset() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + Board board1 = GameBoardFacade.getInstance().getBoard(); + board1.setModifiable(true); + Dimension bi = new Dimension(1200, 900); + this.getScrollView().zoomFit(); + } + + protected void fitBoardViewToScreen() { + scrollView.zoomFit(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/DynamicViewType.java b/src/main/java/edu/rpi/legup/ui/DynamicViewType.java index 8c2f285cd..cf345c4e1 100644 --- a/src/main/java/edu/rpi/legup/ui/DynamicViewType.java +++ b/src/main/java/edu/rpi/legup/ui/DynamicViewType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.ui; public enum DynamicViewType { - BOARD, - PROOF_TREE + BOARD, + PROOF_TREE } diff --git a/src/main/java/edu/rpi/legup/ui/HomePanel.java b/src/main/java/edu/rpi/legup/ui/HomePanel.java index 11f51eb0e..120f39eb2 100644 --- a/src/main/java/edu/rpi/legup/ui/HomePanel.java +++ b/src/main/java/edu/rpi/legup/ui/HomePanel.java @@ -26,648 +26,638 @@ import org.xml.sax.helpers.DefaultHandler; public class HomePanel extends LegupPanel { - private static final Logger LOGGER = LogManager.getLogger(HomePanel.class.getName()); - private LegupUI legupUI; - private JFrame frame; - private JButton[] buttons; - private JLabel[] text; - private JMenuBar menuBar; - private JFileChooser folderBrowser; - - private final int buttonSize = 100; - - private ActionListener openProofListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Object[] items = legupUI.getProofEditor().promptPuzzle(); - if (items == null) { - // The attempt to prompt a puzzle ended gracefully (cancel) - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - legupUI.getProofEditor().loadPuzzle(fileName, puzzleFile); - } - }; - - private ActionListener openPuzzleListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Object[] items = legupUI.getPuzzleEditor().promptPuzzle(); - if (items == null) { - // The attempt to prompt a puzzle ended gracefully (cancel) - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - legupUI.getPuzzleEditor().loadPuzzle(fileName, puzzleFile); - } - }; - - public HomePanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.legupUI = legupUI; - this.frame = frame; - setLayout(new GridLayout(1, 2)); - initText(); - initButtons(); + private static final Logger LOGGER = LogManager.getLogger(HomePanel.class.getName()); + private LegupUI legupUI; + private JFrame frame; + private JButton[] buttons; + private JLabel[] text; + private JMenuBar menuBar; + private JFileChooser folderBrowser; + + private final int buttonSize = 100; + + private ActionListener openProofListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Object[] items = legupUI.getProofEditor().promptPuzzle(); + if (items == null) { + // The attempt to prompt a puzzle ended gracefully (cancel) + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + legupUI.getProofEditor().loadPuzzle(fileName, puzzleFile); + } + }; + + private ActionListener openPuzzleListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Object[] items = legupUI.getPuzzleEditor().promptPuzzle(); + if (items == null) { + // The attempt to prompt a puzzle ended gracefully (cancel) + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + legupUI.getPuzzleEditor().loadPuzzle(fileName, puzzleFile); + } + }; + + public HomePanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.legupUI = legupUI; + this.frame = frame; + setLayout(new GridLayout(1, 2)); + initText(); + initButtons(); + } + + public JMenuBar getMenuBar() { + this.menuBar = new JMenuBar(); + JMenu settings = new JMenu("Settings"); + menuBar.add(settings); + JMenuItem preferences = new JMenuItem("Preferences"); + preferences.addActionListener( + a -> { + PreferencesDialog preferencesDialog = new PreferencesDialog(this.frame); + System.out.println("Preferences clicked"); + }); + settings.addSeparator(); + settings.add(preferences); + + JMenuItem contribute = new JMenuItem("Contribute to Legup"); + contribute.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop().browse(URI.create("https://github.com/Bram-Hub/Legup")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + settings.add(contribute); + + return this.menuBar; + } + + @Override + public void makeVisible() { + render(); + frame.setJMenuBar(this.getMenuBar()); + } + + private static ImageIcon resizeButtonIcon(ImageIcon icon, int width, int height) { + Image image = icon.getImage(); + Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); + return new ImageIcon(resizedImage); + } + + private void initButtons() { + this.buttons = new JButton[4]; + + this.buttons[0] = + new JButton("Solve Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } + }; + + URL button0IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/proof_file.png"); + ImageIcon button0Icon = new ImageIcon(button0IconLocation); + this.buttons[0].setFocusPainted(false); + this.buttons[0].setIcon(resizeButtonIcon(button0Icon, this.buttonSize, this.buttonSize)); + this.buttons[0].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[0].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[0].addActionListener(CursorController.createListener(this, openProofListener)); + + this.buttons[1] = + new JButton("Create Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } + }; + URL button1IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/new_puzzle_file.png"); + ImageIcon button1Icon = new ImageIcon(button1IconLocation); + this.buttons[1].setFocusPainted(false); + this.buttons[1].setIcon(resizeButtonIcon(button1Icon, this.buttonSize, this.buttonSize)); + this.buttons[1].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[1].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[1].addActionListener(l -> this.openNewPuzzleDialog()); + + this.buttons[2] = + new JButton("Edit Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } + }; + URL button2IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/puzzle_file.png"); + ImageIcon button2Icon = new ImageIcon(button2IconLocation); + this.buttons[2].setFocusPainted(false); + this.buttons[2].setIcon(resizeButtonIcon(button2Icon, this.buttonSize, this.buttonSize)); + this.buttons[2].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[2].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[2].addActionListener( + CursorController.createListener(this, openPuzzleListener)); // PLACEHOLDER + + for (int i = 0; i < this.buttons.length - 1; i++) { // -1 to avoid the batch grader button + this.buttons[i].setBounds(200, 200, 700, 700); } + this.buttons[3] = new JButton("Batch Grader"); + this.buttons[3].setFocusPainted(false); + this.buttons[3].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[3].setVerticalTextPosition(AbstractButton.BOTTOM); + + this.buttons[3].addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + use_xml_to_check(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + System.out.println("finished checking the folder"); + } + }); + } + + public void checkFolder() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ - public JMenuBar getMenuBar() { - this.menuBar = new JMenuBar(); - JMenu settings = new JMenu("Settings"); - menuBar.add(settings); - JMenuItem preferences = new JMenuItem("Preferences"); - preferences.addActionListener( - a -> { - PreferencesDialog preferencesDialog = new PreferencesDialog(this.frame); - System.out.println("Preferences clicked"); - }); - settings.addSeparator(); - settings.add(preferences); - - JMenuItem contribute = new JMenuItem("Contribute to Legup"); - contribute.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop() - .browse(URI.create("https://github.com/Bram-Hub/Legup")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - settings.add(contribute); - - return this.menuBar; + JFileChooser folderBrowser = new JFileChooser(); + + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + File folder = folderBrowser.getSelectedFile(); + + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name"); + writer.append(","); + writer.append("File Name"); + writer.append(","); + writer.append("Solved?"); + writer.append("\n"); + + for (final File folderEntry : folder.listFiles(File::isDirectory)) { + writer.append(folderEntry.getName()); + writer.append(","); + int count1 = 0; + for (final File fileEntry : folderEntry.listFiles()) { + if (fileEntry.getName().charAt(0) == '.') { + continue; + } + count1++; + if (count1 > 1) { + writer.append(folderEntry.getName()); + writer.append(","); + } + writer.append(fileEntry.getName()); + writer.append(","); + String fileName = folderEntry.getAbsolutePath() + File.separator + fileEntry.getName(); + System.out.println("This is path " + fileName); + File puzzleFile = new File(fileName); + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(1); + legupUI.getProofEditor(); + GameBoardFacade.getInstance().loadPuzzle(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + legupUI.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + if (puzzle.isPuzzleComplete()) { + writer.append("Solved"); + System.out.println(fileEntry.getName() + " solved"); + } else { + writer.append("Not Solved"); + System.out.println(fileEntry.getName() + " not solved"); + } + writer.append("\n"); + } catch (InvalidFileFormatException e) { + LOGGER.error(e.getMessage()); + } + } + } + if (count1 == 0) { + writer.append("No file"); + writer.append("\n"); + } + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + this.buttons[3].addActionListener((ActionEvent e) -> use_xml_to_check()); } - - @Override - public void makeVisible() { - render(); - frame.setJMenuBar(this.getMenuBar()); + } + + /** + * @effect batch grade using .xml parser - go through a collection of files and report their + * "solved?" status + */ + private void use_xml_to_check() { + /* Select a folder, go through each .xml file in the subfolders, look for "isSolved" flag */ + JFileChooser folderBrowser = new JFileChooser(); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + folderBrowser.setSelectedFile(null); + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + File folder = folderBrowser.getSelectedFile(); + + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Solved?,Last Saved\n"); + // Go through student folders, recurse for inner folders + for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + String path = folderEntry.getName(); + // use this helper function to write to the .csv file + recursive_parser(folderEntry, writer, path, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } - - private static ImageIcon resizeButtonIcon(ImageIcon icon, int width, int height) { - Image image = icon.getImage(); - Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); - return new ImageIcon(resizedImage); + if (resultFile.exists()) { + try { + Desktop desktop = Desktop.getDesktop(); + desktop.open(resultFile); + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + } } + JOptionPane.showMessageDialog(null, "Batch grading complete."); + } + + /** + * @param file - the input file + * @return true if it is a .xml file, else return false + */ + public boolean isxmlfile(File file) { + boolean flag = true; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + builder.parse(file); + flag = true; + } catch (Exception e) { + flag = false; + } + return flag; + } + + /** + * @param folder - the input folder + * @param writer - write to .csv + * @param path - the current path + * @param name - student's name (the first subfolders of the main folder) + * @throws IOException + */ + private void recursive_parser(File folder, BufferedWriter writer, String path, String name) + throws IOException { + // Empty folder + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,Ungradeable\n"); + return; + } + // Go through every other file in the folder + try { + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser saxParser = spf.newSAXParser(); + for (final File fileEntry : Objects.requireNonNull(folder.listFiles())) { + if (fileEntry.getName().equals("result.csv")) { + continue; + } + // Recurse if it is a subfolder + if (fileEntry.isDirectory()) { + recursive_parser(fileEntry, writer, path + "/" + fileEntry.getName(), name); + continue; + } + // Set path name + String fName = fileEntry.getName(); + String fPath = fileEntry.getAbsolutePath(); + if (fileEntry.getName().charAt(0) == '.') { + continue; + } + // write data + writer.write(name); + writer.write(","); + writer.write(fName); + writer.write(","); + path = folder.getAbsolutePath() + File.separator + fileEntry.getName(); + System.out.println(path); + if (isxmlfile(fileEntry)) { + saxParser.parse( + path, + new DefaultHandler() { + @Override + public void startDocument() throws SAXException {} - private void initButtons() { - this.buttons = new JButton[4]; + boolean solvedFlagExists = false; + boolean puzzleTypeExists = false; - this.buttons[0] = - new JButton("Solve Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } - }; - - URL button0IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/proof_file.png"); - ImageIcon button0Icon = new ImageIcon(button0IconLocation); - this.buttons[0].setFocusPainted(false); - this.buttons[0].setIcon(resizeButtonIcon(button0Icon, this.buttonSize, this.buttonSize)); - this.buttons[0].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[0].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[0].addActionListener(CursorController.createListener(this, openProofListener)); - - this.buttons[1] = - new JButton("Create Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } - }; - URL button1IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/new_puzzle_file.png"); - ImageIcon button1Icon = new ImageIcon(button1IconLocation); - this.buttons[1].setFocusPainted(false); - this.buttons[1].setIcon(resizeButtonIcon(button1Icon, this.buttonSize, this.buttonSize)); - this.buttons[1].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[1].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[1].addActionListener(l -> this.openNewPuzzleDialog()); - - this.buttons[2] = - new JButton("Edit Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); + @Override + public void startElement( + String uri, String localName, String qName, Attributes attributes) + throws SAXException { + // append file type to the writer + if (qName.equals("puzzle") + && attributes.getQName(0) == "name" + && !puzzleTypeExists) { + try { + writer.write(attributes.getValue(0)); + writer.write(","); + puzzleTypeExists = true; + } catch (IOException e) { + throw new RuntimeException(e); } - }; - URL button2IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/puzzle_file.png"); - ImageIcon button2Icon = new ImageIcon(button2IconLocation); - this.buttons[2].setFocusPainted(false); - this.buttons[2].setIcon(resizeButtonIcon(button2Icon, this.buttonSize, this.buttonSize)); - this.buttons[2].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[2].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[2].addActionListener( - CursorController.createListener(this, openPuzzleListener)); // PLACEHOLDER - - for (int i = 0; i < this.buttons.length - 1; i++) { // -1 to avoid the batch grader button - this.buttons[i].setBounds(200, 200, 700, 700); - } - this.buttons[3] = new JButton("Batch Grader"); - this.buttons[3].setFocusPainted(false); - this.buttons[3].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[3].setVerticalTextPosition(AbstractButton.BOTTOM); - - this.buttons[3].addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { + } + // append the "solved?" status of the proof to the writer + else if (qName.equals("solved") && !solvedFlagExists) { + String isSolved = attributes.getValue(0); + String lastSaved = attributes.getValue(1); + if (isSolved != null) { + if (isSolved.equals("true")) { try { - use_xml_to_check(); - } catch (Exception ex) { - throw new RuntimeException(ex); + writer.write("Solved"); + } catch (IOException e) { + throw new RuntimeException(e); } - System.out.println("finished checking the folder"); - } - }); - } - - public void checkFolder() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - - JFileChooser folderBrowser = new JFileChooser(); - - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - File folder = folderBrowser.getSelectedFile(); - - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name"); - writer.append(","); - writer.append("File Name"); - writer.append(","); - writer.append("Solved?"); - writer.append("\n"); - - for (final File folderEntry : folder.listFiles(File::isDirectory)) { - writer.append(folderEntry.getName()); - writer.append(","); - int count1 = 0; - for (final File fileEntry : folderEntry.listFiles()) { - if (fileEntry.getName().charAt(0) == '.') { - continue; - } - count1++; - if (count1 > 1) { - writer.append(folderEntry.getName()); - writer.append(","); - } - writer.append(fileEntry.getName()); - writer.append(","); - String fileName = - folderEntry.getAbsolutePath() + File.separator + fileEntry.getName(); - System.out.println("This is path " + fileName); - File puzzleFile = new File(fileName); - if (puzzleFile != null && puzzleFile.exists()) { + } else if (isSolved.equals("false")) { + try { + writer.write("Not Solved"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else { try { - legupUI.displayPanel(1); - legupUI.getProofEditor(); - GameBoardFacade.getInstance().loadPuzzle(fileName); - String puzzleName = - GameBoardFacade.getInstance().getPuzzleModule().getName(); - legupUI.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - if (puzzle.isPuzzleComplete()) { - writer.append("Solved"); - System.out.println(fileEntry.getName() + " solved"); - } else { - writer.append("Not Solved"); - System.out.println(fileEntry.getName() + " not solved"); - } - writer.append("\n"); - } catch (InvalidFileFormatException e) { - LOGGER.error(e.getMessage()); + writer.write("Error"); + } catch (IOException e) { + throw new RuntimeException(e); } + } } + // append when is this proof last saved + if (lastSaved != null) { + try { + writer.write(","); + writer.write(lastSaved); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + solvedFlagExists = true; + } } - if (count1 == 0) { - writer.append("No file"); - writer.append("\n"); - } - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); - this.buttons[3].addActionListener((ActionEvent e) -> use_xml_to_check()); - } - } - /** - * @effect batch grade using .xml parser - go through a collection of files and report their - * "solved?" status - */ - private void use_xml_to_check() { - /* Select a folder, go through each .xml file in the subfolders, look for "isSolved" flag */ - JFileChooser folderBrowser = new JFileChooser(); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - folderBrowser.setSelectedFile(null); - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - File folder = folderBrowser.getSelectedFile(); - - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Solved?,Last Saved\n"); - // Go through student folders, recurse for inner folders - for (final File folderEntry : - Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - String path = folderEntry.getName(); - // use this helper function to write to the .csv file - recursive_parser(folderEntry, writer, path, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); - } - if (resultFile.exists()) { - try { - Desktop desktop = Desktop.getDesktop(); - desktop.open(resultFile); - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); - } - } - JOptionPane.showMessageDialog(null, "Batch grading complete."); - } + @Override + public void characters(char[] ch, int start, int length) throws SAXException {} - /** - * @param file - the input file - * @return true if it is a .xml file, else return false - */ - public boolean isxmlfile(File file) { - boolean flag = true; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - builder.parse(file); - flag = true; - } catch (Exception e) { - flag = false; - } - return flag; - } + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException {} - /** - * @param folder - the input folder - * @param writer - write to .csv - * @param path - the current path - * @param name - student's name (the first subfolders of the main folder) - * @throws IOException - */ - private void recursive_parser(File folder, BufferedWriter writer, String path, String name) - throws IOException { - // Empty folder - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,Ungradeable\n"); - return; - } - // Go through every other file in the folder - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxParser = spf.newSAXParser(); - for (final File fileEntry : Objects.requireNonNull(folder.listFiles())) { - if (fileEntry.getName().equals("result.csv")) { - continue; - } - // Recurse if it is a subfolder - if (fileEntry.isDirectory()) { - recursive_parser(fileEntry, writer, path + "/" + fileEntry.getName(), name); - continue; - } - // Set path name - String fName = fileEntry.getName(); - String fPath = fileEntry.getAbsolutePath(); - if (fileEntry.getName().charAt(0) == '.') { - continue; - } - // write data - writer.write(name); - writer.write(","); - writer.write(fName); - writer.write(","); - path = folder.getAbsolutePath() + File.separator + fileEntry.getName(); - System.out.println(path); - if (isxmlfile(fileEntry)) { - saxParser.parse( - path, - new DefaultHandler() { - @Override - public void startDocument() throws SAXException {} - - boolean solvedFlagExists = false; - boolean puzzleTypeExists = false; - - @Override - public void startElement( - String uri, - String localName, - String qName, - Attributes attributes) - throws SAXException { - // append file type to the writer - if (qName.equals("puzzle") - && attributes.getQName(0) == "name" - && !puzzleTypeExists) { - try { - writer.write(attributes.getValue(0)); - writer.write(","); - puzzleTypeExists = true; - } catch (IOException e) { - throw new RuntimeException(e); - } - } - // append the "solved?" status of the proof to the writer - else if (qName.equals("solved") && !solvedFlagExists) { - String isSolved = attributes.getValue(0); - String lastSaved = attributes.getValue(1); - if (isSolved != null) { - if (isSolved.equals("true")) { - try { - writer.write("Solved"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } else if (isSolved.equals("false")) { - try { - writer.write("Not Solved"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } else { - try { - writer.write("Error"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - // append when is this proof last saved - if (lastSaved != null) { - try { - writer.write(","); - writer.write(lastSaved); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - solvedFlagExists = true; - } - } - - @Override - public void characters(char[] ch, int start, int length) - throws SAXException {} - - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException {} - - @Override - public void endDocument() throws SAXException { - if (!puzzleTypeExists) { - try { - writer.write("not a LEGUP puzzle!"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } else if (!solvedFlagExists) { - try { - writer.write("missing flag!"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - }); - } - // If wrong file type, ungradeable - else { - writer.write("not a \".xml\" file!"); + @Override + public void endDocument() throws SAXException { + if (!puzzleTypeExists) { + try { + writer.write("not a LEGUP puzzle!"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else if (!solvedFlagExists) { + try { + writer.write("missing flag!"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } } - writer.write("\n"); - } - } catch (ParserConfigurationException | SAXException | IOException e) { - LOGGER.error(e.getMessage()); + }); + } + // If wrong file type, ungradeable + else { + writer.write("not a \".xml\" file!"); } + writer.write("\n"); + } + } catch (ParserConfigurationException | SAXException | IOException e) { + LOGGER.error(e.getMessage()); } - - private void initText() { - // TODO: add version text after auto-changing version label is implemented. (text[2] = - // version) - this.text = new JLabel[2]; - - JLabel welcome = new JLabel("Welcome to LEGUP"); - welcome.setFont(new Font("Roboto", Font.BOLD, 23)); - welcome.setAlignmentX(Component.CENTER_ALIGNMENT); - - JLabel credits = new JLabel("A project by Dr. Bram van Heuveln"); - credits.setFont(new Font("Roboto", Font.PLAIN, 12)); - credits.setAlignmentX(Component.CENTER_ALIGNMENT); - - JLabel version = new JLabel("Version 5.1.0"); // This should be autochanged in the future - version.setFont(new Font("Roboto", Font.ITALIC, 10)); - version.setAlignmentX(Component.CENTER_ALIGNMENT); - - this.text[0] = welcome; - this.text[1] = credits; + } + + private void initText() { + // TODO: add version text after auto-changing version label is implemented. (text[2] = + // version) + this.text = new JLabel[2]; + + JLabel welcome = new JLabel("Welcome to LEGUP"); + welcome.setFont(new Font("Roboto", Font.BOLD, 23)); + welcome.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel credits = new JLabel("A project by Dr. Bram van Heuveln"); + credits.setFont(new Font("Roboto", Font.PLAIN, 12)); + credits.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel version = new JLabel("Version 5.1.0"); // This should be autochanged in the future + version.setFont(new Font("Roboto", Font.ITALIC, 10)); + version.setAlignmentX(Component.CENTER_ALIGNMENT); + + this.text[0] = welcome; + this.text[1] = credits; + } + + private void render() { + this.removeAll(); + + this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + this.legupUI.setTitle("LEGUP: A Better Way to Learn Formal Logic"); + + JPanel buttons = new JPanel(); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[0]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[1]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[2]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + + JPanel batchGraderButton = new JPanel(); + batchGraderButton.add(this.buttons[3]); + batchGraderButton.setAlignmentX(Component.CENTER_ALIGNMENT); + + this.add(Box.createRigidArea(new Dimension(0, 5))); + for (int i = 0; i < this.text.length; i++) { + this.add(this.text[i]); } + this.add(buttons); + this.add(batchGraderButton); + this.add(Box.createRigidArea(new Dimension(0, 5))); + } + + private void openNewPuzzleDialog() { + CreatePuzzleDialog cpd = new CreatePuzzleDialog(this.frame, this); + cpd.setVisible(true); + } + + private void checkProofAll() { + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ - private void render() { - this.removeAll(); - - this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); - this.legupUI.setTitle("LEGUP: A Better Way to Learn Formal Logic"); - - JPanel buttons = new JPanel(); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[0]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[1]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[2]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - - JPanel batchGraderButton = new JPanel(); - batchGraderButton.add(this.buttons[3]); - batchGraderButton.setAlignmentX(Component.CENTER_ALIGNMENT); - - this.add(Box.createRigidArea(new Dimension(0, 5))); - for (int i = 0; i < this.text.length; i++) { - this.add(this.text[i]); - } - this.add(buttons); - this.add(batchGraderButton); - this.add(Box.createRigidArea(new Dimension(0, 5))); + LegupPreferences preferences = LegupPreferences.getInstance(); + File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); + folderBrowser = new JFileChooser(preferredDirectory); + + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + + File folder = folderBrowser.getSelectedFile(); + + // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); + + // Go through student folders + for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + // Write path + String path = folderEntry.getName(); + traverseDir(folderEntry, writer, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } - - private void openNewPuzzleDialog() { - CreatePuzzleDialog cpd = new CreatePuzzleDialog(this.frame, this); - cpd.setVisible(true); + JOptionPane.showMessageDialog(null, "Batch grading complete."); + } + + private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { + // Recursively traverse directory + GameBoardFacade facade = GameBoardFacade.getInstance(); + // Folder is empty + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,Ungradeable\n"); + return; } - - private void checkProofAll() { - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - - LegupPreferences preferences = LegupPreferences.getInstance(); - File preferredDirectory = - new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); - folderBrowser = new JFileChooser(preferredDirectory); - - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - - File folder = folderBrowser.getSelectedFile(); - - // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); - - // Go through student folders - for (final File folderEntry : - Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - // Write path - String path = folderEntry.getName(); - traverseDir(folderEntry, writer, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); + // Travese directory, recurse if sub-directory found + // If ungradeable, do not leave a score (0, 1) + for (final File f : Objects.requireNonNull(folder.listFiles())) { + // Recurse + if (f.isDirectory()) { + traverseDir(f, writer, path + "/" + f.getName()); + continue; + } + + // Set path name + writer.append(path).append(","); + + // Load puzzle, run checker + // If wrong file type, ungradeable + String fName = f.getName(); + String fPath = f.getAbsolutePath(); + File puzzleFile = new File(fPath); + if (puzzleFile.exists()) { + // Try to load file. If invalid, note in csv + try { + // Load puzzle, run checker + GameBoardFacade.getInstance().loadPuzzle(fPath); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + + // Write data + writer.append(fName).append(","); + writer.append(puzzle.getName()).append(","); + if (puzzle.isPuzzleComplete()) { + writer.append("Solved\n"); + } else { + writer.append("Unsolved\n"); + } + } catch (InvalidFileFormatException e) { + writer.append(fName).append("InvalidFile,Ungradeable\n"); } - JOptionPane.showMessageDialog(null, "Batch grading complete."); + } else { + LOGGER.debug("Failed to run sim"); + } } - - private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { - // Recursively traverse directory - GameBoardFacade facade = GameBoardFacade.getInstance(); - // Folder is empty - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,Ungradeable\n"); - return; - } - // Travese directory, recurse if sub-directory found - // If ungradeable, do not leave a score (0, 1) - for (final File f : Objects.requireNonNull(folder.listFiles())) { - // Recurse - if (f.isDirectory()) { - traverseDir(f, writer, path + "/" + f.getName()); - continue; - } - - // Set path name - writer.append(path).append(","); - - // Load puzzle, run checker - // If wrong file type, ungradeable - String fName = f.getName(); - String fPath = f.getAbsolutePath(); - File puzzleFile = new File(fPath); - if (puzzleFile.exists()) { - // Try to load file. If invalid, note in csv - try { - // Load puzzle, run checker - GameBoardFacade.getInstance().loadPuzzle(fPath); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - - // Write data - writer.append(fName).append(","); - writer.append(puzzle.getName()).append(","); - if (puzzle.isPuzzleComplete()) { - writer.append("Solved\n"); - } else { - writer.append("Unsolved\n"); - } - } catch (InvalidFileFormatException e) { - writer.append(fName).append("InvalidFile,Ungradeable\n"); - } - } else { - LOGGER.debug("Failed to run sim"); - } - } + } + + public void openEditorWithNewPuzzle(String game, int rows, int columns) + throws IllegalArgumentException { + // Validate the dimensions + GameBoardFacade facade = GameBoardFacade.getInstance(); + boolean isValidDimensions = facade.validateDimensions(game, rows, columns); + if (!isValidDimensions) { + JOptionPane.showMessageDialog( + null, + "The dimensions you entered are invalid. Please double check \n" + + "the number of rows and columns and try again.", + "ERROR: Invalid Dimensions", + JOptionPane.ERROR_MESSAGE); + throw new IllegalArgumentException("ERROR: Invalid dimensions given"); } - public void openEditorWithNewPuzzle(String game, int rows, int columns) - throws IllegalArgumentException { - // Validate the dimensions - GameBoardFacade facade = GameBoardFacade.getInstance(); - boolean isValidDimensions = facade.validateDimensions(game, rows, columns); - if (!isValidDimensions) { - JOptionPane.showMessageDialog( - null, - "The dimensions you entered are invalid. Please double check \n" - + "the number of rows and columns and try again.", - "ERROR: Invalid Dimensions", - JOptionPane.ERROR_MESSAGE); - throw new IllegalArgumentException("ERROR: Invalid dimensions given"); - } - - // Set game type on the puzzle editor - this.legupUI.displayPanel(2); - this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, rows, columns); + // Set game type on the puzzle editor + this.legupUI.displayPanel(2); + this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, rows, columns); + } + + /** + * Opens the puzzle editor for the specified game with the given statements + * + * @param game a String containing the name of the game + * @param statements an array of statements + */ + public void openEditorWithNewPuzzle(String game, String[] statements) { + // Validate the text input + GameBoardFacade facade = GameBoardFacade.getInstance(); + boolean isValidTextInput = facade.validateTextInput(game, statements); + if (!isValidTextInput) { + JOptionPane.showMessageDialog( + null, + "The input you entered is invalid. Please double check \n" + + "your statements and try again.", + "ERROR: Invalid Text Input", + JOptionPane.ERROR_MESSAGE); + throw new IllegalArgumentException("ERROR: Invalid dimensions given"); } - /** - * Opens the puzzle editor for the specified game with the given statements - * - * @param game a String containing the name of the game - * @param statements an array of statements - */ - public void openEditorWithNewPuzzle(String game, String[] statements) { - // Validate the text input - GameBoardFacade facade = GameBoardFacade.getInstance(); - boolean isValidTextInput = facade.validateTextInput(game, statements); - if (!isValidTextInput) { - JOptionPane.showMessageDialog( - null, - "The input you entered is invalid. Please double check \n" - + "your statements and try again.", - "ERROR: Invalid Text Input", - JOptionPane.ERROR_MESSAGE); - throw new IllegalArgumentException("ERROR: Invalid dimensions given"); - } - - // Set game type on the puzzle editor - this.legupUI.displayPanel(2); - this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, statements); - } + // Set game type on the puzzle editor + this.legupUI.displayPanel(2); + this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, statements); + } } diff --git a/src/main/java/edu/rpi/legup/ui/LegupPanel.java b/src/main/java/edu/rpi/legup/ui/LegupPanel.java index d16167b3d..d671e1c4d 100644 --- a/src/main/java/edu/rpi/legup/ui/LegupPanel.java +++ b/src/main/java/edu/rpi/legup/ui/LegupPanel.java @@ -3,8 +3,8 @@ import javax.swing.*; public abstract class LegupPanel extends JPanel { - /** Alerts panel that it will be going visible now */ - protected final int TOOLBAR_ICON_SCALE = 40; + /** Alerts panel that it will be going visible now */ + protected final int TOOLBAR_ICON_SCALE = 40; - public abstract void makeVisible(); + public abstract void makeVisible(); } diff --git a/src/main/java/edu/rpi/legup/ui/LegupUI.java b/src/main/java/edu/rpi/legup/ui/LegupUI.java index 33ae11d0c..030a1df6b 100644 --- a/src/main/java/edu/rpi/legup/ui/LegupUI.java +++ b/src/main/java/edu/rpi/legup/ui/LegupUI.java @@ -15,191 +15,189 @@ import org.apache.logging.log4j.Logger; public class LegupUI extends JFrame implements WindowListener { - private static final Logger LOGGER = LogManager.getLogger(LegupUI.class.getName()); - - protected FileDialog fileDialog; - protected JPanel window; - protected LegupPanel[] panels; - - /** - * Identifies operating system - * - * @return operating system, either mac or win - */ - public static String getOS() { - String os = System.getProperty("os.name").toLowerCase(); - if (os.contains("mac")) { - os = "mac"; - } else { - os = "win"; - } - return os; - } - - /** LegupUI Constructor - creates a new LegupUI to setup the menu and toolbar */ - public LegupUI() { - setTitle("LEGUP"); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - LegupPreferences prefs = LegupPreferences.getInstance(); - - try { - if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { - UIManager.setLookAndFeel(new FlatDarkLaf()); - } else { - UIManager.setLookAndFeel(new FlatLightLaf()); - } - } catch (UnsupportedLookAndFeelException e) { - System.err.println("Not supported ui look and feel"); - } - - fileDialog = new FileDialog(this); - - initPanels(); - displayPanel(0); - - setIconImage( - new ImageIcon( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource( - "edu/rpi/legup/images/Legup/Direct" - + " Rules.gif"))) - .getImage()); - - if (LegupPreferences.getInstance() - .getUserPref(LegupPreferences.START_FULL_SCREEN) - .equals(Boolean.toString(true))) { - setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); - } - - this.addWindowListener(this); - addKeyListener( - new KeyAdapter() { - /** - * Invoked when a key has been typed. This event occurs when a key press is - * followed by a key release. - * - * @param e - */ - @Override - public void keyTyped(KeyEvent e) { - System.err.println(e.getKeyChar()); - super.keyTyped(e); - } - }); - setMinimumSize(getPreferredSize()); - setVisible(true); - } - - private void initPanels() { - window = new JPanel(); - window.setLayout(new BorderLayout()); - add(window); - panels = new LegupPanel[3]; - - panels[0] = new HomePanel(this.fileDialog, this, this); - panels[1] = new ProofEditorPanel(this.fileDialog, this, this); - panels[2] = new PuzzleEditorPanel(this.fileDialog, this, this); - } - - protected void displayPanel(int option) { - if (option > panels.length || option < 0) { - throw new InvalidParameterException("Invalid option"); - } - this.window.removeAll(); - panels[option].makeVisible(); - this.window.add(panels[option]); - pack(); - setLocationRelativeTo(null); - revalidate(); - repaint(); - } - - public ProofEditorPanel getProofEditor() { - return (ProofEditorPanel) panels[1]; - } - - public PuzzleEditorPanel getPuzzleEditor() { - return (PuzzleEditorPanel) panels[2]; - } - - public void repaintTree() { - getProofEditor().repaintTree(); - } - - private void directions() { - JOptionPane.showMessageDialog( - null, - "For every move you make, you must provide a rules for it (located in the Rules" - + " panel).\n" - + "While working on the edu.rpi.legup.puzzle, you may click on the \"Check\"" - + " button to test your proof for correctness.", - "Directions", - JOptionPane.PLAIN_MESSAGE); - } - - public void showStatus(String status, boolean error) { - showStatus(status, error, 1); - } - - public void errorEncountered(String error) { - JOptionPane.showMessageDialog(null, error); - } - - public void showStatus(String status, boolean error, int timer) { - // TODO: implement - } - - // ask to edu.rpi.legup.save current proof - public boolean noquit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - @Override - public void windowOpened(WindowEvent e) {} - - public void windowClosing(WindowEvent e) { - if (GameBoardFacade.getInstance().getHistory().getIndex() > -1) { - if (noquit("Exiting LEGUP?")) { - this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - } else { - this.setDefaultCloseOperation(EXIT_ON_CLOSE); - } - } else { - this.setDefaultCloseOperation(EXIT_ON_CLOSE); - } - } - - public void windowClosed(WindowEvent e) { - System.exit(0); - } - - public void windowIconified(WindowEvent e) {} - - public void windowDeiconified(WindowEvent e) {} - - public void windowActivated(WindowEvent e) {} - - public void windowDeactivated(WindowEvent e) {} - - public BoardView getBoardView() { - return getProofEditor().getBoardView(); - } - - public BoardView getEditorBoardView() { - return getPuzzleEditor().getBoardView(); - } - - public DynamicView getDynamicBoardView() { - return getProofEditor().getDynamicBoardView(); - } - - public DynamicView getEditorDynamicBoardView() { - return getPuzzleEditor().getDynamicBoardView(); - } - - public TreePanel getTreePanel() { - return getProofEditor().getTreePanel(); - } + private static final Logger LOGGER = LogManager.getLogger(LegupUI.class.getName()); + + protected FileDialog fileDialog; + protected JPanel window; + protected LegupPanel[] panels; + + /** + * Identifies operating system + * + * @return operating system, either mac or win + */ + public static String getOS() { + String os = System.getProperty("os.name").toLowerCase(); + if (os.contains("mac")) { + os = "mac"; + } else { + os = "win"; + } + return os; + } + + /** LegupUI Constructor - creates a new LegupUI to setup the menu and toolbar */ + public LegupUI() { + setTitle("LEGUP"); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + LegupPreferences prefs = LegupPreferences.getInstance(); + + try { + if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { + UIManager.setLookAndFeel(new FlatDarkLaf()); + } else { + UIManager.setLookAndFeel(new FlatLightLaf()); + } + } catch (UnsupportedLookAndFeelException e) { + System.err.println("Not supported ui look and feel"); + } + + fileDialog = new FileDialog(this); + + initPanels(); + displayPanel(0); + + setIconImage( + new ImageIcon( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct" + " Rules.gif"))) + .getImage()); + + if (LegupPreferences.getInstance() + .getUserPref(LegupPreferences.START_FULL_SCREEN) + .equals(Boolean.toString(true))) { + setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); + } + + this.addWindowListener(this); + addKeyListener( + new KeyAdapter() { + /** + * Invoked when a key has been typed. This event occurs when a key press is followed by a + * key release. + * + * @param e + */ + @Override + public void keyTyped(KeyEvent e) { + System.err.println(e.getKeyChar()); + super.keyTyped(e); + } + }); + setMinimumSize(getPreferredSize()); + setVisible(true); + } + + private void initPanels() { + window = new JPanel(); + window.setLayout(new BorderLayout()); + add(window); + panels = new LegupPanel[3]; + + panels[0] = new HomePanel(this.fileDialog, this, this); + panels[1] = new ProofEditorPanel(this.fileDialog, this, this); + panels[2] = new PuzzleEditorPanel(this.fileDialog, this, this); + } + + protected void displayPanel(int option) { + if (option > panels.length || option < 0) { + throw new InvalidParameterException("Invalid option"); + } + this.window.removeAll(); + panels[option].makeVisible(); + this.window.add(panels[option]); + pack(); + setLocationRelativeTo(null); + revalidate(); + repaint(); + } + + public ProofEditorPanel getProofEditor() { + return (ProofEditorPanel) panels[1]; + } + + public PuzzleEditorPanel getPuzzleEditor() { + return (PuzzleEditorPanel) panels[2]; + } + + public void repaintTree() { + getProofEditor().repaintTree(); + } + + private void directions() { + JOptionPane.showMessageDialog( + null, + "For every move you make, you must provide a rules for it (located in the Rules" + + " panel).\n" + + "While working on the edu.rpi.legup.puzzle, you may click on the \"Check\"" + + " button to test your proof for correctness.", + "Directions", + JOptionPane.PLAIN_MESSAGE); + } + + public void showStatus(String status, boolean error) { + showStatus(status, error, 1); + } + + public void errorEncountered(String error) { + JOptionPane.showMessageDialog(null, error); + } + + public void showStatus(String status, boolean error, int timer) { + // TODO: implement + } + + // ask to edu.rpi.legup.save current proof + public boolean noquit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + @Override + public void windowOpened(WindowEvent e) {} + + public void windowClosing(WindowEvent e) { + if (GameBoardFacade.getInstance().getHistory().getIndex() > -1) { + if (noquit("Exiting LEGUP?")) { + this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } else { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + } else { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + } + + public void windowClosed(WindowEvent e) { + System.exit(0); + } + + public void windowIconified(WindowEvent e) {} + + public void windowDeiconified(WindowEvent e) {} + + public void windowActivated(WindowEvent e) {} + + public void windowDeactivated(WindowEvent e) {} + + public BoardView getBoardView() { + return getProofEditor().getBoardView(); + } + + public BoardView getEditorBoardView() { + return getPuzzleEditor().getBoardView(); + } + + public DynamicView getDynamicBoardView() { + return getProofEditor().getDynamicBoardView(); + } + + public DynamicView getEditorDynamicBoardView() { + return getPuzzleEditor().getDynamicBoardView(); + } + + public TreePanel getTreePanel() { + return getProofEditor().getTreePanel(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java b/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java index 01d696f19..43cb35584 100644 --- a/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java +++ b/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java @@ -5,5 +5,5 @@ public class ManualPuzzleCreatorDialog extends JDialog { - public ManualPuzzleCreatorDialog() {} + public ManualPuzzleCreatorDialog() {} } diff --git a/src/main/java/edu/rpi/legup/ui/PickGameDialog.java b/src/main/java/edu/rpi/legup/ui/PickGameDialog.java index f703ffcbc..acdc99bee 100644 --- a/src/main/java/edu/rpi/legup/ui/PickGameDialog.java +++ b/src/main/java/edu/rpi/legup/ui/PickGameDialog.java @@ -16,156 +16,156 @@ import javax.swing.JTextField; public class PickGameDialog extends JDialog implements ActionListener { - JLabel gameLabel = new JLabel("Game:"); - String[] games; - JComboBox gameBox; - - JLabel puzzleLabel = new JLabel("Puzzle:"); - String[][] puzzles; - String puzzle; - - JTextField puzzleBox; - - JButton puzzleButton = new JButton("..."); - JFileChooser puzzleChooser = new JFileChooser(); - - JButton ok = new JButton("Ok"); - JButton cancel = new JButton("Cancel"); - - JCheckBox autotreeCheckBox = new JCheckBox("Auto-tree"); - JCheckBox showtreeCheckBox = new JCheckBox("Show tree"); - JCheckBox autojustifyCheckBox = new JCheckBox("Auto-justify"); - - public boolean okPressed = false; - private boolean pickBoth; - - /** - * Initialize the dialog - * - * @param parent the parent JFrame - * @param pickBothAtOnce if true they can pick a game type and a specific edu.rpi.legup.puzzle, - * if false they can only pick a game type - */ - public PickGameDialog(JFrame parent, boolean pickBothAtOnce) { - super(parent, true); - - pickBoth = pickBothAtOnce; - initPuzzles(); - - Rectangle b = parent.getBounds(); - - setSize(350, 200); - setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); - setTitle("Select Puzzle"); - - // listeners - gameBox.addActionListener(this); - ok.addActionListener(this); - cancel.addActionListener(this); - - // add components - Container c = getContentPane(); - c.setLayout(null); - - if (pickBoth) { - gameLabel.setBounds(10, 10, 70, 25); - gameBox.setBounds(80, 10, 190, 25); - } else { - gameLabel.setBounds(10, 30, 70, 25); - gameBox.setBounds(80, 30, 190, 25); - } - - puzzleLabel.setBounds(10, 40, 70, 25); - - puzzleBox.setBounds(80, 40, 190, 25); - puzzleButton.setBounds(270, 40, 25, 25); - - ok.setBounds(20, 130, 60, 25); - cancel.setBounds(170, 130, 90, 25); - - c.add(gameLabel); - c.add(gameBox); + JLabel gameLabel = new JLabel("Game:"); + String[] games; + JComboBox gameBox; + + JLabel puzzleLabel = new JLabel("Puzzle:"); + String[][] puzzles; + String puzzle; + + JTextField puzzleBox; + + JButton puzzleButton = new JButton("..."); + JFileChooser puzzleChooser = new JFileChooser(); + + JButton ok = new JButton("Ok"); + JButton cancel = new JButton("Cancel"); + + JCheckBox autotreeCheckBox = new JCheckBox("Auto-tree"); + JCheckBox showtreeCheckBox = new JCheckBox("Show tree"); + JCheckBox autojustifyCheckBox = new JCheckBox("Auto-justify"); + + public boolean okPressed = false; + private boolean pickBoth; + + /** + * Initialize the dialog + * + * @param parent the parent JFrame + * @param pickBothAtOnce if true they can pick a game type and a specific edu.rpi.legup.puzzle, if + * false they can only pick a game type + */ + public PickGameDialog(JFrame parent, boolean pickBothAtOnce) { + super(parent, true); + + pickBoth = pickBothAtOnce; + initPuzzles(); + + Rectangle b = parent.getBounds(); + + setSize(350, 200); + setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); + setTitle("Select Puzzle"); + + // listeners + gameBox.addActionListener(this); + ok.addActionListener(this); + cancel.addActionListener(this); + + // add components + Container c = getContentPane(); + c.setLayout(null); + + if (pickBoth) { + gameLabel.setBounds(10, 10, 70, 25); + gameBox.setBounds(80, 10, 190, 25); + } else { + gameLabel.setBounds(10, 30, 70, 25); + gameBox.setBounds(80, 30, 190, 25); + } - if (pickBoth) { - c.add(puzzleLabel); - c.add(puzzleBox); - } + puzzleLabel.setBounds(10, 40, 70, 25); - c.add(puzzleButton); - puzzleButton.addActionListener(this); + puzzleBox.setBounds(80, 40, 190, 25); + puzzleButton.setBounds(270, 40, 25, 25); - c.add(ok); - c.add(cancel); + ok.setBounds(20, 130, 60, 25); + cancel.setBounds(170, 130, 90, 25); - autotreeCheckBox.setBounds(20, 70, 100, 25); - showtreeCheckBox.setBounds(20, 90, 100, 25); - autojustifyCheckBox.setBounds(20, 110, 100, 25); + c.add(gameLabel); + c.add(gameBox); - c.add(autotreeCheckBox); - c.add(showtreeCheckBox); - c.add(autojustifyCheckBox); + if (pickBoth) { + c.add(puzzleLabel); + c.add(puzzleBox); } - public void initPuzzles() { - Object[] o = GameBoardFacade.getInstance().getConfig().getPuzzleClassNames().toArray(); + c.add(puzzleButton); + puzzleButton.addActionListener(this); - games = new String[o.length]; + c.add(ok); + c.add(cancel); - for (int x = 0; x < o.length; ++x) { - games[x] = (String) o[x]; - } + autotreeCheckBox.setBounds(20, 70, 100, 25); + showtreeCheckBox.setBounds(20, 90, 100, 25); + autojustifyCheckBox.setBounds(20, 110, 100, 25); - puzzles = new String[games.length][]; - puzzleBox = new JTextField(); - for (int x = 0; x < games.length; ++x) { - puzzles[x] = new String[o.length]; + c.add(autotreeCheckBox); + c.add(showtreeCheckBox); + c.add(autojustifyCheckBox); + } - for (int y = 0; y < o.length; ++y) { - puzzles[x][y] = (String) o[y]; - } - } + public void initPuzzles() { + Object[] o = GameBoardFacade.getInstance().getConfig().getPuzzleClassNames().toArray(); - gameBox = new JComboBox(games); - } + games = new String[o.length]; - public String getPuzzle() { - return puzzleBox.getText(); + for (int x = 0; x < o.length; ++x) { + games[x] = (String) o[x]; } - public String getGame() { - return (String) gameBox.getSelectedItem(); + puzzles = new String[games.length][]; + puzzleBox = new JTextField(); + for (int x = 0; x < games.length; ++x) { + puzzles[x] = new String[o.length]; + + for (int y = 0; y < o.length; ++y) { + puzzles[x][y] = (String) o[y]; + } } - public void actionPerformed(ActionEvent e) { - if (e.getSource() == gameBox) { - int index = gameBox.getSelectedIndex(); + gameBox = new JComboBox(games); + } + + public String getPuzzle() { + return puzzleBox.getText(); + } + + public String getGame() { + return (String) gameBox.getSelectedItem(); + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == gameBox) { + int index = gameBox.getSelectedIndex(); + } else { + if (e.getSource() == ok) { + okPressed = true; + setVisible(false); + } else { + if (e.getSource() == cancel) { + okPressed = false; + setVisible(false); } else { - if (e.getSource() == ok) { - okPressed = true; - setVisible(false); + if (e.getSource() == puzzleButton) { + File f = + new File( + "puzzlefiles" + + File.separator + + gameBox.getSelectedItem().toString().toLowerCase() + + File.separator); + if (f.exists() && f.isDirectory()) { + puzzleChooser = new JFileChooser(f); } else { - if (e.getSource() == cancel) { - okPressed = false; - setVisible(false); - } else { - if (e.getSource() == puzzleButton) { - File f = - new File( - "puzzlefiles" - + File.separator - + gameBox.getSelectedItem().toString().toLowerCase() - + File.separator); - if (f.exists() && f.isDirectory()) { - puzzleChooser = new JFileChooser(f); - } else { - puzzleChooser = new JFileChooser(); - } - if (puzzleChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - puzzleBox.setText(puzzleChooser.getSelectedFile().getAbsolutePath()); - } - } - } + puzzleChooser = new JFileChooser(); + } + if (puzzleChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + puzzleBox.setText(puzzleChooser.getSelectedFile().getAbsolutePath()); } + } } + } } + } } diff --git a/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java b/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java index 475f4bb68..68adb2bae 100644 --- a/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java +++ b/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java @@ -19,419 +19,412 @@ public class PreferencesDialog extends JDialog { - private RuleFrame rulesFrame; - - private static final Logger LOGGER = Logger.getLogger(PreferencesDialog.class.getName()); - - private JCheckBox fullScreen, - autoUpdate, - darkMode, - showMistakes, - showAnnotations, - allowDefault, - generateCases, - immFeedback, - colorBlind; - - private JTextField workDirectory; - - private static Image folderIcon; - - static { - try { - folderIcon = - ImageIO.read( - PreferencesDialog.class.getResource("/edu/rpi/legup/imgs/folder.png")); - } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Unable to locate icons"); - } + private RuleFrame rulesFrame; + + private static final Logger LOGGER = Logger.getLogger(PreferencesDialog.class.getName()); + + private JCheckBox fullScreen, + autoUpdate, + darkMode, + showMistakes, + showAnnotations, + allowDefault, + generateCases, + immFeedback, + colorBlind; + + private JTextField workDirectory; + + private static Image folderIcon; + + static { + try { + folderIcon = + ImageIO.read(PreferencesDialog.class.getResource("/edu/rpi/legup/imgs/folder.png")); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Unable to locate icons"); } - - public static PreferencesDialog CreateDialogForProofEditor(Frame frame, RuleFrame rules) { - PreferencesDialog p = new PreferencesDialog(frame); - p.rulesFrame = rules; - return p; - } - - public PreferencesDialog(Frame frame) { - super(frame); - - setTitle("Preferences"); - - JPanel mainPanel = new JPanel(); - mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - mainPanel.setLayout(new BorderLayout()); - - mainPanel.add(createGeneralTab()); - - JPanel bottomPanel = new JPanel(); - bottomPanel.setBorder(null); - bottomPanel.setLayout(new BorderLayout()); - - JToolBar toolbar = new JToolBar(); - toolbar.setBorder(null); - JButton okButton = new JButton("Ok"); - okButton.addActionListener( - l -> { - applyPreferences(); - this.setVisible(false); - this.dispose(); - }); - toolbar.add(okButton); - JButton cancelButton = new JButton("Cancel"); - cancelButton.addActionListener( - l -> { - this.setVisible(false); - this.dispose(); - }); - toolbar.add(cancelButton); - JButton applyButton = new JButton("Apply"); - applyButton.addActionListener( - l -> { - applyPreferences(); - }); - toolbar.add(applyButton); - bottomPanel.add(toolbar, BorderLayout.EAST); - - mainPanel.add(bottomPanel, BorderLayout.SOUTH); - - setContentPane(mainPanel); - - setSize(600, 400); - setLocationRelativeTo(frame); - setVisible(true); - } - - private void toggleDarkMode(LegupPreferences prefs) { - try { - if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { - UIManager.setLookAndFeel(new FlatDarkLaf()); - } else { - UIManager.setLookAndFeel(new FlatLightLaf()); - } - com.formdev.flatlaf.FlatLaf.updateUI(); - } catch (UnsupportedLookAndFeelException e) { - System.err.println("Not supported ui look and feel"); - } + } + + public static PreferencesDialog CreateDialogForProofEditor(Frame frame, RuleFrame rules) { + PreferencesDialog p = new PreferencesDialog(frame); + p.rulesFrame = rules; + return p; + } + + public PreferencesDialog(Frame frame) { + super(frame); + + setTitle("Preferences"); + + JPanel mainPanel = new JPanel(); + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + mainPanel.setLayout(new BorderLayout()); + + mainPanel.add(createGeneralTab()); + + JPanel bottomPanel = new JPanel(); + bottomPanel.setBorder(null); + bottomPanel.setLayout(new BorderLayout()); + + JToolBar toolbar = new JToolBar(); + toolbar.setBorder(null); + JButton okButton = new JButton("Ok"); + okButton.addActionListener( + l -> { + applyPreferences(); + this.setVisible(false); + this.dispose(); + }); + toolbar.add(okButton); + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener( + l -> { + this.setVisible(false); + this.dispose(); + }); + toolbar.add(cancelButton); + JButton applyButton = new JButton("Apply"); + applyButton.addActionListener( + l -> { + applyPreferences(); + }); + toolbar.add(applyButton); + bottomPanel.add(toolbar, BorderLayout.EAST); + + mainPanel.add(bottomPanel, BorderLayout.SOUTH); + + setContentPane(mainPanel); + + setSize(600, 400); + setLocationRelativeTo(frame); + setVisible(true); + } + + private void toggleDarkMode(LegupPreferences prefs) { + try { + if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { + UIManager.setLookAndFeel(new FlatDarkLaf()); + } else { + UIManager.setLookAndFeel(new FlatLightLaf()); + } + com.formdev.flatlaf.FlatLaf.updateUI(); + } catch (UnsupportedLookAndFeelException e) { + System.err.println("Not supported ui look and feel"); } - - private JScrollPane createGeneralTab() { - LegupPreferences prefs = LegupPreferences.getInstance(); - JScrollPane scrollPane = new JScrollPane(); - JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); - - contentPane.add(createLeftLabel("General Preferences")); - contentPane.add(createLineSeparator()); - - JPanel workRow = new JPanel(); - workRow.setLayout(new BorderLayout()); - JLabel workDirLabel = new JLabel("Work Directory"); - workDirLabel.setToolTipText("This is where the open and save dialogs will open to."); - workRow.add(workDirLabel, BorderLayout.WEST); - workDirectory = new JTextField(prefs.getUserPref(LegupPreferences.WORK_DIRECTORY)); - workRow.add(workDirectory, BorderLayout.CENTER); - JButton openDir = new JButton(new ImageIcon(folderIcon)); - openDir.addActionListener( - a -> { - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(workDirectory.getText())); - chooser.setDialogTitle("Choose work directory"); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setAcceptAllFileFilterUsed(false); - chooser.setVisible(true); - - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - File newFile = chooser.getSelectedFile(); - workDirectory.setText(newFile.toString()); - } - }); - workRow.add(openDir, BorderLayout.EAST); - workRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, workRow.getPreferredSize().height)); - contentPane.add(workRow); - - fullScreen = - new JCheckBox( - "Full Screen", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.START_FULL_SCREEN))); - fullScreen.setToolTipText("If checked this starts Legup in full screen."); - JPanel fullScreenRow = new JPanel(); - fullScreenRow.setLayout(new BorderLayout()); - fullScreenRow.add(fullScreen, BorderLayout.WEST); - fullScreenRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, fullScreenRow.getPreferredSize().height)); - contentPane.add(fullScreenRow); - - autoUpdate = - new JCheckBox( - "Automatically Check for Updates", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_UPDATE))); - autoUpdate.setToolTipText( - "If checked this automatically checks for updates on startup of Legup"); - JPanel autoUpdateRow = new JPanel(); - autoUpdateRow.setLayout(new BorderLayout()); - autoUpdateRow.add(autoUpdate, BorderLayout.WEST); - autoUpdateRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, autoUpdateRow.getPreferredSize().height)); - contentPane.add(autoUpdateRow); - // contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - darkMode = - new JCheckBox( - "Dark Mode", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))); - darkMode.setToolTipText("This turns dark mode on and off"); - JPanel darkModeRow = new JPanel(); - darkModeRow.setLayout(new BorderLayout()); - darkModeRow.add(darkMode, BorderLayout.WEST); - darkModeRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, darkModeRow.getPreferredSize().height)); - contentPane.add(darkModeRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - contentPane.add(createLeftLabel("Board View Preferences")); - contentPane.add(createLineSeparator()); - showMistakes = - new JCheckBox( - "Show Mistakes", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_MISTAKES))); - showMistakes.setToolTipText( - "If checked this show incorrectly applied rule applications in red on the board"); - JPanel showMistakesRow = new JPanel(); - showMistakesRow.setLayout(new BorderLayout()); - showMistakesRow.add(showMistakes, BorderLayout.WEST); - showMistakesRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); - contentPane.add(showMistakesRow); - - showAnnotations = - new JCheckBox( - "Show Annotations", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_ANNOTATIONS))); - showAnnotations.setToolTipText( - "If checked this show incorrectly applied rule applications in red on the board"); - JPanel showAnnotationsRow = new JPanel(); - showAnnotationsRow.setLayout(new BorderLayout()); - showAnnotationsRow.add(showAnnotations, BorderLayout.WEST); - showAnnotationsRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showAnnotationsRow.getPreferredSize().height)); - contentPane.add(showAnnotationsRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - contentPane.add(createLeftLabel("Tree View Preferences")); - contentPane.add(createLineSeparator()); - - allowDefault = - new JCheckBox( - "Allow Default Rule Applications", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES))); - allowDefault.setEnabled(false); - allowDefault.setToolTipText( - "If checked this automatically applies a rule where it can on the board"); - - JPanel allowDefaultRow = new JPanel(); - allowDefaultRow.setLayout(new BorderLayout()); - allowDefaultRow.add(allowDefault, BorderLayout.WEST); - allowDefaultRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, allowDefaultRow.getPreferredSize().height)); - contentPane.add(allowDefaultRow); - - generateCases = - new JCheckBox( - "Automatically Generate Cases", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_GENERATE_CASES))); - generateCases.setToolTipText( - "If checked this automatically generates all cases for a case rule"); - JPanel generateCasesRow = new JPanel(); - generateCasesRow.setLayout(new BorderLayout()); - generateCasesRow.add(generateCases, BorderLayout.WEST); - generateCasesRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, generateCasesRow.getPreferredSize().height)); - contentPane.add(generateCasesRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - immFeedback = - new JCheckBox( - "Provide Immediate Feedback", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); - immFeedback.setToolTipText( - "If checked this will update the colors of the tree view elements immediately"); - JPanel immFeedbackRow = new JPanel(); - immFeedbackRow.setLayout(new BorderLayout()); - immFeedbackRow.add(immFeedback, BorderLayout.WEST); - immFeedbackRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); - contentPane.add(immFeedbackRow); - - contentPane.add(createLeftLabel("Instructor Preferences")); - contentPane.add(createLineSeparator()); - immFeedback = - new JCheckBox( - "Instructor Mode", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); - immFeedback.setToolTipText("Currently unimplemented, this does nothing right now"); - immFeedbackRow.setLayout(new BorderLayout()); - immFeedbackRow.add(immFeedback, BorderLayout.WEST); - immFeedbackRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); - contentPane.add(immFeedbackRow); - - contentPane.add(createLeftLabel("Color Preferences")); - contentPane.add(createLineSeparator()); - colorBlind = - new JCheckBox( - "Deuteranomaly(red/green colorblindness)", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.COLOR_BLIND))); - - JPanel colorBlindRow = new JPanel(); - colorBlindRow.setLayout(new BorderLayout()); - colorBlindRow.add(colorBlind, BorderLayout.WEST); - colorBlindRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); - contentPane.add(colorBlindRow); - - scrollPane.setViewportView(contentPane); - return scrollPane; - } - - private JScrollPane createPuzzleTab(Puzzle puzzle) { - JScrollPane scrollPane = new JScrollPane(); - scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - - JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); - - contentPane.add(createLeftLabel("Rules")); - contentPane.add(createLineSeparator()); - - contentPane.add(createLeftLabel("Direct Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getDirectRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - } - - contentPane.add(createLeftLabel("Case Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getCaseRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - } - - contentPane.add(createLeftLabel("Contradiction Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getContradictionRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - } - - scrollPane.setViewportView(contentPane); - return scrollPane; + } + + private JScrollPane createGeneralTab() { + LegupPreferences prefs = LegupPreferences.getInstance(); + JScrollPane scrollPane = new JScrollPane(); + JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); + + contentPane.add(createLeftLabel("General Preferences")); + contentPane.add(createLineSeparator()); + + JPanel workRow = new JPanel(); + workRow.setLayout(new BorderLayout()); + JLabel workDirLabel = new JLabel("Work Directory"); + workDirLabel.setToolTipText("This is where the open and save dialogs will open to."); + workRow.add(workDirLabel, BorderLayout.WEST); + workDirectory = new JTextField(prefs.getUserPref(LegupPreferences.WORK_DIRECTORY)); + workRow.add(workDirectory, BorderLayout.CENTER); + JButton openDir = new JButton(new ImageIcon(folderIcon)); + openDir.addActionListener( + a -> { + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(workDirectory.getText())); + chooser.setDialogTitle("Choose work directory"); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setAcceptAllFileFilterUsed(false); + chooser.setVisible(true); + + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + File newFile = chooser.getSelectedFile(); + workDirectory.setText(newFile.toString()); + } + }); + workRow.add(openDir, BorderLayout.EAST); + workRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, workRow.getPreferredSize().height)); + contentPane.add(workRow); + + fullScreen = + new JCheckBox( + "Full Screen", Boolean.valueOf(prefs.getUserPref(LegupPreferences.START_FULL_SCREEN))); + fullScreen.setToolTipText("If checked this starts Legup in full screen."); + JPanel fullScreenRow = new JPanel(); + fullScreenRow.setLayout(new BorderLayout()); + fullScreenRow.add(fullScreen, BorderLayout.WEST); + fullScreenRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, fullScreenRow.getPreferredSize().height)); + contentPane.add(fullScreenRow); + + autoUpdate = + new JCheckBox( + "Automatically Check for Updates", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_UPDATE))); + autoUpdate.setToolTipText( + "If checked this automatically checks for updates on startup of Legup"); + JPanel autoUpdateRow = new JPanel(); + autoUpdateRow.setLayout(new BorderLayout()); + autoUpdateRow.add(autoUpdate, BorderLayout.WEST); + autoUpdateRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, autoUpdateRow.getPreferredSize().height)); + contentPane.add(autoUpdateRow); + // contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + darkMode = + new JCheckBox("Dark Mode", Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))); + darkMode.setToolTipText("This turns dark mode on and off"); + JPanel darkModeRow = new JPanel(); + darkModeRow.setLayout(new BorderLayout()); + darkModeRow.add(darkMode, BorderLayout.WEST); + darkModeRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, darkModeRow.getPreferredSize().height)); + contentPane.add(darkModeRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + contentPane.add(createLeftLabel("Board View Preferences")); + contentPane.add(createLineSeparator()); + showMistakes = + new JCheckBox( + "Show Mistakes", Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_MISTAKES))); + showMistakes.setToolTipText( + "If checked this show incorrectly applied rule applications in red on the board"); + JPanel showMistakesRow = new JPanel(); + showMistakesRow.setLayout(new BorderLayout()); + showMistakesRow.add(showMistakes, BorderLayout.WEST); + showMistakesRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); + contentPane.add(showMistakesRow); + + showAnnotations = + new JCheckBox( + "Show Annotations", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_ANNOTATIONS))); + showAnnotations.setToolTipText( + "If checked this show incorrectly applied rule applications in red on the board"); + JPanel showAnnotationsRow = new JPanel(); + showAnnotationsRow.setLayout(new BorderLayout()); + showAnnotationsRow.add(showAnnotations, BorderLayout.WEST); + showAnnotationsRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showAnnotationsRow.getPreferredSize().height)); + contentPane.add(showAnnotationsRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + contentPane.add(createLeftLabel("Tree View Preferences")); + contentPane.add(createLineSeparator()); + + allowDefault = + new JCheckBox( + "Allow Default Rule Applications", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES))); + allowDefault.setEnabled(false); + allowDefault.setToolTipText( + "If checked this automatically applies a rule where it can on the board"); + + JPanel allowDefaultRow = new JPanel(); + allowDefaultRow.setLayout(new BorderLayout()); + allowDefaultRow.add(allowDefault, BorderLayout.WEST); + allowDefaultRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, allowDefaultRow.getPreferredSize().height)); + contentPane.add(allowDefaultRow); + + generateCases = + new JCheckBox( + "Automatically Generate Cases", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_GENERATE_CASES))); + generateCases.setToolTipText( + "If checked this automatically generates all cases for a case rule"); + JPanel generateCasesRow = new JPanel(); + generateCasesRow.setLayout(new BorderLayout()); + generateCasesRow.add(generateCases, BorderLayout.WEST); + generateCasesRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, generateCasesRow.getPreferredSize().height)); + contentPane.add(generateCasesRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + immFeedback = + new JCheckBox( + "Provide Immediate Feedback", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); + immFeedback.setToolTipText( + "If checked this will update the colors of the tree view elements immediately"); + JPanel immFeedbackRow = new JPanel(); + immFeedbackRow.setLayout(new BorderLayout()); + immFeedbackRow.add(immFeedback, BorderLayout.WEST); + immFeedbackRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); + contentPane.add(immFeedbackRow); + + contentPane.add(createLeftLabel("Instructor Preferences")); + contentPane.add(createLineSeparator()); + immFeedback = + new JCheckBox( + "Instructor Mode", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); + immFeedback.setToolTipText("Currently unimplemented, this does nothing right now"); + immFeedbackRow.setLayout(new BorderLayout()); + immFeedbackRow.add(immFeedback, BorderLayout.WEST); + immFeedbackRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); + contentPane.add(immFeedbackRow); + + contentPane.add(createLeftLabel("Color Preferences")); + contentPane.add(createLineSeparator()); + colorBlind = + new JCheckBox( + "Deuteranomaly(red/green colorblindness)", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.COLOR_BLIND))); + + JPanel colorBlindRow = new JPanel(); + colorBlindRow.setLayout(new BorderLayout()); + colorBlindRow.add(colorBlind, BorderLayout.WEST); + colorBlindRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); + contentPane.add(colorBlindRow); + + scrollPane.setViewportView(contentPane); + return scrollPane; + } + + private JScrollPane createPuzzleTab(Puzzle puzzle) { + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + + JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); + + contentPane.add(createLeftLabel("Rules")); + contentPane.add(createLineSeparator()); + + contentPane.add(createLeftLabel("Direct Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getDirectRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); } - private JPanel createRuleRow(Rule rule) { - JPanel ruleRow = new JPanel(); - ruleRow.setLayout(new BorderLayout()); - - JLabel ruleLabel = new JLabel(rule.getRuleName()); - ruleRow.add(ruleLabel, BorderLayout.WEST); - - JLabel ruleAcc = new JLabel(); - ruleAcc.setHorizontalAlignment(JLabel.CENTER); - ruleAcc.setBorder(MaterialBorders.LIGHT_LINE_BORDER); - ruleAcc.setPreferredSize(new Dimension(60, 20)); - ruleAcc.addMouseListener( - new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent e) { - ruleAcc.requestFocusInWindow(); - } - }); - - ruleAcc.addKeyListener( - new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - int keyCode = e.getKeyCode(); - String combo = ""; - if (e.isControlDown()) { - combo += "Ctrl + "; - } else { - if (e.isShiftDown()) { - combo += "Shift + "; - } else { - if (e.isAltDown()) { - combo += "Alt + "; - } - } - } - if (keyCode == KeyEvent.VK_CONTROL - || keyCode == KeyEvent.VK_SHIFT - || keyCode == KeyEvent.VK_ALT) { - return; - } - combo += KeyEvent.getKeyText(keyCode); - ruleAcc.setText(combo); - } - }); - - ruleRow.add(ruleAcc, BorderLayout.EAST); - - ruleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, ruleRow.getPreferredSize().height)); - return ruleRow; + contentPane.add(createLeftLabel("Case Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getCaseRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); } - private JPanel createLeftLabel(String text) { - JPanel labelRow = new JPanel(); - labelRow.setLayout(new BorderLayout()); - JLabel label = new JLabel(text); - label.setFont(MaterialFonts.BOLD); - label.setHorizontalAlignment(JLabel.LEFT); - labelRow.add(label, BorderLayout.WEST); - - labelRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, labelRow.getPreferredSize().height)); - return labelRow; + contentPane.add(createLeftLabel("Contradiction Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getContradictionRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); } - private JSeparator createLineSeparator() { - JSeparator separator = new JSeparator(); - separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5)); - return separator; + scrollPane.setViewportView(contentPane); + return scrollPane; + } + + private JPanel createRuleRow(Rule rule) { + JPanel ruleRow = new JPanel(); + ruleRow.setLayout(new BorderLayout()); + + JLabel ruleLabel = new JLabel(rule.getRuleName()); + ruleRow.add(ruleLabel, BorderLayout.WEST); + + JLabel ruleAcc = new JLabel(); + ruleAcc.setHorizontalAlignment(JLabel.CENTER); + ruleAcc.setBorder(MaterialBorders.LIGHT_LINE_BORDER); + ruleAcc.setPreferredSize(new Dimension(60, 20)); + ruleAcc.addMouseListener( + new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + ruleAcc.requestFocusInWindow(); + } + }); + + ruleAcc.addKeyListener( + new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + int keyCode = e.getKeyCode(); + String combo = ""; + if (e.isControlDown()) { + combo += "Ctrl + "; + } else { + if (e.isShiftDown()) { + combo += "Shift + "; + } else { + if (e.isAltDown()) { + combo += "Alt + "; + } + } + } + if (keyCode == KeyEvent.VK_CONTROL + || keyCode == KeyEvent.VK_SHIFT + || keyCode == KeyEvent.VK_ALT) { + return; + } + combo += KeyEvent.getKeyText(keyCode); + ruleAcc.setText(combo); + } + }); + + ruleRow.add(ruleAcc, BorderLayout.EAST); + + ruleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, ruleRow.getPreferredSize().height)); + return ruleRow; + } + + private JPanel createLeftLabel(String text) { + JPanel labelRow = new JPanel(); + labelRow.setLayout(new BorderLayout()); + JLabel label = new JLabel(text); + label.setFont(MaterialFonts.BOLD); + label.setHorizontalAlignment(JLabel.LEFT); + labelRow.add(label, BorderLayout.WEST); + + labelRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, labelRow.getPreferredSize().height)); + return labelRow; + } + + private JSeparator createLineSeparator() { + JSeparator separator = new JSeparator(); + separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5)); + return separator; + } + + public void applyPreferences() { + LegupPreferences prefs = LegupPreferences.getInstance(); + prefs.setUserPref(LegupPreferences.WORK_DIRECTORY, workDirectory.getText()); + prefs.setUserPref( + LegupPreferences.START_FULL_SCREEN, Boolean.toString(fullScreen.isSelected())); + prefs.setUserPref(LegupPreferences.AUTO_UPDATE, Boolean.toString(autoUpdate.isSelected())); + prefs.setUserPref(LegupPreferences.DARK_MODE, Boolean.toString(darkMode.isSelected())); + prefs.setUserPref(LegupPreferences.SHOW_MISTAKES, Boolean.toString(showMistakes.isSelected())); + prefs.setUserPref( + LegupPreferences.SHOW_ANNOTATIONS, Boolean.toString(showAnnotations.isSelected())); + prefs.setUserPref( + LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); + prefs.setUserPref( + LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(generateCases.isSelected())); + prefs.setUserPref( + LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(immFeedback.isSelected())); + prefs.setUserPref(LegupPreferences.COLOR_BLIND, Boolean.toString(colorBlind.isSelected())); + + if (rulesFrame != null) { + rulesFrame.getCasePanel().updateRules(); + rulesFrame.getDirectRulePanel().updateRules(); + rulesFrame.getContradictionPanel().updateRules(); } - public void applyPreferences() { - LegupPreferences prefs = LegupPreferences.getInstance(); - prefs.setUserPref(LegupPreferences.WORK_DIRECTORY, workDirectory.getText()); - prefs.setUserPref( - LegupPreferences.START_FULL_SCREEN, Boolean.toString(fullScreen.isSelected())); - prefs.setUserPref(LegupPreferences.AUTO_UPDATE, Boolean.toString(autoUpdate.isSelected())); - prefs.setUserPref(LegupPreferences.DARK_MODE, Boolean.toString(darkMode.isSelected())); - prefs.setUserPref( - LegupPreferences.SHOW_MISTAKES, Boolean.toString(showMistakes.isSelected())); - prefs.setUserPref( - LegupPreferences.SHOW_ANNOTATIONS, Boolean.toString(showAnnotations.isSelected())); - prefs.setUserPref( - LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); - prefs.setUserPref( - LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(generateCases.isSelected())); - prefs.setUserPref( - LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(immFeedback.isSelected())); - prefs.setUserPref(LegupPreferences.COLOR_BLIND, Boolean.toString(colorBlind.isSelected())); - - if (rulesFrame != null) { - rulesFrame.getCasePanel().updateRules(); - rulesFrame.getDirectRulePanel().updateRules(); - rulesFrame.getContradictionPanel().updateRules(); - } - - // toggle dark mode based on updated NIGHT_MODE variable - toggleDarkMode(prefs); - } + // toggle dark mode based on updated NIGHT_MODE variable + toggleDarkMode(prefs); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java b/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java index 956f83ba4..4fe1c1ff6 100644 --- a/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java +++ b/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java @@ -37,1090 +37,1050 @@ import org.apache.logging.log4j.Logger; public class ProofEditorPanel extends LegupPanel implements IHistoryListener { - private static final Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName()); - private JMenuBar mBar; - private TreePanel treePanel; - private FileDialog fileDialog; - private JFrame frame; - private RuleFrame ruleFrame; - private DynamicView dynamicBoardView; - private JSplitPane topHalfPanel, mainPanel; - private TitledBorder boardBorder; - - private JButton[] toolBarButtons; - private JMenu file; - private JMenuItem newPuzzle, - resetPuzzle, - saveProofAs, - saveProofChange, - helpTutorial, - preferences, - exit; - private JMenu edit; - private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen; - - private JMenu view; - - private JMenu proof; - private JMenuItem add, delete, merge, collapse; - private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback; - private JMenu about, help; - private JMenuItem helpLegup, aboutLegup; - - private JToolBar toolBar; - private BoardView boardView; - private JFileChooser folderBrowser; - - private LegupUI legupUI; - - public static final int ALLOW_HINTS = 1; - public static final int ALLOW_DEFAPP = 2; - public static final int ALLOW_FULLAI = 4; - public static final int ALLOW_JUST = 8; - public static final int REQ_STEP_JUST = 16; - public static final int IMD_FEEDBACK = 32; - public static final int INTERN_RO = 64; - public static final int AUTO_JUST = 128; - static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; - private static final String[] PROFILES = { - "No Assistance", - "Rigorous Proof", - "Casual Proof", - "Assisted Proof", - "Guided Proof", - "Training-Wheels Proof", - "No Restrictions" - }; - private static final int[] PROF_FLAGS = { - 0, - ALLOW_JUST | REQ_STEP_JUST, - ALLOW_JUST, - ALLOW_HINTS | ALLOW_JUST | AUTO_JUST, - ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST, - ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO, - ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST - }; - private JMenu proofMode = new JMenu("Proof Mode"); - private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length]; - - private static int CONFIG_INDEX = 0; - - protected JMenu ai = new JMenu("AI"); - protected JMenuItem runAI = new JMenuItem("Run AI to completion"); - protected JMenuItem setpAI = new JMenuItem("Run AI one Step"); - protected JMenuItem testAI = new JMenuItem("Test AI!"); - protected JMenuItem hintAI = new JMenuItem("Hint"); - - public ProofEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.fileDialog = fileDialog; - this.frame = frame; - this.legupUI = legupUI; - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(800, 700)); + private static final Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName()); + private JMenuBar mBar; + private TreePanel treePanel; + private FileDialog fileDialog; + private JFrame frame; + private RuleFrame ruleFrame; + private DynamicView dynamicBoardView; + private JSplitPane topHalfPanel, mainPanel; + private TitledBorder boardBorder; + + private JButton[] toolBarButtons; + private JMenu file; + private JMenuItem newPuzzle, + resetPuzzle, + saveProofAs, + saveProofChange, + helpTutorial, + preferences, + exit; + private JMenu edit; + private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen; + + private JMenu view; + + private JMenu proof; + private JMenuItem add, delete, merge, collapse; + private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback; + private JMenu about, help; + private JMenuItem helpLegup, aboutLegup; + + private JToolBar toolBar; + private BoardView boardView; + private JFileChooser folderBrowser; + + private LegupUI legupUI; + + public static final int ALLOW_HINTS = 1; + public static final int ALLOW_DEFAPP = 2; + public static final int ALLOW_FULLAI = 4; + public static final int ALLOW_JUST = 8; + public static final int REQ_STEP_JUST = 16; + public static final int IMD_FEEDBACK = 32; + public static final int INTERN_RO = 64; + public static final int AUTO_JUST = 128; + static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; + private static final String[] PROFILES = { + "No Assistance", + "Rigorous Proof", + "Casual Proof", + "Assisted Proof", + "Guided Proof", + "Training-Wheels Proof", + "No Restrictions" + }; + private static final int[] PROF_FLAGS = { + 0, + ALLOW_JUST | REQ_STEP_JUST, + ALLOW_JUST, + ALLOW_HINTS | ALLOW_JUST | AUTO_JUST, + ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST, + ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO, + ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST + }; + private JMenu proofMode = new JMenu("Proof Mode"); + private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length]; + + private static int CONFIG_INDEX = 0; + + protected JMenu ai = new JMenu("AI"); + protected JMenuItem runAI = new JMenuItem("Run AI to completion"); + protected JMenuItem setpAI = new JMenuItem("Run AI one Step"); + protected JMenuItem testAI = new JMenuItem("Test AI!"); + protected JMenuItem hintAI = new JMenuItem("Hint"); + + public ProofEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.fileDialog = fileDialog; + this.frame = frame; + this.legupUI = legupUI; + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(800, 700)); + } + + @Override + public void makeVisible() { + this.removeAll(); + + setupToolBar(); + setupContent(); + frame.setJMenuBar(getMenuBar()); + } + + public JMenuBar getMenuBar() { + if (mBar != null) return mBar; + mBar = new JMenuBar(); + + file = new JMenu("File"); + newPuzzle = new JMenuItem("Open"); + resetPuzzle = new JMenuItem("Reset Puzzle"); + // genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle + // generator + saveProofAs = new JMenuItem("Save As"); // create a new file to save + saveProofChange = new JMenuItem("Save"); // save to the current file + preferences = new JMenuItem("Preferences"); + helpTutorial = new JMenuItem("Help"); // jump to web page + exit = new JMenuItem("Exit"); + + edit = new JMenu("Edit"); + undo = new JMenuItem("Undo"); + redo = new JMenuItem("Redo"); + + fitBoardToScreen = new JMenuItem("Fit Board to Screen"); + fitTreeToScreen = new JMenuItem("Fit Tree to Screen"); + + view = new JMenu("View"); + + proof = new JMenu("Proof"); + + String os = LegupUI.getOS(); + + add = new JMenuItem("Add"); + add.addActionListener(a -> treePanel.add()); + if (os.equals("mac")) { + add.setAccelerator( + KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); } - - @Override - public void makeVisible() { - this.removeAll(); - - setupToolBar(); - setupContent(); - frame.setJMenuBar(getMenuBar()); + proof.add(add); + + delete = new JMenuItem("Delete"); + delete.addActionListener(a -> treePanel.delete()); + if (os.equals("mac")) { + delete.setAccelerator( + KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); } - - public JMenuBar getMenuBar() { - if (mBar != null) return mBar; - mBar = new JMenuBar(); - - file = new JMenu("File"); - newPuzzle = new JMenuItem("Open"); - resetPuzzle = new JMenuItem("Reset Puzzle"); - // genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle - // generator - saveProofAs = new JMenuItem("Save As"); // create a new file to save - saveProofChange = new JMenuItem("Save"); // save to the current file - preferences = new JMenuItem("Preferences"); - helpTutorial = new JMenuItem("Help"); // jump to web page - exit = new JMenuItem("Exit"); - - edit = new JMenu("Edit"); - undo = new JMenuItem("Undo"); - redo = new JMenuItem("Redo"); - - fitBoardToScreen = new JMenuItem("Fit Board to Screen"); - fitTreeToScreen = new JMenuItem("Fit Tree to Screen"); - - view = new JMenu("View"); - - proof = new JMenu("Proof"); - - String os = LegupUI.getOS(); - - add = new JMenuItem("Add"); - add.addActionListener(a -> treePanel.add()); - if (os.equals("mac")) { - add.setAccelerator( - KeyStroke.getKeyStroke( - 'A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); - } - proof.add(add); - - delete = new JMenuItem("Delete"); - delete.addActionListener(a -> treePanel.delete()); - if (os.equals("mac")) { - delete.setAccelerator( - KeyStroke.getKeyStroke( - 'D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); - } - proof.add(delete); - - merge = new JMenuItem("Merge"); - merge.addActionListener(a -> treePanel.merge()); - if (os.equals("mac")) { - merge.setAccelerator( - KeyStroke.getKeyStroke( - 'M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK)); - } - proof.add(merge); - - collapse = new JMenuItem("Collapse"); - collapse.addActionListener(a -> treePanel.collapse()); - if (os.equals("mac")) { - collapse.setAccelerator( - KeyStroke.getKeyStroke( - 'C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); - } - collapse.setEnabled(false); - proof.add(collapse); - - allowDefault = - new JCheckBoxMenuItem( - "Allow Default Rule Applications", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES) - .equalsIgnoreCase(Boolean.toString(true))); - allowDefault.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.ALLOW_DEFAULT_RULES, - Boolean.toString(allowDefault.isSelected())); - }); - proof.add(allowDefault); - - caseRuleGen = - new JCheckBoxMenuItem( - "Automatically generate cases for CaseRule", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) - .equalsIgnoreCase(Boolean.toString(true))); - caseRuleGen.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.AUTO_GENERATE_CASES, - Boolean.toString(caseRuleGen.isSelected())); - }); - proof.add(caseRuleGen); - - imdFeedback = - new JCheckBoxMenuItem( - "Provide immediate feedback", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK) - .equalsIgnoreCase(Boolean.toString(true))); - imdFeedback.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.IMMEDIATE_FEEDBACK, - Boolean.toString(imdFeedback.isSelected())); - }); - proof.add(imdFeedback); - - about = new JMenu("About"); - helpLegup = new JMenuItem("Help Legup"); - aboutLegup = new JMenuItem("About Legup"); - - mBar.add(file); - file.add(newPuzzle); - newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke( - 'N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); - } - - file.add(resetPuzzle); - resetPuzzle.addActionListener( - a -> { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle != null) { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeNode rootNode = tree.getRootNode(); - if (rootNode != null) { - int confirmReset = - JOptionPane.showConfirmDialog( - this, - "Reset Puzzle to Root Node?", - "Confirm Reset", - JOptionPane.YES_NO_OPTION); - if (confirmReset == JOptionPane.YES_OPTION) { - - List children = rootNode.getChildren(); - children.forEach( - t -> - puzzle.notifyTreeListeners( - l -> l.onTreeElementRemoved(t))); - children.forEach( - t -> - puzzle.notifyBoardListeners( - l -> l.onTreeElementChanged(t))); - rootNode.clearChildren(); - final TreeViewSelection selection = - new TreeViewSelection( - treePanel.getTreeView().getElementView(rootNode)); - puzzle.notifyTreeListeners( - l -> l.onTreeSelectionChanged(selection)); - puzzle.notifyBoardListeners( - listener -> - listener.onTreeElementChanged( - selection - .getFirstSelection() - .getTreeElement())); - GameBoardFacade.getInstance().getHistory().clear(); - } - } - } - }); - if (os.equals("mac")) { - resetPuzzle.setAccelerator( - KeyStroke.getKeyStroke( - 'R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK)); - } - file.addSeparator(); - - file.add(saveProofAs); - saveProofAs.addActionListener((ActionEvent) -> saveProofAs()); - - // save proof as... - if (os.equals("mac")) { - saveProofAs.setAccelerator( - KeyStroke.getKeyStroke( - 'S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); - } - - // save proof change - if (os.equals("mac")) { - saveProofChange.setAccelerator( - KeyStroke.getKeyStroke( - 'A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); - } - - file.add(saveProofChange); - saveProofChange.addActionListener((ActionEvent) -> saveProofChange()); - file.addSeparator(); - - // preference - file.add(preferences); - preferences.addActionListener( - a -> { - PreferencesDialog preferencesDialog = - PreferencesDialog.CreateDialogForProofEditor( - this.frame, this.ruleFrame); - }); - file.addSeparator(); - - // help function - if (os.equals("mac")) { - helpTutorial.setAccelerator( - KeyStroke.getKeyStroke( - 'H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); - } - file.add(helpTutorial); - - helpTutorial.addActionListener((ActionEvent) -> helpTutorial()); - file.addSeparator(); - - // exit - file.add(exit); - exit.addActionListener((ActionEvent) -> exitEditor()); - if (os.equals("mac")) { - exit.setAccelerator( - KeyStroke.getKeyStroke( - 'Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); - } - mBar.add(edit); - - edit.add(undo); - undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); - if (os.equals("mac")) { - undo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); - } - - edit.add(redo); - - // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) - Action redoAction = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - GameBoardFacade.getInstance().getHistory().redo(); - } - }; - if (os.equals("mac")) { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() - + InputEvent.SHIFT_DOWN_MASK), - "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "redoAction"); - redo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() - + InputEvent.SHIFT_DOWN_MASK)); - } else { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), - "redoAction"); - redo.getActionMap().put("redoAction", redoAction); - - // Button in menu will show CTRL-SHIFT-Z as primary keybind - redo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); - } - - edit.add(fitBoardToScreen); - fitBoardToScreen.addActionListener( - (ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); - - edit.add(fitTreeToScreen); - fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen()); - - mBar.add(proof); - - about.add(aboutLegup); - aboutLegup.addActionListener( - l -> { - JOptionPane.showMessageDialog(null, "Version: 5.1.0"); - }); - - about.add(helpLegup); - helpLegup.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop() - .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - - mBar.add(about); - - return mBar; + proof.add(delete); + + merge = new JMenuItem("Merge"); + merge.addActionListener(a -> treePanel.merge()); + if (os.equals("mac")) { + merge.setAccelerator( + KeyStroke.getKeyStroke('M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK)); } - - public void exitEditor() { - // Wipes the puzzle entirely as if LEGUP just started - GameBoardFacade.getInstance().clearPuzzle(); - this.legupUI.displayPanel(0); - treePanel = null; - boardView = null; + proof.add(merge); + + collapse = new JMenuItem("Collapse"); + collapse.addActionListener(a -> treePanel.collapse()); + if (os.equals("mac")) { + collapse.setAccelerator( + KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); + } + collapse.setEnabled(false); + proof.add(collapse); + + allowDefault = + new JCheckBoxMenuItem( + "Allow Default Rule Applications", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES) + .equalsIgnoreCase(Boolean.toString(true))); + allowDefault.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.ALLOW_DEFAULT_RULES, + Boolean.toString(allowDefault.isSelected())); + }); + proof.add(allowDefault); + + caseRuleGen = + new JCheckBoxMenuItem( + "Automatically generate cases for CaseRule", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) + .equalsIgnoreCase(Boolean.toString(true))); + caseRuleGen.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(caseRuleGen.isSelected())); + }); + proof.add(caseRuleGen); + + imdFeedback = + new JCheckBoxMenuItem( + "Provide immediate feedback", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK) + .equalsIgnoreCase(Boolean.toString(true))); + imdFeedback.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(imdFeedback.isSelected())); + }); + proof.add(imdFeedback); + + about = new JMenu("About"); + helpLegup = new JMenuItem("Help Legup"); + aboutLegup = new JMenuItem("About Legup"); + + mBar.add(file); + file.add(newPuzzle); + newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); } - // File opener - public Object[] promptPuzzle() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - if (facade.getBoard() != null) { - if (noquit("Opening a new puzzle?")) { - return new Object[0]; + file.add(resetPuzzle); + resetPuzzle.addActionListener( + a -> { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle != null) { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeNode rootNode = tree.getRootNode(); + if (rootNode != null) { + int confirmReset = + JOptionPane.showConfirmDialog( + this, + "Reset Puzzle to Root Node?", + "Confirm Reset", + JOptionPane.YES_NO_OPTION); + if (confirmReset == JOptionPane.YES_OPTION) { + + List children = rootNode.getChildren(); + children.forEach(t -> puzzle.notifyTreeListeners(l -> l.onTreeElementRemoved(t))); + children.forEach(t -> puzzle.notifyBoardListeners(l -> l.onTreeElementChanged(t))); + rootNode.clearChildren(); + final TreeViewSelection selection = + new TreeViewSelection(treePanel.getTreeView().getElementView(rootNode)); + puzzle.notifyTreeListeners(l -> l.onTreeSelectionChanged(selection)); + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged( + selection.getFirstSelection().getTreeElement())); + GameBoardFacade.getInstance().getHistory().clear(); + } } - } - - LegupPreferences preferences = LegupPreferences.getInstance(); - String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); - if (preferences.getSavedPath() != "") { - preferredDirectory = preferences.getSavedPath(); - } + } + }); + if (os.equals("mac")) { + resetPuzzle.setAccelerator( + KeyStroke.getKeyStroke('R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK)); + } + file.addSeparator(); - File preferredDirectoryFile = new File(preferredDirectory); - JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile); - String fileName = null; - File puzzleFile = null; - - fileBrowser.showOpenDialog(this); - fileBrowser.setVisible(true); - fileBrowser.setCurrentDirectory(new File(preferredDirectory)); - fileBrowser.setDialogTitle("Select Proof File"); - fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - fileBrowser.setAcceptAllFileFilterUsed(false); - - File puzzlePath = fileBrowser.getSelectedFile(); - System.out.println(puzzlePath.getAbsolutePath()); - - if (puzzlePath != null) { - fileName = puzzlePath.getAbsolutePath(); - String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator)); - preferences.setSavedPath(lastDirectoryPath); - puzzleFile = puzzlePath; - } else { - // The attempt to prompt a puzzle ended gracefully (cancel) - return null; - } + file.add(saveProofAs); + saveProofAs.addActionListener((ActionEvent) -> saveProofAs()); - return new Object[] {fileName, puzzleFile}; + // save proof as... + if (os.equals("mac")) { + saveProofAs.setAccelerator( + KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); } - public void loadPuzzle() { - Object[] items = promptPuzzle(); - // Return if items == null (cancel) - if (items == null) { - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - loadPuzzle(fileName, puzzleFile); + // save proof change + if (os.equals("mac")) { + saveProofChange.setAccelerator( + KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); } - public void loadPuzzle(String fileName, File puzzleFile) { - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(1); - GameBoardFacade.getInstance().loadPuzzle(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } catch (InvalidFileFormatException e) { - legupUI.displayPanel(0); - LOGGER.error(e.getMessage()); - if (e.getMessage() - .contains( - "Proof Tree construction error: could not find rule by ID")) { // TO - // DO: make error - // message not - // hardcoded - JOptionPane.showMessageDialog( - null, - "This file runs on an outdated version of Legup\n" - + "and is not compatible with the current version.", - "Error", - JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } else { - JOptionPane.showMessageDialog( - null, - "File does not exist or it cannot be read", - "Error", - JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } - } - } + file.add(saveProofChange); + saveProofChange.addActionListener((ActionEvent) -> saveProofChange()); + file.addSeparator(); + + // preference + file.add(preferences); + preferences.addActionListener( + a -> { + PreferencesDialog preferencesDialog = + PreferencesDialog.CreateDialogForProofEditor(this.frame, this.ruleFrame); + }); + file.addSeparator(); + + // help function + if (os.equals("mac")) { + helpTutorial.setAccelerator( + KeyStroke.getKeyStroke('H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); } - - /** save the proof in the current file */ - private void direct_save() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } - } + file.add(helpTutorial); + + helpTutorial.addActionListener((ActionEvent) -> helpTutorial()); + file.addSeparator(); + + // exit + file.add(exit); + exit.addActionListener((ActionEvent) -> exitEditor()); + if (os.equals("mac")) { + exit.setAccelerator( + KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); } - - /** Create a new file and save proof to it */ - private void saveProofAs() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - - fileDialog.setMode(FileDialog.SAVE); - fileDialog.setTitle("Save As"); - String curFileName = GameBoardFacade.getInstance().getCurFileName(); - if (curFileName == null) { - fileDialog.setDirectory( - LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); - } else { - File curFile = new File(curFileName); - fileDialog.setDirectory(curFile.getParent()); - } - fileDialog.setVisible(true); - - String fileName = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - } - - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } - } + mBar.add(edit); + + edit.add(undo); + undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); + if (os.equals("mac")) { + undo.setAccelerator( + KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); } - // Hyperlink for help button; links to wiki page for tutorials - private void helpTutorial() { - // redirecting to certain help link in wiki - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String puz = puzzle.getName(); - String url; - switch (puz) { - case "LightUp": - url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules"; - break; - case "Nurikabe": - url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules"; - break; - case "TreeTent": - url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules"; - break; - case "Skyscrapers": - url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules"; - break; - case "ShortTruthTable": - url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules"; - break; - default: - url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial"; - } - Runtime rt = Runtime.getRuntime(); - try { - // rt.exec("rundll32 url.dll,FileProtocolHandler "+url); - java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); - } catch (IOException e) { - e.printStackTrace(); - } + edit.add(redo); + + // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) + Action redoAction = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + GameBoardFacade.getInstance().getHistory().redo(); + } + }; + if (os.equals("mac")) { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK), + "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "redoAction"); + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); + } else { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), + "redoAction"); + redo.getActionMap().put("redoAction", redoAction); + + // Button in menu will show CTRL-SHIFT-Z as primary keybind + redo.setAccelerator( + KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); } - // add the new function need to implement - public void add_drop() { - // add the mouse event then we can use the new listener to implement and - // we should create a need jbuttom for it to ship the rule we select. - JPanel panel = new JPanel(); - JButton moveing_buttom = new JButton(); - moveing_buttom.setFocusPainted(false); - moveing_buttom.addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // get the selected rule - } - }); - panel.add(moveing_buttom); + edit.add(fitBoardToScreen); + fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); + + edit.add(fitTreeToScreen); + fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen()); + + mBar.add(proof); + + about.add(aboutLegup); + aboutLegup.addActionListener( + l -> { + JOptionPane.showMessageDialog(null, "Version: 5.1.0"); + }); + + about.add(helpLegup); + helpLegup.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + + mBar.add(about); + + return mBar; + } + + public void exitEditor() { + // Wipes the puzzle entirely as if LEGUP just started + GameBoardFacade.getInstance().clearPuzzle(); + this.legupUI.displayPanel(0); + treePanel = null; + boardView = null; + } + + // File opener + public Object[] promptPuzzle() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + if (facade.getBoard() != null) { + if (noquit("Opening a new puzzle?")) { + return new Object[0]; + } } - // Quick save proof to the current file with a pop window to show "successfully saved" - private void saveProofChange() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - // Save confirmation - JOptionPane.showMessageDialog( - null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE); - } catch (ExportFileException e) { - e.printStackTrace(); - } - } + LegupPreferences preferences = LegupPreferences.getInstance(); + String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); + if (preferences.getSavedPath() != "") { + preferredDirectory = preferences.getSavedPath(); } - // ask to edu.rpi.legup.save current proof - public boolean noquit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; + File preferredDirectoryFile = new File(preferredDirectory); + JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile); + String fileName = null; + File puzzleFile = null; + + fileBrowser.showOpenDialog(this); + fileBrowser.setVisible(true); + fileBrowser.setCurrentDirectory(new File(preferredDirectory)); + fileBrowser.setDialogTitle("Select Proof File"); + fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fileBrowser.setAcceptAllFileFilterUsed(false); + + File puzzlePath = fileBrowser.getSelectedFile(); + System.out.println(puzzlePath.getAbsolutePath()); + + if (puzzlePath != null) { + fileName = puzzlePath.getAbsolutePath(); + String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator)); + preferences.setSavedPath(lastDirectoryPath); + puzzleFile = puzzlePath; + } else { + // The attempt to prompt a puzzle ended gracefully (cancel) + return null; } - /** Sets the main content for the edu.rpi.legup.user interface */ - protected void setupContent() { - // JPanel consoleBox = new JPanel(new BorderLayout()); - JPanel treeBox = new JPanel(new BorderLayout()); - JPanel ruleBox = new JPanel(new BorderLayout()); - - RuleController ruleController = new RuleController(); - ruleFrame = new RuleFrame(ruleController); - ruleBox.add(ruleFrame, BorderLayout.WEST); - - treePanel = new TreePanel(); - - dynamicBoardView = - new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); - TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - JPanel boardPanel = new JPanel(new BorderLayout()); - topHalfPanel = - new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView); - mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel); - topHalfPanel.setPreferredSize(new Dimension(600, 400)); - mainPanel.setPreferredSize(new Dimension(600, 600)); - - boardPanel.add(mainPanel); - boardPanel.setVisible(true); - boardBorder = BorderFactory.createTitledBorder("Board"); - boardBorder.setTitleJustification(TitledBorder.CENTER); - - ruleBox.add(boardPanel); - treeBox.add(ruleBox); - this.add(treeBox); - // consoleBox.add(treeBox); - // - // getContentPane().add(consoleBox); - - // JPopupPanel popupPanel = new JPopupPanel(); - // setGlassPane(popupPanel); - // popupPanel.setVisible(true); - - mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100); - // frame.pack(); - revalidate(); - } + return new Object[] {fileName, puzzleFile}; + } - private void setupToolBar() { - setToolBarButtons(new JButton[ToolbarName.values().length]); - for (int i = 0; i < ToolbarName.values().length; i++) { - String toolBarName = ToolbarName.values()[i].toString(); - URL resourceLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); - - // Scale the image icons down to make the buttons smaller - ImageIcon imageIcon = new ImageIcon(resourceLocation); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, - this.TOOLBAR_ICON_SCALE, - Image.SCALE_SMOOTH)); - - JButton button = new JButton(toolBarName, imageIcon); - button.setFocusPainted(false); - getToolBarButtons()[i] = button; + public void loadPuzzle() { + Object[] items = promptPuzzle(); + // Return if items == null (cancel) + if (items == null) { + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + loadPuzzle(fileName, puzzleFile); + } + + public void loadPuzzle(String fileName, File puzzleFile) { + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(1); + GameBoardFacade.getInstance().loadPuzzle(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } catch (InvalidFileFormatException e) { + legupUI.displayPanel(0); + LOGGER.error(e.getMessage()); + if (e.getMessage() + .contains("Proof Tree construction error: could not find rule by ID")) { // TO + // DO: make error + // message not + // hardcoded + JOptionPane.showMessageDialog( + null, + "This file runs on an outdated version of Legup\n" + + "and is not compatible with the current version.", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } else { + JOptionPane.showMessageDialog( + null, "File does not exist or it cannot be read", "Error", JOptionPane.ERROR_MESSAGE); + loadPuzzle(); } + } + } + } - toolBar = new JToolBar(); - toolBar.setFloatable(false); - toolBar.setRollover(true); - - for (int i = 0; i < getToolBarButtons().length; i++) { - for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { - if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { - toolBar.addSeparator(); - } - } - String toolBarName = ToolbarName.values()[i].toString(); - - toolBar.add(getToolBarButtons()[i]); - getToolBarButtons()[i].setToolTipText(toolBarName); - - getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); - getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); + /** save the proof in the current file */ + private void direct_save() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } + } - // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent - // e) -> - // promptPuzzle()); - // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> - // saveProof()); - // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().undo()); - // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().redo()); - toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener( - (ActionEvent e) -> checkProof()); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); - - toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener( - (ActionEvent e) -> checkProofAll()); - - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true); - - this.add(toolBar, BorderLayout.NORTH); + /** Create a new file and save proof to it */ + private void saveProofAs() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - /** - * Sets the toolbar buttons - * - * @param toolBarButtons toolbar buttons - */ - public void setToolBarButtons(JButton[] toolBarButtons) { - this.toolBarButtons = toolBarButtons; + fileDialog.setMode(FileDialog.SAVE); + fileDialog.setTitle("Save As"); + String curFileName = GameBoardFacade.getInstance().getCurFileName(); + if (curFileName == null) { + fileDialog.setDirectory( + LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); + } else { + File curFile = new File(curFileName); + fileDialog.setDirectory(curFile.getParent()); } + fileDialog.setVisible(true); - /** - * Gets the toolbar buttons - * - * @return toolbar buttons - */ - public JButton[] getToolBarButtons() { - return toolBarButtons; + String fileName = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); } - /** Checks the proof for correctness */ - private void checkProof() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - Tree tree = GameBoardFacade.getInstance().getTree(); - Board board = facade.getBoard(); - Board finalBoard = null; - boolean delayStatus = true; // board.evalDelayStatus(); - - repaintAll(); - - Puzzle puzzle = facade.getPuzzleModule(); - - if (puzzle.isPuzzleComplete()) { - // This is for submission which is not integrated yet - /*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); - if (confirm == JOptionPane.YES_OPTION) { - Submission submission = new Submission(board); - submission.submit(); - }*/ - JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct."); - } else { - String message = "\nThe game board is not solved."; - JOptionPane.showMessageDialog( - null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } } - - private void repaintAll() { - boardView.repaint(); - treePanel.repaint(); + } + + // Hyperlink for help button; links to wiki page for tutorials + private void helpTutorial() { + // redirecting to certain help link in wiki + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - - public void setPuzzleView(Puzzle puzzle) { - this.boardView = puzzle.getBoardView(); - - dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); - this.topHalfPanel.setRightComponent(dynamicBoardView); - this.topHalfPanel.setVisible(true); - String boardType = boardView.getBoard().getClass().getSimpleName(); - boardType = boardType.substring(0, boardType.indexOf("Board")); - TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - this.treePanel.getTreeView().resetView(); - this.treePanel.getTreeView().setTree(puzzle.getTree()); - - puzzle.addTreeListener(treePanel.getTreeView()); - puzzle.addBoardListener(puzzle.getBoardView()); - - ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules()); - ruleFrame.getCasePanel().setRules(puzzle.getCaseRules()); - ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules()); - ruleFrame.getSearchPanel().setSearchBar(puzzle); - - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); - - reloadGui(); + String puz = puzzle.getName(); + String url; + switch (puz) { + case "LightUp": + url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules"; + break; + case "Nurikabe": + url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules"; + break; + case "TreeTent": + url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules"; + break; + case "Skyscrapers": + url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules"; + break; + case "ShortTruthTable": + url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules"; + break; + default: + url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial"; } - - public void reloadGui() { - repaintTree(); + Runtime rt = Runtime.getRuntime(); + try { + // rt.exec("rundll32 url.dll,FileProtocolHandler "+url); + java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); + } catch (IOException e) { + e.printStackTrace(); } - - public void repaintTree() { - treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree()); + } + + // add the new function need to implement + public void add_drop() { + // add the mouse event then we can use the new listener to implement and + // we should create a need jbuttom for it to ship the rule we select. + JPanel panel = new JPanel(); + JButton moveing_buttom = new JButton(); + moveing_buttom.setFocusPainted(false); + moveing_buttom.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // get the selected rule + } + }); + panel.add(moveing_buttom); + } + + // Quick save proof to the current file with a pop window to show "successfully saved" + private void saveProofChange() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - - /** Checks the proof for all files */ - private void checkProofAll() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - - LegupPreferences preferences = LegupPreferences.getInstance(); - File preferredDirectory = - new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); - folderBrowser = new JFileChooser(preferredDirectory); - - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - - File folder = folderBrowser.getSelectedFile(); - - // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); - - // Go through student folders - for (final File folderEntry : - Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - // Write path - String path = folderEntry.getName(); - traverseDir(folderEntry, writer, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); } - JOptionPane.showMessageDialog(null, "Batch grading complete."); + exporter.exportPuzzle(fileName); + // Save confirmation + JOptionPane.showMessageDialog( + null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE); + } catch (ExportFileException e) { + e.printStackTrace(); + } } - - private boolean basicCheckProof(int[][] origCells) { - return false; + } + + // ask to edu.rpi.legup.save current proof + public boolean noquit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + /** Sets the main content for the edu.rpi.legup.user interface */ + protected void setupContent() { + // JPanel consoleBox = new JPanel(new BorderLayout()); + JPanel treeBox = new JPanel(new BorderLayout()); + JPanel ruleBox = new JPanel(new BorderLayout()); + + RuleController ruleController = new RuleController(); + ruleFrame = new RuleFrame(ruleController); + ruleBox.add(ruleFrame, BorderLayout.WEST); + + treePanel = new TreePanel(); + + dynamicBoardView = + new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); + TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + JPanel boardPanel = new JPanel(new BorderLayout()); + topHalfPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView); + mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel); + topHalfPanel.setPreferredSize(new Dimension(600, 400)); + mainPanel.setPreferredSize(new Dimension(600, 600)); + + boardPanel.add(mainPanel); + boardPanel.setVisible(true); + boardBorder = BorderFactory.createTitledBorder("Board"); + boardBorder.setTitleJustification(TitledBorder.CENTER); + + ruleBox.add(boardPanel); + treeBox.add(ruleBox); + this.add(treeBox); + // consoleBox.add(treeBox); + // + // getContentPane().add(consoleBox); + + // JPopupPanel popupPanel = new JPopupPanel(); + // setGlassPane(popupPanel); + // popupPanel.setVisible(true); + + mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100); + // frame.pack(); + revalidate(); + } + + private void setupToolBar() { + setToolBarButtons(new JButton[ToolbarName.values().length]); + for (int i = 0; i < ToolbarName.values().length; i++) { + String toolBarName = ToolbarName.values()[i].toString(); + URL resourceLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); + + // Scale the image icons down to make the buttons smaller + ImageIcon imageIcon = new ImageIcon(resourceLocation); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); + + JButton button = new JButton(toolBarName, imageIcon); + button.setFocusPainted(false); + getToolBarButtons()[i] = button; } - private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { - // Recursively traverse directory - GameBoardFacade facade = GameBoardFacade.getInstance(); + toolBar = new JToolBar(); + toolBar.setFloatable(false); + toolBar.setRollover(true); - // Folder is empty - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,,Ungradeable\n"); - return; + for (int i = 0; i < getToolBarButtons().length; i++) { + for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { + if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { + toolBar.addSeparator(); } + } + String toolBarName = ToolbarName.values()[i].toString(); - // Travese directory, recurse if sub-directory found - // If ungradeable, do not leave a score (0, 1) - for (final File f : Objects.requireNonNull(folder.listFiles())) { - // Recurse - if (f.isDirectory()) { - traverseDir(f, writer, path + "/" + f.getName()); - continue; - } - - // Set path name - writer.append(path).append(","); - - // Load puzzle, run checker - // If wrong file type, ungradeable - String fName = f.getName(); - String fPath = f.getAbsolutePath(); - File puzzleFile = new File(fPath); - if (puzzleFile.exists()) { - // Try to load file. If invalid, note in csv - try { - // Load puzzle, run checker - GameBoardFacade.getInstance().loadPuzzle(fPath); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - - // Write data - writer.append(fName).append(","); - writer.append(puzzle.getName()).append(","); - if (puzzle.isPuzzleComplete()) { - writer.append("1,Solved\n"); - } else { - writer.append("0,Unsolved\n"); - } - } catch (InvalidFileFormatException e) { - writer.append(fName).append(",Invalid,,Ungradeable\n"); - } - } else { - LOGGER.debug("Failed to run sim"); - } - } - } + toolBar.add(getToolBarButtons()[i]); + getToolBarButtons()[i].setToolTipText(toolBarName); - public BoardView getBoardView() { - return boardView; + getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); + getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); } - public DynamicView getDynamicBoardView() { - return dynamicBoardView; + // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent + // e) -> + // promptPuzzle()); + // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> + // saveProof()); + // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().undo()); + // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().redo()); + toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener((ActionEvent e) -> checkProof()); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); + + toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener( + (ActionEvent e) -> checkProofAll()); + + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true); + + this.add(toolBar, BorderLayout.NORTH); + } + + /** + * Sets the toolbar buttons + * + * @param toolBarButtons toolbar buttons + */ + public void setToolBarButtons(JButton[] toolBarButtons) { + this.toolBarButtons = toolBarButtons; + } + + /** + * Gets the toolbar buttons + * + * @return toolbar buttons + */ + public JButton[] getToolBarButtons() { + return toolBarButtons; + } + + /** Checks the proof for correctness */ + private void checkProof() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + Tree tree = GameBoardFacade.getInstance().getTree(); + Board board = facade.getBoard(); + Board finalBoard = null; + boolean delayStatus = true; // board.evalDelayStatus(); + + repaintAll(); + + Puzzle puzzle = facade.getPuzzleModule(); + + if (puzzle.isPuzzleComplete()) { + // This is for submission which is not integrated yet + /*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); + if (confirm == JOptionPane.YES_OPTION) { + Submission submission = new Submission(board); + submission.submit(); + }*/ + JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct."); + } else { + String message = "\nThe game board is not solved."; + JOptionPane.showMessageDialog(null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE); } + } + + private void repaintAll() { + boardView.repaint(); + treePanel.repaint(); + } + + public void setPuzzleView(Puzzle puzzle) { + this.boardView = puzzle.getBoardView(); + + dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); + this.topHalfPanel.setRightComponent(dynamicBoardView); + this.topHalfPanel.setVisible(true); + String boardType = boardView.getBoard().getClass().getSimpleName(); + boardType = boardType.substring(0, boardType.indexOf("Board")); + TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + this.treePanel.getTreeView().resetView(); + this.treePanel.getTreeView().setTree(puzzle.getTree()); + + puzzle.addTreeListener(treePanel.getTreeView()); + puzzle.addBoardListener(puzzle.getBoardView()); + + ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules()); + ruleFrame.getCasePanel().setRules(puzzle.getCaseRules()); + ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules()); + ruleFrame.getSearchPanel().setSearchBar(puzzle); + + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); + + reloadGui(); + } + + public void reloadGui() { + repaintTree(); + } + + public void repaintTree() { + treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree()); + } + + /** Checks the proof for all files */ + private void checkProofAll() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ - public TreePanel getTreePanel() { - return treePanel; + LegupPreferences preferences = LegupPreferences.getInstance(); + File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); + folderBrowser = new JFileChooser(preferredDirectory); + + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + + File folder = folderBrowser.getSelectedFile(); + + // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); + + // Go through student folders + for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + // Write path + String path = folderEntry.getName(); + traverseDir(folderEntry, writer, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } + JOptionPane.showMessageDialog(null, "Batch grading complete."); + } - /** - * Called when a action is pushed onto the edu.rpi.legup.history stack - * - * @param command action to push onto the stack - */ - @Override - public void onPushChange(ICommand command) { - LOGGER.info("Pushing " + command.getClass().getSimpleName() + " to stack."); - undo.setEnabled(true); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(true); - redo.setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + private boolean basicCheckProof(int[][] origCells) { + return false; + } - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); - } + private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { + // Recursively traverse directory + GameBoardFacade facade = GameBoardFacade.getInstance(); - /** Called when the history is cleared */ - @Override - public void onClearHistory() { - // undo.setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // redo.setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + // Folder is empty + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,,Ungradeable\n"); + return; } - /** - * Called when an action is redone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - @Override - public void onRedo(boolean isBottom, boolean isTop) { - undo.setEnabled(!isBottom); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); - redo.setEnabled(!isTop); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); - if (isBottom) { - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } else { - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + // Travese directory, recurse if sub-directory found + // If ungradeable, do not leave a score (0, 1) + for (final File f : Objects.requireNonNull(folder.listFiles())) { + // Recurse + if (f.isDirectory()) { + traverseDir(f, writer, path + "/" + f.getName()); + continue; + } + + // Set path name + writer.append(path).append(","); + + // Load puzzle, run checker + // If wrong file type, ungradeable + String fName = f.getName(); + String fPath = f.getAbsolutePath(); + File puzzleFile = new File(fPath); + if (puzzleFile.exists()) { + // Try to load file. If invalid, note in csv + try { + // Load puzzle, run checker + GameBoardFacade.getInstance().loadPuzzle(fPath); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + + // Write data + writer.append(fName).append(","); + writer.append(puzzle.getName()).append(","); + if (puzzle.isPuzzleComplete()) { + writer.append("1,Solved\n"); + } else { + writer.append("0,Unsolved\n"); + } + } catch (InvalidFileFormatException e) { + writer.append(fName).append(",Invalid,,Ungradeable\n"); } + } else { + LOGGER.debug("Failed to run sim"); + } } - - /** - * Called when an action is undone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - @Override - public void onUndo(boolean isBottom, boolean isTop) { - undo.setEnabled(!isBottom); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); - redo.setEnabled(!isTop); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - if (isBottom) { - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } else { - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); - } + } + + public BoardView getBoardView() { + return boardView; + } + + public DynamicView getDynamicBoardView() { + return dynamicBoardView; + } + + public TreePanel getTreePanel() { + return treePanel; + } + + /** + * Called when a action is pushed onto the edu.rpi.legup.history stack + * + * @param command action to push onto the stack + */ + @Override + public void onPushChange(ICommand command) { + LOGGER.info("Pushing " + command.getClass().getSimpleName() + " to stack."); + undo.setEnabled(true); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(true); + redo.setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + } + + /** Called when the history is cleared */ + @Override + public void onClearHistory() { + // undo.setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // redo.setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + } + + /** + * Called when an action is redone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + @Override + public void onRedo(boolean isBottom, boolean isTop) { + undo.setEnabled(!isBottom); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); + redo.setEnabled(!isTop); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); + if (isBottom) { + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } else { + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); } - - /** Submits the proof file */ - private void submit() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - Board board = facade.getBoard(); - boolean delayStatus = true; // board.evalDelayStatus(); - repaintAll(); - - Puzzle pm = facade.getPuzzleModule(); - if (pm.isPuzzleComplete() && delayStatus) { - // 0 means yes, 1 means no (Java's fault...) - int confirm = - JOptionPane.showConfirmDialog( - null, - "Are you sure you wish to submit?", - "Proof Submission", - JOptionPane.YES_NO_OPTION); - if (confirm == 0) { - Submission submission = new Submission(board); - submission.submit(); - } - } else { - JOptionPane.showConfirmDialog( - null, - "Your proof is incorrect! Are you sure you wish to submit?", - "Proof Submission", - JOptionPane.YES_NO_OPTION); - Submission submit = new Submission(board); - } + } + + /** + * Called when an action is undone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + @Override + public void onUndo(boolean isBottom, boolean isTop) { + undo.setEnabled(!isBottom); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); + redo.setEnabled(!isTop); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + if (isBottom) { + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } else { + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); } - - public void showStatus(String status, boolean error, int timer) { - // TODO: implement + } + + /** Submits the proof file */ + private void submit() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + Board board = facade.getBoard(); + boolean delayStatus = true; // board.evalDelayStatus(); + repaintAll(); + + Puzzle pm = facade.getPuzzleModule(); + if (pm.isPuzzleComplete() && delayStatus) { + // 0 means yes, 1 means no (Java's fault...) + int confirm = + JOptionPane.showConfirmDialog( + null, + "Are you sure you wish to submit?", + "Proof Submission", + JOptionPane.YES_NO_OPTION); + if (confirm == 0) { + Submission submission = new Submission(board); + submission.submit(); + } + } else { + JOptionPane.showConfirmDialog( + null, + "Your proof is incorrect! Are you sure you wish to submit?", + "Proof Submission", + JOptionPane.YES_NO_OPTION); + Submission submit = new Submission(board); } + } - protected void fitTreeViewToScreen() { - this.treePanel.getTreeView().zoomFit(); - } + public void showStatus(String status, boolean error, int timer) { + // TODO: implement + } + + protected void fitTreeViewToScreen() { + this.treePanel.getTreeView().zoomFit(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java b/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java index b3cd30ffb..91a042c4d 100644 --- a/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java +++ b/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java @@ -30,550 +30,532 @@ public class PuzzleEditorPanel extends LegupPanel implements IHistoryListener { - private static final Logger LOGGER = LogManager.getLogger(PuzzleEditorPanel.class.getName()); - private JMenu[] menus; - private JMenuItem helpLegup, aboutLegup; - private JMenuBar menuBar; - private JToolBar toolBar; - private JFrame frame; - private JButton[] buttons; + private static final Logger LOGGER = LogManager.getLogger(PuzzleEditorPanel.class.getName()); + private JMenu[] menus; + private JMenuItem helpLegup, aboutLegup; + private JMenuBar menuBar; + private JToolBar toolBar; + private JFrame frame; + private JButton[] buttons; + JSplitPane splitPanel; + private JButton[] toolBarButtons; + private JPanel elementPanel; + private DynamicView dynamicBoardView; + private BoardView boardView; + private TitledBorder boardBorder; + // private JSplitPane splitPanel, topHalfPanel; + private FileDialog fileDialog; + private JMenuItem undo, redo, fitBoardToScreen; + private ElementFrame elementFrame; + private JPanel treePanel; + private LegupUI legupUI; + private EditorElementController editorElementController; + static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; + + public PuzzleEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.fileDialog = fileDialog; + this.frame = frame; + this.legupUI = legupUI; + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(800, 700)); + } + + protected void setupContent() { JSplitPane splitPanel; - private JButton[] toolBarButtons; - private JPanel elementPanel; - private DynamicView dynamicBoardView; - private BoardView boardView; - private TitledBorder boardBorder; - // private JSplitPane splitPanel, topHalfPanel; - private FileDialog fileDialog; - private JMenuItem undo, redo, fitBoardToScreen; - private ElementFrame elementFrame; - private JPanel treePanel; - private LegupUI legupUI; - private EditorElementController editorElementController; - static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; - - public PuzzleEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.fileDialog = fileDialog; - this.frame = frame; - this.legupUI = legupUI; - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(800, 700)); + JPanel elementBox = new JPanel(new BorderLayout()); + + editorElementController = new EditorElementController(); + elementFrame = new ElementFrame(editorElementController); + elementBox.add(elementFrame, BorderLayout.WEST); + + dynamicBoardView = + new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); + TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + JPanel boardPanel = new JPanel(new BorderLayout()); + splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, elementFrame, dynamicBoardView); + splitPanel.setPreferredSize(new Dimension(600, 400)); + + boardPanel.add(splitPanel); + boardBorder = BorderFactory.createTitledBorder("Board"); + boardBorder.setTitleJustification(TitledBorder.CENTER); + + elementBox.add(boardPanel); + this.add(elementBox); + + splitPanel.setDividerLocation(splitPanel.getMaximumDividerLocation() + 100); + this.splitPanel = splitPanel; + revalidate(); + } + + public void setMenuBar() { + String os = LegupUI.getOS(); + menuBar = new JMenuBar(); + menus = new JMenu[3]; + + // create menus + + // FILE + menus[0] = new JMenu("File"); + + // file>new + JMenuItem newPuzzle = new JMenuItem("New"); + newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); } - - protected void setupContent() { - JSplitPane splitPanel; - JPanel elementBox = new JPanel(new BorderLayout()); - - editorElementController = new EditorElementController(); - elementFrame = new ElementFrame(editorElementController); - elementBox.add(elementFrame, BorderLayout.WEST); - - dynamicBoardView = - new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); - TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - JPanel boardPanel = new JPanel(new BorderLayout()); - splitPanel = - new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, elementFrame, dynamicBoardView); - splitPanel.setPreferredSize(new Dimension(600, 400)); - - boardPanel.add(splitPanel); - boardBorder = BorderFactory.createTitledBorder("Board"); - boardBorder.setTitleJustification(TitledBorder.CENTER); - - elementBox.add(boardPanel); - this.add(elementBox); - - splitPanel.setDividerLocation(splitPanel.getMaximumDividerLocation() + 100); - this.splitPanel = splitPanel; - revalidate(); + // file>save + JMenuItem savePuzzle = new JMenuItem("Save As"); + savePuzzle.addActionListener((ActionEvent) -> savePuzzle()); + JMenuItem directSavePuzzle = new JMenuItem("Direct Save Proof "); + directSavePuzzle.addActionListener((ActionEvent) -> direct_save()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); } - public void setMenuBar() { - String os = LegupUI.getOS(); - menuBar = new JMenuBar(); - menus = new JMenu[3]; - - // create menus - - // FILE - menus[0] = new JMenu("File"); - - // file>new - JMenuItem newPuzzle = new JMenuItem("New"); - newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke( - 'N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); - } - // file>save - JMenuItem savePuzzle = new JMenuItem("Save As"); - savePuzzle.addActionListener((ActionEvent) -> savePuzzle()); - JMenuItem directSavePuzzle = new JMenuItem("Direct Save Proof "); - directSavePuzzle.addActionListener((ActionEvent) -> direct_save()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke( - 'D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); - } - - JMenuItem exit = new JMenuItem("Exit"); - exit.addActionListener((ActionEvent) -> exitEditor()); - if (os.equals("mac")) { - exit.setAccelerator( - KeyStroke.getKeyStroke( - 'Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); - } - menus[0].add(newPuzzle); - menus[0].add(savePuzzle); - menus[0].add(directSavePuzzle); - menus[0].add(exit); - - // EDIT - menus[1] = new JMenu("Edit"); - // edit>undo - undo = new JMenuItem("Undo"); - // edit>redo - redo = new JMenuItem("Redo"); - fitBoardToScreen = new JMenuItem("Fit Board to Screen"); - - menus[1].add(undo); - undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); - if (os.equals("mac")) { - undo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); - } - - menus[1].add(redo); - - // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) - Action redoAction = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - GameBoardFacade.getInstance().getHistory().redo(); - } - }; - if (os.equals("mac")) { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() - + InputEvent.SHIFT_DOWN_MASK), - "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "redoAction"); - redo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() - + InputEvent.SHIFT_DOWN_MASK)); - } else { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), - "redoAction"); - redo.getActionMap().put("redoAction", redoAction); - - // Button in menu will show CTRL-SHIFT-Z as primary keybind - redo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); - } - - menus[1].add(fitBoardToScreen); - fitBoardToScreen.addActionListener( - (ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); - - // HELP - menus[2] = new JMenu("Help"); - helpLegup = new JMenuItem("Help Legup"); - aboutLegup = new JMenuItem("About Legup"); - menus[2].add(helpLegup); - menus[2].add(aboutLegup); - helpLegup.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop() - .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - menus[2].add(aboutLegup); - aboutLegup.addActionListener( - l -> { - JOptionPane.showMessageDialog(null, "Version: 5.1.0"); - }); - // add menus to menubar - for (JMenu menu : menus) { - menuBar.add(menu); - } - frame.setJMenuBar(menuBar); + JMenuItem exit = new JMenuItem("Exit"); + exit.addActionListener((ActionEvent) -> exitEditor()); + if (os.equals("mac")) { + exit.setAccelerator( + KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); } - - public void exitEditor() { - // Wipes the puzzle entirely as if LEGUP just started - GameBoardFacade.getInstance().clearPuzzle(); - this.legupUI.displayPanel(0); - treePanel = null; - boardView = null; + menus[0].add(newPuzzle); + menus[0].add(savePuzzle); + menus[0].add(directSavePuzzle); + menus[0].add(exit); + + // EDIT + menus[1] = new JMenu("Edit"); + // edit>undo + undo = new JMenuItem("Undo"); + // edit>redo + redo = new JMenuItem("Redo"); + fitBoardToScreen = new JMenuItem("Fit Board to Screen"); + + menus[1].add(undo); + undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); + if (os.equals("mac")) { + undo.setAccelerator( + KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); } - @Override - public void makeVisible() { - this.removeAll(); - - setupToolBar(); - setupContent(); - setMenuBar(); + menus[1].add(redo); + + // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) + Action redoAction = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + GameBoardFacade.getInstance().getHistory().redo(); + } + }; + if (os.equals("mac")) { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK), + "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "redoAction"); + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); + } else { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), + "redoAction"); + redo.getActionMap().put("redoAction", redoAction); + + // Button in menu will show CTRL-SHIFT-Z as primary keybind + redo.setAccelerator( + KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); } - private void setupToolBar() { - setToolBarButtons(new JButton[ToolbarName.values().length + 1]); - int lastone = 0; - for (int i = 0; i < ToolbarName.values().length - 1; i++) { - String toolBarName = ToolbarName.values()[i].toString(); - URL resourceLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); - - // Scale the image icons down to make the buttons smaller - ImageIcon imageIcon = new ImageIcon(resourceLocation); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, - this.TOOLBAR_ICON_SCALE, - Image.SCALE_SMOOTH)); - - JButton button = new JButton(toolBarName, imageIcon); - button.setFocusPainted(false); - getToolBarButtons()[i] = button; - lastone = i; - } - - URL check_and_save = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Check.png"); - ImageIcon imageIcon = new ImageIcon(check_and_save); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, - this.TOOLBAR_ICON_SCALE, - Image.SCALE_SMOOTH)); - - JButton checkandsave = new JButton("check and Save", imageIcon); - checkandsave.setFocusPainted(false); - checkandsave.addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // savePuzzle(); - String filename = savePuzzle(); - File puzzlename = new File(filename); - System.out.println(filename); - - GameBoardFacade.getInstance().getLegupUI().displayPanel(1); - GameBoardFacade.getInstance() - .getLegupUI() - .getProofEditor() - .loadPuzzle(filename, new File(filename)); - String puzzleName = - GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzlename.getName()); - } - }); - getToolBarButtons()[lastone + 1] = checkandsave; - System.out.println("it is create new file"); - - toolBar = new JToolBar(); - toolBar.setFloatable(false); - toolBar.setRollover(true); - - for (int i = 0; i < getToolBarButtons().length - 1; i++) { - for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { - if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { - toolBar.addSeparator(); - } - } - String toolBarName = ToolbarName.values()[i].toString(); - - toolBar.add(getToolBarButtons()[i]); - getToolBarButtons()[i].setToolTipText(toolBarName); - - getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); - getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); - } - - // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent - // e) -> - // promptPuzzle()); - // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> - // saveProof()); - // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().undo()); - // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().redo()); - toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); - - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); - - this.add(toolBar, BorderLayout.NORTH); + menus[1].add(fitBoardToScreen); + fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); + + // HELP + menus[2] = new JMenu("Help"); + helpLegup = new JMenuItem("Help Legup"); + aboutLegup = new JMenuItem("About Legup"); + menus[2].add(helpLegup); + menus[2].add(aboutLegup); + helpLegup.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + menus[2].add(aboutLegup); + aboutLegup.addActionListener( + l -> { + JOptionPane.showMessageDialog(null, "Version: 5.1.0"); + }); + // add menus to menubar + for (JMenu menu : menus) { + menuBar.add(menu); } - - public void loadPuzzleFromHome(String game, int rows, int columns) - throws IllegalArgumentException { - GameBoardFacade facade = GameBoardFacade.getInstance(); - try { - facade.loadPuzzle(game, rows, columns); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (RuntimeException e) { - e.printStackTrace(); - LOGGER.error(e.getMessage()); - } + frame.setJMenuBar(menuBar); + } + + public void exitEditor() { + // Wipes the puzzle entirely as if LEGUP just started + GameBoardFacade.getInstance().clearPuzzle(); + this.legupUI.displayPanel(0); + treePanel = null; + boardView = null; + } + + @Override + public void makeVisible() { + this.removeAll(); + + setupToolBar(); + setupContent(); + setMenuBar(); + } + + private void setupToolBar() { + setToolBarButtons(new JButton[ToolbarName.values().length + 1]); + int lastone = 0; + for (int i = 0; i < ToolbarName.values().length - 1; i++) { + String toolBarName = ToolbarName.values()[i].toString(); + URL resourceLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); + + // Scale the image icons down to make the buttons smaller + ImageIcon imageIcon = new ImageIcon(resourceLocation); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); + + JButton button = new JButton(toolBarName, imageIcon); + button.setFocusPainted(false); + getToolBarButtons()[i] = button; + lastone = i; } - public void loadPuzzleFromHome(String game, String[] statements) { - GameBoardFacade facade = GameBoardFacade.getInstance(); - try { - facade.loadPuzzle(game, statements); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (RuntimeException e) { - e.printStackTrace(); - LOGGER.error(e.getMessage()); + URL check_and_save = + ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Check.png"); + ImageIcon imageIcon = new ImageIcon(check_and_save); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); + + JButton checkandsave = new JButton("check and Save", imageIcon); + checkandsave.setFocusPainted(false); + checkandsave.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // savePuzzle(); + String filename = savePuzzle(); + File puzzlename = new File(filename); + System.out.println(filename); + + GameBoardFacade.getInstance().getLegupUI().displayPanel(1); + GameBoardFacade.getInstance() + .getLegupUI() + .getProofEditor() + .loadPuzzle(filename, new File(filename)); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzlename.getName()); + } + }); + getToolBarButtons()[lastone + 1] = checkandsave; + System.out.println("it is create new file"); + + toolBar = new JToolBar(); + toolBar.setFloatable(false); + toolBar.setRollover(true); + + for (int i = 0; i < getToolBarButtons().length - 1; i++) { + for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { + if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { + toolBar.addSeparator(); } - } + } + String toolBarName = ToolbarName.values()[i].toString(); - // File opener - public Object[] promptPuzzle() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - if (facade.getBoard() != null) { - if (noQuit("Opening a new puzzle to edit?")) { - return new Object[0]; - } - } - if (fileDialog == null) { - fileDialog = new FileDialog(this.frame); - } - LegupPreferences preferences = LegupPreferences.getInstance(); - String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); - - fileDialog.setMode(FileDialog.LOAD); - fileDialog.setTitle("Select Puzzle"); - fileDialog.setDirectory(preferredDirectory); - fileDialog.setVisible(true); - String fileName = null; - File puzzleFile = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - puzzleFile = new File(fileName); - } else { - // The attempt to prompt a puzzle ended gracefully (cancel) - return null; - } + toolBar.add(getToolBarButtons()[i]); + getToolBarButtons()[i].setToolTipText(toolBarName); - return new Object[] {fileName, puzzleFile}; + getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); + getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); } - public void loadPuzzle() { - Object[] items = promptPuzzle(); - // Return if items == null (cancel) - if (items == null) { - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - loadPuzzle(fileName, puzzleFile); + // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent + // e) -> + // promptPuzzle()); + // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> + // saveProof()); + // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().undo()); + // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().redo()); + toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); + + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + + this.add(toolBar, BorderLayout.NORTH); + } + + public void loadPuzzleFromHome(String game, int rows, int columns) + throws IllegalArgumentException { + GameBoardFacade facade = GameBoardFacade.getInstance(); + try { + facade.loadPuzzle(game, rows, columns); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (RuntimeException e) { + e.printStackTrace(); + LOGGER.error(e.getMessage()); } - - public void loadPuzzle(String fileName, File puzzleFile) { - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(2); - GameBoardFacade.getInstance().loadPuzzleEditor(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } catch (InvalidFileFormatException e) { - legupUI.displayPanel(0); - LOGGER.error(e.getMessage()); - JOptionPane.showMessageDialog( - null, - "File does not exist, cannot be read, or cannot be edited", - "Error", - JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } - } + } + + public void loadPuzzleFromHome(String game, String[] statements) { + GameBoardFacade facade = GameBoardFacade.getInstance(); + try { + facade.loadPuzzle(game, statements); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (RuntimeException e) { + e.printStackTrace(); + LOGGER.error(e.getMessage()); } - - public boolean noQuit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; + } + + // File opener + public Object[] promptPuzzle() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + if (facade.getBoard() != null) { + if (noQuit("Opening a new puzzle to edit?")) { + return new Object[0]; + } + } + if (fileDialog == null) { + fileDialog = new FileDialog(this.frame); + } + LegupPreferences preferences = LegupPreferences.getInstance(); + String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); + + fileDialog.setMode(FileDialog.LOAD); + fileDialog.setTitle("Select Puzzle"); + fileDialog.setDirectory(preferredDirectory); + fileDialog.setVisible(true); + String fileName = null; + File puzzleFile = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + puzzleFile = new File(fileName); + } else { + // The attempt to prompt a puzzle ended gracefully (cancel) + return null; } - @Override - public void onPushChange(ICommand command) {} - - @Override - public void onUndo(boolean isBottom, boolean isTop) {} - - @Override - public void onRedo(boolean isBottom, boolean isTop) {} + return new Object[] {fileName, puzzleFile}; + } - @Override - public void onClearHistory() { - // undo.setEnabled(false); - // redo.setEnabled(false); + public void loadPuzzle() { + Object[] items = promptPuzzle(); + // Return if items == null (cancel) + if (items == null) { + return; } - - public BoardView getBoardView() { - return boardView; + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + loadPuzzle(fileName, puzzleFile); + } + + public void loadPuzzle(String fileName, File puzzleFile) { + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(2); + GameBoardFacade.getInstance().loadPuzzleEditor(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } catch (InvalidFileFormatException e) { + legupUI.displayPanel(0); + LOGGER.error(e.getMessage()); + JOptionPane.showMessageDialog( + null, + "File does not exist, cannot be read, or cannot be edited", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } } - - public JButton[] getToolBarButtons() { - return toolBarButtons; + } + + public boolean noQuit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + @Override + public void onPushChange(ICommand command) {} + + @Override + public void onUndo(boolean isBottom, boolean isTop) {} + + @Override + public void onRedo(boolean isBottom, boolean isTop) {} + + @Override + public void onClearHistory() { + // undo.setEnabled(false); + // redo.setEnabled(false); + } + + public BoardView getBoardView() { + return boardView; + } + + public JButton[] getToolBarButtons() { + return toolBarButtons; + } + + public void setToolBarButtons(JButton[] toolBarButtons) { + this.toolBarButtons = toolBarButtons; + } + + private void repaintAll() { + boardView.repaint(); + } + + public void setPuzzleView(Puzzle puzzle) { + this.boardView = puzzle.getBoardView(); + editorElementController.setElementController(boardView.getElementController()); + dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); + if (this.splitPanel != null) { + this.splitPanel.setRightComponent(dynamicBoardView); + this.splitPanel.setVisible(true); } - public void setToolBarButtons(JButton[] toolBarButtons) { - this.toolBarButtons = toolBarButtons; - } + TitledBorder titleBoard = + BorderFactory.createTitledBorder(boardView.getClass().getSimpleName()); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); - private void repaintAll() { - boardView.repaint(); + puzzle.addBoardListener(puzzle.getBoardView()); + System.out.println("Setting elements"); + if (this.elementFrame != null) { + elementFrame.setElements(puzzle); } - public void setPuzzleView(Puzzle puzzle) { - this.boardView = puzzle.getBoardView(); - editorElementController.setElementController(boardView.getElementController()); - dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); - if (this.splitPanel != null) { - this.splitPanel.setRightComponent(dynamicBoardView); - this.splitPanel.setVisible(true); - } - - TitledBorder titleBoard = - BorderFactory.createTitledBorder(boardView.getClass().getSimpleName()); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); + } - puzzle.addBoardListener(puzzle.getBoardView()); - System.out.println("Setting elements"); - if (this.elementFrame != null) { - elementFrame.setElements(puzzle); - } - - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); + /** Saves a puzzle */ + private void direct_save() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; } - - /** Saves a puzzle */ - private void direct_save() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } } + } - private String savePuzzle() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return ""; - } + private String savePuzzle() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return ""; + } - // for TreeTent, need to check validity before saving - if (Objects.equals(puzzle.getName(), "TreeTent")) { - if (!puzzle.checkValidity()) { - int input = - JOptionPane.showConfirmDialog( - null, - "The puzzle you edited is not " - + "valid, would you still like to save? "); - if (input != 0) { - return ""; - } - } + // for TreeTent, need to check validity before saving + if (Objects.equals(puzzle.getName(), "TreeTent")) { + if (!puzzle.checkValidity()) { + int input = + JOptionPane.showConfirmDialog( + null, "The puzzle you edited is not " + "valid, would you still like to save? "); + if (input != 0) { + return ""; } + } + } - if (fileDialog == null) { - fileDialog = new FileDialog(this.frame); - } + if (fileDialog == null) { + fileDialog = new FileDialog(this.frame); + } - fileDialog.setMode(FileDialog.SAVE); - fileDialog.setTitle("Save Proof"); - String curFileName = GameBoardFacade.getInstance().getCurFileName(); - if (curFileName == null) { - fileDialog.setDirectory( - LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); - } else { - File curFile = new File(curFileName); - fileDialog.setDirectory(curFile.getParent()); - } - fileDialog.setVisible(true); + fileDialog.setMode(FileDialog.SAVE); + fileDialog.setTitle("Save Proof"); + String curFileName = GameBoardFacade.getInstance().getCurFileName(); + if (curFileName == null) { + fileDialog.setDirectory( + LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); + } else { + File curFile = new File(curFileName); + fileDialog.setDirectory(curFile.getParent()); + } + fileDialog.setVisible(true); - String fileName = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - } + String fileName = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + } - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); - } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); } - return fileName; + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } } + return fileName; + } - public DynamicView getDynamicBoardView() { - return dynamicBoardView; - } + public DynamicView getDynamicBoardView() { + return dynamicBoardView; + } } diff --git a/src/main/java/edu/rpi/legup/ui/ScrollView.java b/src/main/java/edu/rpi/legup/ui/ScrollView.java index 0bf8335a2..5d072ebf5 100644 --- a/src/main/java/edu/rpi/legup/ui/ScrollView.java +++ b/src/main/java/edu/rpi/legup/ui/ScrollView.java @@ -7,310 +7,307 @@ import javax.swing.*; public class ScrollView extends JScrollPane { - private static final Logger LOGGER = Logger.getLogger(ScrollView.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ScrollView.class.getName()); - private static final double minScale = 0.25; - private static final double maxScale = 4.0; - private static final double[] levels = {0.25, 1.0 / 3.0, 0.50, 2.0 / 3.0, 1.0, 2.0, 3.0, 4.0}; + private static final double minScale = 0.25; + private static final double maxScale = 4.0; + private static final double[] levels = {0.25, 1.0 / 3.0, 0.50, 2.0 / 3.0, 1.0, 2.0, 3.0, 4.0}; - private Dimension viewSize; - private Dimension zoomSize; - private TreeSet zoomLevels; + private Dimension viewSize; + private Dimension zoomSize; + private TreeSet zoomLevels; - private double scale; + private double scale; - private Controller controller; - private ZoomablePane canvas; - private ZoomWidget widget; + private Controller controller; + private ZoomablePane canvas; + private ZoomWidget widget; - /** - * ScrollView Constructor - creates a ScrollView object using the controller handle the ui - * events - * - * @param controller controller that handles the ui events - */ - public ScrollView(Controller controller) { - super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS); + /** + * ScrollView Constructor - creates a ScrollView object using the controller handle the ui events + * + * @param controller controller that handles the ui events + */ + public ScrollView(Controller controller) { + super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS); - viewSize = new Dimension(); - zoomSize = new Dimension(); - scale = 1.0; + viewSize = new Dimension(); + zoomSize = new Dimension(); + scale = 1.0; - this.canvas = new ZoomablePane(this); + this.canvas = new ZoomablePane(this); - viewport.setView(canvas); + viewport.setView(canvas); - zoomLevels = new TreeSet<>(); - for (Double level : levels) { - zoomLevels.add(level); - } - - widget = new ZoomWidget(this); - setCorner(JScrollPane.LOWER_RIGHT_CORNER, widget); - - setWheelScrollingEnabled(false); - - this.controller = controller; - controller.setViewer(this); - canvas.addMouseMotionListener(controller); - canvas.addMouseListener(controller); - viewport.addMouseWheelListener(controller); - viewport.addMouseListener(controller); - viewport.addMouseMotionListener(controller); + zoomLevels = new TreeSet<>(); + for (Double level : levels) { + zoomLevels.add(level); } - /** - * Creates a customized viewport for the scroll pane - * - * @return viewport for the scroll pane - */ - @Override - protected JViewport createViewport() { - return new JViewport() { - @Override - protected LayoutManager createLayoutManager() { - return new ViewportLayout() { - @Override - public void layoutContainer(Container parent) { - Point point = viewport.getViewPosition(); - // determine the maximum x and y view positions - int mx = canvas.getWidth() - viewport.getWidth(); - int my = canvas.getHeight() - viewport.getHeight(); - // obey edge boundaries - if (point.x < 0) { - point.x = 0; - } - if (point.x > mx) { - point.x = mx; - } - if (point.y < 0) { - point.y = 0; - } - if (point.y > my) { - point.y = my; - } - // center margins - if (mx < 0) { - point.x = mx / 2; - } - if (my < 0) { - point.y = my / 2; - } - viewport.setViewPosition(point); - } - }; + widget = new ZoomWidget(this); + setCorner(JScrollPane.LOWER_RIGHT_CORNER, widget); + + setWheelScrollingEnabled(false); + + this.controller = controller; + controller.setViewer(this); + canvas.addMouseMotionListener(controller); + canvas.addMouseListener(controller); + viewport.addMouseWheelListener(controller); + viewport.addMouseListener(controller); + viewport.addMouseMotionListener(controller); + } + + /** + * Creates a customized viewport for the scroll pane + * + * @return viewport for the scroll pane + */ + @Override + protected JViewport createViewport() { + return new JViewport() { + @Override + protected LayoutManager createLayoutManager() { + return new ViewportLayout() { + @Override + public void layoutContainer(Container parent) { + Point point = viewport.getViewPosition(); + // determine the maximum x and y view positions + int mx = canvas.getWidth() - viewport.getWidth(); + int my = canvas.getHeight() - viewport.getHeight(); + // obey edge boundaries + if (point.x < 0) { + point.x = 0; } - }; - } - - /** Updates zoomSize and view viewSize with the new scale */ - private void updateSize() { - zoomSize.setSize((int) (viewSize.width * scale), (int) (viewSize.height * scale)); - viewport.setViewSize(zoomSize); - } - - /** - * Updates the viewport position - * - * @param point point to set the viewport to - * @param magnification magnification to set the viewport to - */ - public void updatePosition(Point point, double magnification) { - Point position = viewport.getViewPosition(); - position.x = (int) ((double) (point.x + position.x) * magnification - point.x + 0.0); - position.y = (int) ((double) (point.y + position.y) * magnification - point.y + 0.0); - viewport.setViewPosition(position); - } - - /** - * Zooms in or out on a position within the dynamicView - * - * @param n level of zoom - n less than 0 is zoom in, n greater than 0 is zoom out - * @param point position to zoom in on - */ - public void zoom(int n, Point point) { - // if no Point is given, keep current center - if (point == null) { - point = - new Point( - viewport.getWidth() / 2 + viewport.getX(), - viewport.getHeight() / 2 + viewport.getY()); - } - // magnification level - double mag = (double) n * 1.05; - // zoom in - if (n < 0) { - mag = -mag; - // check zoom bounds - if (scale * mag > maxScale) { - mag = maxScale / scale; + if (point.x > mx) { + point.x = mx; } - // update - scale *= mag; - updateSize(); - updatePosition(point, mag); - // zoom out - } else { - mag = 1 / mag; - // check zoom bounds - if (scale * mag < minScale) { - mag = minScale / scale; + if (point.y < 0) { + point.y = 0; } - // update - scale *= mag; - updatePosition(point, mag); - updateSize(); - } - // update the scrollpane and subclass - revalidate(); - } - - public void zoomTo(double newScale) { - // check zoom bounds - if (newScale < minScale) { - newScale = minScale; - } - if (newScale > maxScale) { - newScale = maxScale; - } - if (newScale == scale) { - return; - } - // calculate the newScale and center point - double mag = newScale / scale; - Point p = - new Point( - viewport.getWidth() / 2 + viewport.getX(), - viewport.getHeight() / 2 + viewport.getY()); - - // set scale directly - scale = newScale; - // zoom in - if (mag > 1.0) { - updateSize(); - updatePosition(p, mag); - // zoom out - } else { - updatePosition(p, mag); - updateSize(); - } - // update the scrollpane and subclass - revalidate(); - } - - /** Get the ideal zoom based on the viewSize */ - public void zoomFit() { - if (viewport.getWidth() != 0 && viewport.getHeight() != 0) { - double fitWidth = (viewport.getWidth() - 8.0) / viewSize.width; - double fitHeight = (viewport.getHeight() - 8.0) / viewSize.height; - - zoomTo(Math.min(fitWidth, fitHeight)); - } - } - - /** Zooms in to the next zoom level */ - public void zoomIn() { - // find the next valid zoom level - Double newScale = zoomLevels.higher(scale); - if (newScale != null) { - zoomTo(newScale); - } + if (point.y > my) { + point.y = my; + } + // center margins + if (mx < 0) { + point.x = mx / 2; + } + if (my < 0) { + point.y = my / 2; + } + viewport.setViewPosition(point); + } + }; + } + }; + } + + /** Updates zoomSize and view viewSize with the new scale */ + private void updateSize() { + zoomSize.setSize((int) (viewSize.width * scale), (int) (viewSize.height * scale)); + viewport.setViewSize(zoomSize); + } + + /** + * Updates the viewport position + * + * @param point point to set the viewport to + * @param magnification magnification to set the viewport to + */ + public void updatePosition(Point point, double magnification) { + Point position = viewport.getViewPosition(); + position.x = (int) ((double) (point.x + position.x) * magnification - point.x + 0.0); + position.y = (int) ((double) (point.y + position.y) * magnification - point.y + 0.0); + viewport.setViewPosition(position); + } + + /** + * Zooms in or out on a position within the dynamicView + * + * @param n level of zoom - n less than 0 is zoom in, n greater than 0 is zoom out + * @param point position to zoom in on + */ + public void zoom(int n, Point point) { + // if no Point is given, keep current center + if (point == null) { + point = + new Point( + viewport.getWidth() / 2 + viewport.getX(), + viewport.getHeight() / 2 + viewport.getY()); } - - /** Zooms out to the previous zoom level */ - public void zoomOut() { - // find the next valid zoom level - Double newScale = zoomLevels.lower(scale); - if (newScale != null) { - zoomTo(newScale); - } + // magnification level + double mag = (double) n * 1.05; + // zoom in + if (n < 0) { + mag = -mag; + // check zoom bounds + if (scale * mag > maxScale) { + mag = maxScale / scale; + } + // update + scale *= mag; + updateSize(); + updatePosition(point, mag); + // zoom out + } else { + mag = 1 / mag; + // check zoom bounds + if (scale * mag < minScale) { + mag = minScale / scale; + } + // update + scale *= mag; + updatePosition(point, mag); + updateSize(); } - - /** - * Converts canvas coordinates to draw coordinates - * - * @param point canvas coordinate - * @return draw coordinate as Point - */ - public Point getActualPoint(Point point) { - return new Point((int) (point.x / scale), (int) (point.y / scale)); + // update the scrollpane and subclass + revalidate(); + } + + public void zoomTo(double newScale) { + // check zoom bounds + if (newScale < minScale) { + newScale = minScale; } - - /** - * Gets the zoom amount - * - * @return zoom scale - */ - public int getZoom() { - return (int) (scale * 100.0); + if (newScale > maxScale) { + newScale = maxScale; } - - /** - * Gets the scale for the dynamic dynamicView - * - * @return scale of the dynamic dynamicView - */ - public double getScale() { - return scale; + if (newScale == scale) { + return; } - - /** - * Sets the background of the viewport - * - * @param c color of the background - */ - public void setBackground(Color c) { - viewport.setBackground(c); + // calculate the newScale and center point + double mag = newScale / scale; + Point p = + new Point( + viewport.getWidth() / 2 + viewport.getX(), viewport.getHeight() / 2 + viewport.getY()); + + // set scale directly + scale = newScale; + // zoom in + if (mag > 1.0) { + updateSize(); + updatePosition(p, mag); + // zoom out + } else { + updatePosition(p, mag); + updateSize(); } + // update the scrollpane and subclass + revalidate(); + } - /** - * Gets the dimension of the viewport - * - * @return dimension of the viewport - */ - public Dimension getSize() { - return viewSize; - } + /** Get the ideal zoom based on the viewSize */ + public void zoomFit() { + if (viewport.getWidth() != 0 && viewport.getHeight() != 0) { + double fitWidth = (viewport.getWidth() - 8.0) / viewSize.width; + double fitHeight = (viewport.getHeight() - 8.0) / viewSize.height; - /** - * Sets the dimension of the viewport - * - * @param size new dimension of the viewport - */ - public void setSize(Dimension size) { - this.viewSize = size; - updateSize(); + zoomTo(Math.min(fitWidth, fitHeight)); } - - public ZoomablePane getCanvas() { - return canvas; + } + + /** Zooms in to the next zoom level */ + public void zoomIn() { + // find the next valid zoom level + Double newScale = zoomLevels.higher(scale); + if (newScale != null) { + zoomTo(newScale); } - - /** - * Draws the ScrollView - * - * @param graphics2D Graphics2D object used for drawing - */ - protected void draw(Graphics2D graphics2D) { - graphics2D.setRenderingHint( - RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics2D.setRenderingHint( - RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); - canvas.paint(graphics2D); - } - - /** - * Scroll up or down on the ScrollView - * - * @param mag The magnitude for scroll up positive is scroll up, negative is scroll down, - * recommend to use getWheelRotation() as the mag - */ - public void scroll(int mag) { - Point point = super.viewport.getViewPosition(); - // the point changing speed changes with the scale - point.y += mag * getZoom() / 20; - viewport.setViewPosition(point); - updateSize(); - revalidate(); + } + + /** Zooms out to the previous zoom level */ + public void zoomOut() { + // find the next valid zoom level + Double newScale = zoomLevels.lower(scale); + if (newScale != null) { + zoomTo(newScale); } + } + + /** + * Converts canvas coordinates to draw coordinates + * + * @param point canvas coordinate + * @return draw coordinate as Point + */ + public Point getActualPoint(Point point) { + return new Point((int) (point.x / scale), (int) (point.y / scale)); + } + + /** + * Gets the zoom amount + * + * @return zoom scale + */ + public int getZoom() { + return (int) (scale * 100.0); + } + + /** + * Gets the scale for the dynamic dynamicView + * + * @return scale of the dynamic dynamicView + */ + public double getScale() { + return scale; + } + + /** + * Sets the background of the viewport + * + * @param c color of the background + */ + public void setBackground(Color c) { + viewport.setBackground(c); + } + + /** + * Gets the dimension of the viewport + * + * @return dimension of the viewport + */ + public Dimension getSize() { + return viewSize; + } + + /** + * Sets the dimension of the viewport + * + * @param size new dimension of the viewport + */ + public void setSize(Dimension size) { + this.viewSize = size; + updateSize(); + } + + public ZoomablePane getCanvas() { + return canvas; + } + + /** + * Draws the ScrollView + * + * @param graphics2D Graphics2D object used for drawing + */ + protected void draw(Graphics2D graphics2D) { + graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics2D.setRenderingHint( + RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + canvas.paint(graphics2D); + } + + /** + * Scroll up or down on the ScrollView + * + * @param mag The magnitude for scroll up positive is scroll up, negative is scroll down, + * recommend to use getWheelRotation() as the mag + */ + public void scroll(int mag) { + Point point = super.viewport.getViewPosition(); + // the point changing speed changes with the scale + point.y += mag * getZoom() / 20; + viewport.setViewPosition(point); + updateSize(); + revalidate(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ToolbarName.java b/src/main/java/edu/rpi/legup/ui/ToolbarName.java index ba02ebd2e..1e0cbe7fb 100644 --- a/src/main/java/edu/rpi/legup/ui/ToolbarName.java +++ b/src/main/java/edu/rpi/legup/ui/ToolbarName.java @@ -1,30 +1,30 @@ package edu.rpi.legup.ui; public enum ToolbarName { - HINT, - CHECK, - SUBMIT, - DIRECTIONS, - CHECK_ALL; + HINT, + CHECK, + SUBMIT, + DIRECTIONS, + CHECK_ALL; - /** - * Gets the String representation of the ToolbarName enum - * - * @return String representing the enum - */ - public String toString() { - String str = super.toString(); - str = str.replace("_", " "); - str = str.toLowerCase(); - str = str.substring(0, 1).toUpperCase() + str.substring(1); - for (int i = 0; i < str.length(); i++) { - if (str.charAt(i) == ' ') { - str = - str.substring(0, i + 1) - + str.substring(i + 1, i + 2).toUpperCase() - + str.substring(i + 2); - } - } - return str; + /** + * Gets the String representation of the ToolbarName enum + * + * @return String representing the enum + */ + public String toString() { + String str = super.toString(); + str = str.replace("_", " "); + str = str.toLowerCase(); + str = str.substring(0, 1).toUpperCase() + str.substring(1); + for (int i = 0; i < str.length(); i++) { + if (str.charAt(i) == ' ') { + str = + str.substring(0, i + 1) + + str.substring(i + 1, i + 2).toUpperCase() + + str.substring(i + 2); + } } + return str; + } } diff --git a/src/main/java/edu/rpi/legup/ui/WrapLayout.java b/src/main/java/edu/rpi/legup/ui/WrapLayout.java index 1e25b36d2..085e09738 100644 --- a/src/main/java/edu/rpi/legup/ui/WrapLayout.java +++ b/src/main/java/edu/rpi/legup/ui/WrapLayout.java @@ -6,162 +6,162 @@ /** FlowLayout subclass that fully supports wrapping of components. */ public class WrapLayout extends FlowLayout { - private Dimension preferredLayoutSize; - - /** - * Constructs a new WrapLayout with a left alignment and a default 5-unit - * horizontal and vertical gap. - */ - public WrapLayout() { - super(LEFT); - } - - /** - * Constructs a new FlowLayout with the specified alignment and a default 5-unit - * horizontal and vertical gap. The value of the alignment argument must be one of - * WrapLayout, WrapLayout, or WrapLayout. - * - * @param align the alignment value - */ - public WrapLayout(int align) { - super(align); - } - - /** - * Creates a new flow layout manager with the indicated alignment and the indicated horizontal - * and vertical gaps. - * - *

The value of the alignment argument must be one of WrapLayout, - * WrapLayout - * , or WrapLayout. - * - * @param align the alignment value - * @param hgap the horizontal gap between components - * @param vgap the vertical gap between components - */ - public WrapLayout(int align, int hgap, int vgap) { - super(align, hgap, vgap); - } - - /** - * Returns the preferred dimensions for this layout given the visible components in the - * specified target container. - * - * @param target the component which needs to be laid out - * @return the preferred dimensions to lay out the subcomponents of the specified container - */ - @Override - public Dimension preferredLayoutSize(Container target) { - return layoutSize(target, true); - } - - /** - * Returns the minimum dimensions needed to layout the visible components contained in the - * specified target container. - * - * @param target the component which needs to be laid out - * @return the minimum dimensions to lay out the subcomponents of the specified container - */ - @Override - public Dimension minimumLayoutSize(Container target) { - Dimension minimum = layoutSize(target, false); - minimum.width -= (getHgap() + 1); - return minimum; - } - - /** - * Returns the minimum or preferred dimension needed to layout the target container. - * - * @param target target to get layout dimension for - * @param preferred should preferred dimension be calculated - * @return the dimension to layout the target container - */ - private Dimension layoutSize(Container target, boolean preferred) { - synchronized (target.getTreeLock()) { - // Each row must fit with the width allocated to the containter. - // When the container width = 0, the preferred width of the container - // has not yet been calculated so lets ask for the maximum. - - int targetWidth = target.getSize().width; - - if (targetWidth == 0) { - targetWidth = Integer.MAX_VALUE; - } - - int hgap = getHgap(); - int vgap = getVgap(); - Insets insets = target.getInsets(); - int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); - int maxWidth = targetWidth - horizontalInsetsAndGap; - - // Fit components into the allowed width - - Dimension dim = new Dimension(0, 0); - int rowWidth = 0; - int rowHeight = 0; - - int nmembers = target.getComponentCount(); - - for (int i = 0; i < nmembers; i++) { - Component m = target.getComponent(i); - - if (m.isVisible()) { - Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); - - // Can't add the component to current row. Start a new row. - - if (rowWidth + d.width > maxWidth) { - addRow(dim, rowWidth, rowHeight); - rowWidth = 0; - rowHeight = 0; - } + private Dimension preferredLayoutSize; + + /** + * Constructs a new WrapLayout with a left alignment and a default 5-unit horizontal + * and vertical gap. + */ + public WrapLayout() { + super(LEFT); + } + + /** + * Constructs a new FlowLayout with the specified alignment and a default 5-unit + * horizontal and vertical gap. The value of the alignment argument must be one of + * WrapLayout, WrapLayout, or WrapLayout. + * + * @param align the alignment value + */ + public WrapLayout(int align) { + super(align); + } + + /** + * Creates a new flow layout manager with the indicated alignment and the indicated horizontal and + * vertical gaps. + * + *

The value of the alignment argument must be one of WrapLayout, + * WrapLayout + * , or WrapLayout. + * + * @param align the alignment value + * @param hgap the horizontal gap between components + * @param vgap the vertical gap between components + */ + public WrapLayout(int align, int hgap, int vgap) { + super(align, hgap, vgap); + } + + /** + * Returns the preferred dimensions for this layout given the visible components in the specified + * target container. + * + * @param target the component which needs to be laid out + * @return the preferred dimensions to lay out the subcomponents of the specified container + */ + @Override + public Dimension preferredLayoutSize(Container target) { + return layoutSize(target, true); + } + + /** + * Returns the minimum dimensions needed to layout the visible components contained in the + * specified target container. + * + * @param target the component which needs to be laid out + * @return the minimum dimensions to lay out the subcomponents of the specified container + */ + @Override + public Dimension minimumLayoutSize(Container target) { + Dimension minimum = layoutSize(target, false); + minimum.width -= (getHgap() + 1); + return minimum; + } + + /** + * Returns the minimum or preferred dimension needed to layout the target container. + * + * @param target target to get layout dimension for + * @param preferred should preferred dimension be calculated + * @return the dimension to layout the target container + */ + private Dimension layoutSize(Container target, boolean preferred) { + synchronized (target.getTreeLock()) { + // Each row must fit with the width allocated to the containter. + // When the container width = 0, the preferred width of the container + // has not yet been calculated so lets ask for the maximum. + + int targetWidth = target.getSize().width; + + if (targetWidth == 0) { + targetWidth = Integer.MAX_VALUE; + } + + int hgap = getHgap(); + int vgap = getVgap(); + Insets insets = target.getInsets(); + int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); + int maxWidth = targetWidth - horizontalInsetsAndGap; + + // Fit components into the allowed width + + Dimension dim = new Dimension(0, 0); + int rowWidth = 0; + int rowHeight = 0; + + int nmembers = target.getComponentCount(); + + for (int i = 0; i < nmembers; i++) { + Component m = target.getComponent(i); + + if (m.isVisible()) { + Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); + + // Can't add the component to current row. Start a new row. + + if (rowWidth + d.width > maxWidth) { + addRow(dim, rowWidth, rowHeight); + rowWidth = 0; + rowHeight = 0; + } - // Add a horizontal gap for all components after the first + // Add a horizontal gap for all components after the first - if (rowWidth != 0) { - rowWidth += hgap; - } + if (rowWidth != 0) { + rowWidth += hgap; + } - rowWidth += d.width; - rowHeight = Math.max(rowHeight, d.height); - } - } + rowWidth += d.width; + rowHeight = Math.max(rowHeight, d.height); + } + } - addRow(dim, rowWidth, rowHeight); + addRow(dim, rowWidth, rowHeight); - dim.width += horizontalInsetsAndGap; - dim.height += insets.top + insets.bottom + vgap * 2; + dim.width += horizontalInsetsAndGap; + dim.height += insets.top + insets.bottom + vgap * 2; - // When using a scroll pane or the DecoratedLookAndFeel we need to - // make sure the preferred dimension is less than the dimension of the - // target containter so shrinking the container dimension works - // correctly. Removing the horizontal gap is an easy way to do this. + // When using a scroll pane or the DecoratedLookAndFeel we need to + // make sure the preferred dimension is less than the dimension of the + // target containter so shrinking the container dimension works + // correctly. Removing the horizontal gap is an easy way to do this. - Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); + Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); - if (scrollPane != null) { - dim.width -= (hgap + 1); - } + if (scrollPane != null) { + dim.width -= (hgap + 1); + } - return dim; - } + return dim; } - - /** - * A new row has been completed. Use the dimensions of this row to update the preferred - * dimension for the container. - * - * @param dim update the width and height when appropriate - * @param rowWidth the width of the row to add - * @param rowHeight the height of the row to add - */ - private void addRow(Dimension dim, int rowWidth, int rowHeight) { - dim.width = Math.max(dim.width, rowWidth); - - if (dim.height > 0) { - dim.height += getVgap(); - } - - dim.height += rowHeight; + } + + /** + * A new row has been completed. Use the dimensions of this row to update the preferred dimension + * for the container. + * + * @param dim update the width and height when appropriate + * @param rowWidth the width of the row to add + * @param rowHeight the height of the row to add + */ + private void addRow(Dimension dim, int rowWidth, int rowHeight) { + dim.width = Math.max(dim.width, rowWidth); + + if (dim.height > 0) { + dim.height += getVgap(); } + + dim.height += rowHeight; + } } diff --git a/src/main/java/edu/rpi/legup/ui/ZoomWidget.java b/src/main/java/edu/rpi/legup/ui/ZoomWidget.java index aa5b65c4e..0afe0c2d1 100644 --- a/src/main/java/edu/rpi/legup/ui/ZoomWidget.java +++ b/src/main/java/edu/rpi/legup/ui/ZoomWidget.java @@ -11,46 +11,46 @@ import javax.swing.event.ChangeListener; public class ZoomWidget extends JLabel { - private ScrollView parent; - private PopupSlider palette = new PopupSlider(); - private MouseAdapter open = - new MouseAdapter() { - public void mouseClicked(MouseEvent e) { - palette.slider.setValue(parent.getZoom()); - palette.show(e.getComponent(), 0, 0); - } - }; - - /** - * ZoomWidget Constructor creates a zoom widget for a ScrollView object - * - * @param parent dynamicView to which to the ZoomWidget is applied to - */ - public ZoomWidget(ScrollView parent) { - super(new ImageIcon("zoom.png")); - this.parent = parent; - addMouseListener(open); - } - - /** */ - private class PopupSlider extends JPopupMenu implements ChangeListener { - private static final long serialVersionUID = 8225019381200459814L; - - private JSlider slider; - - public PopupSlider() { - slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 200); - slider.setMajorTickSpacing(25); - slider.setPaintTicks(true); - - add(slider); - slider.addChangeListener(this); + private ScrollView parent; + private PopupSlider palette = new PopupSlider(); + private MouseAdapter open = + new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + palette.slider.setValue(parent.getZoom()); + palette.show(e.getComponent(), 0, 0); } + }; + + /** + * ZoomWidget Constructor creates a zoom widget for a ScrollView object + * + * @param parent dynamicView to which to the ZoomWidget is applied to + */ + public ZoomWidget(ScrollView parent) { + super(new ImageIcon("zoom.png")); + this.parent = parent; + addMouseListener(open); + } + + /** */ + private class PopupSlider extends JPopupMenu implements ChangeListener { + private static final long serialVersionUID = 8225019381200459814L; + + private JSlider slider; + + public PopupSlider() { + slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 200); + slider.setMajorTickSpacing(25); + slider.setPaintTicks(true); + + add(slider); + slider.addChangeListener(this); + } - public void stateChanged(ChangeEvent e) { - if (slider.getValueIsAdjusting()) { - parent.zoomTo((double) slider.getValue() / 100.0); - } - } + public void stateChanged(ChangeEvent e) { + if (slider.getValueIsAdjusting()) { + parent.zoomTo((double) slider.getValue() / 100.0); + } } + } } diff --git a/src/main/java/edu/rpi/legup/ui/ZoomablePane.java b/src/main/java/edu/rpi/legup/ui/ZoomablePane.java index 934d31c53..121047448 100644 --- a/src/main/java/edu/rpi/legup/ui/ZoomablePane.java +++ b/src/main/java/edu/rpi/legup/ui/ZoomablePane.java @@ -6,35 +6,35 @@ import javax.swing.*; public class ZoomablePane extends JLayeredPane { - private ScrollView viewer; + private ScrollView viewer; - /** - * ZoomablePane Constructor creates scalable JComponent - * - * @param viewer dynamic dynamicView - */ - public ZoomablePane(ScrollView viewer) { - this.viewer = viewer; - } + /** + * ZoomablePane Constructor creates scalable JComponent + * + * @param viewer dynamic dynamicView + */ + public ZoomablePane(ScrollView viewer) { + this.viewer = viewer; + } - /** - * Paints the JComponents - * - * @param graphics graphics object used to paint the JComponent - */ - public void paint(Graphics graphics) { - Graphics2D graphics2D = (Graphics2D) graphics; - graphics2D.scale(viewer.getScale(), viewer.getScale()); - viewer.draw(graphics2D); - } + /** + * Paints the JComponents + * + * @param graphics graphics object used to paint the JComponent + */ + public void paint(Graphics graphics) { + Graphics2D graphics2D = (Graphics2D) graphics; + graphics2D.scale(viewer.getScale(), viewer.getScale()); + viewer.draw(graphics2D); + } - /** - * Processes an event and sends it to the dynamicView - * - * @param e AWTEvent to process - */ - protected void processEvent(AWTEvent e) { - viewer.dispatchEvent(e); - super.processEvent(e); - } + /** + * Processes an event and sends it to the dynamicView + * + * @param e AWTEvent to process + */ + protected void processEvent(AWTEvent e) { + viewer.dispatchEvent(e); + super.processEvent(e); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java b/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java index ca03f1e25..f917ef9b0 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java @@ -12,201 +12,197 @@ import java.util.ArrayList; public abstract class BoardView extends ScrollView implements IBoardListener { - protected TreeElement treeElement; - protected Board board; - protected ArrayList elementViews; - protected ElementController elementController; - protected ElementSelection selection; - - /** - * BoardView Constructor creates a view for the board object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - * @param elementController controller that handles the ui events - */ - public BoardView(BoardController boardController, ElementController elementController) { - super(boardController); - this.treeElement = null; - this.board = null; - this.elementViews = new ArrayList<>(); - this.elementController = elementController; - this.selection = new ElementSelection(); - - elementController.setBoardView(this); - addMouseListener(elementController); - addMouseMotionListener(elementController); - addKeyListener(elementController); - } - - /** Initializes the initial dimension of the viewport for the BoardView */ - public abstract void initSize(); - - /** - * Gets the dimension of the board view - * - * @return dimension of the board view - */ - protected abstract Dimension getProperSize(); - - /** - * Gets the ElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return ElementView at the specified index - */ - public abstract ElementView getElement(int index); - - /** - * Sets the ElementView list - * - * @param elements ElementView list - */ - public void setElementViews(ArrayList elements) { - elementViews = elements; - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - public ElementView getElement(Point point) { - Point scaledPoint = - new Point( - (int) Math.round(point.x / getScale()), - (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - return null; - } - - /** - * Gets the ElementSelection for this BoardView - * - * @return the ElementSelection - */ - public ElementSelection getSelection() { - return selection; - } - - /** - * Gets the board associated with this view - * - * @return board - */ - public Board getBoard() { - return board; - } - - /** - * Sets the board associated with this view - * - * @param board board - */ - public void setBoard(Board board) { - if (this.board != board) { - this.board = board; - - if (board instanceof CaseBoard) { - setCasePickable(); - } else { - for (ElementView elementView : elementViews) { - elementView.setPuzzleElement( - board.getPuzzleElement(elementView.getPuzzleElement())); - elementView.setShowCasePicker(false); - } - } - } - } - - protected void setCasePickable() { - CaseBoard caseBoard = (CaseBoard) board; - Board baseBoard = caseBoard.getBaseBoard(); - + protected TreeElement treeElement; + protected Board board; + protected ArrayList elementViews; + protected ElementController elementController; + protected ElementSelection selection; + + /** + * BoardView Constructor creates a view for the board object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + * @param elementController controller that handles the ui events + */ + public BoardView(BoardController boardController, ElementController elementController) { + super(boardController); + this.treeElement = null; + this.board = null; + this.elementViews = new ArrayList<>(); + this.elementController = elementController; + this.selection = new ElementSelection(); + + elementController.setBoardView(this); + addMouseListener(elementController); + addMouseMotionListener(elementController); + addKeyListener(elementController); + } + + /** Initializes the initial dimension of the viewport for the BoardView */ + public abstract void initSize(); + + /** + * Gets the dimension of the board view + * + * @return dimension of the board view + */ + protected abstract Dimension getProperSize(); + + /** + * Gets the ElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return ElementView at the specified index + */ + public abstract ElementView getElement(int index); + + /** + * Sets the ElementView list + * + * @param elements ElementView list + */ + public void setElementViews(ArrayList elements) { + elementViews = elements; + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + public ElementView getElement(Point point) { + Point scaledPoint = + new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + return null; + } + + /** + * Gets the ElementSelection for this BoardView + * + * @return the ElementSelection + */ + public ElementSelection getSelection() { + return selection; + } + + /** + * Gets the board associated with this view + * + * @return board + */ + public Board getBoard() { + return board; + } + + /** + * Sets the board associated with this view + * + * @param board board + */ + public void setBoard(Board board) { + if (this.board != board) { + this.board = board; + + if (board instanceof CaseBoard) { + setCasePickable(); + } else { for (ElementView elementView : elementViews) { - PuzzleElement puzzleElement = - baseBoard.getPuzzleElement(elementView.getPuzzleElement()); - elementView.setPuzzleElement(puzzleElement); - elementView.setShowCasePicker(true); - elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - } - - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - this.treeElement = treeElement; - setBoard(treeElement.getBoard()); - repaint(); - } - - /** - * Called when the a case board has been added to the view. - * - * @param caseBoard case board to be added - */ - @Override - public void onCaseBoardAdded(CaseBoard caseBoard) { - setBoard(caseBoard); - repaint(); - } - - public TreeElement getTreeElement() { - return this.treeElement; - } - - /** - * Gets the amount of edu.rpi.legup.puzzle elements for this board - * - * @return the amount of edu.rpi.legup.puzzle elements for this board - */ - public int getElementCount() { - return elementViews.size(); - } - - /** - * Gets the PuzzleElements associated with the BoardView - * - * @return list of PuzzleElements - */ - public ArrayList getElementViews() { - return elementViews; - } - - public ElementController getElementController() { - return elementController; - } - - @Override - public void draw(Graphics2D graphics2D) { - drawBoard(graphics2D); - } - - public void drawBoard(Graphics2D graphics2D) { - for (ElementView element : elementViews) { - element.draw(graphics2D); + elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); + elementView.setShowCasePicker(false); } - } - - /** - * Called when the board puzzleElement changed - * - * @param puzzleElement puzzleElement of the puzzleElement that changed - */ - @Override - public void onBoardDataChanged(PuzzleElement puzzleElement) { - repaint(); - } - - public abstract DataSelectionView getSelectionPopupMenu(); + } + } + } + + protected void setCasePickable() { + CaseBoard caseBoard = (CaseBoard) board; + Board baseBoard = caseBoard.getBaseBoard(); + + for (ElementView elementView : elementViews) { + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); + elementView.setPuzzleElement(puzzleElement); + elementView.setShowCasePicker(true); + elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + } + + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + this.treeElement = treeElement; + setBoard(treeElement.getBoard()); + repaint(); + } + + /** + * Called when the a case board has been added to the view. + * + * @param caseBoard case board to be added + */ + @Override + public void onCaseBoardAdded(CaseBoard caseBoard) { + setBoard(caseBoard); + repaint(); + } + + public TreeElement getTreeElement() { + return this.treeElement; + } + + /** + * Gets the amount of edu.rpi.legup.puzzle elements for this board + * + * @return the amount of edu.rpi.legup.puzzle elements for this board + */ + public int getElementCount() { + return elementViews.size(); + } + + /** + * Gets the PuzzleElements associated with the BoardView + * + * @return list of PuzzleElements + */ + public ArrayList getElementViews() { + return elementViews; + } + + public ElementController getElementController() { + return elementController; + } + + @Override + public void draw(Graphics2D graphics2D) { + drawBoard(graphics2D); + } + + public void drawBoard(Graphics2D graphics2D) { + for (ElementView element : elementViews) { + element.draw(graphics2D); + } + } + + /** + * Called when the board puzzleElement changed + * + * @param puzzleElement puzzleElement of the puzzleElement that changed + */ + @Override + public void onBoardDataChanged(PuzzleElement puzzleElement) { + repaint(); + } + + public abstract DataSelectionView getSelectionPopupMenu(); } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java b/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java index cedfa08fe..3c6e78f5d 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java @@ -7,8 +7,8 @@ public class DataSelectionView extends JPopupMenu { - public DataSelectionView(ElementController controller) { - setBackground(Color.GRAY); - setBorder(new BevelBorder(BevelBorder.RAISED)); - } + public DataSelectionView(ElementController controller) { + setBackground(Color.GRAY); + setBorder(new BevelBorder(BevelBorder.RAISED)); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java b/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java index 8e6f2cb18..cce569af3 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java @@ -4,71 +4,71 @@ import java.util.ArrayList; public class ElementSelection { - private ArrayList selection; - private ElementView hover; - private Point mousePoint; + private ArrayList selection; + private ElementView hover; + private Point mousePoint; - public ElementSelection() { - this.selection = new ArrayList<>(); - this.hover = null; - this.mousePoint = null; - } + public ElementSelection() { + this.selection = new ArrayList<>(); + this.hover = null; + this.mousePoint = null; + } - public ArrayList getSelection() { - return selection; - } + public ArrayList getSelection() { + return selection; + } - public ElementView getFirstSelection() { - return selection.size() == 0 ? null : selection.get(0); - } + public ElementView getFirstSelection() { + return selection.size() == 0 ? null : selection.get(0); + } - public void toggleSelection(ElementView elementView) { - if (selection.contains(elementView)) { - selection.remove(elementView); - elementView.setSelected(false); - } else { - selection.add(elementView); - elementView.setSelected(true); - } + public void toggleSelection(ElementView elementView) { + if (selection.contains(elementView)) { + selection.remove(elementView); + elementView.setSelected(false); + } else { + selection.add(elementView); + elementView.setSelected(true); } + } - public void newSelection(ElementView elementView) { - clearSelection(); - selection.add(elementView); - elementView.setSelected(true); - } + public void newSelection(ElementView elementView) { + clearSelection(); + selection.add(elementView); + elementView.setSelected(true); + } - public void clearSelection() { - for (ElementView elementView : selection) { - elementView.setSelected(false); - } - selection.clear(); + public void clearSelection() { + for (ElementView elementView : selection) { + elementView.setSelected(false); } + selection.clear(); + } - public ElementView getHover() { - return hover; - } + public ElementView getHover() { + return hover; + } - public void newHover(ElementView newHovered) { - newHovered.setHover(true); - if (hover != null) { - hover.setHover(false); - } - hover = newHovered; + public void newHover(ElementView newHovered) { + newHovered.setHover(true); + if (hover != null) { + hover.setHover(false); } + hover = newHovered; + } - public void clearHover() { - if (hover != null) { - hover.setHover(false); - hover = null; - } + public void clearHover() { + if (hover != null) { + hover.setHover(false); + hover = null; } + } - public Point getMousePoint() { - return mousePoint; - } + public Point getMousePoint() { + return mousePoint; + } - public void setMousePoint(Point point) { - this.mousePoint = point; - } + public void setMousePoint(Point point) { + this.mousePoint = point; + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java b/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java index 83b2cb099..6cca76bcd 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java @@ -10,338 +10,331 @@ import javax.swing.*; public abstract class ElementView implements Shape { - protected int index; - protected Point location; - protected Dimension size; - protected PuzzleElement puzzleElement; - private Color hoverColor; - private Color modifiedColor; - private Color caseColor; - private Color invalidColor; - private boolean showCasePicker; - private boolean isCaseRulePickable; - private boolean isHover; - private boolean isSelected; - - /** - * ElementView Constructor creates a puzzleElement view - * - * @param puzzleElement puzzleElement to which the view uses to draw - */ - public ElementView(PuzzleElement puzzleElement) { - this.puzzleElement = puzzleElement; - this.hoverColor = new Color(0x79, 0x86, 0xCB, 255); - this.modifiedColor = new Color(0x64, 0xDD, 0x17, 255); - this.caseColor = new Color(0x1A, 0x23, 0x7E, 200); - this.invalidColor = new Color(0xf4, 0x43, 0x36, 200); - this.isHover = false; - this.isSelected = false; - this.isCaseRulePickable = false; - } - - /** - * Determines if the specified point is within the ElementView - * - * @param point point to check - * @return true if the point is within the ElementView, false otherwise - */ - public boolean isWithinBounds(Point point) { - return point.x >= location.x - && point.x <= location.x + size.width - && point.y >= location.y - && point.y <= location.y + size.height; - } - - /** - * Draws the puzzle element on the screen - * - * @param graphics2D graphics2D object used for drawing - */ - public void draw(Graphics2D graphics2D) { - drawElement(graphics2D); - if (puzzleElement.isGiven()) { - drawGiven(graphics2D); - } - if (puzzleElement.isModified()) { - drawModified(graphics2D); - } - if (showCasePicker && isCaseRulePickable) { - drawCase(graphics2D); - } - if (isHover) { - drawHover(graphics2D); - } - } - - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 2, size.height - 2)); - - graphics2D.setColor(Color.BLACK); - FontMetrics metrics = graphics2D.getFontMetrics(graphics2D.getFont()); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } - - public void drawGiven(Graphics2D graphics2D) {} - - public void drawHover(Graphics2D graphics2D) { - graphics2D.setColor(hoverColor); - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public void drawModified(Graphics2D graphics2D) { - graphics2D.setColor(puzzleElement.isValid() ? modifiedColor : invalidColor); - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public void drawCase(Graphics2D graphics2D) { - graphics2D.setColor(caseColor); - graphics2D.fill( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public BufferedImage getImage() { - BufferedImage image = - new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics2D = image.createGraphics(); - drawElement(graphics2D); - graphics2D.dispose(); - return image; - } - - /** - * Gets the index of the ElementView - * - * @return index of the ElementView - */ - public int getIndex() { - return index; - } - - /** - * Sets the index of the ElementView - * - * @param index index of the ElementView - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Gets the location of the ElementView - * - * @return location of the ElementView - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the ElementView - * - * @param location location of the ElementView - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Gets the dimension of the ElementView - * - * @return dimension of the ElementView - */ - public Dimension getSize() { - return size; - } - - /** - * Sets the dimension of the ElementView - * - * @param size dimension of the ElementView - */ - public void setSize(Dimension size) { - this.size = size; - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - public PuzzleElement getPuzzleElement() { - return puzzleElement; - } - - /** - * Sets the PuzzleElement associated with this view - * - * @param data PuzzleElement associated with this view - */ - public void setPuzzleElement(PuzzleElement data) { - this.puzzleElement = data; - } - - public boolean isShowCasePicker() { - return showCasePicker; - } - - public void setShowCasePicker(boolean showCasePicker) { - this.showCasePicker = showCasePicker; - } - - /** - * Gets the isCaseRulePickable field to determine if this ElementView should be highlighted in - * some way to indicate if it can be chosen by the CaseRule - * - * @return true if the ElementView can be chosen for the CaseRule, false otherwise - */ - public boolean isCaseRulePickable() { - return isCaseRulePickable; - } - - /** - * Sets the isCaseRulePickable field to determine if this ElementView should be highlighted in - * some way to indicate if it can be chosen by the CaseRule - * - * @param isCaseRulePickable true if the ElementView can be chosen for the CaseRule, false - * otherwise - */ - public void setCaseRulePickable(boolean isCaseRulePickable) { - this.isCaseRulePickable = isCaseRulePickable; - } - - /** - * Gets the high-light color - * - * @return high-light color - */ - public Color getHoverColor() { - return hoverColor; - } - - /** - * Sets the high-light color - * - * @param hoverColor high-light color - */ - public void setHoverColor(Color hoverColor) { - this.hoverColor = hoverColor; - } - - /** - * Gets whether the puzzleElement is currently being hovered over - * - * @return true if the puzzleElement is currently being hover over, false otherwise - */ - public boolean isHover() { - return isHover; - } - - /** - * Sets whether the puzzleElement is being hover over - * - * @param hover true if the puzzleElement is correctly being hover over, false otherwise - */ - public void setHover(boolean hover) { - isHover = hover; - } - - /** - * Gets whether the puzzleElement is being selected - * - * @return tue if the puzzleElement is currently selected, false otherwise - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets whether the puzzleElement is being selected - * - * @param selected tue if the puzzleElement is currently selected, false otherwise - */ - public void setSelected(boolean selected) { - isSelected = selected; - } - - public JMenuItem getSelectionMenuItem() { - JMenuItem item = new JMenuItem(puzzleElement.getData() + ""); - return item; - } - - @Override - public boolean contains(double x, double y) { - return x >= location.x - && x <= location.x + size.width - && y >= location.y - && y <= location.y + size.height; - } - - @Override - public boolean contains(Point2D point) { - return contains(point.getX(), point.getY()); - } - - @Override - public boolean intersects(double x, double y, double width, double height) { - return (x + width >= location.x && x <= location.x + size.width) - || (y + height >= location.y && y <= location.y + size.height); - } - - @Override - public boolean intersects(Rectangle2D rectangle2D) { - return intersects( - rectangle2D.getX(), - rectangle2D.getY(), - rectangle2D.getWidth(), - rectangle2D.getHeight()); - } - - @Override - public boolean contains(double x, double y, double width, double height) { - return (x + width >= location.x && x <= location.x + size.width) - && (y + height >= location.y && y <= location.y + size.height); - } - - @Override - public boolean contains(Rectangle2D rectangle2D) { - return contains( - rectangle2D.getX(), - rectangle2D.getY(), - rectangle2D.getWidth(), - rectangle2D.getHeight()); - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at); - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return new Rectangle(location.x, location.y, size.width, size.height) - .getPathIterator(at, flatness); - } - - @Override - public Rectangle getBounds() { - return new Rectangle(location.x, location.y, size.width, size.height); - } - - @Override - public Rectangle2D getBounds2D() { - return new Rectangle(location.x, location.y, size.width, size.height); - } + protected int index; + protected Point location; + protected Dimension size; + protected PuzzleElement puzzleElement; + private Color hoverColor; + private Color modifiedColor; + private Color caseColor; + private Color invalidColor; + private boolean showCasePicker; + private boolean isCaseRulePickable; + private boolean isHover; + private boolean isSelected; + + /** + * ElementView Constructor creates a puzzleElement view + * + * @param puzzleElement puzzleElement to which the view uses to draw + */ + public ElementView(PuzzleElement puzzleElement) { + this.puzzleElement = puzzleElement; + this.hoverColor = new Color(0x79, 0x86, 0xCB, 255); + this.modifiedColor = new Color(0x64, 0xDD, 0x17, 255); + this.caseColor = new Color(0x1A, 0x23, 0x7E, 200); + this.invalidColor = new Color(0xf4, 0x43, 0x36, 200); + this.isHover = false; + this.isSelected = false; + this.isCaseRulePickable = false; + } + + /** + * Determines if the specified point is within the ElementView + * + * @param point point to check + * @return true if the point is within the ElementView, false otherwise + */ + public boolean isWithinBounds(Point point) { + return point.x >= location.x + && point.x <= location.x + size.width + && point.y >= location.y + && point.y <= location.y + size.height; + } + + /** + * Draws the puzzle element on the screen + * + * @param graphics2D graphics2D object used for drawing + */ + public void draw(Graphics2D graphics2D) { + drawElement(graphics2D); + if (puzzleElement.isGiven()) { + drawGiven(graphics2D); + } + if (puzzleElement.isModified()) { + drawModified(graphics2D); + } + if (showCasePicker && isCaseRulePickable) { + drawCase(graphics2D); + } + if (isHover) { + drawHover(graphics2D); + } + } + + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 2, size.height - 2)); + + graphics2D.setColor(Color.BLACK); + FontMetrics metrics = graphics2D.getFontMetrics(graphics2D.getFont()); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } + + public void drawGiven(Graphics2D graphics2D) {} + + public void drawHover(Graphics2D graphics2D) { + graphics2D.setColor(hoverColor); + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public void drawModified(Graphics2D graphics2D) { + graphics2D.setColor(puzzleElement.isValid() ? modifiedColor : invalidColor); + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public void drawCase(Graphics2D graphics2D) { + graphics2D.setColor(caseColor); + graphics2D.fill( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public BufferedImage getImage() { + BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics2D = image.createGraphics(); + drawElement(graphics2D); + graphics2D.dispose(); + return image; + } + + /** + * Gets the index of the ElementView + * + * @return index of the ElementView + */ + public int getIndex() { + return index; + } + + /** + * Sets the index of the ElementView + * + * @param index index of the ElementView + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Gets the location of the ElementView + * + * @return location of the ElementView + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the ElementView + * + * @param location location of the ElementView + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Gets the dimension of the ElementView + * + * @return dimension of the ElementView + */ + public Dimension getSize() { + return size; + } + + /** + * Sets the dimension of the ElementView + * + * @param size dimension of the ElementView + */ + public void setSize(Dimension size) { + this.size = size; + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + public PuzzleElement getPuzzleElement() { + return puzzleElement; + } + + /** + * Sets the PuzzleElement associated with this view + * + * @param data PuzzleElement associated with this view + */ + public void setPuzzleElement(PuzzleElement data) { + this.puzzleElement = data; + } + + public boolean isShowCasePicker() { + return showCasePicker; + } + + public void setShowCasePicker(boolean showCasePicker) { + this.showCasePicker = showCasePicker; + } + + /** + * Gets the isCaseRulePickable field to determine if this ElementView should be highlighted in + * some way to indicate if it can be chosen by the CaseRule + * + * @return true if the ElementView can be chosen for the CaseRule, false otherwise + */ + public boolean isCaseRulePickable() { + return isCaseRulePickable; + } + + /** + * Sets the isCaseRulePickable field to determine if this ElementView should be highlighted in + * some way to indicate if it can be chosen by the CaseRule + * + * @param isCaseRulePickable true if the ElementView can be chosen for the CaseRule, false + * otherwise + */ + public void setCaseRulePickable(boolean isCaseRulePickable) { + this.isCaseRulePickable = isCaseRulePickable; + } + + /** + * Gets the high-light color + * + * @return high-light color + */ + public Color getHoverColor() { + return hoverColor; + } + + /** + * Sets the high-light color + * + * @param hoverColor high-light color + */ + public void setHoverColor(Color hoverColor) { + this.hoverColor = hoverColor; + } + + /** + * Gets whether the puzzleElement is currently being hovered over + * + * @return true if the puzzleElement is currently being hover over, false otherwise + */ + public boolean isHover() { + return isHover; + } + + /** + * Sets whether the puzzleElement is being hover over + * + * @param hover true if the puzzleElement is correctly being hover over, false otherwise + */ + public void setHover(boolean hover) { + isHover = hover; + } + + /** + * Gets whether the puzzleElement is being selected + * + * @return tue if the puzzleElement is currently selected, false otherwise + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets whether the puzzleElement is being selected + * + * @param selected tue if the puzzleElement is currently selected, false otherwise + */ + public void setSelected(boolean selected) { + isSelected = selected; + } + + public JMenuItem getSelectionMenuItem() { + JMenuItem item = new JMenuItem(puzzleElement.getData() + ""); + return item; + } + + @Override + public boolean contains(double x, double y) { + return x >= location.x + && x <= location.x + size.width + && y >= location.y + && y <= location.y + size.height; + } + + @Override + public boolean contains(Point2D point) { + return contains(point.getX(), point.getY()); + } + + @Override + public boolean intersects(double x, double y, double width, double height) { + return (x + width >= location.x && x <= location.x + size.width) + || (y + height >= location.y && y <= location.y + size.height); + } + + @Override + public boolean intersects(Rectangle2D rectangle2D) { + return intersects( + rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); + } + + @Override + public boolean contains(double x, double y, double width, double height) { + return (x + width >= location.x && x <= location.x + size.width) + && (y + height >= location.y && y <= location.y + size.height); + } + + @Override + public boolean contains(Rectangle2D rectangle2D) { + return contains( + rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at); + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return new Rectangle(location.x, location.y, size.width, size.height) + .getPathIterator(at, flatness); + } + + @Override + public Rectangle getBounds() { + return new Rectangle(location.x, location.y, size.width, size.height); + } + + @Override + public Rectangle2D getBounds2D() { + return new Rectangle(location.x, location.y, size.width, size.height); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java b/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java index c40303192..34f41b60d 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java @@ -6,82 +6,80 @@ import java.awt.Dimension; public class GridBoardView extends BoardView { - protected Dimension gridSize; - protected Dimension elementSize; + protected Dimension gridSize; + protected Dimension elementSize; - /** - * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - * @param gridSize dimension of the grid - * @param elementController controller that handles the ui events - */ - public GridBoardView( - BoardController boardController, - ElementController elementController, - Dimension gridSize) { - this(boardController, elementController); - this.gridSize = gridSize; - this.elementSize = new Dimension(30, 30); - initSize(); - } + /** + * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + * @param gridSize dimension of the grid + * @param elementController controller that handles the ui events + */ + public GridBoardView( + BoardController boardController, ElementController elementController, Dimension gridSize) { + this(boardController, elementController); + this.gridSize = gridSize; + this.elementSize = new Dimension(30, 30); + initSize(); + } - /** - * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - */ - private GridBoardView(BoardController boardController, ElementController elementController) { - super(boardController, elementController); - setBackground(new Color(0xE0E0E0)); - } + /** + * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + */ + private GridBoardView(BoardController boardController, ElementController elementController) { + super(boardController, elementController); + setBackground(new Color(0xE0E0E0)); + } - /** - * Gets the GridElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return GridElementView at the specified index - */ - public GridElementView getElement(int index) { - if (index < elementViews.size()) { - return (GridElementView) elementViews.get(index); - } - return null; + /** + * Gets the GridElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return GridElementView at the specified index + */ + public GridElementView getElement(int index) { + if (index < elementViews.size()) { + return (GridElementView) elementViews.get(index); } + return null; + } - public GridElementView getElement(int xIndex, int yIndex) { - if (xIndex < gridSize.width && yIndex < gridSize.height) { - return (GridElementView) elementViews.get(yIndex * gridSize.width + xIndex); - } - return null; + public GridElementView getElement(int xIndex, int yIndex) { + if (xIndex < gridSize.width && yIndex < gridSize.height) { + return (GridElementView) elementViews.get(yIndex * gridSize.width + xIndex); } + return null; + } - /** Initializes the initial dimension of the viewport for the GridBoardView */ - @Override - public void initSize() { - setSize(getProperSize()); - zoomFit(); - } + /** Initializes the initial dimension of the viewport for the GridBoardView */ + @Override + public void initSize() { + setSize(getProperSize()); + zoomFit(); + } - /** - * Helper method to determine the proper dimension of the grid view - * - * @return proper dimension of the grid view - */ - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = gridSize.width * elementSize.width; - boardViewSize.height = gridSize.height * elementSize.height; - return boardViewSize; - } + /** + * Helper method to determine the proper dimension of the grid view + * + * @return proper dimension of the grid view + */ + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = gridSize.width * elementSize.width; + boardViewSize.height = gridSize.height * elementSize.height; + return boardViewSize; + } - public DataSelectionView getSelectionPopupMenu() { - return null; - } + public DataSelectionView getSelectionPopupMenu() { + return null; + } - public Dimension getElementSize() { - return this.elementSize; - } + public Dimension getElementSize() { + return this.elementSize; + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java b/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java index 440b3a693..4a3d84261 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java @@ -3,7 +3,7 @@ import edu.rpi.legup.model.gameboard.GridCell; public class GridElementView extends ElementView { - public GridElementView(GridCell cell) { - super(cell); - } + public GridElementView(GridCell cell) { + super(cell); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java b/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java index b2d3e31dd..ee8060e3c 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java @@ -4,28 +4,28 @@ import javax.swing.*; public class SelectionItemView extends JMenuItem { - private PuzzleElement data; + private PuzzleElement data; - public SelectionItemView(PuzzleElement data, Icon icon) { - super(icon); - this.data = data; - } + public SelectionItemView(PuzzleElement data, Icon icon) { + super(icon); + this.data = data; + } - public SelectionItemView(PuzzleElement data, String display) { - super(display); - this.data = data; - } + public SelectionItemView(PuzzleElement data, String display) { + super(display); + this.data = data; + } - public SelectionItemView(PuzzleElement data, int display) { - super(String.valueOf(display)); - this.data = data; - } + public SelectionItemView(PuzzleElement data, int display) { + super(String.valueOf(display)); + this.data = data; + } - public SelectionItemView(PuzzleElement data) { - this(data, (Integer) data.getData()); - } + public SelectionItemView(PuzzleElement data) { + this(data, (Integer) data.getData()); + } - public PuzzleElement getData() { - return data; - } + public PuzzleElement getData() { + return data; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java index 8469343f3..613822c14 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java @@ -10,338 +10,334 @@ import javax.swing.plaf.basic.BasicLookAndFeel; public class LegupLookAndFeel extends BasicLookAndFeel { - /** - * Return a short string that identifies this look and feel, e.g. "CDE/Motif". This string - * should be appropriate for a menu item. Distinct look and feels should have different names, - * e.g. a subclass of MotifLookAndFeel that changes the way a few components are rendered should - * be called "CDE/Motif My Way"; something that would be useful to a user trying to select a - * L&F from a list of names. - * - * @return short identifier for the look and feel - */ - @Override - public String getName() { - return "Legup"; - } - - /** - * Return a string that identifies this look and feel. This string will be used by - * applications/services that want to recognize well known look and feel implementations. - * Presently the well known names are "Motif", "Windows", "Mac", "Metal". Note that a - * LookAndFeel derived from a well known superclass that doesn't make any fundamental changes to - * the look or feel shouldn't override this method. - * - * @return identifier for the look and feel - */ - @Override - public String getID() { - return "Legup Look and Feel"; - } - - /** - * Return a one line description of this look and feel implementation, e.g. "The CDE/Motif Look - * and Feel". This string is intended for the user, e.g. in the title of a window or in a - * ToolTip message. - * - * @return short description for the look and feel - */ - @Override - public String getDescription() { - return "Material design look and feel for Legup"; - } - - /** - * If the underlying platform has a "native" look and feel, and this is an implementation of it, - * return {@code true}. For example, when the underlying platform is Solaris running CDE a - * CDE/Motif look and feel implementation would return {@code true}. - * - * @return {@code true} if this look and feel represents the underlying platform look and feel - */ - @Override - public boolean isNativeLookAndFeel() { - return true; - } - - /** - * Return {@code true} if the underlying platform supports and or permits this look and feel. - * This method returns {@code false} if the look and feel depends on special resources or legal - * agreements that aren't defined for the current platform. - * - * @return {@code true} if this is a supported look and feel - * @see UIManager#setLookAndFeel - */ - @Override - public boolean isSupportedLookAndFeel() { - return true; - } - - /** - * Initializes the look and feel. While this method is public, it should only be invoked by the - * {@code UIManager} when a look and feel is installed as the current look and feel. This method - * is invoked before the {@code UIManager} invokes {@code getDefaults}. This method is intended - * to perform any initialization for the look and feel. Subclasses should do any one-time setup - * they need here, rather than in a static initializer, because look and feel class objects may - * be loaded just to discover that {@code isSupportedLookAndFeel()} returns {@code false}. - * - * @see #uninitialize - * @see UIManager#setLookAndFeel - */ - @Override - public void initialize() { - super.initialize(); - } - - /** - * Populates {@code table} with mappings from {@code uiClassID} to the fully qualified name of - * the ui class. The value for a particular {@code uiClassID} is {@code - * "javax.swing.plaf.basic.Basic + uiClassID"}. For example, the value for the {@code uiClassID} - * {@code TreeUI} is {@code "javax.swing.plaf.basic.BasicTreeUI"}. - * - * @param table the {@code UIDefaults} instance the entries are added to - * @throws NullPointerException if {@code table} is {@code null} - * @see LookAndFeel - * @see #getDefaults - */ - @Override - protected void initClassDefaults(UIDefaults table) { - super.initClassDefaults(table); - - table.put("ButtonUI", MaterialButtonUI.class.getCanonicalName()); - table.put("TextFieldUI", MaterialTextFieldUI.class.getCanonicalName()); - table.put("PasswordFieldUI", MaterialPasswordFieldUI.class.getCanonicalName()); - table.put("TableUI", MaterialTableUI.class.getCanonicalName()); - table.put("TableHeaderUI", MaterialTableHeaderUI.class.getCanonicalName()); - table.put("TreeUI", MaterialTreeUI.class.getCanonicalName()); - table.put("SpinnerUI", MaterialSpinnerUI.class.getCanonicalName()); - table.put("PanelUI", MaterialPanelUI.class.getCanonicalName()); - table.put("LabelUI", MaterialLabelUI.class.getCanonicalName()); - table.put("MenuItemUI", MaterialMenuItemUI.class.getCanonicalName()); - // table.put ("MenuBarUI", .class.getCanonicalName()); - table.put("MenuUI", MaterialMenuUI.class.getCanonicalName()); - table.put("CheckBoxUI", MaterialCheckBoxUI.class.getCanonicalName()); - table.put("RadioButtonUI", MaterialRadioButtonUI.class.getCanonicalName()); - table.put("TabbedPaneUI", MaterialTabbedPaneUI.class.getCanonicalName()); - table.put("ToggleButtonUI", MaterialToggleButtonUI.class.getCanonicalName()); - table.put("ScrollBarUI", MaterialScrollBarUI.class.getCanonicalName()); - table.put("ComboBoxUI", MaterialComboBoxUI.class.getCanonicalName()); - table.put("PopupMenuUI", MaterialPopupMenuUI.class.getCanonicalName()); - table.put("ToolBarUI", MaterialToolBarUI.class.getCanonicalName()); - table.put("SliderUI", MaterialSliderUI.class.getCanonicalName()); - table.put("ProgressBarUI", MaterialProgressBarUI.class.getCanonicalName()); - table.put("RadioButtonMenuItemUI", MaterialRadioButtonMenuItemUI.class.getCanonicalName()); - table.put("CheckBoxMenuItemUI", MaterialCheckBoxMenuItemUI.class.getCanonicalName()); - table.put("TextPaneUI", MaterialTextPaneUI.class.getCanonicalName()); - table.put("EditorPaneUI", MaterialEditorPaneUI.class.getCanonicalName()); - table.put("SeparatorUI", MaterialSeparatorUI.class.getCanonicalName()); - table.put("FileChooserUI", MaterialFileChooserUI.class.getCanonicalName()); - table.put("ToolTipUI", MaterialToolTipUI.class.getCanonicalName()); - table.put("SplitPaneUI", MaterialSplitPaneUI.class.getCanonicalName()); - // table.put ("ColorChooserUI", ); - } - - @Override - protected void initComponentDefaults(UIDefaults table) { - super.initComponentDefaults(table); - - table.put("Button.highlight", MaterialColors.GRAY_300); - table.put("Button.opaque", false); - table.put("Button.border", BorderFactory.createEmptyBorder(7, 17, 7, 17)); - table.put("Button.background", MaterialColors.GRAY_200); - table.put("Button.foreground", Color.BLACK); - table.put("Button.font", MaterialFonts.MEDIUM); - - table.put("CheckBox.font", MaterialFonts.REGULAR); - table.put("CheckBox.background", Color.WHITE); - table.put("CheckBox.foreground", Color.BLACK); - table.put("CheckBox.icon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); - table.put("CheckBox.selectedIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); - - table.put("ComboBox.font", MaterialFonts.REGULAR); - table.put("ComboBox.background", Color.WHITE); - table.put("ComboBox.foreground", Color.BLACK); - table.put( - "ComboBox.border", - BorderFactory.createCompoundBorder( - MaterialBorders.LIGHT_LINE_BORDER, - BorderFactory.createEmptyBorder(0, 5, 0, 0))); - table.put("ComboBox.buttonBackground", MaterialColors.GRAY_300); - table.put("ComboBox.selectionBackground", Color.WHITE); - table.put("ComboBox.selectionForeground", Color.BLACK); - table.put("ComboBox.selectedInDropDownBackground", MaterialColors.GRAY_200); - - table.put("Label.font", MaterialFonts.REGULAR); - table.put("Label.background", Color.WHITE); - table.put("Label.foreground", Color.BLACK); - table.put("Label.border", BorderFactory.createEmptyBorder()); - - table.put("Menu.font", MaterialFonts.BOLD); - table.put("Menu.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("Menu.background", Color.WHITE); - table.put("Menu.foreground", Color.BLACK); - table.put("Menu.opaque", true); - table.put("Menu.selectionBackground", MaterialColors.GRAY_200); - table.put("Menu.selectionForeground", Color.BLACK); - table.put("Menu.disabledForeground", new Color(0, 0, 0, 100)); - table.put("Menu.menuPopupOffsetY", 3); - - table.put("MenuBar.font", MaterialFonts.BOLD); - table.put("MenuBar.background", Color.WHITE); - table.put("MenuBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); - table.put("MenuBar.foreground", Color.BLACK); - - table.put("MenuItem.disabledForeground", new Color(0, 0, 0, 100)); - table.put("MenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("MenuItem.selectionForeground", Color.BLACK); - table.put("MenuItem.font", MaterialFonts.MEDIUM); - table.put("MenuItem.background", Color.WHITE); - table.put("MenuItem.foreground", Color.BLACK); - table.put("MenuItem.border", BorderFactory.createEmptyBorder(5, 0, 5, 0)); - - table.put("OptionPane.background", Color.WHITE); - table.put("OptionPane.border", MaterialBorders.DEFAULT_SHADOW_BORDER); - table.put("OptionPane.font", MaterialFonts.REGULAR); - - table.put("Panel.font", MaterialFonts.REGULAR); - table.put("Panel.background", Color.WHITE); - table.put("Panel.border", BorderFactory.createEmptyBorder()); - - table.put("PopupMenu.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("PopupMenu.background", Color.WHITE); - table.put("PopupMenu.foreground", Color.BLACK); - - table.put("RadioButton.font", MaterialFonts.REGULAR); - table.put("RadioButton.background", Color.WHITE); - table.put("RadioButton.foreground", Color.BLACK); - table.put("RadioButton.icon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); - table.put("RadioButton.selectedIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); - - table.put("Spinner.font", MaterialFonts.REGULAR); - table.put("Spinner.background", Color.WHITE); - table.put("Spinner.foreground", Color.BLACK); - table.put("Spinner.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("Spinner.arrowButtonBackground", MaterialColors.GRAY_200); - table.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); - - table.put("ScrollBar.font", MaterialFonts.REGULAR); - table.put("ScrollBar.track", MaterialColors.GRAY_200); - table.put("ScrollBar.thumb", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbDarkShadow", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbHighlight", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbShadow", MaterialColors.GRAY_300); - table.put("ScrollBar.arrowButtonBackground", MaterialColors.GRAY_300); - table.put("ScrollBar.arrowButtonBorder", BorderFactory.createEmptyBorder()); - - table.put("ScrollPane.background", Color.WHITE); - table.put("ScrollPane.border", BorderFactory.createEmptyBorder()); - table.put("ScrollPane.font", MaterialFonts.REGULAR); - - table.put("Slider.font", MaterialFonts.REGULAR); - table.put("Slider.background", Color.WHITE); - table.put("Slider.foreground", MaterialColors.GRAY_700); - table.put("Slider.trackColor", Color.BLACK); - // table.put ("Slider.border", - // BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, - // BorderFactory.createEmptyBorder (5, 5, 5, 5))); - - table.put("SplitPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("SplitPane.background", Color.WHITE); - table.put("SplitPane.dividerSize", 10); - table.put("SplitPaneDivider.border", MaterialBorders.LIGHT_SHADOW_BORDER); - - table.put("TabbedPane.font", MaterialFonts.REGULAR); - table.put("TabbedPane.background", Color.WHITE); - table.put("TabbedPane.foreground", Color.BLACK); - table.put("TabbedPane.border", BorderFactory.createEmptyBorder()); - table.put("TabbedPane.shadow", null); - table.put("TabbedPane.darkShadow", null); - table.put("TabbedPane.highlight", MaterialColors.GRAY_200); - table.put("TabbedPane.borderHighlightColor", MaterialColors.GRAY_300); - - table.put("Table.selectionBackground", MaterialColors.GRAY_100); - table.put("Table.selectionForeground", Color.BLACK); - table.put("Table.background", Color.WHITE); - table.put("Table.font", MaterialFonts.REGULAR); - table.put("Table.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("Table.gridColor", MaterialColors.GRAY_200); - table.put("TableHeader.background", MaterialColors.GRAY_200); - table.put("TableHeader.font", MaterialFonts.BOLD); - table.put( - "TableHeader.cellBorder", - BorderFactory.createCompoundBorder( - MaterialBorders.LIGHT_LINE_BORDER, - BorderFactory.createEmptyBorder(5, 5, 5, 5))); - - table.put("TextArea.background", MaterialColors.GRAY_200); - table.put("TextArea.border", BorderFactory.createEmptyBorder()); - table.put("TextArea.foreground", Color.BLACK); - - table.put("ToggleButton.border", BorderFactory.createEmptyBorder()); - table.put("ToggleButton.font", MaterialFonts.REGULAR); - table.put("ToggleButton.background", Color.WHITE); - table.put("ToggleButton.foreground", Color.BLACK); - table.put("ToggleButton.icon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_OFF)); - table.put("ToggleButton.selectedIcon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_ON)); - - table.put("ToolBar.font", MaterialFonts.REGULAR); - table.put("ToolBar.background", Color.WHITE); - table.put("ToolBar.foreground", Color.BLACK); - table.put("ToolBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); - table.put("ToolBar.dockingBackground", MaterialColors.LIGHT_GREEN_A100); - table.put("ToolBar.floatingBackground", MaterialColors.GRAY_200); - - table.put("Tree.font", MaterialFonts.REGULAR); - table.put("Tree.selectionForeground", Color.BLACK); - table.put("Tree.foreground", Color.BLACK); - table.put("Tree.selectionBackground", MaterialColors.GRAY_200); - table.put("Tree.background", Color.WHITE); - table.put("Tree.closedIcon", new ImageIcon(MaterialImages.RIGHT_ARROW)); - table.put("Tree.openIcon", new ImageIcon(MaterialImages.DOWN_ARROW)); - table.put("Tree.selectionBorderColor", null); - - table.put("RadioButtonMenuItem.foreground", Color.BLACK); - table.put("RadioButtonMenuItem.selectionForeground", Color.BLACK); - // If it changes the background of the menuitem it must change this too, irrespective of its - // setting - table.put("RadioButtonMenuItem.background", UIManager.getColor("MenuItem.background")); - table.put("RadioButtonMenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("RadioButtonMenuItem.checkIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); - table.put( - "RadioButtonMenuItem.selectedCheckIcon", - new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); - - // If it changes the background of the menuitem it must change this too, irrespective of its - // setting - table.put("CheckBoxMenuItem.background", UIManager.getColor("MenuItem.background")); - table.put("CheckBoxMenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("CheckBoxMenuItem.foreground", Color.BLACK); - table.put("CheckBoxMenuItem.selectionForeground", Color.BLACK); - table.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("CheckBoxMenuItem.checkIcon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); - table.put( - "CheckBoxMenuItem.selectedCheckIcon", - new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); - - table.put("TextPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("TextPane.background", MaterialColors.GRAY_50); - table.put("TextPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); - table.put("TextPane.inactiveForeground", MaterialColors.GRAY_500); - table.put("TextPane.font", MaterialFonts.REGULAR); - - table.put("EditorPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("EditorPane.background", MaterialColors.GRAY_50); - table.put("EditorPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); - table.put("EditorPane.inactiveForeground", MaterialColors.GRAY_500); - table.put("EditorPane.font", MaterialFonts.REGULAR); - - table.put("Separator.background", MaterialColors.GRAY_300); - table.put("Separator.foreground", MaterialColors.GRAY_300); - - table.put("ToolTip.background", MaterialColors.GRAY_500); - table.put("ToolTip.foreground", MaterialColors.GRAY_50); - table.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - - table.put("ColorChooser.background", MaterialColors.WHITE); - table.put("ColorChooser.foreground", MaterialColors.BLACK); - } + /** + * Return a short string that identifies this look and feel, e.g. "CDE/Motif". This string should + * be appropriate for a menu item. Distinct look and feels should have different names, e.g. a + * subclass of MotifLookAndFeel that changes the way a few components are rendered should be + * called "CDE/Motif My Way"; something that would be useful to a user trying to select a L&F + * from a list of names. + * + * @return short identifier for the look and feel + */ + @Override + public String getName() { + return "Legup"; + } + + /** + * Return a string that identifies this look and feel. This string will be used by + * applications/services that want to recognize well known look and feel implementations. + * Presently the well known names are "Motif", "Windows", "Mac", "Metal". Note that a LookAndFeel + * derived from a well known superclass that doesn't make any fundamental changes to the look or + * feel shouldn't override this method. + * + * @return identifier for the look and feel + */ + @Override + public String getID() { + return "Legup Look and Feel"; + } + + /** + * Return a one line description of this look and feel implementation, e.g. "The CDE/Motif Look + * and Feel". This string is intended for the user, e.g. in the title of a window or in a ToolTip + * message. + * + * @return short description for the look and feel + */ + @Override + public String getDescription() { + return "Material design look and feel for Legup"; + } + + /** + * If the underlying platform has a "native" look and feel, and this is an implementation of it, + * return {@code true}. For example, when the underlying platform is Solaris running CDE a + * CDE/Motif look and feel implementation would return {@code true}. + * + * @return {@code true} if this look and feel represents the underlying platform look and feel + */ + @Override + public boolean isNativeLookAndFeel() { + return true; + } + + /** + * Return {@code true} if the underlying platform supports and or permits this look and feel. This + * method returns {@code false} if the look and feel depends on special resources or legal + * agreements that aren't defined for the current platform. + * + * @return {@code true} if this is a supported look and feel + * @see UIManager#setLookAndFeel + */ + @Override + public boolean isSupportedLookAndFeel() { + return true; + } + + /** + * Initializes the look and feel. While this method is public, it should only be invoked by the + * {@code UIManager} when a look and feel is installed as the current look and feel. This method + * is invoked before the {@code UIManager} invokes {@code getDefaults}. This method is intended to + * perform any initialization for the look and feel. Subclasses should do any one-time setup they + * need here, rather than in a static initializer, because look and feel class objects may be + * loaded just to discover that {@code isSupportedLookAndFeel()} returns {@code false}. + * + * @see #uninitialize + * @see UIManager#setLookAndFeel + */ + @Override + public void initialize() { + super.initialize(); + } + + /** + * Populates {@code table} with mappings from {@code uiClassID} to the fully qualified name of the + * ui class. The value for a particular {@code uiClassID} is {@code "javax.swing.plaf.basic.Basic + * + uiClassID"}. For example, the value for the {@code uiClassID} {@code TreeUI} is {@code + * "javax.swing.plaf.basic.BasicTreeUI"}. + * + * @param table the {@code UIDefaults} instance the entries are added to + * @throws NullPointerException if {@code table} is {@code null} + * @see LookAndFeel + * @see #getDefaults + */ + @Override + protected void initClassDefaults(UIDefaults table) { + super.initClassDefaults(table); + + table.put("ButtonUI", MaterialButtonUI.class.getCanonicalName()); + table.put("TextFieldUI", MaterialTextFieldUI.class.getCanonicalName()); + table.put("PasswordFieldUI", MaterialPasswordFieldUI.class.getCanonicalName()); + table.put("TableUI", MaterialTableUI.class.getCanonicalName()); + table.put("TableHeaderUI", MaterialTableHeaderUI.class.getCanonicalName()); + table.put("TreeUI", MaterialTreeUI.class.getCanonicalName()); + table.put("SpinnerUI", MaterialSpinnerUI.class.getCanonicalName()); + table.put("PanelUI", MaterialPanelUI.class.getCanonicalName()); + table.put("LabelUI", MaterialLabelUI.class.getCanonicalName()); + table.put("MenuItemUI", MaterialMenuItemUI.class.getCanonicalName()); + // table.put ("MenuBarUI", .class.getCanonicalName()); + table.put("MenuUI", MaterialMenuUI.class.getCanonicalName()); + table.put("CheckBoxUI", MaterialCheckBoxUI.class.getCanonicalName()); + table.put("RadioButtonUI", MaterialRadioButtonUI.class.getCanonicalName()); + table.put("TabbedPaneUI", MaterialTabbedPaneUI.class.getCanonicalName()); + table.put("ToggleButtonUI", MaterialToggleButtonUI.class.getCanonicalName()); + table.put("ScrollBarUI", MaterialScrollBarUI.class.getCanonicalName()); + table.put("ComboBoxUI", MaterialComboBoxUI.class.getCanonicalName()); + table.put("PopupMenuUI", MaterialPopupMenuUI.class.getCanonicalName()); + table.put("ToolBarUI", MaterialToolBarUI.class.getCanonicalName()); + table.put("SliderUI", MaterialSliderUI.class.getCanonicalName()); + table.put("ProgressBarUI", MaterialProgressBarUI.class.getCanonicalName()); + table.put("RadioButtonMenuItemUI", MaterialRadioButtonMenuItemUI.class.getCanonicalName()); + table.put("CheckBoxMenuItemUI", MaterialCheckBoxMenuItemUI.class.getCanonicalName()); + table.put("TextPaneUI", MaterialTextPaneUI.class.getCanonicalName()); + table.put("EditorPaneUI", MaterialEditorPaneUI.class.getCanonicalName()); + table.put("SeparatorUI", MaterialSeparatorUI.class.getCanonicalName()); + table.put("FileChooserUI", MaterialFileChooserUI.class.getCanonicalName()); + table.put("ToolTipUI", MaterialToolTipUI.class.getCanonicalName()); + table.put("SplitPaneUI", MaterialSplitPaneUI.class.getCanonicalName()); + // table.put ("ColorChooserUI", ); + } + + @Override + protected void initComponentDefaults(UIDefaults table) { + super.initComponentDefaults(table); + + table.put("Button.highlight", MaterialColors.GRAY_300); + table.put("Button.opaque", false); + table.put("Button.border", BorderFactory.createEmptyBorder(7, 17, 7, 17)); + table.put("Button.background", MaterialColors.GRAY_200); + table.put("Button.foreground", Color.BLACK); + table.put("Button.font", MaterialFonts.MEDIUM); + + table.put("CheckBox.font", MaterialFonts.REGULAR); + table.put("CheckBox.background", Color.WHITE); + table.put("CheckBox.foreground", Color.BLACK); + table.put("CheckBox.icon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); + table.put("CheckBox.selectedIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); + + table.put("ComboBox.font", MaterialFonts.REGULAR); + table.put("ComboBox.background", Color.WHITE); + table.put("ComboBox.foreground", Color.BLACK); + table.put( + "ComboBox.border", + BorderFactory.createCompoundBorder( + MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(0, 5, 0, 0))); + table.put("ComboBox.buttonBackground", MaterialColors.GRAY_300); + table.put("ComboBox.selectionBackground", Color.WHITE); + table.put("ComboBox.selectionForeground", Color.BLACK); + table.put("ComboBox.selectedInDropDownBackground", MaterialColors.GRAY_200); + + table.put("Label.font", MaterialFonts.REGULAR); + table.put("Label.background", Color.WHITE); + table.put("Label.foreground", Color.BLACK); + table.put("Label.border", BorderFactory.createEmptyBorder()); + + table.put("Menu.font", MaterialFonts.BOLD); + table.put("Menu.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("Menu.background", Color.WHITE); + table.put("Menu.foreground", Color.BLACK); + table.put("Menu.opaque", true); + table.put("Menu.selectionBackground", MaterialColors.GRAY_200); + table.put("Menu.selectionForeground", Color.BLACK); + table.put("Menu.disabledForeground", new Color(0, 0, 0, 100)); + table.put("Menu.menuPopupOffsetY", 3); + + table.put("MenuBar.font", MaterialFonts.BOLD); + table.put("MenuBar.background", Color.WHITE); + table.put("MenuBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); + table.put("MenuBar.foreground", Color.BLACK); + + table.put("MenuItem.disabledForeground", new Color(0, 0, 0, 100)); + table.put("MenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("MenuItem.selectionForeground", Color.BLACK); + table.put("MenuItem.font", MaterialFonts.MEDIUM); + table.put("MenuItem.background", Color.WHITE); + table.put("MenuItem.foreground", Color.BLACK); + table.put("MenuItem.border", BorderFactory.createEmptyBorder(5, 0, 5, 0)); + + table.put("OptionPane.background", Color.WHITE); + table.put("OptionPane.border", MaterialBorders.DEFAULT_SHADOW_BORDER); + table.put("OptionPane.font", MaterialFonts.REGULAR); + + table.put("Panel.font", MaterialFonts.REGULAR); + table.put("Panel.background", Color.WHITE); + table.put("Panel.border", BorderFactory.createEmptyBorder()); + + table.put("PopupMenu.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("PopupMenu.background", Color.WHITE); + table.put("PopupMenu.foreground", Color.BLACK); + + table.put("RadioButton.font", MaterialFonts.REGULAR); + table.put("RadioButton.background", Color.WHITE); + table.put("RadioButton.foreground", Color.BLACK); + table.put("RadioButton.icon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); + table.put("RadioButton.selectedIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); + + table.put("Spinner.font", MaterialFonts.REGULAR); + table.put("Spinner.background", Color.WHITE); + table.put("Spinner.foreground", Color.BLACK); + table.put("Spinner.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("Spinner.arrowButtonBackground", MaterialColors.GRAY_200); + table.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); + + table.put("ScrollBar.font", MaterialFonts.REGULAR); + table.put("ScrollBar.track", MaterialColors.GRAY_200); + table.put("ScrollBar.thumb", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbDarkShadow", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbHighlight", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbShadow", MaterialColors.GRAY_300); + table.put("ScrollBar.arrowButtonBackground", MaterialColors.GRAY_300); + table.put("ScrollBar.arrowButtonBorder", BorderFactory.createEmptyBorder()); + + table.put("ScrollPane.background", Color.WHITE); + table.put("ScrollPane.border", BorderFactory.createEmptyBorder()); + table.put("ScrollPane.font", MaterialFonts.REGULAR); + + table.put("Slider.font", MaterialFonts.REGULAR); + table.put("Slider.background", Color.WHITE); + table.put("Slider.foreground", MaterialColors.GRAY_700); + table.put("Slider.trackColor", Color.BLACK); + // table.put ("Slider.border", + // BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, + // BorderFactory.createEmptyBorder (5, 5, 5, 5))); + + table.put("SplitPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("SplitPane.background", Color.WHITE); + table.put("SplitPane.dividerSize", 10); + table.put("SplitPaneDivider.border", MaterialBorders.LIGHT_SHADOW_BORDER); + + table.put("TabbedPane.font", MaterialFonts.REGULAR); + table.put("TabbedPane.background", Color.WHITE); + table.put("TabbedPane.foreground", Color.BLACK); + table.put("TabbedPane.border", BorderFactory.createEmptyBorder()); + table.put("TabbedPane.shadow", null); + table.put("TabbedPane.darkShadow", null); + table.put("TabbedPane.highlight", MaterialColors.GRAY_200); + table.put("TabbedPane.borderHighlightColor", MaterialColors.GRAY_300); + + table.put("Table.selectionBackground", MaterialColors.GRAY_100); + table.put("Table.selectionForeground", Color.BLACK); + table.put("Table.background", Color.WHITE); + table.put("Table.font", MaterialFonts.REGULAR); + table.put("Table.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("Table.gridColor", MaterialColors.GRAY_200); + table.put("TableHeader.background", MaterialColors.GRAY_200); + table.put("TableHeader.font", MaterialFonts.BOLD); + table.put( + "TableHeader.cellBorder", + BorderFactory.createCompoundBorder( + MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(5, 5, 5, 5))); + + table.put("TextArea.background", MaterialColors.GRAY_200); + table.put("TextArea.border", BorderFactory.createEmptyBorder()); + table.put("TextArea.foreground", Color.BLACK); + + table.put("ToggleButton.border", BorderFactory.createEmptyBorder()); + table.put("ToggleButton.font", MaterialFonts.REGULAR); + table.put("ToggleButton.background", Color.WHITE); + table.put("ToggleButton.foreground", Color.BLACK); + table.put("ToggleButton.icon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_OFF)); + table.put("ToggleButton.selectedIcon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_ON)); + + table.put("ToolBar.font", MaterialFonts.REGULAR); + table.put("ToolBar.background", Color.WHITE); + table.put("ToolBar.foreground", Color.BLACK); + table.put("ToolBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); + table.put("ToolBar.dockingBackground", MaterialColors.LIGHT_GREEN_A100); + table.put("ToolBar.floatingBackground", MaterialColors.GRAY_200); + + table.put("Tree.font", MaterialFonts.REGULAR); + table.put("Tree.selectionForeground", Color.BLACK); + table.put("Tree.foreground", Color.BLACK); + table.put("Tree.selectionBackground", MaterialColors.GRAY_200); + table.put("Tree.background", Color.WHITE); + table.put("Tree.closedIcon", new ImageIcon(MaterialImages.RIGHT_ARROW)); + table.put("Tree.openIcon", new ImageIcon(MaterialImages.DOWN_ARROW)); + table.put("Tree.selectionBorderColor", null); + + table.put("RadioButtonMenuItem.foreground", Color.BLACK); + table.put("RadioButtonMenuItem.selectionForeground", Color.BLACK); + // If it changes the background of the menuitem it must change this too, irrespective of its + // setting + table.put("RadioButtonMenuItem.background", UIManager.getColor("MenuItem.background")); + table.put("RadioButtonMenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("RadioButtonMenuItem.checkIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); + table.put( + "RadioButtonMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); + + // If it changes the background of the menuitem it must change this too, irrespective of its + // setting + table.put("CheckBoxMenuItem.background", UIManager.getColor("MenuItem.background")); + table.put("CheckBoxMenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("CheckBoxMenuItem.foreground", Color.BLACK); + table.put("CheckBoxMenuItem.selectionForeground", Color.BLACK); + table.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("CheckBoxMenuItem.checkIcon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); + table.put( + "CheckBoxMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); + + table.put("TextPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("TextPane.background", MaterialColors.GRAY_50); + table.put("TextPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); + table.put("TextPane.inactiveForeground", MaterialColors.GRAY_500); + table.put("TextPane.font", MaterialFonts.REGULAR); + + table.put("EditorPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("EditorPane.background", MaterialColors.GRAY_50); + table.put("EditorPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); + table.put("EditorPane.inactiveForeground", MaterialColors.GRAY_500); + table.put("EditorPane.font", MaterialFonts.REGULAR); + + table.put("Separator.background", MaterialColors.GRAY_300); + table.put("Separator.foreground", MaterialColors.GRAY_300); + + table.put("ToolTip.background", MaterialColors.GRAY_500); + table.put("ToolTip.foreground", MaterialColors.GRAY_50); + table.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + table.put("ColorChooser.background", MaterialColors.WHITE); + table.put("ColorChooser.foreground", MaterialColors.BLACK); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java index db7d604a0..a0fdc487a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java @@ -5,13 +5,13 @@ public class MaterialUIMovement { - private MaterialUIMovement() {} + private MaterialUIMovement() {} - public static void add(JComponent c, Color fadeTo, int steps, int interval) { - new MaterialUITimer(c, fadeTo, steps, interval); - } + public static void add(JComponent c, Color fadeTo, int steps, int interval) { + new MaterialUITimer(c, fadeTo, steps, interval); + } - public static void add(JComponent c, Color fadeTo) { - add(c, fadeTo, 5, 1000 / 30); - } + public static void add(JComponent c, Color fadeTo) { + add(c, fadeTo, 5, 1000 / 30); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java index f989185c7..b5ca8415f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java @@ -10,99 +10,99 @@ public class MaterialUITimer implements MouseListener, ActionListener { - private Color from, to; - private boolean forward; - private int alpha, steps; - private int[] forwardDeltas, backwardDeltas; - - private JComponent component; - private Timer timer; - - protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { - this.from = component.getBackground(); - this.to = to; - - this.forwardDeltas = new int[4]; - this.backwardDeltas = new int[4]; - - forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; - forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; - forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; - forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; - - backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; - backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; - backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; - backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; - - this.steps = steps; - - this.component = component; - this.component.addMouseListener(this); - timer = new Timer(interval, this); - } - - private Color nextColor() { - int rValue = from.getRed() - alpha * forwardDeltas[0]; - int gValue = from.getGreen() - alpha * forwardDeltas[1]; - int bValue = from.getBlue() - alpha * forwardDeltas[2]; - int aValue = from.getAlpha() - alpha * forwardDeltas[3]; - - return new Color(rValue, gValue, bValue, aValue); - } - - private Color previousColor() { - int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; - int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; - int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; - int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; - - return new Color(rValue, gValue, bValue, aValue); - } - - @Override - public void mousePressed(MouseEvent me) { - alpha = steps - 1; - forward = false; - timer.start(); - - alpha = 0; - forward = true; - timer.start(); - } - - @Override - public void mouseReleased(MouseEvent me) {} - - @Override - public void mouseClicked(MouseEvent me) {} - - @Override - public void mouseExited(MouseEvent me) { - alpha = steps - 1; - forward = false; - timer.start(); - } - - @Override - public void mouseEntered(MouseEvent me) { - alpha = 0; - forward = true; - timer.start(); + private Color from, to; + private boolean forward; + private int alpha, steps; + private int[] forwardDeltas, backwardDeltas; + + private JComponent component; + private Timer timer; + + protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { + this.from = component.getBackground(); + this.to = to; + + this.forwardDeltas = new int[4]; + this.backwardDeltas = new int[4]; + + forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; + forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; + forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; + forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; + + backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; + backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; + backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; + backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; + + this.steps = steps; + + this.component = component; + this.component.addMouseListener(this); + timer = new Timer(interval, this); + } + + private Color nextColor() { + int rValue = from.getRed() - alpha * forwardDeltas[0]; + int gValue = from.getGreen() - alpha * forwardDeltas[1]; + int bValue = from.getBlue() - alpha * forwardDeltas[2]; + int aValue = from.getAlpha() - alpha * forwardDeltas[3]; + + return new Color(rValue, gValue, bValue, aValue); + } + + private Color previousColor() { + int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; + int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; + int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; + int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; + + return new Color(rValue, gValue, bValue, aValue); + } + + @Override + public void mousePressed(MouseEvent me) { + alpha = steps - 1; + forward = false; + timer.start(); + + alpha = 0; + forward = true; + timer.start(); + } + + @Override + public void mouseReleased(MouseEvent me) {} + + @Override + public void mouseClicked(MouseEvent me) {} + + @Override + public void mouseExited(MouseEvent me) { + alpha = steps - 1; + forward = false; + timer.start(); + } + + @Override + public void mouseEntered(MouseEvent me) { + alpha = 0; + forward = true; + timer.start(); + } + + @Override + public void actionPerformed(ActionEvent ae) { + if (forward) { + component.setBackground(nextColor()); + ++alpha; + } else { + component.setBackground(previousColor()); + --alpha; } - @Override - public void actionPerformed(ActionEvent ae) { - if (forward) { - component.setBackground(nextColor()); - ++alpha; - } else { - component.setBackground(previousColor()); - --alpha; - } - - if (alpha == steps + 1 || alpha == -1) { - timer.stop(); - } + if (alpha == steps + 1 || alpha == -1) { + timer.stop(); } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java index debe6e215..5fbc8c1aa 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java @@ -12,33 +12,33 @@ public class MaterialButtonUI extends BasicButtonUI { - public static ComponentUI createUI(final JComponent c) { - return new MaterialButtonUI(); - } + public static ComponentUI createUI(final JComponent c) { + return new MaterialButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - AbstractButton button = (AbstractButton) c; - MaterialUIMovement.add(c, MaterialColors.GRAY_300); - button.setOpaque(UIManager.getBoolean("Button.opaque")); - button.setBorder(UIManager.getBorder("Button.border")); - button.setBackground(UIManager.getColor("Button.background")); - button.setForeground(UIManager.getColor("Button.foreground")); - button.setFont(UIManager.getFont("Button.font")); - } + AbstractButton button = (AbstractButton) c; + MaterialUIMovement.add(c, MaterialColors.GRAY_300); + button.setOpaque(UIManager.getBoolean("Button.opaque")); + button.setBorder(UIManager.getBorder("Button.border")); + button.setBackground(UIManager.getColor("Button.background")); + button.setForeground(UIManager.getColor("Button.foreground")); + button.setFont(UIManager.getFont("Button.font")); + } - @Override - public void paint(Graphics g, JComponent c) { - AbstractButton b = (AbstractButton) c; - g = MaterialDrawingUtils.getAliasedGraphics(g); - paintBackground(g, b); - super.paint(g, c); - } + @Override + public void paint(Graphics g, JComponent c) { + AbstractButton b = (AbstractButton) c; + g = MaterialDrawingUtils.getAliasedGraphics(g); + paintBackground(g, b); + super.paint(g, c); + } - private void paintBackground(Graphics g, JComponent c) { - g.setColor(c.getBackground()); - g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 7, 7); - } + private void paintBackground(Graphics g, JComponent c) { + g.setColor(c.getBackground()); + g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 7, 7); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java index 8f0df3604..18870c571 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java @@ -15,48 +15,48 @@ */ public class MaterialCheckBoxMenuItemUI extends BasicCheckBoxMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialCheckBoxMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialCheckBoxMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintMenuItem( - Graphics g, - JComponent c, - Icon checkIcon, - Icon arrowIcon, - Color background, - Color foreground, - int defaultTextIconGap) { - JCheckBoxMenuItem checkBoxMenuItem = (JCheckBoxMenuItem) c; - if (checkBoxMenuItem.isSelected()) { - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - checkBoxMenuItem, - UIManager.getIcon("CheckBoxMenuItem.selectedCheckIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - return; - } - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - checkBoxMenuItem, - UIManager.getIcon("CheckBoxMenuItem.checkIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); + @Override + protected void paintMenuItem( + Graphics g, + JComponent c, + Icon checkIcon, + Icon arrowIcon, + Color background, + Color foreground, + int defaultTextIconGap) { + JCheckBoxMenuItem checkBoxMenuItem = (JCheckBoxMenuItem) c; + if (checkBoxMenuItem.isSelected()) { + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + checkBoxMenuItem, + UIManager.getIcon("CheckBoxMenuItem.selectedCheckIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + return; } + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + checkBoxMenuItem, + UIManager.getIcon("CheckBoxMenuItem.checkIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java index 4a9725d52..e851617f9 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java @@ -11,24 +11,24 @@ // TODO cambio colore icone combo box public class MaterialCheckBoxUI extends BasicCheckBoxUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialCheckBoxUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialCheckBoxUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JCheckBox checkBox = (JCheckBox) c; - checkBox.setFont(UIManager.getFont("CheckBox.font")); - checkBox.setBackground(UIManager.getColor("CheckBox.background")); - checkBox.setForeground(UIManager.getColor("CheckBox.foreground")); - checkBox.setIcon(UIManager.getIcon("CheckBox.icon")); - checkBox.setSelectedIcon(UIManager.getIcon("CheckBox.selectedIcon")); - } + JCheckBox checkBox = (JCheckBox) c; + checkBox.setFont(UIManager.getFont("CheckBox.font")); + checkBox.setBackground(UIManager.getColor("CheckBox.background")); + checkBox.setForeground(UIManager.getColor("CheckBox.foreground")); + checkBox.setIcon(UIManager.getIcon("CheckBox.icon")); + checkBox.setSelectedIcon(UIManager.getIcon("CheckBox.selectedIcon")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java index 73573d8f8..e8e0957e1 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java @@ -9,21 +9,20 @@ public class MaterialComboBoxRenderer extends BasicComboBoxRenderer { - @Override - public Component getListCellRendererComponent( - JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JComponent component = - (JComponent) - super.getListCellRendererComponent( - list, value, index, isSelected, cellHasFocus); + @Override + public Component getListCellRendererComponent( + JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JComponent component = + (JComponent) + super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - component.setForeground(UIManager.getColor("ComboBox.foreground")); - component.setBackground( - isSelected || cellHasFocus - ? UIManager.getColor("ComboBox.selectedInDropDownBackground") - : UIManager.getColor("ComboBox.background")); + component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + component.setForeground(UIManager.getColor("ComboBox.foreground")); + component.setBackground( + isSelected || cellHasFocus + ? UIManager.getColor("ComboBox.selectedInDropDownBackground") + : UIManager.getColor("ComboBox.background")); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java index 8cd52995b..3cd934502 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java @@ -15,42 +15,42 @@ public class MaterialComboBoxUI extends BasicComboBoxUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialComboBoxUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JComboBox comboBox = (JComboBox) c; - comboBox.setFont(UIManager.getFont("ComboBox.font")); - comboBox.setBackground(UIManager.getColor("ComboBox.background")); - comboBox.setForeground(UIManager.getColor("ComboBox.foreground")); - comboBox.setBorder(UIManager.getBorder("ComboBox.border")); - comboBox.setLightWeightPopupEnabled(true); - comboBox.setRenderer(new MaterialComboBoxRenderer()); - } - - @Override - protected JButton createArrowButton() { - Icon icon = UIManager.getIcon("ComboBox.buttonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.SOUTH); - } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ComboBox.buttonBackground")); - button.setBorder(BorderFactory.createEmptyBorder()); - - return button; - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + public static ComponentUI createUI(JComponent c) { + return new MaterialComboBoxUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JComboBox comboBox = (JComboBox) c; + comboBox.setFont(UIManager.getFont("ComboBox.font")); + comboBox.setBackground(UIManager.getColor("ComboBox.background")); + comboBox.setForeground(UIManager.getColor("ComboBox.foreground")); + comboBox.setBorder(UIManager.getBorder("ComboBox.border")); + comboBox.setLightWeightPopupEnabled(true); + comboBox.setRenderer(new MaterialComboBoxRenderer()); + } + + @Override + protected JButton createArrowButton() { + Icon icon = UIManager.getIcon("ComboBox.buttonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.SOUTH); } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ComboBox.buttonBackground")); + button.setBorder(BorderFactory.createEmptyBorder()); + + return button; + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java index 786f289bb..df165a608 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java @@ -9,12 +9,12 @@ */ public class MaterialEditorPaneUI extends BasicEditorPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialEditorPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialEditorPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java index b8046c569..ffcca1064 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java @@ -11,48 +11,48 @@ public class MaterialFileChooserUI extends MetalFileChooserUI { - public MaterialFileChooserUI(JFileChooser fileChooser) { - super(fileChooser); - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialFileChooserUI((JFileChooser) c); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - JFileChooser fileChooser = (JFileChooser) c; - MaterialFileChooserUI ui = (MaterialFileChooserUI) fileChooser.getUI(); - - ui.uninstallIcons(fileChooser); - ui.uninstallComponents(fileChooser); - ui.clearIconCache(); - - ui.computerIcon = new ImageIcon(MaterialImages.COMPUTER); - ui.directoryIcon = new ImageIcon(MaterialImages.FOLDER); - ui.fileIcon = new ImageIcon(MaterialImages.FILE); - ui.floppyDriveIcon = new ImageIcon(MaterialImages.FLOPPY_DRIVE); - ui.hardDriveIcon = new ImageIcon(MaterialImages.HARD_DRIVE); - - ui.homeFolderIcon = new ImageIcon(MaterialImages.HOME); - ui.listViewIcon = new ImageIcon(MaterialImages.LIST); - ui.detailsViewIcon = new ImageIcon(MaterialImages.DETAILS); - ui.newFolderIcon = new ImageIcon(MaterialImages.NEW_FOLDER); - ui.upFolderIcon = new ImageIcon(MaterialImages.BACK_ARROW); - - ui.openButtonText = "OPEN"; - ui.cancelButtonText = "CANCEL"; - ui.helpButtonText = "HELP"; - ui.saveButtonText = "SAVE"; - ui.directoryOpenButtonText = "OPEN"; - ui.updateButtonText = "UPDATE"; - - ui.installComponents(fileChooser); - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + public MaterialFileChooserUI(JFileChooser fileChooser) { + super(fileChooser); + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialFileChooserUI((JFileChooser) c); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + JFileChooser fileChooser = (JFileChooser) c; + MaterialFileChooserUI ui = (MaterialFileChooserUI) fileChooser.getUI(); + + ui.uninstallIcons(fileChooser); + ui.uninstallComponents(fileChooser); + ui.clearIconCache(); + + ui.computerIcon = new ImageIcon(MaterialImages.COMPUTER); + ui.directoryIcon = new ImageIcon(MaterialImages.FOLDER); + ui.fileIcon = new ImageIcon(MaterialImages.FILE); + ui.floppyDriveIcon = new ImageIcon(MaterialImages.FLOPPY_DRIVE); + ui.hardDriveIcon = new ImageIcon(MaterialImages.HARD_DRIVE); + + ui.homeFolderIcon = new ImageIcon(MaterialImages.HOME); + ui.listViewIcon = new ImageIcon(MaterialImages.LIST); + ui.detailsViewIcon = new ImageIcon(MaterialImages.DETAILS); + ui.newFolderIcon = new ImageIcon(MaterialImages.NEW_FOLDER); + ui.upFolderIcon = new ImageIcon(MaterialImages.BACK_ARROW); + + ui.openButtonText = "OPEN"; + ui.cancelButtonText = "CANCEL"; + ui.helpButtonText = "HELP"; + ui.saveButtonText = "SAVE"; + ui.directoryOpenButtonText = "OPEN"; + ui.updateButtonText = "UPDATE"; + + ui.installComponents(fileChooser); + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java index e19fc1fed..de43761a9 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java @@ -10,24 +10,24 @@ public class MaterialLabelUI extends BasicLabelUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialLabelUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialLabelUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JLabel label = (JLabel) c; - label.setOpaque(true); - label.setFont(UIManager.getFont("Label.font")); - label.setBackground(UIManager.getColor("Label.background")); - label.setForeground(UIManager.getColor("Label.foreground")); - label.setBorder(UIManager.getBorder("Label.border")); - } + JLabel label = (JLabel) c; + label.setOpaque(true); + label.setFont(UIManager.getFont("Label.font")); + label.setBackground(UIManager.getColor("Label.background")); + label.setForeground(UIManager.getColor("Label.foreground")); + label.setBorder(UIManager.getBorder("Label.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java index 011d61862..decb5908d 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java @@ -10,23 +10,23 @@ public class MaterialMenuBarUI extends BasicMenuBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenuBar menuBar = (JMenuBar) c; - menuBar.setFont(UIManager.getFont("MenuBar.font")); - menuBar.setBackground(UIManager.getColor("MenuBar.background")); - menuBar.setBorder(UIManager.getBorder("MenuBar.border")); - menuBar.setForeground(UIManager.getColor("MenuBar.foreground")); - } + JMenuBar menuBar = (JMenuBar) c; + menuBar.setFont(UIManager.getFont("MenuBar.font")); + menuBar.setBackground(UIManager.getColor("MenuBar.background")); + menuBar.setBorder(UIManager.getBorder("MenuBar.border")); + menuBar.setForeground(UIManager.getColor("MenuBar.foreground")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java index a8c572b62..32b537bd1 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java @@ -11,25 +11,25 @@ public class MaterialMenuItemUI extends BasicMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenuItem menuItem = (JMenuItem) c; - menuItem.setFont(UIManager.getFont("MenuItem.font")); - menuItem.setBackground(UIManager.getColor("MenuItem.background")); - menuItem.setForeground(UIManager.getColor("MenuItem.foreground")); - menuItem.setHorizontalAlignment(SwingConstants.LEFT); - menuItem.setVerticalAlignment(SwingConstants.CENTER); - menuItem.setBorder(UIManager.getBorder("MenuItem.border")); - } + JMenuItem menuItem = (JMenuItem) c; + menuItem.setFont(UIManager.getFont("MenuItem.font")); + menuItem.setBackground(UIManager.getColor("MenuItem.background")); + menuItem.setForeground(UIManager.getColor("MenuItem.foreground")); + menuItem.setHorizontalAlignment(SwingConstants.LEFT); + menuItem.setVerticalAlignment(SwingConstants.CENTER); + menuItem.setBorder(UIManager.getBorder("MenuItem.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java index 16c1b9270..d45c3f37f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java @@ -10,24 +10,24 @@ public class MaterialMenuUI extends BasicMenuUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenu menu = (JMenu) c; - menu.setFont(UIManager.getFont("Menu.font")); - menu.setBorder(UIManager.getBorder("Menu.border")); - menu.setBackground(UIManager.getColor("Menu.background")); - menu.setForeground(UIManager.getColor("Menu.foreground")); - menu.setOpaque(UIManager.getBoolean("Menu.opaque")); - } + JMenu menu = (JMenu) c; + menu.setFont(UIManager.getFont("Menu.font")); + menu.setBorder(UIManager.getBorder("Menu.border")); + menu.setBackground(UIManager.getColor("Menu.background")); + menu.setForeground(UIManager.getColor("Menu.foreground")); + menu.setOpaque(UIManager.getBoolean("Menu.opaque")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java index ae7a9be6b..005d439d6 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java @@ -10,23 +10,23 @@ public class MaterialPanelUI extends BasicPanelUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialPanelUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialPanelUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JPanel panel = (JPanel) c; - panel.setOpaque(true); - panel.setFont(UIManager.getFont("Panel.font")); - panel.setBackground(UIManager.getColor("Panel.background")); - panel.setBorder(UIManager.getBorder("Panel.border")); - } + JPanel panel = (JPanel) c; + panel.setOpaque(true); + panel.setFont(UIManager.getFont("Panel.font")); + panel.setBackground(UIManager.getColor("Panel.background")); + panel.setBorder(UIManager.getBorder("Panel.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java index d4778402b..f4f02ff4f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java @@ -27,192 +27,185 @@ import javax.swing.text.View; public class MaterialPasswordFieldUI extends BasicPasswordFieldUI - implements FocusListener, PropertyChangeListener { - - private Color focusedBackground; - private Color unfocusedBackground; - private Color focusedSelectionBackground; - private Color unfocusedSelectionBackground; - - public static ComponentUI createUI(JComponent c) { - return new MaterialPasswordFieldUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JPasswordField passwordField = (JPasswordField) c; - passwordField.setOpaque(false); - passwordField.setBorder(BorderFactory.createEmptyBorder(5, 2, 10, 0)); - passwordField.setBackground(MaterialColors.LIGHT_BLUE_400); - - this.focusedBackground = passwordField.getBackground(); - this.unfocusedBackground = MaterialColors.GRAY_200; - - this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); - this.unfocusedSelectionBackground = unfocusedBackground; - } - - @Override - protected void installListeners() { - getComponent().addFocusListener(this); - getComponent().addPropertyChangeListener(this); - } - - @Override - protected void installKeyboardActions() { - super.installKeyboardActions(); - - Action selectAll = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().selectAll(); - } - }; - - Action delete = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (getComponent().getSelectedText() == null) { - int pos = getComponent().getCaretPosition() - 1; - - if (pos >= 0) { - getComponent().select(pos, pos + 1); - getComponent().replaceSelection(""); - } - } else { - getComponent().replaceSelection(""); - } - } - }; - - Action left = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent() - .setCaretPosition( - Math.max(0, getComponent().getCaretPosition() - 1)); - } - }; - - Action right = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent() - .setCaretPosition( - Math.min( - getComponent().getText().length(), - getComponent().getCaretPosition() + 1)); - } - }; - - // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to - // getMenuShortcutKeyMaskEx() - getComponent() - .getInputMap() - .put( - KeyStroke.getKeyStroke( - KeyEvent.VK_A, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "selectAll"); - getComponent() - .getInputMap() - .put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); - - getComponent().getActionMap().put("selectAll", selectAll); - getComponent().getActionMap().put("delete", delete); - getComponent().getActionMap().put("left", left); - getComponent().getActionMap().put("right", right); - } - - @Override - public void paintSafely(Graphics g) { - JPasswordField c = (JPasswordField) getComponent(); - g = MaterialDrawingUtils.getAliasedGraphics(g); - - if (getComponent().hasFocus()) { - c.setBackground(focusedBackground); - c.setSelectionColor(focusedSelectionBackground); - } else { - c.setBackground(unfocusedBackground); - c.setSelectionColor(unfocusedSelectionBackground); - } - - int x = getComponent().getInsets().left; - int y = getComponent().getInsets().top; - int w = - getComponent().getWidth() - - getComponent().getInsets().left - - getComponent().getInsets().right; - - g.setColor(c.getBackground()); - g.fillRect(x, c.getHeight() - y, w, 2); - - super.paintSafely(g); + implements FocusListener, PropertyChangeListener { + + private Color focusedBackground; + private Color unfocusedBackground; + private Color focusedSelectionBackground; + private Color unfocusedSelectionBackground; + + public static ComponentUI createUI(JComponent c) { + return new MaterialPasswordFieldUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JPasswordField passwordField = (JPasswordField) c; + passwordField.setOpaque(false); + passwordField.setBorder(BorderFactory.createEmptyBorder(5, 2, 10, 0)); + passwordField.setBackground(MaterialColors.LIGHT_BLUE_400); + + this.focusedBackground = passwordField.getBackground(); + this.unfocusedBackground = MaterialColors.GRAY_200; + + this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); + this.unfocusedSelectionBackground = unfocusedBackground; + } + + @Override + protected void installListeners() { + getComponent().addFocusListener(this); + getComponent().addPropertyChangeListener(this); + } + + @Override + protected void installKeyboardActions() { + super.installKeyboardActions(); + + Action selectAll = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().selectAll(); + } + }; + + Action delete = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (getComponent().getSelectedText() == null) { + int pos = getComponent().getCaretPosition() - 1; + + if (pos >= 0) { + getComponent().select(pos, pos + 1); + getComponent().replaceSelection(""); + } + } else { + getComponent().replaceSelection(""); + } + } + }; + + Action left = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); + } + }; + + Action right = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.min( + getComponent().getText().length(), getComponent().getCaretPosition() + 1)); + } + }; + + // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to + // getMenuShortcutKeyMaskEx() + getComponent() + .getInputMap() + .put( + KeyStroke.getKeyStroke( + KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "selectAll"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); + + getComponent().getActionMap().put("selectAll", selectAll); + getComponent().getActionMap().put("delete", delete); + getComponent().getActionMap().put("left", left); + getComponent().getActionMap().put("right", right); + } + + @Override + public void paintSafely(Graphics g) { + JPasswordField c = (JPasswordField) getComponent(); + g = MaterialDrawingUtils.getAliasedGraphics(g); + + if (getComponent().hasFocus()) { + c.setBackground(focusedBackground); + c.setSelectionColor(focusedSelectionBackground); + } else { + c.setBackground(unfocusedBackground); + c.setSelectionColor(unfocusedSelectionBackground); } - @Override - public void paintBackground(Graphics g) { - super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); + int x = getComponent().getInsets().left; + int y = getComponent().getInsets().top; + int w = + getComponent().getWidth() + - getComponent().getInsets().left + - getComponent().getInsets().right; + + g.setColor(c.getBackground()); + g.fillRect(x, c.getHeight() - y, w, 2); + + super.paintSafely(g); + } + + @Override + public void paintBackground(Graphics g) { + super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); + } + + @Override + public void focusGained(FocusEvent e) { + e.getComponent().setBackground(focusedBackground); + } + + @Override + public void focusLost(FocusEvent e) { + e.getComponent().setBackground(unfocusedBackground); + } + + @Override + public void propertyChange(PropertyChangeEvent pce) { + if (pce.getPropertyName().equals("background")) { + Color newColor = (Color) pce.getNewValue(); + + if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { + this.focusedBackground = (Color) pce.getNewValue(); + this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); + } } + } - @Override - public void focusGained(FocusEvent e) { - e.getComponent().setBackground(focusedBackground); - } + @Override + public View create(Element elem) { + return new MaterialPasswordView(elem); + } - @Override - public void focusLost(FocusEvent e) { - e.getComponent().setBackground(unfocusedBackground); - } + private static class MaterialPasswordView extends PasswordView { - @Override - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName().equals("background")) { - Color newColor = (Color) pce.getNewValue(); - - if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { - this.focusedBackground = (Color) pce.getNewValue(); - this.focusedSelectionBackground = - MaterialColors.bleach(this.focusedBackground, 0.3f); - } - } + private MaterialPasswordView(Element elem) { + super(elem); } + // depreciated in Java 9 and above - replace method with float drawEchoCharacter(Graphics2D + // g, + // float x, float y, char c) @Override - public View create(Element elem) { - return new MaterialPasswordView(elem); - } - - private static class MaterialPasswordView extends PasswordView { - - private MaterialPasswordView(Element elem) { - super(elem); - } - - // depreciated in Java 9 and above - replace method with float drawEchoCharacter(Graphics2D - // g, - // float x, float y, char c) - @Override - protected int drawEchoCharacter(Graphics g, int x, int y, char c) { - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + protected int drawEchoCharacter(Graphics g, int x, int y, char c) { + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - FontMetrics fm = g2.getFontMetrics(); - int r = fm.charWidth(c) - 2; + FontMetrics fm = g2.getFontMetrics(); + int r = fm.charWidth(c) - 2; - g2.setPaint(Color.BLACK); - g2.fillOval(x + 1, y + 5 - fm.getAscent(), r, r); - g2.dispose(); + g2.setPaint(Color.BLACK); + g2.fillOval(x + 1, y + 5 - fm.getAscent(), r, r); + g2.dispose(); - return x + fm.charWidth(c); - } + return x + fm.charWidth(c); } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java index d7baaf5df..a864e9a41 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java @@ -10,22 +10,22 @@ public class MaterialPopupMenuUI extends BasicPopupMenuUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialPopupMenuUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialPopupMenuUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JPopupMenu popupMenu = (JPopupMenu) c; - popupMenu.setBorder(UIManager.getBorder("PopupMenu.border")); - popupMenu.setBackground(UIManager.getColor("PopupMenu.background")); - popupMenu.setForeground(UIManager.getColor("PopupMenu.foreground")); - } + JPopupMenu popupMenu = (JPopupMenu) c; + popupMenu.setBorder(UIManager.getBorder("PopupMenu.border")); + popupMenu.setBackground(UIManager.getColor("PopupMenu.background")); + popupMenu.setForeground(UIManager.getColor("PopupMenu.foreground")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java index 7f91a779f..062204e11 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java @@ -14,22 +14,22 @@ */ public class MaterialProgressBarUI extends BasicProgressBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialProgressBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialProgressBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JProgressBar progressBar = (JProgressBar) c; - progressBar.setBorder(MaterialBorders.LIGHT_LINE_BORDER); - progressBar.setBackground(MaterialColors.GRAY_200); - progressBar.setForeground(MaterialColors.LIGHT_BLUE_400); - } + JProgressBar progressBar = (JProgressBar) c; + progressBar.setBorder(MaterialBorders.LIGHT_LINE_BORDER); + progressBar.setBackground(MaterialColors.GRAY_200); + progressBar.setForeground(MaterialColors.LIGHT_BLUE_400); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java index 69a9cae53..92aa97726 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java @@ -15,51 +15,51 @@ */ public class MaterialRadioButtonMenuItemUI extends BasicRadioButtonMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialRadioButtonMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialRadioButtonMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; - // j.setBackground(MaterialColors.WHITE); - j.setBorder(UIManager.getBorder("MenuItem.border")); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; + // j.setBackground(MaterialColors.WHITE); + j.setBorder(UIManager.getBorder("MenuItem.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintMenuItem( - Graphics g, - JComponent c, - Icon checkIcon, - Icon arrowIcon, - Color background, - Color foreground, - int defaultTextIconGap) { - JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; - if (j.isSelected()) { - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - c, - UIManager.getIcon("RadioButtonMenuItem.selectedCheckIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - return; - } - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - c, - UIManager.getIcon("RadioButtonMenuItem.checkIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); + @Override + protected void paintMenuItem( + Graphics g, + JComponent c, + Icon checkIcon, + Icon arrowIcon, + Color background, + Color foreground, + int defaultTextIconGap) { + JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; + if (j.isSelected()) { + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + c, + UIManager.getIcon("RadioButtonMenuItem.selectedCheckIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + return; } + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + c, + UIManager.getIcon("RadioButtonMenuItem.checkIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java index 6418d4f17..517d9086d 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java @@ -14,24 +14,24 @@ // TODO cambio colore del radio button. public class MaterialRadioButtonUI extends BasicRadioButtonUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialRadioButtonUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialRadioButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JRadioButton radioButton = (JRadioButton) c; - radioButton.setFont(UIManager.getFont("RadioButton.font")); - radioButton.setBackground(UIManager.getColor("RadioButton.background")); - radioButton.setForeground(UIManager.getColor("RadioButton.foreground")); - radioButton.setIcon(UIManager.getIcon("RadioButton.icon")); - radioButton.setSelectedIcon(UIManager.getIcon("RadioButton.selectedIcon")); - } + JRadioButton radioButton = (JRadioButton) c; + radioButton.setFont(UIManager.getFont("RadioButton.font")); + radioButton.setBackground(UIManager.getColor("RadioButton.background")); + radioButton.setForeground(UIManager.getColor("RadioButton.foreground")); + radioButton.setIcon(UIManager.getIcon("RadioButton.icon")); + radioButton.setSelectedIcon(UIManager.getIcon("RadioButton.selectedIcon")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java index 164209b3f..c433ddf92 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java @@ -16,49 +16,49 @@ public class MaterialScrollBarUI extends BasicScrollBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialScrollBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialScrollBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JScrollBar scrollBar = (JScrollBar) c; - scrollBar.setFont(UIManager.getFont("ScrollBar.font")); - trackColor = UIManager.getColor("ScrollBar.track"); - thumbColor = UIManager.getColor("ScrollBar.thumb"); - thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); - thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); - thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); - } + JScrollBar scrollBar = (JScrollBar) c; + scrollBar.setFont(UIManager.getFont("ScrollBar.font")); + trackColor = UIManager.getColor("ScrollBar.track"); + thumbColor = UIManager.getColor("ScrollBar.thumb"); + thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); + thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); + thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected JButton createDecreaseButton(int orientation) { - JButton button = new BasicArrowButton(orientation); + @Override + protected JButton createDecreaseButton(int orientation) { + JButton button = new BasicArrowButton(orientation); - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); - return button; - } + return button; + } - @Override - protected JButton createIncreaseButton(int orientation) { - JButton button = new BasicArrowButton(orientation); + @Override + protected JButton createIncreaseButton(int orientation) { + JButton button = new BasicArrowButton(orientation); - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); - return button; - } + return button; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java index 042b53d1b..36ee98b90 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java @@ -8,17 +8,17 @@ public class MaterialSeparatorUI extends BasicSeparatorUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialSeparatorUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialSeparatorUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java index 7ac2fe350..3195c05e0 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java @@ -13,131 +13,131 @@ // TODO cambio grafica slider public class MaterialSliderUI extends BasicSliderUI { - private static final int NORMAL_THUMB_RADIUS = 6; - private static final int DRAG_THUMB_RADIUS = 10; - private static final Dimension THUMB_SIZE = - new Dimension(DRAG_THUMB_RADIUS * 2, DRAG_THUMB_RADIUS * 2); - - public MaterialSliderUI(JSlider slider) { - super(slider); - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialSliderUI((JSlider) c); + private static final int NORMAL_THUMB_RADIUS = 6; + private static final int DRAG_THUMB_RADIUS = 10; + private static final Dimension THUMB_SIZE = + new Dimension(DRAG_THUMB_RADIUS * 2, DRAG_THUMB_RADIUS * 2); + + public MaterialSliderUI(JSlider slider) { + super(slider); + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialSliderUI((JSlider) c); + } + + private static void drawCircle(Graphics g, int x, int y, int radius) { + g.fillOval(x - radius, y - radius, radius * 2, radius * 2); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JSlider slider = (JSlider) c; + slider.setFont(UIManager.getFont("Slider.font")); + slider.setBackground(UIManager.getColor("Slider.background")); + slider.setForeground(UIManager.getColor("Slider.foreground")); + slider.setBorder(UIManager.getBorder("Slider.border")); + } + + @Override + public Dimension getThumbSize() { + return THUMB_SIZE; + } + + @Override + public void paintThumb(Graphics g) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + + int cx = thumbRect.x + thumbRect.width / 2; + int cy = thumbRect.y + thumbRect.height / 2; + + if (isDragging()) { + g.setColor(MaterialColors.bleach(slider.getForeground(), 0.5f)); + drawCircle(g, cx, cy, DRAG_THUMB_RADIUS); } - private static void drawCircle(Graphics g, int x, int y, int radius) { - g.fillOval(x - radius, y - radius, radius * 2, radius * 2); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JSlider slider = (JSlider) c; - slider.setFont(UIManager.getFont("Slider.font")); - slider.setBackground(UIManager.getColor("Slider.background")); - slider.setForeground(UIManager.getColor("Slider.foreground")); - slider.setBorder(UIManager.getBorder("Slider.border")); + g.setColor(slider.getForeground()); + drawCircle(g, cx, cy, NORMAL_THUMB_RADIUS); + + // need to redraw loaded part of progress line + Line loaded = getTrack(true); + g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + } + + @Override + public void paintTrack(Graphics g) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + + g.setColor(UIManager.getColor("Slider.trackColor")); + Line unloaded = getTrack(false); + g.drawLine(unloaded.x1, unloaded.y1, unloaded.x2, unloaded.y2); + + g.setColor(slider.getForeground()); + Line loaded = getTrack(true); + g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + } + + private Line getTrack(boolean loaded) { + if (slider.getOrientation() == JSlider.HORIZONTAL) { + Line left = + new Line( + trackRect.x, + thumbRect.y + thumbRect.height / 2, + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2); + Line right = + new Line( + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2, + trackRect.x + trackRect.width, + thumbRect.y + thumbRect.height / 2); + + if (loaded) { + return slider.getInverted() ? right : left; + } else { + return slider.getInverted() ? left : right; + } + } else { + Line top = + new Line( + thumbRect.x + thumbRect.width / 2, + trackRect.y, + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2); + Line bottom = + new Line( + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2, + thumbRect.x + thumbRect.width / 2, + trackRect.y + trackRect.height); + + if (loaded) { + return slider.getInverted() ? top : bottom; + } else { + return slider.getInverted() ? bottom : top; + } } + } - @Override - public Dimension getThumbSize() { - return THUMB_SIZE; - } - - @Override - public void paintThumb(Graphics g) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - - int cx = thumbRect.x + thumbRect.width / 2; - int cy = thumbRect.y + thumbRect.height / 2; - - if (isDragging()) { - g.setColor(MaterialColors.bleach(slider.getForeground(), 0.5f)); - drawCircle(g, cx, cy, DRAG_THUMB_RADIUS); - } - - g.setColor(slider.getForeground()); - drawCircle(g, cx, cy, NORMAL_THUMB_RADIUS); + @Override + public void paintFocus(Graphics g) {} - // need to redraw loaded part of progress line - Line loaded = getTrack(true); - g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); - } - - @Override - public void paintTrack(Graphics g) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - - g.setColor(UIManager.getColor("Slider.trackColor")); - Line unloaded = getTrack(false); - g.drawLine(unloaded.x1, unloaded.y1, unloaded.x2, unloaded.y2); - - g.setColor(slider.getForeground()); - Line loaded = getTrack(true); - g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); - } - - private Line getTrack(boolean loaded) { - if (slider.getOrientation() == JSlider.HORIZONTAL) { - Line left = - new Line( - trackRect.x, - thumbRect.y + thumbRect.height / 2, - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2); - Line right = - new Line( - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2, - trackRect.x + trackRect.width, - thumbRect.y + thumbRect.height / 2); - - if (loaded) { - return slider.getInverted() ? right : left; - } else { - return slider.getInverted() ? left : right; - } - } else { - Line top = - new Line( - thumbRect.x + thumbRect.width / 2, - trackRect.y, - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2); - Line bottom = - new Line( - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2, - thumbRect.x + thumbRect.width / 2, - trackRect.y + trackRect.height); - - if (loaded) { - return slider.getInverted() ? top : bottom; - } else { - return slider.getInverted() ? bottom : top; - } - } - } - - @Override - public void paintFocus(Graphics g) {} - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - private static class Line { + private static class Line { - int x1, y1, x2, y2; + int x1, y1, x2, y2; - Line(int x1, int y1, int x2, int y2) { - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - } + Line(int x1, int y1, int x2, int y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java index ecfcbab17..71428661a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java @@ -15,68 +15,68 @@ public class MaterialSpinnerUI extends BasicSpinnerUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialSpinnerUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); + public static ComponentUI createUI(JComponent c) { + return new MaterialSpinnerUI(); + } - JSpinner spinner = (JSpinner) c; - spinner.setOpaque(false); - spinner.setFont(UIManager.getFont("Spinner.font")); - spinner.setBackground(UIManager.getColor("Spinner.background")); - spinner.setForeground(UIManager.getColor("Spinner.foreground")); - spinner.setBorder(UIManager.getBorder("Spinner.border")); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); - @Override - protected JComponent createEditor() { - JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) super.createEditor(); - editor.getTextField().setUI(new MaterialTextFieldUI(false)); + JSpinner spinner = (JSpinner) c; + spinner.setOpaque(false); + spinner.setFont(UIManager.getFont("Spinner.font")); + spinner.setBackground(UIManager.getColor("Spinner.background")); + spinner.setForeground(UIManager.getColor("Spinner.foreground")); + spinner.setBorder(UIManager.getBorder("Spinner.border")); + } - return editor; - } + @Override + protected JComponent createEditor() { + JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) super.createEditor(); + editor.getTextField().setUI(new MaterialTextFieldUI(false)); - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + return editor; + } - @Override - protected Component createNextButton() { - Icon icon = UIManager.getIcon("Spinner.nextButtonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.NORTH); - } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); - installNextButtonListeners(button); + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - return button; + @Override + protected Component createNextButton() { + Icon icon = UIManager.getIcon("Spinner.nextButtonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.NORTH); } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); + installNextButtonListeners(button); - @Override - protected Component createPreviousButton() { - Icon icon = UIManager.getIcon("Spinner.previousButtonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.SOUTH); - } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); - installPreviousButtonListeners(button); + return button; + } - return button; + @Override + protected Component createPreviousButton() { + Icon icon = UIManager.getIcon("Spinner.previousButtonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.SOUTH); } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); + installPreviousButtonListeners(button); + + return button; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java index 0ec5db987..c33ea201a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java @@ -4,20 +4,20 @@ import javax.swing.plaf.basic.BasicSplitPaneUI; public class MaterialSplitPaneDivider extends BasicSplitPaneDivider { - public MaterialSplitPaneDivider(BasicSplitPaneUI ui) { - super(ui); - // oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, - // "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); - // oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, - // "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); - // centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), - // ui, "SplitPane.centerOneTouchButtons", true); - // setLayout(new DividerLayout()); - // setBasicSplitPaneUI(ui); - // orientation = splitPane.getOrientation(); - // setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? - // Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : - // Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); - // setBackground(UIManager.getColor("SplitPane.background")); - } + public MaterialSplitPaneDivider(BasicSplitPaneUI ui) { + super(ui); + // oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, + // "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); + // oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, + // "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); + // centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), + // ui, "SplitPane.centerOneTouchButtons", true); + // setLayout(new DividerLayout()); + // setBasicSplitPaneUI(ui); + // orientation = splitPane.getOrientation(); + // setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? + // Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : + // Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); + // setBackground(UIManager.getColor("SplitPane.background")); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java index 33cee1316..d95f3f766 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java @@ -4,24 +4,24 @@ import javax.swing.plaf.basic.BasicSplitPaneUI; public class MaterialSplitPaneUI extends BasicSplitPaneUI { - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JSplitPane splitPane = (JSplitPane) c; - splitPane.setOpaque(false); - splitPane.setBorder(UIManager.getBorder("SplitPane.border")); - splitPane.setBackground(UIManager.getColor("SplitPane.background")); - splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); - } + JSplitPane splitPane = (JSplitPane) c; + splitPane.setOpaque(false); + splitPane.setBorder(UIManager.getBorder("SplitPane.border")); + splitPane.setBackground(UIManager.getColor("SplitPane.background")); + splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); + } - // /** - // * Creates the default divider. - // * - // * @return the default divider - // */ - // @Override - // public BasicSplitPaneDivider createDefaultDivider() { - // return new MaterialSplitPaneDivider(this); - // } + // /** + // * Creates the default divider. + // * + // * @return the default divider + // */ + // @Override + // public BasicSplitPaneDivider createDefaultDivider() { + // return new MaterialSplitPaneDivider(this); + // } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java index 878ed8479..bcc6d68f4 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java @@ -11,86 +11,72 @@ public class MaterialTabbedPaneUI extends BasicTabbedPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTabbedPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTabbedPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JTabbedPane tabbedPane = (JTabbedPane) c; - tabbedPane.setOpaque(false); - tabbedPane.setFont(UIManager.getFont("TabbedPane.font")); - tabbedPane.setBackground(UIManager.getColor("TabbedPane.background")); - tabbedPane.setForeground(UIManager.getColor("TabbedPane.foreground")); - tabbedPane.setBorder(UIManager.getBorder("TabbedPane.border")); + JTabbedPane tabbedPane = (JTabbedPane) c; + tabbedPane.setOpaque(false); + tabbedPane.setFont(UIManager.getFont("TabbedPane.font")); + tabbedPane.setBackground(UIManager.getColor("TabbedPane.background")); + tabbedPane.setForeground(UIManager.getColor("TabbedPane.foreground")); + tabbedPane.setBorder(UIManager.getBorder("TabbedPane.border")); - darkShadow = UIManager.getColor("TabbedPane.darkShadow"); - shadow = UIManager.getColor("TabbedPane.shadow"); - lightHighlight = UIManager.getColor("TabbedPane.highlight"); - } + darkShadow = UIManager.getColor("TabbedPane.darkShadow"); + shadow = UIManager.getColor("TabbedPane.shadow"); + lightHighlight = UIManager.getColor("TabbedPane.highlight"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintTabBackground( - Graphics g, - int tabPlacement, - int tabIndex, - int x, - int y, - int w, - int h, - boolean isSelected) { - g.setColor(isSelected ? lightHighlight : tabPane.getBackground()); - g.fillRect(x, y, w, h); - } + @Override + protected void paintTabBackground( + Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { + g.setColor(isSelected ? lightHighlight : tabPane.getBackground()); + g.fillRect(x, y, w, h); + } - @Override - protected void paintTabBorder( - Graphics g, - int tabPlacement, - int tabIndex, - int x, - int y, - int w, - int h, - boolean isSelected) { - g.setColor(UIManager.getColor("TabbedPane.borderHighlightColor")); - g.drawRect(x, y, w, h); - } + @Override + protected void paintTabBorder( + Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { + g.setColor(UIManager.getColor("TabbedPane.borderHighlightColor")); + g.drawRect(x, y, w, h); + } - @Override - protected void paintFocusIndicator( - Graphics g, - int tabPlacement, - Rectangle[] rects, - int tabIndex, - Rectangle iconRect, - Rectangle textRect, - boolean isSelected) { - // do nothing - } + @Override + protected void paintFocusIndicator( + Graphics g, + int tabPlacement, + Rectangle[] rects, + int tabIndex, + Rectangle iconRect, + Rectangle textRect, + boolean isSelected) { + // do nothing + } - @Override - protected void paintTab( - Graphics g, - int tabPlacement, - Rectangle[] rects, - int tabIndex, - Rectangle iconRect, - Rectangle textRect) { - // for some reason tabs aren't painted properly by paint() - super.paintTab( - MaterialDrawingUtils.getAliasedGraphics(g), - tabPlacement, - rects, - tabIndex, - iconRect, - textRect); - } + @Override + protected void paintTab( + Graphics g, + int tabPlacement, + Rectangle[] rects, + int tabIndex, + Rectangle iconRect, + Rectangle textRect) { + // for some reason tabs aren't painted properly by paint() + super.paintTab( + MaterialDrawingUtils.getAliasedGraphics(g), + tabPlacement, + rects, + tabIndex, + iconRect, + textRect); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java index b4e07e95f..3f8cdc80b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java @@ -7,26 +7,25 @@ public class MaterialTableCellEditor extends DefaultCellEditor { - public MaterialTableCellEditor() { - super(init()); - } + public MaterialTableCellEditor() { + super(init()); + } - private static JTextField init() { - JTextField textField = new JTextField(); - textField.setUI(new MaterialTextFieldUI(false)); + private static JTextField init() { + JTextField textField = new JTextField(); + textField.setUI(new MaterialTextFieldUI(false)); - return textField; - } + return textField; + } - @Override - public Component getTableCellEditorComponent( - JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { - JTextField textField = - (JTextField) - super.getTableCellEditorComponent( - table, value, isSelected, rowIndex, vColIndex); - textField.setText(value.toString()); + @Override + public Component getTableCellEditorComponent( + JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { + JTextField textField = + (JTextField) + super.getTableCellEditorComponent(table, value, isSelected, rowIndex, vColIndex); + textField.setText(value.toString()); - return textField; - } + return textField; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java index 8fe0438e8..2dd33246a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java @@ -9,20 +9,19 @@ public class MaterialTableCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent( - JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - JComponent component = - (JComponent) - super.getTableCellRendererComponent( - table, value, isSelected, hasFocus, row, column); + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JComponent component = + (JComponent) + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - // hides yellow selection highlight - component.setBorder(BorderFactory.createEmptyBorder()); + // hides yellow selection highlight + component.setBorder(BorderFactory.createEmptyBorder()); - this.setHorizontalAlignment(SwingConstants.CENTER); - this.setVerticalAlignment(SwingConstants.CENTER); + this.setHorizontalAlignment(SwingConstants.CENTER); + this.setVerticalAlignment(SwingConstants.CENTER); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java index 01f4db191..458b8062a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java @@ -9,20 +9,19 @@ public class MaterialTableHeaderCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent( - JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - JComponent component = - (JComponent) - super.getTableCellRendererComponent( - table, value, isSelected, hasFocus, row, column); - component.setBorder(UIManager.getBorder("TableHeader.cellBorder")); - component.setFont(UIManager.getFont("TableHeader.font")); - component.setBackground(UIManager.getColor("TableHeader.background")); + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JComponent component = + (JComponent) + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + component.setBorder(UIManager.getBorder("TableHeader.cellBorder")); + component.setFont(UIManager.getFont("TableHeader.font")); + component.setBackground(UIManager.getColor("TableHeader.background")); - this.setHorizontalAlignment(SwingConstants.CENTER); - this.setVerticalAlignment(SwingConstants.CENTER); + this.setHorizontalAlignment(SwingConstants.CENTER); + this.setVerticalAlignment(SwingConstants.CENTER); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java index 7a1eadb92..e039aba97 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java @@ -9,20 +9,20 @@ public class MaterialTableHeaderUI extends BasicTableHeaderUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTableHeaderUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTableHeaderUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JTableHeader header = (JTableHeader) c; - header.setDefaultRenderer(new MaterialTableHeaderCellRenderer()); - } + JTableHeader header = (JTableHeader) c; + header.setDefaultRenderer(new MaterialTableHeaderCellRenderer()); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java index 91c68c973..af3d7fbc5 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java @@ -10,37 +10,37 @@ public class MaterialTableUI extends BasicTableUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTableUI(); + public static ComponentUI createUI(JComponent c) { + return new MaterialTableUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTable table = (JTable) c; + table.setOpaque(false); + table.setSelectionForeground(UIManager.getColor("Table.selectionForeground")); + table.setBackground(UIManager.getColor("Table.background")); + table.setFont(UIManager.getFont("Table.font")); + table.setBorder(UIManager.getBorder("Table.border")); + table.setGridColor(UIManager.getColor("Table.gridColor")); + table.setSelectionBackground(UIManager.getColor("Table.selectionBackground")); + + table.getTableHeader().setResizingAllowed(true); + int rowHeight = UIManager.getInt("Table.rowHeight"); + if (rowHeight > 0) { + table.setRowHeight(rowHeight); + } else { + table.setRowHeight(table.getRowHeight() + 25); } - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTable table = (JTable) c; - table.setOpaque(false); - table.setSelectionForeground(UIManager.getColor("Table.selectionForeground")); - table.setBackground(UIManager.getColor("Table.background")); - table.setFont(UIManager.getFont("Table.font")); - table.setBorder(UIManager.getBorder("Table.border")); - table.setGridColor(UIManager.getColor("Table.gridColor")); - table.setSelectionBackground(UIManager.getColor("Table.selectionBackground")); - - table.getTableHeader().setResizingAllowed(true); - int rowHeight = UIManager.getInt("Table.rowHeight"); - if (rowHeight > 0) { - table.setRowHeight(rowHeight); - } else { - table.setRowHeight(table.getRowHeight() + 25); - } - - table.setDefaultRenderer(Object.class, new MaterialTableCellRenderer()); - table.setDefaultEditor(Object.class, new MaterialTableCellEditor()); - } + table.setDefaultRenderer(Object.class, new MaterialTableCellRenderer()); + table.setDefaultEditor(Object.class, new MaterialTableCellEditor()); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java index 5cfd2fc88..874392573 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java @@ -22,196 +22,189 @@ import javax.swing.plaf.basic.BasicTextFieldUI; public class MaterialTextFieldUI extends BasicTextFieldUI - implements FocusListener, PropertyChangeListener { - - private Color focusedBackground; - private Color unfocusedBackground; - private Color focusedSelectionBackground; - private Color unfocusedSelectionBackground; - private boolean drawLine; - - public MaterialTextFieldUI() { - this(true); - } - - public MaterialTextFieldUI(boolean drawLine) { - super(); - this.drawLine = drawLine; - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialTextFieldUI(); + implements FocusListener, PropertyChangeListener { + + private Color focusedBackground; + private Color unfocusedBackground; + private Color focusedSelectionBackground; + private Color unfocusedSelectionBackground; + private boolean drawLine; + + public MaterialTextFieldUI() { + this(true); + } + + public MaterialTextFieldUI(boolean drawLine) { + super(); + this.drawLine = drawLine; + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialTextFieldUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTextField textField = (JTextField) c; + textField.setOpaque(false); + textField.setBorder( + drawLine + ? BorderFactory.createEmptyBorder(5, 2, 10, 0) + : BorderFactory.createEmptyBorder(2, 2, 2, 2)); + + textField.setBackground(MaterialColors.LIGHT_BLUE_400); + textField.setFont(MaterialFonts.REGULAR); + + this.focusedBackground = textField.getBackground(); + this.unfocusedBackground = MaterialColors.GRAY_200; + + this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); + this.unfocusedSelectionBackground = unfocusedBackground; + } + + @Override + protected void installListeners() { + super.installListeners(); + getComponent().addFocusListener(this); + getComponent().addPropertyChangeListener(this); + } + + @Override + protected void installKeyboardActions() { + super.installKeyboardActions(); + + Action selectAll = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().selectAll(); + } + }; + + Action delete = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (getComponent().getSelectedText() == null) { + int pos = getComponent().getCaretPosition() - 1; + + if (pos >= 0) { + getComponent().select(pos, pos + 1); + getComponent().replaceSelection(""); + } + } else { + getComponent().replaceSelection(""); + } + } + }; + + Action left = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); + } + }; + + Action right = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.min( + getComponent().getText().length(), getComponent().getCaretPosition() + 1)); + } + }; + + Action enter = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + ((JTextField) getComponent()).postActionEvent(); + } + }; + + // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to + // getMenuShortcutKeyMaskEx() + getComponent() + .getInputMap() + .put( + KeyStroke.getKeyStroke( + KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "selectAll"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); + + getComponent().getActionMap().put("selectAll", selectAll); + getComponent().getActionMap().put("delete", delete); + getComponent().getActionMap().put("left", left); + getComponent().getActionMap().put("right", right); + getComponent().getActionMap().put("enter", enter); + } + + @Override + public void paintSafely(Graphics g) { + JTextField c = (JTextField) getComponent(); + g = MaterialDrawingUtils.getAliasedGraphics(g); + + Color lineColor; + + if (getComponent().hasFocus()) { + lineColor = focusedBackground; + c.setSelectionColor(focusedSelectionBackground); + } else { + lineColor = unfocusedBackground; + c.setSelectionColor(unfocusedSelectionBackground); } - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTextField textField = (JTextField) c; - textField.setOpaque(false); - textField.setBorder( - drawLine - ? BorderFactory.createEmptyBorder(5, 2, 10, 0) - : BorderFactory.createEmptyBorder(2, 2, 2, 2)); - - textField.setBackground(MaterialColors.LIGHT_BLUE_400); - textField.setFont(MaterialFonts.REGULAR); - - this.focusedBackground = textField.getBackground(); - this.unfocusedBackground = MaterialColors.GRAY_200; - - this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); - this.unfocusedSelectionBackground = unfocusedBackground; - } + g.setColor(lineColor); + getComponent().setBackground(lineColor); - @Override - protected void installListeners() { - super.installListeners(); - getComponent().addFocusListener(this); - getComponent().addPropertyChangeListener(this); - } + if (drawLine) { + int x = getComponent().getInsets().left; + int y = getComponent().getInsets().top; + int w = + getComponent().getWidth() + - getComponent().getInsets().left + - getComponent().getInsets().right; - @Override - protected void installKeyboardActions() { - super.installKeyboardActions(); - - Action selectAll = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().selectAll(); - } - }; - - Action delete = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (getComponent().getSelectedText() == null) { - int pos = getComponent().getCaretPosition() - 1; - - if (pos >= 0) { - getComponent().select(pos, pos + 1); - getComponent().replaceSelection(""); - } - } else { - getComponent().replaceSelection(""); - } - } - }; - - Action left = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent() - .setCaretPosition( - Math.max(0, getComponent().getCaretPosition() - 1)); - } - }; - - Action right = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent() - .setCaretPosition( - Math.min( - getComponent().getText().length(), - getComponent().getCaretPosition() + 1)); - } - }; - - Action enter = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - ((JTextField) getComponent()).postActionEvent(); - } - }; - - // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to - // getMenuShortcutKeyMaskEx() - getComponent() - .getInputMap() - .put( - KeyStroke.getKeyStroke( - KeyEvent.VK_A, - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "selectAll"); - getComponent() - .getInputMap() - .put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); - - getComponent().getActionMap().put("selectAll", selectAll); - getComponent().getActionMap().put("delete", delete); - getComponent().getActionMap().put("left", left); - getComponent().getActionMap().put("right", right); - getComponent().getActionMap().put("enter", enter); + g.fillRect(x, c.getHeight() - y, w, 2); } - @Override - public void paintSafely(Graphics g) { - JTextField c = (JTextField) getComponent(); - g = MaterialDrawingUtils.getAliasedGraphics(g); - - Color lineColor; - - if (getComponent().hasFocus()) { - lineColor = focusedBackground; - c.setSelectionColor(focusedSelectionBackground); - } else { - lineColor = unfocusedBackground; - c.setSelectionColor(unfocusedSelectionBackground); - } - - g.setColor(lineColor); - getComponent().setBackground(lineColor); - - if (drawLine) { - int x = getComponent().getInsets().left; - int y = getComponent().getInsets().top; - int w = - getComponent().getWidth() - - getComponent().getInsets().left - - getComponent().getInsets().right; - - g.fillRect(x, c.getHeight() - y, w, 2); - } + super.paintSafely(g); + } - super.paintSafely(g); - } - - @Override - public void paintBackground(final Graphics g) { - super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); - } + @Override + public void paintBackground(final Graphics g) { + super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); + } - @Override - public void focusGained(FocusEvent e) { - e.getComponent().setBackground(focusedBackground); - } + @Override + public void focusGained(FocusEvent e) { + e.getComponent().setBackground(focusedBackground); + } - @Override - public void focusLost(FocusEvent e) { - e.getComponent().setBackground(unfocusedBackground); - } + @Override + public void focusLost(FocusEvent e) { + e.getComponent().setBackground(unfocusedBackground); + } - @Override - public void propertyChange(PropertyChangeEvent pce) { - super.propertyChange(pce); + @Override + public void propertyChange(PropertyChangeEvent pce) { + super.propertyChange(pce); - if (pce.getPropertyName().equals("background")) { - Color newColor = (Color) pce.getNewValue(); + if (pce.getPropertyName().equals("background")) { + Color newColor = (Color) pce.getNewValue(); - if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { - this.focusedBackground = (Color) pce.getNewValue(); - this.focusedSelectionBackground = - MaterialColors.bleach(this.focusedBackground, 0.3f); - } - } + if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { + this.focusedBackground = (Color) pce.getNewValue(); + this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); + } } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java index f70048468..61fba8d33 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java @@ -9,12 +9,12 @@ */ public class MaterialTextPaneUI extends BasicTextPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTextPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTextPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java index 3749366e9..42786abba 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java @@ -10,28 +10,28 @@ public class MaterialToggleButtonUI extends BasicToggleButtonUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToggleButtonUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToggleButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JToggleButton toggleButton = (JToggleButton) c; - toggleButton.setBorder(UIManager.getBorder("ToggleButton.border")); - toggleButton.setFont(UIManager.getFont("ToggleButton.font")); - toggleButton.setBackground(UIManager.getColor("ToggleButton.background")); - toggleButton.setForeground(UIManager.getColor("ToggleButton.foreground")); + JToggleButton toggleButton = (JToggleButton) c; + toggleButton.setBorder(UIManager.getBorder("ToggleButton.border")); + toggleButton.setFont(UIManager.getFont("ToggleButton.font")); + toggleButton.setBackground(UIManager.getColor("ToggleButton.background")); + toggleButton.setForeground(UIManager.getColor("ToggleButton.foreground")); - if (toggleButton.getIcon() == null && toggleButton.getSelectedIcon() == null) { - toggleButton.setIcon(UIManager.getIcon("ToggleButton.icon")); - toggleButton.setSelectedIcon(UIManager.getIcon("ToggleButton.selectedIcon")); - } + if (toggleButton.getIcon() == null && toggleButton.getSelectedIcon() == null) { + toggleButton.setIcon(UIManager.getIcon("ToggleButton.icon")); + toggleButton.setSelectedIcon(UIManager.getIcon("ToggleButton.selectedIcon")); } + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java index 10251eb73..58a752c59 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java @@ -10,28 +10,28 @@ public class MaterialToolBarUI extends BasicToolBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToolBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToolBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - JToolBar toolBar = (JToolBar) c; + @Override + public void installUI(JComponent c) { + super.installUI(c); + JToolBar toolBar = (JToolBar) c; - toolBar.setFont(UIManager.getFont("ToolBar.font")); - toolBar.setBackground(UIManager.getColor("ToolBar.background")); - toolBar.setForeground(UIManager.getColor("ToolBar.foreground")); - toolBar.setBorder(UIManager.getBorder("ToolBar.border")); + toolBar.setFont(UIManager.getFont("ToolBar.font")); + toolBar.setBackground(UIManager.getColor("ToolBar.background")); + toolBar.setForeground(UIManager.getColor("ToolBar.foreground")); + toolBar.setBorder(UIManager.getBorder("ToolBar.border")); - this.dockingBorderColor = null; - this.floatingBorderColor = null; - this.dockingColor = UIManager.getColor("ToolBar.dockingBackground"); - this.floatingColor = UIManager.getColor("ToolBar.floatingBackground"); - } + this.dockingBorderColor = null; + this.floatingBorderColor = null; + this.dockingColor = UIManager.getColor("ToolBar.dockingBackground"); + this.floatingColor = UIManager.getColor("ToolBar.floatingBackground"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java index 87e415e4c..2b023c920 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java @@ -8,17 +8,17 @@ public class MaterialToolTipUI extends BasicToolTipUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToolTipUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToolTipUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java index ee9b0fcff..6565ca731 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java @@ -11,43 +11,43 @@ public class MaterialTreeCellEditor extends DefaultTreeCellEditor { - private JTextField textField; - - public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { - super(tree, renderer); - init(); - } - - public MaterialTreeCellEditor( - JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { - super(tree, renderer, editor); - init(); - } - - private void init() { - textField = new JTextField(); - textField.setUI(new MaterialTextFieldUI()); - - textField.addKeyListener( - new KeyAdapter() { - @Override - public void keyTyped(KeyEvent e) { - if (e.getKeyChar() == KeyEvent.VK_ENTER) { - stopCellEditing(); - } - } - }); - } - - @Override - public Component getTreeCellEditorComponent( - JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { - textField.setText(value.toString()); - return textField; - } - - @Override - public Object getCellEditorValue() { - return textField.getText(); - } + private JTextField textField; + + public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { + super(tree, renderer); + init(); + } + + public MaterialTreeCellEditor( + JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { + super(tree, renderer, editor); + init(); + } + + private void init() { + textField = new JTextField(); + textField.setUI(new MaterialTextFieldUI()); + + textField.addKeyListener( + new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + if (e.getKeyChar() == KeyEvent.VK_ENTER) { + stopCellEditing(); + } + } + }); + } + + @Override + public Component getTreeCellEditorComponent( + JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { + textField.setText(value.toString()); + return textField; + } + + @Override + public Object getCellEditorValue() { + return textField.getText(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java index 6ac5acabb..f4e85bba2 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java @@ -9,37 +9,37 @@ public class MaterialTreeCellRenderer extends DefaultTreeCellRenderer { - public MaterialTreeCellRenderer() { - setTextSelectionColor(UIManager.getColor("Tree.selectionForeground")); - setTextNonSelectionColor(UIManager.getColor("Tree.foreground")); - - setBackgroundSelectionColor(UIManager.getColor("Tree.selectionBackground")); - setBackgroundNonSelectionColor(UIManager.getColor("Tree.background")); - - setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor")); - - setClosedIcon(UIManager.getIcon("Tree.closedIcon")); - setOpenIcon(UIManager.getIcon("Tree.openIcon")); - setLeafIcon(null); - - setFont(UIManager.getFont("Tree.font")); - } - - @Override - public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean isSelected, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { - JComponent component = - (JComponent) - super.getTreeCellRendererComponent( - tree, value, isSelected, expanded, leaf, row, hasFocus); - component.setBorder(BorderFactory.createEmptyBorder(5, 2, 5, 2)); - - return component; - } + public MaterialTreeCellRenderer() { + setTextSelectionColor(UIManager.getColor("Tree.selectionForeground")); + setTextNonSelectionColor(UIManager.getColor("Tree.foreground")); + + setBackgroundSelectionColor(UIManager.getColor("Tree.selectionBackground")); + setBackgroundNonSelectionColor(UIManager.getColor("Tree.background")); + + setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor")); + + setClosedIcon(UIManager.getIcon("Tree.closedIcon")); + setOpenIcon(UIManager.getIcon("Tree.openIcon")); + setLeafIcon(null); + + setFont(UIManager.getFont("Tree.font")); + } + + @Override + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean isSelected, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + JComponent component = + (JComponent) + super.getTreeCellRendererComponent( + tree, value, isSelected, expanded, leaf, row, hasFocus); + component.setBorder(BorderFactory.createEmptyBorder(5, 2, 5, 2)); + + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java index 7d38c62f3..f21b0dfaa 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java @@ -12,33 +12,33 @@ public class MaterialTreeUI extends BasicTreeUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTreeUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - JTree tree = (JTree) c; - - DefaultTreeCellRenderer renderer = new MaterialTreeCellRenderer(); - TreeCellEditor editor = new MaterialTreeCellEditor(tree, renderer); - - tree.setCellRenderer(renderer); - tree.setCellEditor(editor); - - tree.setFont(UIManager.getFont("Tree.font")); - tree.setRowHeight(0); - tree.setInvokesStopCellEditing(true); - - MaterialTreeUI ui = (MaterialTreeUI) tree.getUI(); - ui.setLeftChildIndent(10); - ui.setRightChildIndent(10); - } - - @Override - public void paint(Graphics g, JComponent c) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - super.paint(g, c); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTreeUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + JTree tree = (JTree) c; + + DefaultTreeCellRenderer renderer = new MaterialTreeCellRenderer(); + TreeCellEditor editor = new MaterialTreeCellEditor(tree, renderer); + + tree.setCellRenderer(renderer); + tree.setCellEditor(editor); + + tree.setFont(UIManager.getFont("Tree.font")); + tree.setRowHeight(0); + tree.setInvokesStopCellEditing(true); + + MaterialTreeUI ui = (MaterialTreeUI) tree.getUI(); + ui.setLeftChildIndent(10); + ui.setRightChildIndent(10); + } + + @Override + public void paint(Graphics g, JComponent c) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + super.paint(g, c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java index ce3244d4d..e0b9ca436 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java @@ -29,410 +29,389 @@ */ public class DropShadowBorder extends AbstractBorder implements Border { - private static final Map> CACHE = - new HashMap>(); - private Color lineColor; - private int lineWidth; - private int shadowSize; - private float shadowOpacity; - private int cornerSize; - private boolean showTopShadow; - private boolean showLeftShadow; - private boolean showBottomShadow; - private boolean showRightShadow; - - public DropShadowBorder() { - this(UIManager.getColor("Control"), 1, 5); - } - - public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) { - this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true); - } - - public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) { - this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true); - } - - public DropShadowBorder( - Color lineColor, - int lineWidth, - int shadowSize, - float shadowOpacity, - int cornerSize, - boolean showTopShadow, - boolean showLeftShadow, - boolean showBottomShadow, - boolean showRightShadow) { - this.lineColor = lineColor; - this.lineWidth = lineWidth; - this.shadowSize = shadowSize; - this.shadowOpacity = shadowOpacity; - this.cornerSize = cornerSize; - this.showTopShadow = showTopShadow; - this.showLeftShadow = showLeftShadow; - this.showBottomShadow = showBottomShadow; - this.showRightShadow = showRightShadow; - } - - /** */ - public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { - /* - * 1) Get images for this border - * 2) Paint the images for each side of the border that should be painted - */ - Map images = getImages(null); - - // compute the edges of the components -- not including the border - // Insets borderInsets = getBorderInsets (c); - // int leftEdge = x + borderInsets.left - lineWidth; - // int rightEdge = x + width - borderInsets.right; - // int topEdge = y + borderInsets.top - lineWidth; - // int bottomEdge = y + height - borderInsets.bottom; - Graphics2D g2 = (Graphics2D) graphics; - g2.setColor(lineColor); - - // The location and size of the shadows depends on which shadows are being - // drawn. For instance, if the left & bottom shadows are being drawn, then - // the left shadows extends all the way down to the corner, a corner is drawn, - // and then the bottom shadows begins at the corner. If, however, only the - // bottom shadows is drawn, then the bottom-left corner is drawn to the - // right of the corner, and the bottom shadows is somewhat shorter than before. - - Point topLeftShadowPoint = null; - if (showLeftShadow || showTopShadow) { - topLeftShadowPoint = new Point(); - if (showLeftShadow && !showTopShadow) { - topLeftShadowPoint.setLocation(x, y + shadowSize); - } else { - if (showLeftShadow && showTopShadow) { - topLeftShadowPoint.setLocation(x, y); - } else { - if (!showLeftShadow && showTopShadow) { - topLeftShadowPoint.setLocation(x + shadowSize, y); - } - } - } - } - - Point bottomLeftShadowPoint = null; - if (showLeftShadow || showBottomShadow) { - bottomLeftShadowPoint = new Point(); - if (showLeftShadow && !showBottomShadow) { - bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); - } else { - if (showLeftShadow && showBottomShadow) { - bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); - } else { - if (!showLeftShadow && showBottomShadow) { - bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); - } - } - } - } - - Point bottomRightShadowPoint = null; - if (showRightShadow || showBottomShadow) { - bottomRightShadowPoint = new Point(); - if (showRightShadow && !showBottomShadow) { - bottomRightShadowPoint.setLocation( - x + width - shadowSize, y + height - shadowSize - shadowSize); - } else { - if (showRightShadow && showBottomShadow) { - bottomRightShadowPoint.setLocation( - x + width - shadowSize, y + height - shadowSize); - } else { - if (!showRightShadow && showBottomShadow) { - bottomRightShadowPoint.setLocation( - x + width - shadowSize - shadowSize, y + height - shadowSize); - } - } - } - } - - Point topRightShadowPoint = null; - if (showRightShadow || showTopShadow) { - topRightShadowPoint = new Point(); - if (showRightShadow && !showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize); - } else { - if (showRightShadow && showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize, y); - } else { - if (!showRightShadow && showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); - } - } - } - } - - if (showLeftShadow) { - Rectangle leftShadowRect = - new Rectangle( - x, - (int) (topLeftShadowPoint.getY() + shadowSize), - shadowSize, - (int) - (bottomLeftShadowPoint.getY() - - topLeftShadowPoint.getY() - - shadowSize)); - g2.drawImage( - images.get(Position.LEFT) - .getScaledInstance( - leftShadowRect.width, leftShadowRect.height, Image.SCALE_FAST), - leftShadowRect.x, - leftShadowRect.y, - null); - } - - if (showBottomShadow) { - Rectangle bottomShadowRect = - new Rectangle( - (int) (bottomLeftShadowPoint.getX() + shadowSize), - y + height - shadowSize, - (int) - (bottomRightShadowPoint.getX() - - bottomLeftShadowPoint.getX() - - shadowSize), - shadowSize); - g2.drawImage( - images.get(Position.BOTTOM) - .getScaledInstance( - bottomShadowRect.width, - bottomShadowRect.height, - Image.SCALE_FAST), - bottomShadowRect.x, - bottomShadowRect.y, - null); - } - - if (showRightShadow) { - Rectangle rightShadowRect = - new Rectangle( - x + width - shadowSize, - (int) (topRightShadowPoint.getY() + shadowSize), - shadowSize, - (int) - (bottomRightShadowPoint.getY() - - topRightShadowPoint.getY() - - shadowSize)); - g2.drawImage( - images.get(Position.RIGHT) - .getScaledInstance( - rightShadowRect.width, - rightShadowRect.height, - Image.SCALE_FAST), - rightShadowRect.x, - rightShadowRect.y, - null); - } - - if (showTopShadow) { - Rectangle topShadowRect = - new Rectangle( - (int) topLeftShadowPoint.getX() + shadowSize, - y, - (int) - (topRightShadowPoint.getX() - - topLeftShadowPoint.getX() - - shadowSize), - shadowSize); - g2.drawImage( - images.get(Position.TOP) - .getScaledInstance( - topShadowRect.width, topShadowRect.height, Image.SCALE_FAST), - topShadowRect.x, - topShadowRect.y, - null); - } - - if (showLeftShadow || showTopShadow) { - g2.drawImage( - images.get(Position.TOP_LEFT), - null, - (int) topLeftShadowPoint.getX(), - (int) topLeftShadowPoint.getY()); - } - if (showLeftShadow || showBottomShadow) { - g2.drawImage( - images.get(Position.BOTTOM_LEFT), - null, - (int) bottomLeftShadowPoint.getX(), - (int) bottomLeftShadowPoint.getY()); - } - if (showRightShadow || showBottomShadow) { - g2.drawImage( - images.get(Position.BOTTOM_RIGHT), - null, - (int) bottomRightShadowPoint.getX(), - (int) bottomRightShadowPoint.getY()); - } - if (showRightShadow || showTopShadow) { - g2.drawImage( - images.get(Position.TOP_RIGHT), - null, - (int) topRightShadowPoint.getX(), - (int) topRightShadowPoint.getY()); + private static final Map> CACHE = + new HashMap>(); + private Color lineColor; + private int lineWidth; + private int shadowSize; + private float shadowOpacity; + private int cornerSize; + private boolean showTopShadow; + private boolean showLeftShadow; + private boolean showBottomShadow; + private boolean showRightShadow; + + public DropShadowBorder() { + this(UIManager.getColor("Control"), 1, 5); + } + + public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) { + this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true); + } + + public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) { + this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true); + } + + public DropShadowBorder( + Color lineColor, + int lineWidth, + int shadowSize, + float shadowOpacity, + int cornerSize, + boolean showTopShadow, + boolean showLeftShadow, + boolean showBottomShadow, + boolean showRightShadow) { + this.lineColor = lineColor; + this.lineWidth = lineWidth; + this.shadowSize = shadowSize; + this.shadowOpacity = shadowOpacity; + this.cornerSize = cornerSize; + this.showTopShadow = showTopShadow; + this.showLeftShadow = showLeftShadow; + this.showBottomShadow = showBottomShadow; + this.showRightShadow = showRightShadow; + } + + /** */ + public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { + /* + * 1) Get images for this border + * 2) Paint the images for each side of the border that should be painted + */ + Map images = getImages(null); + + // compute the edges of the components -- not including the border + // Insets borderInsets = getBorderInsets (c); + // int leftEdge = x + borderInsets.left - lineWidth; + // int rightEdge = x + width - borderInsets.right; + // int topEdge = y + borderInsets.top - lineWidth; + // int bottomEdge = y + height - borderInsets.bottom; + Graphics2D g2 = (Graphics2D) graphics; + g2.setColor(lineColor); + + // The location and size of the shadows depends on which shadows are being + // drawn. For instance, if the left & bottom shadows are being drawn, then + // the left shadows extends all the way down to the corner, a corner is drawn, + // and then the bottom shadows begins at the corner. If, however, only the + // bottom shadows is drawn, then the bottom-left corner is drawn to the + // right of the corner, and the bottom shadows is somewhat shorter than before. + + Point topLeftShadowPoint = null; + if (showLeftShadow || showTopShadow) { + topLeftShadowPoint = new Point(); + if (showLeftShadow && !showTopShadow) { + topLeftShadowPoint.setLocation(x, y + shadowSize); + } else { + if (showLeftShadow && showTopShadow) { + topLeftShadowPoint.setLocation(x, y); + } else { + if (!showLeftShadow && showTopShadow) { + topLeftShadowPoint.setLocation(x + shadowSize, y); + } } + } } - private Map getImages(Graphics2D g2) { - // first, check to see if an image for this size has already been rendered - // if so, use the cache. Else, draw and save - Map images = CACHE.get(shadowSize); - if (images == null) { - images = new HashMap(); - - /* - * Do draw a drop shadows, I have to: - * 1) Create a rounded rectangle - * 2) Create a BufferedImage to draw the rounded rect in - * 3) Translate the graphics for the image, so that the rectangle - * is centered in the drawn space. The border around the rectangle - * needs to be shadowWidth wide, so that there is space for the - * shadows to be drawn. - * 4) Draw the rounded rect as black, with an opacity of 50% - * 5) Create the BLUR_KERNEL - * 6) Blur the image - * 7) copy off the corners, sides, etc into images to be used for - * drawing the Border - */ - int rectWidth = cornerSize + 1; - RoundRectangle2D rect = - new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); - int imageWidth = rectWidth + shadowSize * 2; - BufferedImage image = - new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); - Graphics2D buffer = (Graphics2D) image.getGraphics(); - buffer.setRenderingHint( - RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - buffer.setRenderingHint( - RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - buffer.setRenderingHint( - RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - buffer.setRenderingHint( - RenderingHints.KEY_FRACTIONALMETRICS, - RenderingHints.VALUE_FRACTIONALMETRICS_ON); - buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); - buffer.translate(shadowSize, shadowSize); - buffer.fill(rect); - float blurry = 1.0f / (float) (shadowSize * shadowSize); // 1.0f / (float)(shadowSize * - // shadowSize); - float[] blurKernel = new float[shadowSize * shadowSize]; - for (int i = 0; i < blurKernel.length; i++) { - blurKernel[i] = blurry; - } - ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); - BufferedImage targetImage = - new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); - ((Graphics2D) targetImage.getGraphics()) - .drawImage(image, blur, -(shadowSize / 2), -(shadowSize / 2)); - - int x = 1; - int y = 1; - int w = shadowSize; - int h = shadowSize; - images.put(Position.TOP_LEFT, targetImage.getSubimage(x, y, w, h)); - x = 1; - y = h; - w = shadowSize; - h = 1; - images.put(Position.LEFT, targetImage.getSubimage(x, y, w, h)); - x = 1; - y = rectWidth; - w = shadowSize; - h = shadowSize; - images.put(Position.BOTTOM_LEFT, targetImage.getSubimage(x, y, w, h)); - x = cornerSize + 1; - y = rectWidth; - w = 1; - h = shadowSize; - images.put(Position.BOTTOM, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = x; - w = shadowSize; - h = shadowSize; - images.put(Position.BOTTOM_RIGHT, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = cornerSize + 1; - w = shadowSize; - h = 1; - images.put(Position.RIGHT, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = 1; - w = shadowSize; - h = shadowSize; - images.put(Position.TOP_RIGHT, targetImage.getSubimage(x, y, w, h)); - x = shadowSize; - y = 1; - w = 1; - h = shadowSize; - images.put(Position.TOP, targetImage.getSubimage(x, y, w, h)); - - buffer.dispose(); - image.flush(); + Point bottomLeftShadowPoint = null; + if (showLeftShadow || showBottomShadow) { + bottomLeftShadowPoint = new Point(); + if (showLeftShadow && !showBottomShadow) { + bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); + } else { + if (showLeftShadow && showBottomShadow) { + bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); + } else { + if (!showLeftShadow && showBottomShadow) { + bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); + } } - return images; + } } - /** */ - public Insets getBorderInsets(Component c) { - int top = 4 + (showTopShadow ? lineWidth + shadowSize : lineWidth); - int left = 4 + (showLeftShadow ? lineWidth + shadowSize : lineWidth); - int bottom = 4 + (showBottomShadow ? lineWidth + shadowSize : lineWidth); - int right = 4 + (showRightShadow ? lineWidth + shadowSize : lineWidth); - - return new Insets(top, left, bottom, right); + Point bottomRightShadowPoint = null; + if (showRightShadow || showBottomShadow) { + bottomRightShadowPoint = new Point(); + if (showRightShadow && !showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize, y + height - shadowSize - shadowSize); + } else { + if (showRightShadow && showBottomShadow) { + bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); + } else { + if (!showRightShadow && showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize - shadowSize, y + height - shadowSize); + } + } + } } - /** */ - public boolean isBorderOpaque() { - return true; + Point topRightShadowPoint = null; + if (showRightShadow || showTopShadow) { + topRightShadowPoint = new Point(); + if (showRightShadow && !showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize); + } else { + if (showRightShadow && showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize, y); + } else { + if (!showRightShadow && showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); + } + } + } } - public boolean isShowTopShadow() { - return showTopShadow; + if (showLeftShadow) { + Rectangle leftShadowRect = + new Rectangle( + x, + (int) (topLeftShadowPoint.getY() + shadowSize), + shadowSize, + (int) (bottomLeftShadowPoint.getY() - topLeftShadowPoint.getY() - shadowSize)); + g2.drawImage( + images + .get(Position.LEFT) + .getScaledInstance(leftShadowRect.width, leftShadowRect.height, Image.SCALE_FAST), + leftShadowRect.x, + leftShadowRect.y, + null); } - public boolean isShowLeftShadow() { - return showLeftShadow; + if (showBottomShadow) { + Rectangle bottomShadowRect = + new Rectangle( + (int) (bottomLeftShadowPoint.getX() + shadowSize), + y + height - shadowSize, + (int) (bottomRightShadowPoint.getX() - bottomLeftShadowPoint.getX() - shadowSize), + shadowSize); + g2.drawImage( + images + .get(Position.BOTTOM) + .getScaledInstance(bottomShadowRect.width, bottomShadowRect.height, Image.SCALE_FAST), + bottomShadowRect.x, + bottomShadowRect.y, + null); } - public boolean isShowRightShadow() { - return showRightShadow; + if (showRightShadow) { + Rectangle rightShadowRect = + new Rectangle( + x + width - shadowSize, + (int) (topRightShadowPoint.getY() + shadowSize), + shadowSize, + (int) (bottomRightShadowPoint.getY() - topRightShadowPoint.getY() - shadowSize)); + g2.drawImage( + images + .get(Position.RIGHT) + .getScaledInstance(rightShadowRect.width, rightShadowRect.height, Image.SCALE_FAST), + rightShadowRect.x, + rightShadowRect.y, + null); } - public boolean isShowBottomShadow() { - return showBottomShadow; + if (showTopShadow) { + Rectangle topShadowRect = + new Rectangle( + (int) topLeftShadowPoint.getX() + shadowSize, + y, + (int) (topRightShadowPoint.getX() - topLeftShadowPoint.getX() - shadowSize), + shadowSize); + g2.drawImage( + images + .get(Position.TOP) + .getScaledInstance(topShadowRect.width, topShadowRect.height, Image.SCALE_FAST), + topShadowRect.x, + topShadowRect.y, + null); } - public int getLineWidth() { - return lineWidth; + if (showLeftShadow || showTopShadow) { + g2.drawImage( + images.get(Position.TOP_LEFT), + null, + (int) topLeftShadowPoint.getX(), + (int) topLeftShadowPoint.getY()); } - - public Color getLineColor() { - return lineColor; + if (showLeftShadow || showBottomShadow) { + g2.drawImage( + images.get(Position.BOTTOM_LEFT), + null, + (int) bottomLeftShadowPoint.getX(), + (int) bottomLeftShadowPoint.getY()); } - - public int getShadowSize() { - return shadowSize; + if (showRightShadow || showBottomShadow) { + g2.drawImage( + images.get(Position.BOTTOM_RIGHT), + null, + (int) bottomRightShadowPoint.getX(), + (int) bottomRightShadowPoint.getY()); } - - public float getShadowOpacity() { - return shadowOpacity; - } - - public int getCornerSize() { - return cornerSize; + if (showRightShadow || showTopShadow) { + g2.drawImage( + images.get(Position.TOP_RIGHT), + null, + (int) topRightShadowPoint.getX(), + (int) topRightShadowPoint.getY()); } - - private enum Position { - TOP, - TOP_LEFT, - LEFT, - BOTTOM_LEFT, - BOTTOM, - BOTTOM_RIGHT, - RIGHT, - TOP_RIGHT + } + + private Map getImages(Graphics2D g2) { + // first, check to see if an image for this size has already been rendered + // if so, use the cache. Else, draw and save + Map images = CACHE.get(shadowSize); + if (images == null) { + images = new HashMap(); + + /* + * Do draw a drop shadows, I have to: + * 1) Create a rounded rectangle + * 2) Create a BufferedImage to draw the rounded rect in + * 3) Translate the graphics for the image, so that the rectangle + * is centered in the drawn space. The border around the rectangle + * needs to be shadowWidth wide, so that there is space for the + * shadows to be drawn. + * 4) Draw the rounded rect as black, with an opacity of 50% + * 5) Create the BLUR_KERNEL + * 6) Blur the image + * 7) copy off the corners, sides, etc into images to be used for + * drawing the Border + */ + int rectWidth = cornerSize + 1; + RoundRectangle2D rect = + new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); + int imageWidth = rectWidth + shadowSize * 2; + BufferedImage image = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); + Graphics2D buffer = (Graphics2D) image.getGraphics(); + buffer.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + buffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + buffer.setRenderingHint( + RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + buffer.setRenderingHint( + RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); + buffer.translate(shadowSize, shadowSize); + buffer.fill(rect); + float blurry = 1.0f / (float) (shadowSize * shadowSize); // 1.0f / (float)(shadowSize * + // shadowSize); + float[] blurKernel = new float[shadowSize * shadowSize]; + for (int i = 0; i < blurKernel.length; i++) { + blurKernel[i] = blurry; + } + ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); + BufferedImage targetImage = + new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); + ((Graphics2D) targetImage.getGraphics()) + .drawImage(image, blur, -(shadowSize / 2), -(shadowSize / 2)); + + int x = 1; + int y = 1; + int w = shadowSize; + int h = shadowSize; + images.put(Position.TOP_LEFT, targetImage.getSubimage(x, y, w, h)); + x = 1; + y = h; + w = shadowSize; + h = 1; + images.put(Position.LEFT, targetImage.getSubimage(x, y, w, h)); + x = 1; + y = rectWidth; + w = shadowSize; + h = shadowSize; + images.put(Position.BOTTOM_LEFT, targetImage.getSubimage(x, y, w, h)); + x = cornerSize + 1; + y = rectWidth; + w = 1; + h = shadowSize; + images.put(Position.BOTTOM, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = x; + w = shadowSize; + h = shadowSize; + images.put(Position.BOTTOM_RIGHT, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = cornerSize + 1; + w = shadowSize; + h = 1; + images.put(Position.RIGHT, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = 1; + w = shadowSize; + h = shadowSize; + images.put(Position.TOP_RIGHT, targetImage.getSubimage(x, y, w, h)); + x = shadowSize; + y = 1; + w = 1; + h = shadowSize; + images.put(Position.TOP, targetImage.getSubimage(x, y, w, h)); + + buffer.dispose(); + image.flush(); } + return images; + } + + /** */ + public Insets getBorderInsets(Component c) { + int top = 4 + (showTopShadow ? lineWidth + shadowSize : lineWidth); + int left = 4 + (showLeftShadow ? lineWidth + shadowSize : lineWidth); + int bottom = 4 + (showBottomShadow ? lineWidth + shadowSize : lineWidth); + int right = 4 + (showRightShadow ? lineWidth + shadowSize : lineWidth); + + return new Insets(top, left, bottom, right); + } + + /** */ + public boolean isBorderOpaque() { + return true; + } + + public boolean isShowTopShadow() { + return showTopShadow; + } + + public boolean isShowLeftShadow() { + return showLeftShadow; + } + + public boolean isShowRightShadow() { + return showRightShadow; + } + + public boolean isShowBottomShadow() { + return showBottomShadow; + } + + public int getLineWidth() { + return lineWidth; + } + + public Color getLineColor() { + return lineColor; + } + + public int getShadowSize() { + return shadowSize; + } + + public float getShadowOpacity() { + return shadowOpacity; + } + + public int getCornerSize() { + return cornerSize; + } + + private enum Position { + TOP, + TOP_LEFT, + LEFT, + BOTTOM_LEFT, + BOTTOM, + BOTTOM_RIGHT, + RIGHT, + TOP_RIGHT + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java index 8c2e3eeec..049ce78af 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java @@ -6,15 +6,15 @@ public class MaterialBorders { - public static final Border LIGHT_LINE_BORDER = - BorderFactory.createLineBorder(MaterialColors.GRAY_200, 1); - public static final Border THICK_LINE_BORDER = - BorderFactory.createLineBorder(MaterialColors.GRAY_200, 2); + public static final Border LIGHT_LINE_BORDER = + BorderFactory.createLineBorder(MaterialColors.GRAY_200, 1); + public static final Border THICK_LINE_BORDER = + BorderFactory.createLineBorder(MaterialColors.GRAY_200, 2); - public static final Border LIGHT_SHADOW_BORDER = - new DropShadowBorder(Color.BLACK, 0, 4, 0.3f, 12, true, true, true, true); - public static final Border DEFAULT_SHADOW_BORDER = - new DropShadowBorder(Color.BLACK, 5, 5, 0.3f, 12, true, true, true, true); + public static final Border LIGHT_SHADOW_BORDER = + new DropShadowBorder(Color.BLACK, 0, 4, 0.3f, 12, true, true, true, true); + public static final Border DEFAULT_SHADOW_BORDER = + new DropShadowBorder(Color.BLACK, 5, 5, 0.3f, 12, true, true, true, true); - private MaterialBorders() {} + private MaterialBorders() {} } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java index 00cb0720a..f9678d403 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java @@ -3,270 +3,270 @@ import java.awt.*; public class MaterialColors { - public static final Color RED_50 = new Color(255, 235, 238); - public static final Color RED_100 = new Color(255, 205, 210); - public static final Color RED_200 = new Color(239, 154, 154); - public static final Color RED_300 = new Color(229, 115, 115); - public static final Color RED_400 = new Color(239, 83, 80); - public static final Color RED_500 = new Color(244, 67, 54); - public static final Color RED_600 = new Color(229, 57, 53); - public static final Color RED_700 = new Color(211, 47, 47); - public static final Color RED_800 = new Color(198, 40, 40); - public static final Color RED_900 = new Color(183, 28, 28); - public static final Color RED_A100 = new Color(255, 138, 128); - public static final Color RED_A200 = new Color(255, 82, 82); - public static final Color RED_A400 = new Color(255, 23, 68); - public static final Color RED_A700 = new Color(213, 0, 0); - public static final Color PINK_50 = new Color(252, 228, 236); - public static final Color PINK_100 = new Color(248, 187, 208); - public static final Color PINK_200 = new Color(244, 143, 177); - public static final Color PINK_300 = new Color(240, 98, 146); - public static final Color PINK_400 = new Color(236, 64, 122); - public static final Color PINK_500 = new Color(233, 30, 99); - public static final Color PINK_600 = new Color(216, 27, 96); - public static final Color PINK_700 = new Color(194, 24, 91); - public static final Color PINK_800 = new Color(173, 20, 87); - public static final Color PINK_900 = new Color(136, 14, 79); - public static final Color PINK_A100 = new Color(255, 128, 171); - public static final Color PINK_A200 = new Color(255, 64, 129); - public static final Color PINK_A400 = new Color(245, 0, 87); - public static final Color PINK_A700 = new Color(197, 17, 98); - public static final Color PURPLE_50 = new Color(243, 229, 245); - public static final Color PURPLE_100 = new Color(225, 190, 231); - public static final Color PURPLE_200 = new Color(206, 147, 216); - public static final Color PURPLE_300 = new Color(186, 104, 200); - public static final Color PURPLE_400 = new Color(171, 71, 188); - public static final Color PURPLE_500 = new Color(156, 39, 176); - public static final Color PURPLE_600 = new Color(142, 36, 170); - public static final Color PURPLE_700 = new Color(123, 31, 162); - public static final Color PURPLE_800 = new Color(106, 27, 154); - public static final Color PURPLE_900 = new Color(74, 20, 140); - public static final Color PURPLE_A100 = new Color(234, 128, 252); - public static final Color PURPLE_A200 = new Color(224, 64, 251); - public static final Color PURPLE_A400 = new Color(213, 0, 249); - public static final Color PURPLE_A700 = new Color(170, 0, 255); - public static final Color DEEP_PURPLE_50 = new Color(237, 231, 246); - public static final Color DEEP_PURPLE_100 = new Color(209, 196, 233); - public static final Color DEEP_PURPLE_200 = new Color(179, 157, 219); - public static final Color DEEP_PURPLE_300 = new Color(149, 117, 205); - public static final Color DEEP_PURPLE_400 = new Color(126, 87, 194); - public static final Color DEEP_PURPLE_500 = new Color(103, 58, 183); - public static final Color DEEP_PURPLE_600 = new Color(94, 53, 177); - public static final Color DEEP_PURPLE_700 = new Color(81, 45, 168); - public static final Color DEEP_PURPLE_800 = new Color(69, 39, 160); - public static final Color DEEP_PURPLE_900 = new Color(49, 27, 146); - public static final Color DEEP_PURPLE_A100 = new Color(179, 136, 255); - public static final Color DEEP_PURPLE_A200 = new Color(124, 77, 255); - public static final Color DEEP_PURPLE_A400 = new Color(101, 31, 255); - public static final Color DEEP_PURPLE_A700 = new Color(98, 0, 234); - public static final Color INDIGO_50 = new Color(232, 234, 246); - public static final Color INDIGO_100 = new Color(197, 202, 233); - public static final Color INDIGO_200 = new Color(159, 168, 218); - public static final Color INDIGO_300 = new Color(121, 134, 203); - public static final Color INDIGO_400 = new Color(92, 107, 192); - public static final Color INDIGO_500 = new Color(63, 81, 181); - public static final Color INDIGO_600 = new Color(57, 73, 171); - public static final Color INDIGO_700 = new Color(48, 63, 159); - public static final Color INDIGO_800 = new Color(40, 53, 147); - public static final Color INDIGO_900 = new Color(26, 35, 126); - public static final Color INDIGO_A100 = new Color(140, 158, 255); - public static final Color INDIGO_A200 = new Color(83, 109, 254); - public static final Color INDIGO_A400 = new Color(61, 90, 254); - public static final Color INDIGO_A700 = new Color(48, 79, 254); - public static final Color BLUE_50 = new Color(227, 242, 253); - public static final Color BLUE_100 = new Color(187, 222, 251); - public static final Color BLUE_200 = new Color(144, 202, 249); - public static final Color BLUE_300 = new Color(100, 181, 246); - public static final Color BLUE_400 = new Color(66, 165, 245); - public static final Color BLUE_500 = new Color(33, 150, 243); - public static final Color BLUE_600 = new Color(30, 136, 229); - public static final Color BLUE_700 = new Color(25, 118, 210); - public static final Color BLUE_800 = new Color(21, 101, 192); - public static final Color BLUE_900 = new Color(13, 71, 161); - public static final Color BLUE_A100 = new Color(130, 177, 255); - public static final Color BLUE_A200 = new Color(68, 138, 255); - public static final Color BLUE_A400 = new Color(41, 121, 255); - public static final Color BLUE_A700 = new Color(41, 98, 255); - public static final Color LIGHT_BLUE_50 = new Color(225, 245, 254); - public static final Color LIGHT_BLUE_100 = new Color(179, 229, 252); - public static final Color LIGHT_BLUE_200 = new Color(129, 212, 250); - public static final Color LIGHT_BLUE_300 = new Color(79, 195, 247); - public static final Color LIGHT_BLUE_400 = new Color(41, 182, 246); - public static final Color LIGHT_BLUE_500 = new Color(3, 169, 244); - public static final Color LIGHT_BLUE_600 = new Color(3, 155, 229); - public static final Color LIGHT_BLUE_700 = new Color(2, 136, 209); - public static final Color LIGHT_BLUE_800 = new Color(2, 119, 189); - public static final Color LIGHT_BLUE_900 = new Color(1, 87, 155); - public static final Color LIGHT_BLUE_A100 = new Color(128, 216, 255); - public static final Color LIGHT_BLUE_A200 = new Color(64, 196, 255); - public static final Color LIGHT_BLUE_A400 = new Color(0, 176, 255); - public static final Color LIGHT_BLUE_A700 = new Color(0, 145, 234); - public static final Color CYAN_50 = new Color(224, 247, 250); - public static final Color CYAN_100 = new Color(178, 235, 242); - public static final Color CYAN_200 = new Color(128, 222, 234); - public static final Color CYAN_300 = new Color(77, 208, 225); - public static final Color CYAN_400 = new Color(38, 198, 218); - public static final Color CYAN_500 = new Color(0, 188, 212); - public static final Color CYAN_600 = new Color(0, 172, 193); - public static final Color CYAN_700 = new Color(0, 151, 167); - public static final Color CYAN_800 = new Color(0, 131, 143); - public static final Color CYAN_900 = new Color(0, 96, 100); - public static final Color CYAN_A100 = new Color(132, 255, 255); - public static final Color CYAN_A200 = new Color(24, 255, 255); - public static final Color CYAN_A400 = new Color(0, 229, 255); - public static final Color CYAN_A700 = new Color(0, 184, 212); - public static final Color TEAL_50 = new Color(224, 242, 241); - public static final Color TEAL_100 = new Color(178, 223, 219); - public static final Color TEAL_200 = new Color(128, 203, 196); - public static final Color TEAL_300 = new Color(77, 182, 172); - public static final Color TEAL_400 = new Color(38, 166, 154); - public static final Color TEAL_500 = new Color(0, 150, 136); - public static final Color TEAL_600 = new Color(0, 137, 123); - public static final Color TEAL_700 = new Color(0, 121, 107); - public static final Color TEAL_800 = new Color(0, 105, 92); - public static final Color TEAL_900 = new Color(0, 77, 64); - public static final Color TEAL_A100 = new Color(167, 255, 235); - public static final Color TEAL_A200 = new Color(100, 255, 218); - public static final Color TEAL_A400 = new Color(29, 233, 182); - public static final Color TEAL_A700 = new Color(0, 191, 165); - public static final Color GREEN_50 = new Color(232, 245, 233); - public static final Color GREEN_100 = new Color(200, 230, 201); - public static final Color GREEN_200 = new Color(165, 214, 167); - public static final Color GREEN_300 = new Color(129, 199, 132); - public static final Color GREEN_400 = new Color(102, 187, 106); - public static final Color GREEN_500 = new Color(76, 175, 80); - public static final Color GREEN_600 = new Color(67, 160, 71); - public static final Color GREEN_700 = new Color(56, 142, 60); - public static final Color GREEN_800 = new Color(46, 125, 50); - public static final Color GREEN_900 = new Color(27, 94, 32); - public static final Color GREEN_A100 = new Color(185, 246, 202); - public static final Color GREEN_A200 = new Color(105, 240, 174); - public static final Color GREEN_A400 = new Color(0, 230, 118); - public static final Color GREEN_A700 = new Color(0, 200, 83); - public static final Color LIGHT_GREEN_50 = new Color(241, 248, 233); - public static final Color LIGHT_GREEN_100 = new Color(220, 237, 200); - public static final Color LIGHT_GREEN_200 = new Color(197, 225, 165); - public static final Color LIGHT_GREEN_300 = new Color(174, 213, 129); - public static final Color LIGHT_GREEN_400 = new Color(156, 204, 101); - public static final Color LIGHT_GREEN_500 = new Color(139, 195, 74); - public static final Color LIGHT_GREEN_600 = new Color(124, 179, 66); - public static final Color LIGHT_GREEN_700 = new Color(104, 159, 56); - public static final Color LIGHT_GREEN_800 = new Color(85, 139, 47); - public static final Color LIGHT_GREEN_900 = new Color(51, 105, 30); - public static final Color LIGHT_GREEN_A100 = new Color(204, 255, 144); - public static final Color LIGHT_GREEN_A200 = new Color(178, 255, 89); - public static final Color LIGHT_GREEN_A400 = new Color(118, 255, 3); - public static final Color LIGHT_GREEN_A700 = new Color(100, 221, 23); - public static final Color LIME_50 = new Color(249, 251, 231); - public static final Color LIME_100 = new Color(240, 244, 195); - public static final Color LIME_200 = new Color(230, 238, 156); - public static final Color LIME_300 = new Color(220, 231, 117); - public static final Color LIME_400 = new Color(212, 225, 87); - public static final Color LIME_500 = new Color(205, 220, 57); - public static final Color LIME_600 = new Color(192, 202, 51); - public static final Color LIME_700 = new Color(175, 180, 43); - public static final Color LIME_800 = new Color(158, 157, 36); - public static final Color LIME_900 = new Color(130, 119, 23); - public static final Color LIME_A100 = new Color(244, 255, 129); - public static final Color LIME_A200 = new Color(238, 255, 65); - public static final Color LIME_A400 = new Color(198, 255, 0); - public static final Color LIME_A700 = new Color(174, 234, 0); - public static final Color YELLOW_50 = new Color(255, 253, 231); - public static final Color YELLOW_100 = new Color(255, 249, 196); - public static final Color YELLOW_200 = new Color(255, 245, 157); - public static final Color YELLOW_300 = new Color(255, 241, 118); - public static final Color YELLOW_400 = new Color(255, 238, 88); - public static final Color YELLOW_500 = new Color(255, 235, 59); - public static final Color YELLOW_600 = new Color(253, 216, 53); - public static final Color YELLOW_700 = new Color(251, 192, 45); - public static final Color YELLOW_800 = new Color(249, 168, 37); - public static final Color YELLOW_900 = new Color(245, 127, 23); - public static final Color YELLOW_A100 = new Color(255, 255, 141); - public static final Color YELLOW_A200 = new Color(255, 255, 0); - public static final Color YELLOW_A400 = new Color(255, 234, 0); - public static final Color YELLOW_A700 = new Color(255, 214, 0); - public static final Color AMBER_50 = new Color(255, 248, 225); - public static final Color AMBER_100 = new Color(255, 236, 179); - public static final Color AMBER_200 = new Color(255, 224, 130); - public static final Color AMBER_300 = new Color(255, 213, 79); - public static final Color AMBER_400 = new Color(255, 202, 40); - public static final Color AMBER_500 = new Color(255, 193, 7); - public static final Color AMBER_600 = new Color(255, 179, 0); - public static final Color AMBER_700 = new Color(255, 160, 0); - public static final Color AMBER_800 = new Color(255, 143, 0); - public static final Color AMBER_900 = new Color(255, 111, 0); - public static final Color AMBER_A100 = new Color(255, 229, 127); - public static final Color AMBER_A200 = new Color(255, 215, 64); - public static final Color AMBER_A400 = new Color(255, 196, 0); - public static final Color AMBER_A700 = new Color(255, 171, 0); - public static final Color ORANGE_50 = new Color(255, 243, 224); - public static final Color ORANGE_100 = new Color(255, 224, 178); - public static final Color ORANGE_200 = new Color(255, 204, 128); - public static final Color ORANGE_300 = new Color(255, 183, 77); - public static final Color ORANGE_400 = new Color(255, 167, 38); - public static final Color ORANGE_500 = new Color(255, 152, 0); - public static final Color ORANGE_600 = new Color(251, 140, 0); - public static final Color ORANGE_700 = new Color(245, 124, 0); - public static final Color ORANGE_800 = new Color(239, 108, 0); - public static final Color ORANGE_900 = new Color(230, 81, 0); - public static final Color ORANGE_A100 = new Color(255, 209, 128); - public static final Color ORANGE_A200 = new Color(255, 171, 64); - public static final Color ORANGE_A400 = new Color(255, 145, 0); - public static final Color ORANGE_A700 = new Color(255, 109, 0); - public static final Color DEEP_ORANGE_50 = new Color(251, 233, 231); - public static final Color DEEP_ORANGE_100 = new Color(255, 204, 188); - public static final Color DEEP_ORANGE_200 = new Color(255, 171, 145); - public static final Color DEEP_ORANGE_300 = new Color(255, 138, 101); - public static final Color DEEP_ORANGE_400 = new Color(255, 112, 67); - public static final Color DEEP_ORANGE_500 = new Color(255, 87, 34); - public static final Color DEEP_ORANGE_600 = new Color(244, 81, 30); - public static final Color DEEP_ORANGE_700 = new Color(230, 74, 25); - public static final Color DEEP_ORANGE_800 = new Color(216, 67, 21); - public static final Color DEEP_ORANGE_900 = new Color(191, 54, 12); - public static final Color DEEP_ORANGE_A100 = new Color(255, 158, 128); - public static final Color DEEP_ORANGE_A200 = new Color(255, 110, 64); - public static final Color DEEP_ORANGE_A400 = new Color(255, 61, 0); - public static final Color DEEP_ORANGE_A700 = new Color(221, 44, 0); - public static final Color BROWN_50 = new Color(239, 235, 233); - public static final Color BROWN_100 = new Color(215, 204, 200); - public static final Color BROWN_200 = new Color(188, 170, 164); - public static final Color BROWN_300 = new Color(161, 136, 127); - public static final Color BROWN_400 = new Color(141, 110, 99); - public static final Color BROWN_500 = new Color(121, 85, 72); - public static final Color BROWN_600 = new Color(109, 76, 65); - public static final Color BROWN_700 = new Color(93, 64, 55); - public static final Color BROWN_800 = new Color(78, 52, 46); - public static final Color BROWN_900 = new Color(62, 39, 35); - public static final Color GRAY_50 = new Color(250, 250, 250); - public static final Color GRAY_100 = new Color(245, 245, 245); - public static final Color GRAY_200 = new Color(238, 238, 238); - public static final Color GRAY_300 = new Color(224, 224, 224); - public static final Color GRAY_400 = new Color(189, 189, 189); - public static final Color GRAY_500 = new Color(158, 158, 158); - public static final Color GRAY_600 = new Color(117, 117, 117); - public static final Color GRAY_700 = new Color(97, 97, 97); - public static final Color GRAY_800 = new Color(66, 66, 66); - public static final Color GRAY_900 = new Color(33, 33, 33); - public static final Color BLUE_GRAY_50 = new Color(236, 239, 241); - public static final Color BLUE_GRAY_100 = new Color(207, 216, 220); - public static final Color BLUE_GRAY_200 = new Color(176, 190, 197); - public static final Color BLUE_GRAY_300 = new Color(144, 164, 174); - public static final Color BLUE_GRAY_400 = new Color(120, 144, 156); - public static final Color BLUE_GRAY_500 = new Color(96, 125, 139); - public static final Color BLUE_GRAY_600 = new Color(84, 110, 122); - public static final Color BLUE_GRAY_700 = new Color(69, 90, 100); - public static final Color BLUE_GRAY_800 = new Color(55, 71, 79); - public static final Color BLUE_GRAY_900 = new Color(38, 50, 56); - public static final Color BLACK = new Color(0, 0, 0); - public static final Color WHITE = new Color(255, 255, 255); - public static final Color TRANSPARENT = new Color(0, 0, 0, 255); + public static final Color RED_50 = new Color(255, 235, 238); + public static final Color RED_100 = new Color(255, 205, 210); + public static final Color RED_200 = new Color(239, 154, 154); + public static final Color RED_300 = new Color(229, 115, 115); + public static final Color RED_400 = new Color(239, 83, 80); + public static final Color RED_500 = new Color(244, 67, 54); + public static final Color RED_600 = new Color(229, 57, 53); + public static final Color RED_700 = new Color(211, 47, 47); + public static final Color RED_800 = new Color(198, 40, 40); + public static final Color RED_900 = new Color(183, 28, 28); + public static final Color RED_A100 = new Color(255, 138, 128); + public static final Color RED_A200 = new Color(255, 82, 82); + public static final Color RED_A400 = new Color(255, 23, 68); + public static final Color RED_A700 = new Color(213, 0, 0); + public static final Color PINK_50 = new Color(252, 228, 236); + public static final Color PINK_100 = new Color(248, 187, 208); + public static final Color PINK_200 = new Color(244, 143, 177); + public static final Color PINK_300 = new Color(240, 98, 146); + public static final Color PINK_400 = new Color(236, 64, 122); + public static final Color PINK_500 = new Color(233, 30, 99); + public static final Color PINK_600 = new Color(216, 27, 96); + public static final Color PINK_700 = new Color(194, 24, 91); + public static final Color PINK_800 = new Color(173, 20, 87); + public static final Color PINK_900 = new Color(136, 14, 79); + public static final Color PINK_A100 = new Color(255, 128, 171); + public static final Color PINK_A200 = new Color(255, 64, 129); + public static final Color PINK_A400 = new Color(245, 0, 87); + public static final Color PINK_A700 = new Color(197, 17, 98); + public static final Color PURPLE_50 = new Color(243, 229, 245); + public static final Color PURPLE_100 = new Color(225, 190, 231); + public static final Color PURPLE_200 = new Color(206, 147, 216); + public static final Color PURPLE_300 = new Color(186, 104, 200); + public static final Color PURPLE_400 = new Color(171, 71, 188); + public static final Color PURPLE_500 = new Color(156, 39, 176); + public static final Color PURPLE_600 = new Color(142, 36, 170); + public static final Color PURPLE_700 = new Color(123, 31, 162); + public static final Color PURPLE_800 = new Color(106, 27, 154); + public static final Color PURPLE_900 = new Color(74, 20, 140); + public static final Color PURPLE_A100 = new Color(234, 128, 252); + public static final Color PURPLE_A200 = new Color(224, 64, 251); + public static final Color PURPLE_A400 = new Color(213, 0, 249); + public static final Color PURPLE_A700 = new Color(170, 0, 255); + public static final Color DEEP_PURPLE_50 = new Color(237, 231, 246); + public static final Color DEEP_PURPLE_100 = new Color(209, 196, 233); + public static final Color DEEP_PURPLE_200 = new Color(179, 157, 219); + public static final Color DEEP_PURPLE_300 = new Color(149, 117, 205); + public static final Color DEEP_PURPLE_400 = new Color(126, 87, 194); + public static final Color DEEP_PURPLE_500 = new Color(103, 58, 183); + public static final Color DEEP_PURPLE_600 = new Color(94, 53, 177); + public static final Color DEEP_PURPLE_700 = new Color(81, 45, 168); + public static final Color DEEP_PURPLE_800 = new Color(69, 39, 160); + public static final Color DEEP_PURPLE_900 = new Color(49, 27, 146); + public static final Color DEEP_PURPLE_A100 = new Color(179, 136, 255); + public static final Color DEEP_PURPLE_A200 = new Color(124, 77, 255); + public static final Color DEEP_PURPLE_A400 = new Color(101, 31, 255); + public static final Color DEEP_PURPLE_A700 = new Color(98, 0, 234); + public static final Color INDIGO_50 = new Color(232, 234, 246); + public static final Color INDIGO_100 = new Color(197, 202, 233); + public static final Color INDIGO_200 = new Color(159, 168, 218); + public static final Color INDIGO_300 = new Color(121, 134, 203); + public static final Color INDIGO_400 = new Color(92, 107, 192); + public static final Color INDIGO_500 = new Color(63, 81, 181); + public static final Color INDIGO_600 = new Color(57, 73, 171); + public static final Color INDIGO_700 = new Color(48, 63, 159); + public static final Color INDIGO_800 = new Color(40, 53, 147); + public static final Color INDIGO_900 = new Color(26, 35, 126); + public static final Color INDIGO_A100 = new Color(140, 158, 255); + public static final Color INDIGO_A200 = new Color(83, 109, 254); + public static final Color INDIGO_A400 = new Color(61, 90, 254); + public static final Color INDIGO_A700 = new Color(48, 79, 254); + public static final Color BLUE_50 = new Color(227, 242, 253); + public static final Color BLUE_100 = new Color(187, 222, 251); + public static final Color BLUE_200 = new Color(144, 202, 249); + public static final Color BLUE_300 = new Color(100, 181, 246); + public static final Color BLUE_400 = new Color(66, 165, 245); + public static final Color BLUE_500 = new Color(33, 150, 243); + public static final Color BLUE_600 = new Color(30, 136, 229); + public static final Color BLUE_700 = new Color(25, 118, 210); + public static final Color BLUE_800 = new Color(21, 101, 192); + public static final Color BLUE_900 = new Color(13, 71, 161); + public static final Color BLUE_A100 = new Color(130, 177, 255); + public static final Color BLUE_A200 = new Color(68, 138, 255); + public static final Color BLUE_A400 = new Color(41, 121, 255); + public static final Color BLUE_A700 = new Color(41, 98, 255); + public static final Color LIGHT_BLUE_50 = new Color(225, 245, 254); + public static final Color LIGHT_BLUE_100 = new Color(179, 229, 252); + public static final Color LIGHT_BLUE_200 = new Color(129, 212, 250); + public static final Color LIGHT_BLUE_300 = new Color(79, 195, 247); + public static final Color LIGHT_BLUE_400 = new Color(41, 182, 246); + public static final Color LIGHT_BLUE_500 = new Color(3, 169, 244); + public static final Color LIGHT_BLUE_600 = new Color(3, 155, 229); + public static final Color LIGHT_BLUE_700 = new Color(2, 136, 209); + public static final Color LIGHT_BLUE_800 = new Color(2, 119, 189); + public static final Color LIGHT_BLUE_900 = new Color(1, 87, 155); + public static final Color LIGHT_BLUE_A100 = new Color(128, 216, 255); + public static final Color LIGHT_BLUE_A200 = new Color(64, 196, 255); + public static final Color LIGHT_BLUE_A400 = new Color(0, 176, 255); + public static final Color LIGHT_BLUE_A700 = new Color(0, 145, 234); + public static final Color CYAN_50 = new Color(224, 247, 250); + public static final Color CYAN_100 = new Color(178, 235, 242); + public static final Color CYAN_200 = new Color(128, 222, 234); + public static final Color CYAN_300 = new Color(77, 208, 225); + public static final Color CYAN_400 = new Color(38, 198, 218); + public static final Color CYAN_500 = new Color(0, 188, 212); + public static final Color CYAN_600 = new Color(0, 172, 193); + public static final Color CYAN_700 = new Color(0, 151, 167); + public static final Color CYAN_800 = new Color(0, 131, 143); + public static final Color CYAN_900 = new Color(0, 96, 100); + public static final Color CYAN_A100 = new Color(132, 255, 255); + public static final Color CYAN_A200 = new Color(24, 255, 255); + public static final Color CYAN_A400 = new Color(0, 229, 255); + public static final Color CYAN_A700 = new Color(0, 184, 212); + public static final Color TEAL_50 = new Color(224, 242, 241); + public static final Color TEAL_100 = new Color(178, 223, 219); + public static final Color TEAL_200 = new Color(128, 203, 196); + public static final Color TEAL_300 = new Color(77, 182, 172); + public static final Color TEAL_400 = new Color(38, 166, 154); + public static final Color TEAL_500 = new Color(0, 150, 136); + public static final Color TEAL_600 = new Color(0, 137, 123); + public static final Color TEAL_700 = new Color(0, 121, 107); + public static final Color TEAL_800 = new Color(0, 105, 92); + public static final Color TEAL_900 = new Color(0, 77, 64); + public static final Color TEAL_A100 = new Color(167, 255, 235); + public static final Color TEAL_A200 = new Color(100, 255, 218); + public static final Color TEAL_A400 = new Color(29, 233, 182); + public static final Color TEAL_A700 = new Color(0, 191, 165); + public static final Color GREEN_50 = new Color(232, 245, 233); + public static final Color GREEN_100 = new Color(200, 230, 201); + public static final Color GREEN_200 = new Color(165, 214, 167); + public static final Color GREEN_300 = new Color(129, 199, 132); + public static final Color GREEN_400 = new Color(102, 187, 106); + public static final Color GREEN_500 = new Color(76, 175, 80); + public static final Color GREEN_600 = new Color(67, 160, 71); + public static final Color GREEN_700 = new Color(56, 142, 60); + public static final Color GREEN_800 = new Color(46, 125, 50); + public static final Color GREEN_900 = new Color(27, 94, 32); + public static final Color GREEN_A100 = new Color(185, 246, 202); + public static final Color GREEN_A200 = new Color(105, 240, 174); + public static final Color GREEN_A400 = new Color(0, 230, 118); + public static final Color GREEN_A700 = new Color(0, 200, 83); + public static final Color LIGHT_GREEN_50 = new Color(241, 248, 233); + public static final Color LIGHT_GREEN_100 = new Color(220, 237, 200); + public static final Color LIGHT_GREEN_200 = new Color(197, 225, 165); + public static final Color LIGHT_GREEN_300 = new Color(174, 213, 129); + public static final Color LIGHT_GREEN_400 = new Color(156, 204, 101); + public static final Color LIGHT_GREEN_500 = new Color(139, 195, 74); + public static final Color LIGHT_GREEN_600 = new Color(124, 179, 66); + public static final Color LIGHT_GREEN_700 = new Color(104, 159, 56); + public static final Color LIGHT_GREEN_800 = new Color(85, 139, 47); + public static final Color LIGHT_GREEN_900 = new Color(51, 105, 30); + public static final Color LIGHT_GREEN_A100 = new Color(204, 255, 144); + public static final Color LIGHT_GREEN_A200 = new Color(178, 255, 89); + public static final Color LIGHT_GREEN_A400 = new Color(118, 255, 3); + public static final Color LIGHT_GREEN_A700 = new Color(100, 221, 23); + public static final Color LIME_50 = new Color(249, 251, 231); + public static final Color LIME_100 = new Color(240, 244, 195); + public static final Color LIME_200 = new Color(230, 238, 156); + public static final Color LIME_300 = new Color(220, 231, 117); + public static final Color LIME_400 = new Color(212, 225, 87); + public static final Color LIME_500 = new Color(205, 220, 57); + public static final Color LIME_600 = new Color(192, 202, 51); + public static final Color LIME_700 = new Color(175, 180, 43); + public static final Color LIME_800 = new Color(158, 157, 36); + public static final Color LIME_900 = new Color(130, 119, 23); + public static final Color LIME_A100 = new Color(244, 255, 129); + public static final Color LIME_A200 = new Color(238, 255, 65); + public static final Color LIME_A400 = new Color(198, 255, 0); + public static final Color LIME_A700 = new Color(174, 234, 0); + public static final Color YELLOW_50 = new Color(255, 253, 231); + public static final Color YELLOW_100 = new Color(255, 249, 196); + public static final Color YELLOW_200 = new Color(255, 245, 157); + public static final Color YELLOW_300 = new Color(255, 241, 118); + public static final Color YELLOW_400 = new Color(255, 238, 88); + public static final Color YELLOW_500 = new Color(255, 235, 59); + public static final Color YELLOW_600 = new Color(253, 216, 53); + public static final Color YELLOW_700 = new Color(251, 192, 45); + public static final Color YELLOW_800 = new Color(249, 168, 37); + public static final Color YELLOW_900 = new Color(245, 127, 23); + public static final Color YELLOW_A100 = new Color(255, 255, 141); + public static final Color YELLOW_A200 = new Color(255, 255, 0); + public static final Color YELLOW_A400 = new Color(255, 234, 0); + public static final Color YELLOW_A700 = new Color(255, 214, 0); + public static final Color AMBER_50 = new Color(255, 248, 225); + public static final Color AMBER_100 = new Color(255, 236, 179); + public static final Color AMBER_200 = new Color(255, 224, 130); + public static final Color AMBER_300 = new Color(255, 213, 79); + public static final Color AMBER_400 = new Color(255, 202, 40); + public static final Color AMBER_500 = new Color(255, 193, 7); + public static final Color AMBER_600 = new Color(255, 179, 0); + public static final Color AMBER_700 = new Color(255, 160, 0); + public static final Color AMBER_800 = new Color(255, 143, 0); + public static final Color AMBER_900 = new Color(255, 111, 0); + public static final Color AMBER_A100 = new Color(255, 229, 127); + public static final Color AMBER_A200 = new Color(255, 215, 64); + public static final Color AMBER_A400 = new Color(255, 196, 0); + public static final Color AMBER_A700 = new Color(255, 171, 0); + public static final Color ORANGE_50 = new Color(255, 243, 224); + public static final Color ORANGE_100 = new Color(255, 224, 178); + public static final Color ORANGE_200 = new Color(255, 204, 128); + public static final Color ORANGE_300 = new Color(255, 183, 77); + public static final Color ORANGE_400 = new Color(255, 167, 38); + public static final Color ORANGE_500 = new Color(255, 152, 0); + public static final Color ORANGE_600 = new Color(251, 140, 0); + public static final Color ORANGE_700 = new Color(245, 124, 0); + public static final Color ORANGE_800 = new Color(239, 108, 0); + public static final Color ORANGE_900 = new Color(230, 81, 0); + public static final Color ORANGE_A100 = new Color(255, 209, 128); + public static final Color ORANGE_A200 = new Color(255, 171, 64); + public static final Color ORANGE_A400 = new Color(255, 145, 0); + public static final Color ORANGE_A700 = new Color(255, 109, 0); + public static final Color DEEP_ORANGE_50 = new Color(251, 233, 231); + public static final Color DEEP_ORANGE_100 = new Color(255, 204, 188); + public static final Color DEEP_ORANGE_200 = new Color(255, 171, 145); + public static final Color DEEP_ORANGE_300 = new Color(255, 138, 101); + public static final Color DEEP_ORANGE_400 = new Color(255, 112, 67); + public static final Color DEEP_ORANGE_500 = new Color(255, 87, 34); + public static final Color DEEP_ORANGE_600 = new Color(244, 81, 30); + public static final Color DEEP_ORANGE_700 = new Color(230, 74, 25); + public static final Color DEEP_ORANGE_800 = new Color(216, 67, 21); + public static final Color DEEP_ORANGE_900 = new Color(191, 54, 12); + public static final Color DEEP_ORANGE_A100 = new Color(255, 158, 128); + public static final Color DEEP_ORANGE_A200 = new Color(255, 110, 64); + public static final Color DEEP_ORANGE_A400 = new Color(255, 61, 0); + public static final Color DEEP_ORANGE_A700 = new Color(221, 44, 0); + public static final Color BROWN_50 = new Color(239, 235, 233); + public static final Color BROWN_100 = new Color(215, 204, 200); + public static final Color BROWN_200 = new Color(188, 170, 164); + public static final Color BROWN_300 = new Color(161, 136, 127); + public static final Color BROWN_400 = new Color(141, 110, 99); + public static final Color BROWN_500 = new Color(121, 85, 72); + public static final Color BROWN_600 = new Color(109, 76, 65); + public static final Color BROWN_700 = new Color(93, 64, 55); + public static final Color BROWN_800 = new Color(78, 52, 46); + public static final Color BROWN_900 = new Color(62, 39, 35); + public static final Color GRAY_50 = new Color(250, 250, 250); + public static final Color GRAY_100 = new Color(245, 245, 245); + public static final Color GRAY_200 = new Color(238, 238, 238); + public static final Color GRAY_300 = new Color(224, 224, 224); + public static final Color GRAY_400 = new Color(189, 189, 189); + public static final Color GRAY_500 = new Color(158, 158, 158); + public static final Color GRAY_600 = new Color(117, 117, 117); + public static final Color GRAY_700 = new Color(97, 97, 97); + public static final Color GRAY_800 = new Color(66, 66, 66); + public static final Color GRAY_900 = new Color(33, 33, 33); + public static final Color BLUE_GRAY_50 = new Color(236, 239, 241); + public static final Color BLUE_GRAY_100 = new Color(207, 216, 220); + public static final Color BLUE_GRAY_200 = new Color(176, 190, 197); + public static final Color BLUE_GRAY_300 = new Color(144, 164, 174); + public static final Color BLUE_GRAY_400 = new Color(120, 144, 156); + public static final Color BLUE_GRAY_500 = new Color(96, 125, 139); + public static final Color BLUE_GRAY_600 = new Color(84, 110, 122); + public static final Color BLUE_GRAY_700 = new Color(69, 90, 100); + public static final Color BLUE_GRAY_800 = new Color(55, 71, 79); + public static final Color BLUE_GRAY_900 = new Color(38, 50, 56); + public static final Color BLACK = new Color(0, 0, 0); + public static final Color WHITE = new Color(255, 255, 255); + public static final Color TRANSPARENT = new Color(0, 0, 0, 255); - private MaterialColors() {} + private MaterialColors() {} - public static Color bleach(Color color, float amount) { - int red = (int) ((color.getRed() * (1 - amount) / 255 + amount) * 255); - int green = (int) ((color.getGreen() * (1 - amount) / 255 + amount) * 255); - int blue = (int) ((color.getBlue() * (1 - amount) / 255 + amount) * 255); - return new Color(red, green, blue); - } + public static Color bleach(Color color, float amount) { + int red = (int) ((color.getRed() * (1 - amount) / 255 + amount) * 255); + int green = (int) ((color.getGreen() * (1 - amount) / 255 + amount) * 255); + int blue = (int) ((color.getBlue() * (1 - amount) / 255 + amount) * 255); + return new Color(red, green, blue); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java index f5e209b0d..30c4fdeda 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java @@ -8,28 +8,28 @@ public class MaterialDrawingUtils { - static { - System.setProperty("awt.useSystemAAFontSettings", "on"); - System.setProperty("swing.aatext", "true"); - System.setProperty("sun.java2d.xrender", "true"); - } + static { + System.setProperty("awt.useSystemAAFontSettings", "on"); + System.setProperty("swing.aatext", "true"); + System.setProperty("sun.java2d.xrender", "true"); + } - public static Graphics getAliasedGraphics(Graphics g) { - Map hints = - (Map) - Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); - if (hints != null) { - hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + public static Graphics getAliasedGraphics(Graphics g) { + Map hints = + (Map) + Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); + if (hints != null) { + hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - Graphics2D g2d = (Graphics2D) g; - g2d.addRenderingHints(hints); + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(hints); - // g2d.addRenderingHints (new RenderingHints (RenderingHints.KEY_ANTIALIASING, - // RenderingHints.VALUE_ANTIALIAS_ON)); - return g2d; - } else { - // Desktop hints not supported on this platform - return g; - } + // g2d.addRenderingHints (new RenderingHints (RenderingHints.KEY_ANTIALIASING, + // RenderingHints.VALUE_ANTIALIAS_ON)); + return g2d; + } else { + // Desktop hints not supported on this platform + return g; } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java index e5d1de56c..cb6a79f86 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java @@ -9,52 +9,51 @@ public class MaterialFonts { - private static final Map fontSettings = new HashMap<>(); - - public static final Font BLACK = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Black.ttf"); - public static final Font BLACK_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BlackItalic.ttf"); - public static final Font BOLD = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Bold.ttf"); - public static final Font BOLD_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BoldItalic.ttf"); - public static final Font ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Italic.ttf"); - public static final Font LIGHT = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Light.ttf"); - public static final Font LIGHT_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-LightItalic.ttf"); - public static final Font MEDIUM = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Medium.ttf"); - public static final Font MEDIUM_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-MediumItalic.ttf"); - public static final Font REGULAR = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf"); - public static final Font THIN = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Thin.ttf"); - public static final Font THIN_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-ThinItalic.ttf"); - - private static Font loadFont(String fontPath) { - if (fontSettings.isEmpty()) { - fontSettings.put(TextAttribute.SIZE, 14f); - fontSettings.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); - } - - try (InputStream inputStream = MaterialFonts.class.getResourceAsStream(fontPath)) { - return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(fontSettings); - } catch (IOException | FontFormatException e) { - e.printStackTrace(); - throw new RuntimeException("Font " + fontPath + " wasn't loaded"); - } + private static final Map fontSettings = new HashMap<>(); + + public static final Font BLACK = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Black.ttf"); + public static final Font BLACK_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BlackItalic.ttf"); + public static final Font BOLD = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Bold.ttf"); + public static final Font BOLD_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BoldItalic.ttf"); + public static final Font ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Italic.ttf"); + public static final Font LIGHT = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Light.ttf"); + public static final Font LIGHT_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-LightItalic.ttf"); + public static final Font MEDIUM = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Medium.ttf"); + public static final Font MEDIUM_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-MediumItalic.ttf"); + public static final Font REGULAR = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf"); + public static final Font THIN = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Thin.ttf"); + public static final Font THIN_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-ThinItalic.ttf"); + + private static Font loadFont(String fontPath) { + if (fontSettings.isEmpty()) { + fontSettings.put(TextAttribute.SIZE, 14f); + fontSettings.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); } - public static Font getRegularFont(float size) { - final Map map = new HashMap<>(); - map.put(TextAttribute.SIZE, size); - map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); - - try (InputStream inputStream = - MaterialFonts.class.getResourceAsStream( - "/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf")) { - return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(map); - } catch (IOException | FontFormatException e) { - e.printStackTrace(); - throw new RuntimeException("Font regular wasn't loaded"); - } + try (InputStream inputStream = MaterialFonts.class.getResourceAsStream(fontPath)) { + return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(fontSettings); + } catch (IOException | FontFormatException e) { + e.printStackTrace(); + throw new RuntimeException("Font " + fontPath + " wasn't loaded"); } + } + + public static Font getRegularFont(float size) { + final Map map = new HashMap<>(); + map.put(TextAttribute.SIZE, size); + map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + + try (InputStream inputStream = + MaterialFonts.class.getResourceAsStream("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf")) { + return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(map); + } catch (IOException | FontFormatException e) { + e.printStackTrace(); + throw new RuntimeException("Font regular wasn't loaded"); + } + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java index a1a716c76..93abff7a2 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java @@ -7,43 +7,41 @@ public class MaterialImages { - public static final BufferedImage RIGHT_ARROW = loadImg("/edu/rpi/legup/imgs/right_arrow.png"); - public static final BufferedImage DOWN_ARROW = loadImg("/edu/rpi/legup/imgs/down_arrow.png"); - public static final BufferedImage UP_ARROW = loadImg("/edu/rpi/legup/imgs/up_arrow.png"); - public static final BufferedImage PAINTED_CHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/painted_checked_box.png"); - public static final BufferedImage OUTLINED_CHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/outlined_checked_box.png"); - public static final BufferedImage UNCHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/unchecked_box.png"); - public static final BufferedImage RADIO_BUTTON_ON = - loadImg("/edu/rpi/legup/imgs/radio_button_on.png"); - public static final BufferedImage RADIO_BUTTON_OFF = - loadImg("/edu/rpi/legup/imgs/radio_button_off.png"); - public static final BufferedImage TOGGLE_BUTTON_ON = - loadImg("/edu/rpi/legup/imgs/toggle_on.png"); - public static final BufferedImage TOGGLE_BUTTON_OFF = - loadImg("/edu/rpi/legup/imgs/toggle_off.png"); - public static final BufferedImage BACK_ARROW = loadImg("/edu/rpi/legup/imgs/back_arrow.png"); - public static final BufferedImage COMPUTER = loadImg("/edu/rpi/legup/imgs/computer.png"); - public static final BufferedImage FILE = loadImg("/edu/rpi/legup/imgs/file.png"); - public static final BufferedImage FLOPPY_DRIVE = - loadImg("/edu/rpi/legup/imgs/floppy_drive.png"); - public static final BufferedImage FOLDER = loadImg("/edu/rpi/legup/imgs/folder.png"); - public static final BufferedImage HARD_DRIVE = loadImg("/edu/rpi/legup/imgs/hard_drive.png"); - public static final BufferedImage HOME = loadImg("/edu/rpi/legup/imgs/home.png"); - public static final BufferedImage LIST = loadImg("/edu/rpi/legup/imgs/list.png"); - public static final BufferedImage NEW_FOLDER = loadImg("/edu/rpi/legup/imgs/new_folder.png"); - public static final BufferedImage DETAILS = loadImg("/edu/rpi/legup/imgs/details.png"); + public static final BufferedImage RIGHT_ARROW = loadImg("/edu/rpi/legup/imgs/right_arrow.png"); + public static final BufferedImage DOWN_ARROW = loadImg("/edu/rpi/legup/imgs/down_arrow.png"); + public static final BufferedImage UP_ARROW = loadImg("/edu/rpi/legup/imgs/up_arrow.png"); + public static final BufferedImage PAINTED_CHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/painted_checked_box.png"); + public static final BufferedImage OUTLINED_CHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/outlined_checked_box.png"); + public static final BufferedImage UNCHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/unchecked_box.png"); + public static final BufferedImage RADIO_BUTTON_ON = + loadImg("/edu/rpi/legup/imgs/radio_button_on.png"); + public static final BufferedImage RADIO_BUTTON_OFF = + loadImg("/edu/rpi/legup/imgs/radio_button_off.png"); + public static final BufferedImage TOGGLE_BUTTON_ON = loadImg("/edu/rpi/legup/imgs/toggle_on.png"); + public static final BufferedImage TOGGLE_BUTTON_OFF = + loadImg("/edu/rpi/legup/imgs/toggle_off.png"); + public static final BufferedImage BACK_ARROW = loadImg("/edu/rpi/legup/imgs/back_arrow.png"); + public static final BufferedImage COMPUTER = loadImg("/edu/rpi/legup/imgs/computer.png"); + public static final BufferedImage FILE = loadImg("/edu/rpi/legup/imgs/file.png"); + public static final BufferedImage FLOPPY_DRIVE = loadImg("/edu/rpi/legup/imgs/floppy_drive.png"); + public static final BufferedImage FOLDER = loadImg("/edu/rpi/legup/imgs/folder.png"); + public static final BufferedImage HARD_DRIVE = loadImg("/edu/rpi/legup/imgs/hard_drive.png"); + public static final BufferedImage HOME = loadImg("/edu/rpi/legup/imgs/home.png"); + public static final BufferedImage LIST = loadImg("/edu/rpi/legup/imgs/list.png"); + public static final BufferedImage NEW_FOLDER = loadImg("/edu/rpi/legup/imgs/new_folder.png"); + public static final BufferedImage DETAILS = loadImg("/edu/rpi/legup/imgs/details.png"); - private MaterialImages() {} + private MaterialImages() {} - private static BufferedImage loadImg(String imgPath) { - try (InputStream inputStream = MaterialImages.class.getResourceAsStream(imgPath)) { - return ImageIO.read(inputStream); - } catch (IOException e) { - e.printStackTrace(); - throw new RuntimeException("Image " + imgPath + " wasn't loaded"); - } + private static BufferedImage loadImg(String imgPath) { + try (InputStream inputStream = MaterialImages.class.getResourceAsStream(imgPath)) { + return ImageIO.read(inputStream); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Image " + imgPath + " wasn't loaded"); } + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java index 1fb0a16ab..c3c70db31 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java @@ -3,18 +3,18 @@ import javax.swing.ImageIcon; public class CaseRulePanel extends RulePanel { - /** - * CaseRulePanel Constructor creates a CaseRulePanel - * - * @param ruleFrame rule frame that this CaseRulePanel is contained in - */ - CaseRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Case Rules.gif")); - this.name = "Case Rules"; - this.toolTip = "Case Rules"; - } + /** + * CaseRulePanel Constructor creates a CaseRulePanel + * + * @param ruleFrame rule frame that this CaseRulePanel is contained in + */ + CaseRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Case Rules.gif")); + this.name = "Case Rules"; + this.toolTip = "Case Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java index ae9444db2..1e7d6066c 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java @@ -6,16 +6,16 @@ public class CaseRuleSelectionView extends JPanel { - public CaseRuleSelectionView(RuleButton ruleButton) { - setLayout(new WrapLayout()); - Button button1 = new Button(ruleButton.getX() + ", " + ruleButton.getY()); - button1.setSize(50, 50); - Button button2 = new Button("How"); - button2.setSize(50, 50); + public CaseRuleSelectionView(RuleButton ruleButton) { + setLayout(new WrapLayout()); + Button button1 = new Button(ruleButton.getX() + ", " + ruleButton.getY()); + button1.setSize(50, 50); + Button button2 = new Button("How"); + button2.setSize(50, 50); - add(button1); - add(button2); + add(button1); + add(button2); - revalidate(); - } + revalidate(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java index f695491fb..5f5fb6aaf 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java @@ -3,18 +3,18 @@ import javax.swing.*; public class ContradictionRulePanel extends RulePanel { - /** - * ContradictionRulePanel Constructor creates a ContradictionRulePanel - * - * @param ruleFrame rule frame that this ContradictionRulePanel is contained in - */ - ContradictionRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Contradictions.gif")); - this.name = "Contradiction Rules"; - this.toolTip = "Contradiction Rules"; - } + /** + * ContradictionRulePanel Constructor creates a ContradictionRulePanel + * + * @param ruleFrame rule frame that this ContradictionRulePanel is contained in + */ + ContradictionRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Contradictions.gif")); + this.name = "Contradiction Rules"; + this.toolTip = "Contradiction Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java index 2795f2df7..a89811a64 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java @@ -5,20 +5,20 @@ import org.apache.logging.log4j.Logger; public class DirectRulePanel extends RulePanel { - private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); - /** - * DirectRulePanel Constructor creates a basic rule panel - * - * @param ruleFrame rule frame that this basic rule panel is contained in - */ - DirectRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Direct Rules"; - this.toolTip = "Direct Rules"; - } + /** + * DirectRulePanel Constructor creates a basic rule panel + * + * @param ruleFrame rule frame that this basic rule panel is contained in + */ + DirectRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Direct Rules"; + this.toolTip = "Direct Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java index e9c274250..6100b6964 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java @@ -4,36 +4,36 @@ import javax.swing.*; public class RuleButton extends JButton { - private Rule rule; + private Rule rule; - /** - * RuleButton Constructor - creates a button for a rule - * - * @param rule rule to create the button - */ - RuleButton(Rule rule) { - super( - rule.getRuleName(), - rule.getImageIcon()); // display rules' name under rule when load the icon - this.rule = rule; - this.setFocusPainted(false); - } + /** + * RuleButton Constructor - creates a button for a rule + * + * @param rule rule to create the button + */ + RuleButton(Rule rule) { + super( + rule.getRuleName(), + rule.getImageIcon()); // display rules' name under rule when load the icon + this.rule = rule; + this.setFocusPainted(false); + } - /** - * Gets the Rule from this button - * - * @return Rule from this button - */ - public Rule getRule() { - return rule; - } + /** + * Gets the Rule from this button + * + * @return Rule from this button + */ + public Rule getRule() { + return rule; + } - /** - * Sets the Rule for this button - * - * @param rule Rule for this button - */ - void setRule(Rule rule) { - this.rule = rule; - } + /** + * Sets the Rule for this button + * + * @param rule Rule for this button + */ + void setRule(Rule rule) { + this.rule = rule; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java index 6279f93a4..2f31f24dc 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java @@ -11,168 +11,165 @@ import javax.swing.border.TitledBorder; public class RuleFrame extends JPanel { - private static final String checkBox = " \u2714 "; - private static final String xBox = " \u2718 "; - private static final String htmlHead = ""; - private static final String htmlTail = ""; - - private DirectRulePanel DirectRulePanel; - private ContradictionRulePanel contradictionPanel; - private CaseRulePanel casePanel; - - private SearchBarPanel searchPanel; - - private JTabbedPane tabbedPane; - private JLabel status; - private ButtonGroup buttonGroup; - - private RuleController controller; - - public RuleFrame(RuleController controller) { - - MaterialTabbedPaneUI tabOverride = - new MaterialTabbedPaneUI() { - // this prevents the tabs from moving around when you select them - @Override - protected boolean shouldRotateTabRuns(int i) { - return false; - } - }; - - this.controller = controller; - - this.tabbedPane = new JTabbedPane(); - this.tabbedPane.setUI(tabOverride); - this.status = new JLabel(); - this.buttonGroup = new ButtonGroup(); - - DirectRulePanel = new DirectRulePanel(this); - JScrollPane newbrp = new JScrollPane(DirectRulePanel); - newbrp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab( - DirectRulePanel.getName(), - DirectRulePanel.getIcon(), - newbrp, - DirectRulePanel.getToolTip()); - - casePanel = new CaseRulePanel(this); - JScrollPane newcp = new JScrollPane(casePanel); - newcp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(casePanel.name, casePanel.icon, newcp, casePanel.toolTip); - - contradictionPanel = new ContradictionRulePanel(this); - JScrollPane newp = new JScrollPane(contradictionPanel); - newp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab( - contradictionPanel.name, contradictionPanel.icon, newp, contradictionPanel.toolTip); - - searchPanel = new SearchBarPanel(this); - JScrollPane newsp = new JScrollPane(searchPanel); - newsp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(searchPanel.name, searchPanel.icon, newsp, searchPanel.toolTip); - - setLayout(new BorderLayout()); - setMinimumSize(new Dimension(250, 256)); - setPreferredSize(new Dimension(355, 256)); - - add(tabbedPane); - add(status, BorderLayout.SOUTH); - - TitledBorder title = BorderFactory.createTitledBorder("Rules"); - title.setTitleJustification(TitledBorder.CENTER); - setBorder(title); - } - - /** - * Gets the button group for the rule frame - * - * @return button group - */ - public ButtonGroup getButtonGroup() { - return buttonGroup; - } - - public void setSelectionByRule(Rule rule) { - DirectRulePanel.setSelectionByRule(rule); - casePanel.setSelectionByRule(rule); - contradictionPanel.setSelectionByRule(rule); - } - - /** Reset the rules button and status string */ - public void resetRuleButtons() { - resetStatus(); - } - - /** Reset the status label to the empty string */ - public void resetStatus() { - // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().updateStatus(); - } - - /** Resets the dimension of the rule frame */ - public void resetSize() { - int buttonWidth = - ((RulePanel) tabbedPane.getSelectedComponent()).getRuleButtons()[0].getWidth(); - this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); - } - - /** - * Set the status label to a value. Use resetStatus to clear it. - * - * @param check true iff we want a check box, if false we'll have a red x box - * @param text the text we're setting the label to display - */ - public void setStatus(boolean check, String text) { - String box = (check ? checkBox : xBox); - // status.setText(htmlHead + box + text + htmlTail); - // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().getStatus().setText(htmlHead + box + text + htmlTail); - } - - /** - * Sets all the rules for the rule frame - * - * @param puzzle edu.rpi.legup.puzzle game - */ - public void setRules(Puzzle puzzle) { - DirectRulePanel.setRules(puzzle.getDirectRules()); - contradictionPanel.setRules(puzzle.getContradictionRules()); - casePanel.setRules(puzzle.getCaseRules()); - } - - /** - * Board puzzleElement has changed - * - * @param board board state - */ - public void boardDataChanged(Board board) { - this.resetStatus(); - } - - /** - * Gets the RuleController for this RuleFrame - * - * @return rule controller - */ - public RuleController getController() { - return controller; - } - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - public DirectRulePanel getDirectRulePanel() { - return DirectRulePanel; - } - - public CaseRulePanel getCasePanel() { - return casePanel; - } - - public ContradictionRulePanel getContradictionPanel() { - return contradictionPanel; - } - - public SearchBarPanel getSearchPanel() { - return searchPanel; - } + private static final String checkBox = " \u2714 "; + private static final String xBox = " \u2718 "; + private static final String htmlHead = ""; + private static final String htmlTail = ""; + + private DirectRulePanel DirectRulePanel; + private ContradictionRulePanel contradictionPanel; + private CaseRulePanel casePanel; + + private SearchBarPanel searchPanel; + + private JTabbedPane tabbedPane; + private JLabel status; + private ButtonGroup buttonGroup; + + private RuleController controller; + + public RuleFrame(RuleController controller) { + + MaterialTabbedPaneUI tabOverride = + new MaterialTabbedPaneUI() { + // this prevents the tabs from moving around when you select them + @Override + protected boolean shouldRotateTabRuns(int i) { + return false; + } + }; + + this.controller = controller; + + this.tabbedPane = new JTabbedPane(); + this.tabbedPane.setUI(tabOverride); + this.status = new JLabel(); + this.buttonGroup = new ButtonGroup(); + + DirectRulePanel = new DirectRulePanel(this); + JScrollPane newbrp = new JScrollPane(DirectRulePanel); + newbrp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab( + DirectRulePanel.getName(), DirectRulePanel.getIcon(), newbrp, DirectRulePanel.getToolTip()); + + casePanel = new CaseRulePanel(this); + JScrollPane newcp = new JScrollPane(casePanel); + newcp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab(casePanel.name, casePanel.icon, newcp, casePanel.toolTip); + + contradictionPanel = new ContradictionRulePanel(this); + JScrollPane newp = new JScrollPane(contradictionPanel); + newp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab( + contradictionPanel.name, contradictionPanel.icon, newp, contradictionPanel.toolTip); + + searchPanel = new SearchBarPanel(this); + JScrollPane newsp = new JScrollPane(searchPanel); + newsp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab(searchPanel.name, searchPanel.icon, newsp, searchPanel.toolTip); + + setLayout(new BorderLayout()); + setMinimumSize(new Dimension(250, 256)); + setPreferredSize(new Dimension(355, 256)); + + add(tabbedPane); + add(status, BorderLayout.SOUTH); + + TitledBorder title = BorderFactory.createTitledBorder("Rules"); + title.setTitleJustification(TitledBorder.CENTER); + setBorder(title); + } + + /** + * Gets the button group for the rule frame + * + * @return button group + */ + public ButtonGroup getButtonGroup() { + return buttonGroup; + } + + public void setSelectionByRule(Rule rule) { + DirectRulePanel.setSelectionByRule(rule); + casePanel.setSelectionByRule(rule); + contradictionPanel.setSelectionByRule(rule); + } + + /** Reset the rules button and status string */ + public void resetRuleButtons() { + resetStatus(); + } + + /** Reset the status label to the empty string */ + public void resetStatus() { + // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().updateStatus(); + } + + /** Resets the dimension of the rule frame */ + public void resetSize() { + int buttonWidth = + ((RulePanel) tabbedPane.getSelectedComponent()).getRuleButtons()[0].getWidth(); + this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); + } + + /** + * Set the status label to a value. Use resetStatus to clear it. + * + * @param check true iff we want a check box, if false we'll have a red x box + * @param text the text we're setting the label to display + */ + public void setStatus(boolean check, String text) { + String box = (check ? checkBox : xBox); + // status.setText(htmlHead + box + text + htmlTail); + // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().getStatus().setText(htmlHead + box + text + htmlTail); + } + + /** + * Sets all the rules for the rule frame + * + * @param puzzle edu.rpi.legup.puzzle game + */ + public void setRules(Puzzle puzzle) { + DirectRulePanel.setRules(puzzle.getDirectRules()); + contradictionPanel.setRules(puzzle.getContradictionRules()); + casePanel.setRules(puzzle.getCaseRules()); + } + + /** + * Board puzzleElement has changed + * + * @param board board state + */ + public void boardDataChanged(Board board) { + this.resetStatus(); + } + + /** + * Gets the RuleController for this RuleFrame + * + * @return rule controller + */ + public RuleController getController() { + return controller; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public DirectRulePanel getDirectRulePanel() { + return DirectRulePanel; + } + + public CaseRulePanel getCasePanel() { + return casePanel; + } + + public ContradictionRulePanel getContradictionPanel() { + return contradictionPanel; + } + + public SearchBarPanel getSearchPanel() { + return searchPanel; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java index 5d985d5c2..50bd8a110 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java @@ -10,343 +10,336 @@ import javax.swing.*; public abstract class RulePanel extends JPanel { - protected ImageIcon icon; - protected String name; - protected String toolTip; - - protected RuleButton[] ruleButtons; - protected JPanel searchBarPanel; - JTextField textField; - protected RuleFrame ruleFrame; - protected List rules; - - /** - * RulePanel Constructor creates a RulePanel - * - * @param ruleFrame rule frame that this RulePanel is contained in - */ - public RulePanel(RuleFrame ruleFrame) { - this.ruleFrame = ruleFrame; - this.rules = new ArrayList<>(); - setLayout(new WrapLayout()); + protected ImageIcon icon; + protected String name; + protected String toolTip; + + protected RuleButton[] ruleButtons; + protected JPanel searchBarPanel; + JTextField textField; + protected RuleFrame ruleFrame; + protected List rules; + + /** + * RulePanel Constructor creates a RulePanel + * + * @param ruleFrame rule frame that this RulePanel is contained in + */ + public RulePanel(RuleFrame ruleFrame) { + this.ruleFrame = ruleFrame; + this.rules = new ArrayList<>(); + setLayout(new WrapLayout()); + } + + /** + * Gets the rule rule buttons + * + * @return rule ruleButtons + */ + public RuleButton[] getRuleButtons() { + return ruleButtons; + } + + /** + * Sets the rules for this rule panel + * + * @param rules list of the rules + */ + public void setRules(List rules) { + this.rules = rules; + clearButtons(); + + ruleButtons = new RuleButton[rules.size()]; + + for (int i = 0; i < rules.size(); i++) { + Rule rule = rules.get(i); + + ruleButtons[i] = new RuleButton(rule); + ruleButtons[i].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[i].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[i].setVerticalTextPosition(JButton.BOTTOM); + + ruleFrame.getButtonGroup().add(ruleButtons[i]); + ruleButtons[i].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); // showing description + ruleButtons[i].addActionListener(ruleFrame.getController()); + add(ruleButtons[i]); } + revalidate(); + } - /** - * Gets the rule rule buttons - * - * @return rule ruleButtons - */ - public RuleButton[] getRuleButtons() { - return ruleButtons; + public void updateRules() { + for (Rule rule : rules) { + rule.loadImage(); } - - /** - * Sets the rules for this rule panel - * - * @param rules list of the rules - */ - public void setRules(List rules) { - this.rules = rules; - clearButtons(); - - ruleButtons = new RuleButton[rules.size()]; - - for (int i = 0; i < rules.size(); i++) { - Rule rule = rules.get(i); - - ruleButtons[i] = new RuleButton(rule); - ruleButtons[i].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[i].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[i].setVerticalTextPosition(JButton.BOTTOM); - - ruleFrame.getButtonGroup().add(ruleButtons[i]); - ruleButtons[i].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); // showing description - ruleButtons[i].addActionListener(ruleFrame.getController()); - add(ruleButtons[i]); + setRules(rules); + } + + /** + * Search a certain rule in all the puzzles and set it for the searchBarPanel + * + * @param puzzle puzzle where the rule is being searched for + * @param ruleName rule that is being compared to each puzzle + *

This function is the searching algorithm for "public void setSearchBar(Puzzle + * allPuzzle)" (below) + *

It takes two param Puzzle puzzle and String ruleName puzzle contains rules, this + * function will compare each rule of puzzle with ruleName, to find exact same, similar rules, + * or all the rules with same start letter (if input is a signal letter) + */ + public void searchForRule(Puzzle puzzle, String ruleName) { + + List> allrules = new ArrayList>(3); + allrules.add(0, puzzle.getDirectRules()); + allrules.add(1, puzzle.getCaseRules()); + allrules.add(2, puzzle.getContradictionRules()); + + ruleButtons = new RuleButton[100]; + int similarfound = 0; + + for (int i = 0; i < allrules.size(); i++) { + for (int j = 0; j < allrules.get(i).size(); j++) { + Rule rule = allrules.get(i).get(j); + if ((ruleName).equals(rule.getRuleName().toUpperCase())) { + + ruleButtons[0] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[0]); + + ruleButtons[0].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[0].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[0].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[0].setToolTipText(rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[0].addActionListener(ruleFrame.getController()); + add(ruleButtons[0]); + revalidate(); + return; + + } else { + if (similarityCheck(ruleName, rule.getRuleName().toUpperCase()) > 0.2) { + ruleButtons[similarfound] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); + + ruleButtons[similarfound].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[similarfound].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[similarfound].addActionListener(ruleFrame.getController()); + add(ruleButtons[similarfound]); + similarfound += 1; + revalidate(); + } else { + if ((ruleName.charAt(0)) == (rule.getRuleName().toUpperCase()).charAt(0)) { + ruleButtons[similarfound] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); + + ruleButtons[similarfound].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[similarfound].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[similarfound].addActionListener(ruleFrame.getController()); + add(ruleButtons[similarfound]); + similarfound += 1; + revalidate(); + } + } } - revalidate(); + } } - public void updateRules() { - for (Rule rule : rules) { - rule.loadImage(); - } - setRules(rules); + if (ruleButtons[0] == null) { + JOptionPane.showMessageDialog( + null, "Please input the correct rule name", "Confirm", JOptionPane.INFORMATION_MESSAGE); } - - /** - * Search a certain rule in all the puzzles and set it for the searchBarPanel - * - * @param puzzle puzzle where the rule is being searched for - * @param ruleName rule that is being compared to each puzzle - *

This function is the searching algorithm for "public void setSearchBar(Puzzle - * allPuzzle)" (below) - *

It takes two param Puzzle puzzle and String ruleName puzzle contains rules, this - * function will compare each rule of puzzle with ruleName, to find exact same, similar - * rules, or all the rules with same start letter (if input is a signal letter) - */ - public void searchForRule(Puzzle puzzle, String ruleName) { - - List> allrules = new ArrayList>(3); - allrules.add(0, puzzle.getDirectRules()); - allrules.add(1, puzzle.getCaseRules()); - allrules.add(2, puzzle.getContradictionRules()); - - ruleButtons = new RuleButton[100]; - int similarfound = 0; - - for (int i = 0; i < allrules.size(); i++) { - for (int j = 0; j < allrules.get(i).size(); j++) { - Rule rule = allrules.get(i).get(j); - if ((ruleName).equals(rule.getRuleName().toUpperCase())) { - - ruleButtons[0] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[0]); - - ruleButtons[0].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[0].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[0].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[0].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[0].addActionListener(ruleFrame.getController()); - add(ruleButtons[0]); - revalidate(); - return; - - } else { - if (similarityCheck(ruleName, rule.getRuleName().toUpperCase()) > 0.2) { - ruleButtons[similarfound] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); - - ruleButtons[similarfound].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[similarfound].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[similarfound].addActionListener(ruleFrame.getController()); - add(ruleButtons[similarfound]); - similarfound += 1; - revalidate(); - } else { - if ((ruleName.charAt(0)) == (rule.getRuleName().toUpperCase()).charAt(0)) { - ruleButtons[similarfound] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); - - ruleButtons[similarfound].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[similarfound].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[similarfound].addActionListener(ruleFrame.getController()); - add(ruleButtons[similarfound]); - similarfound += 1; - revalidate(); - } - } - } - } - } - - if (ruleButtons[0] == null) { - JOptionPane.showMessageDialog( - null, - "Please input the correct rule name", - "Confirm", - JOptionPane.INFORMATION_MESSAGE); - } + } + + /** + * Calculates the similarity (a number within 0 and 1) between two strings. This function will + * take two para String s1 and String s2, which s1 is the user's input and s2 is the compared + * really rule name + * + * @param s1 user's input + * @param s2 the compared really rule name + * @return a similarity degree between 0 and 1 similarityCheck will use a helper function to + * calculate a similarity degree(from 0 to 1). closer to 0 means less similar, and closer to 1 + * means more similar. + */ + public static double similarityCheck(String s1, String s2) { + String longer = s1, shorter = s2; + if (s1.length() < s2.length()) { // longer should always have greater length + longer = s2; + shorter = s1; } - - /** - * Calculates the similarity (a number within 0 and 1) between two strings. This function will - * take two para String s1 and String s2, which s1 is the user's input and s2 is the compared - * really rule name - * - * @param s1 user's input - * @param s2 the compared really rule name - * @return a similarity degree between 0 and 1 similarityCheck will use a helper function to - * calculate a similarity degree(from 0 to 1). closer to 0 means less similar, and closer to - * 1 means more similar. - */ - public static double similarityCheck(String s1, String s2) { - String longer = s1, shorter = s2; - if (s1.length() < s2.length()) { // longer should always have greater length - longer = s2; - shorter = s1; - } - int longerLength = longer.length(); - if (longerLength == 0) { - return 1.0; /* both strings are zero length */ - } - return (longerLength - editDistance(longer, shorter)) / (double) longerLength; + int longerLength = longer.length(); + if (longerLength == 0) { + return 1.0; /* both strings are zero length */ } - - /** - * Help function for similarityCheck(); - * - * @param s1 user's input - * @param s2 the compared really rule name - * @return a similarity degree between 0 and 1 - */ - public static int editDistance(String s1, String s2) { - s1 = s1.toLowerCase(); - s2 = s2.toLowerCase(); - - int[] costs = new int[s2.length() + 1]; - for (int i = 0; i <= s1.length(); i++) { - int lastValue = i; - for (int j = 0; j <= s2.length(); j++) { - if (i == 0) { - costs[j] = j; - } else { - if (j > 0) { - int newValue = costs[j - 1]; - if (s1.charAt(i - 1) != s2.charAt(j - 1)) { - newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; - } - costs[j - 1] = lastValue; - lastValue = newValue; - } - } - } - if (i > 0) { - costs[s2.length()] = lastValue; + return (longerLength - editDistance(longer, shorter)) / (double) longerLength; + } + + /** + * Help function for similarityCheck(); + * + * @param s1 user's input + * @param s2 the compared really rule name + * @return a similarity degree between 0 and 1 + */ + public static int editDistance(String s1, String s2) { + s1 = s1.toLowerCase(); + s2 = s2.toLowerCase(); + + int[] costs = new int[s2.length() + 1]; + for (int i = 0; i <= s1.length(); i++) { + int lastValue = i; + for (int j = 0; j <= s2.length(); j++) { + if (i == 0) { + costs[j] = j; + } else { + if (j > 0) { + int newValue = costs[j - 1]; + if (s1.charAt(i - 1) != s2.charAt(j - 1)) { + newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; } + costs[j - 1] = lastValue; + lastValue = newValue; + } } - return costs[s2.length()]; - } - - /** - * Sets the search bar for SearchBarPanel search bar allows user to input a name to get relative - * rules once a name is entered and click ok will load (a/several) rule icon, which has all the - * functions just as other rule icons. - * - * @param allPuzzle name of rule input - */ - public void setSearchBar(Puzzle allPuzzle) { - - searchBarPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 6, 6)); - - textField = new JTextField(); - ruleFrame.addComponentListener( - new ComponentAdapter() { - public void componentResized(ComponentEvent componentEvent) { - Component c = componentEvent.getComponent(); - textField.setColumns((8 + (c.getWidth() - 250) / 10) - 1); - } - }); - - add(searchBarPanel); - JLabel findLabel = new JLabel("Search:"); - searchBarPanel.add(findLabel); - searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); - searchBarPanel.add(textField); - searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); - JButton findButton = new JButton("Go"); - ActionListener action = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent event) { - if (ruleButtons != null) { - for (int i = 0; i != ruleButtons.length; i++) { - if (ruleButtons[i] == null) { - continue; - } - ruleButtons[i].removeActionListener(ruleFrame.getController()); - } - } - String inputRule = textField.getText().toUpperCase().trim(); - - if (!inputRule.isEmpty()) { - if (ruleButtons != null) { - - for (int x = 0; x < ruleButtons.length; ++x) { - if (ruleButtons[x] == null) { - continue; - } - remove(ruleButtons[x]); - } - } - searchForRule(allPuzzle, inputRule); - } else { - JOptionPane.showMessageDialog( - null, - "Please give a name", - "Confirm", - JOptionPane.INFORMATION_MESSAGE); - } - } - }; - textField.addActionListener(action); - findButton.addActionListener(action); - searchBarPanel.add(findButton); + } + if (i > 0) { + costs[s2.length()] = lastValue; + } } - - /** - * Sets the selection by the specified rule - * - * @param rule rule to set the selection to - */ - public void setSelectionByRule(Rule rule) { - if (ruleButtons != null) { - for (int i = 0; i < ruleButtons.length; i++) { - if (rules.get(i).equals(rule)) { - ruleButtons[i].setSelected(true); - break; + return costs[s2.length()]; + } + + /** + * Sets the search bar for SearchBarPanel search bar allows user to input a name to get relative + * rules once a name is entered and click ok will load (a/several) rule icon, which has all the + * functions just as other rule icons. + * + * @param allPuzzle name of rule input + */ + public void setSearchBar(Puzzle allPuzzle) { + + searchBarPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 6, 6)); + + textField = new JTextField(); + ruleFrame.addComponentListener( + new ComponentAdapter() { + public void componentResized(ComponentEvent componentEvent) { + Component c = componentEvent.getComponent(); + textField.setColumns((8 + (c.getWidth() - 250) / 10) - 1); + } + }); + + add(searchBarPanel); + JLabel findLabel = new JLabel("Search:"); + searchBarPanel.add(findLabel); + searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); + searchBarPanel.add(textField); + searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); + JButton findButton = new JButton("Go"); + ActionListener action = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + if (ruleButtons != null) { + for (int i = 0; i != ruleButtons.length; i++) { + if (ruleButtons[i] == null) { + continue; } + ruleButtons[i].removeActionListener(ruleFrame.getController()); + } } - } - } + String inputRule = textField.getText().toUpperCase().trim(); + + if (!inputRule.isEmpty()) { + if (ruleButtons != null) { - /** Clears the rule buttons off this panel */ - protected void clearButtons() { - if (ruleButtons != null) { - removeAll(); - for (int x = 0; x < ruleButtons.length; ++x) { - ruleButtons[x].removeActionListener(ruleFrame.getController()); + for (int x = 0; x < ruleButtons.length; ++x) { + if (ruleButtons[x] == null) { + continue; + } + remove(ruleButtons[x]); + } + } + searchForRule(allPuzzle, inputRule); + } else { + JOptionPane.showMessageDialog( + null, "Please give a name", "Confirm", JOptionPane.INFORMATION_MESSAGE); } + } + }; + textField.addActionListener(action); + findButton.addActionListener(action); + searchBarPanel.add(findButton); + } + + /** + * Sets the selection by the specified rule + * + * @param rule rule to set the selection to + */ + public void setSelectionByRule(Rule rule) { + if (ruleButtons != null) { + for (int i = 0; i < ruleButtons.length; i++) { + if (rules.get(i).equals(rule)) { + ruleButtons[i].setSelected(true); + break; } + } } - - /** - * Gets the rules associated with this panel - * - * @return the rules - */ - public List getRules() { - return rules; - } - - public ImageIcon getIcon() { - return icon; - } - - public void setIcon(ImageIcon icon) { - this.icon = icon; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getToolTip() { - return toolTip; - } - - public void setToolTip(String toolTip) { - this.toolTip = toolTip; + } + + /** Clears the rule buttons off this panel */ + protected void clearButtons() { + if (ruleButtons != null) { + removeAll(); + for (int x = 0; x < ruleButtons.length; ++x) { + ruleButtons[x].removeActionListener(ruleFrame.getController()); + } } + } + + /** + * Gets the rules associated with this panel + * + * @return the rules + */ + public List getRules() { + return rules; + } + + public ImageIcon getIcon() { + return icon; + } + + public void setIcon(ImageIcon icon) { + this.icon = icon; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + public String getToolTip() { + return toolTip; + } + + public void setToolTip(String toolTip) { + this.toolTip = toolTip; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java index aba4707cd..b0dddc2c7 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java @@ -3,19 +3,19 @@ import javax.swing.*; public class SearchBarPanel extends RulePanel { - /** - * SearchBarPanel Constructor creates a SearchBarPanel - * - * @param ruleFrame rule frame that this SearchBarPanel is contained in - *

This class is used to create a panel named "search bar" - */ - SearchBarPanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Zoom In.png")); - this.name = "Search Rules"; - this.toolTip = "Search Rules"; - } + /** + * SearchBarPanel Constructor creates a SearchBarPanel + * + * @param ruleFrame rule frame that this SearchBarPanel is contained in + *

This class is used to create a panel named "search bar" + */ + SearchBarPanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Zoom In.png")); + this.name = "Search Rules"; + this.toolTip = "Search Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java index 33c04717d..00b8ec0bb 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java @@ -5,169 +5,169 @@ import java.awt.*; public abstract class TreeElementView implements Shape { - protected TreeElement treeElement; - protected double span; - protected int depth; - protected boolean isSelected; - protected boolean isHover; - protected TreeElementType type; - protected boolean isVisible; - protected boolean isCollapsed; - - /** - * TreeElementView Constructor creates a tree puzzleElement view - * - * @param type tree puzzleElement type - * @param treeElement tree puzzleElement puzzleElement associated with this view - */ - protected TreeElementView(TreeElementType type, TreeElement treeElement) { - this.type = type; - this.treeElement = treeElement; - this.isSelected = false; - this.isHover = false; - this.isVisible = true; - } - - /** - * Draws the tree puzzleElement view - * - * @param graphics2D graphics2D object used to draw the tree puzzleElement view - */ - public abstract void draw(Graphics2D graphics2D); - - /** - * Gets the span for the sub tree rooted at this view - * - * @return span bounded y span - */ - public double getSpan() { - return span; - } - - /** - * Sets the span for the sub tree rooted at this view. - * - * @param span bounded y span - */ - public void setSpan(double span) { - this.span = span; - } - - /** - * Gets the depth of this tree puzzleElement in the tree - * - * @return depth of this tree puzzleElement - */ - public int getDepth() { - return depth; - } - - /** - * Sets the depth of this tree puzzleElement in the tree - * - * @param depth depth of this tree puzzleElement - */ - public void setDepth(int depth) { - this.depth = depth; - } - - /** - * Gets the tree puzzleElement type for this view - * - * @return tree puzzleElement type - */ - public TreeElementType getType() { - return type; - } - - /** - * Gets the tree puzzleElement associated with this view - * - * @return tree puzzleElement associated with this view - */ - public TreeElement getTreeElement() { - return treeElement; - } - - /** - * Sets the tree puzzleElement associated with this view - * - * @param treeElement tree puzzleElement associated with this view - */ - public void setTreeElement(TreeElement treeElement) { - this.treeElement = treeElement; - } - - /** - * Gets the mouse selection - * - * @return mouse selection - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets the mouse selection - * - * @param isSelected mouse selection - */ - public void setSelected(boolean isSelected) { - this.isSelected = isSelected; - } - - /** - * Gets the mouse hover - * - * @return mouse hover - */ - public boolean isHover() { - return isHover; - } - - /** - * Sets the mouse hover - * - * @param isHovered mouse hover - */ - public void setHover(boolean isHovered) { - this.isHover = isHovered; - } - - /** - * Gets the visibility of the tree puzzleElement. Tells the TreeView whether or not to draw the - * tree puzzleElement - * - * @return visibility of the tree puzzleElement - */ - public boolean isVisible() { - return isVisible; - } - - /** - * Sets the visibility of the tree puzzleElement - * - * @param isVisible visibility of the tree puzzleElement - */ - public void setVisible(boolean isVisible) { - this.isVisible = isVisible; - } - - /** - * Is this tree node view collapsed in the view - * - * @return true if the node is collapsed, false otherwise - */ - public boolean isCollapsed() { - return isCollapsed; - } - - /** - * Sets the tree node view collapsed field - * - * @param isCollapsed true if the node is collapsed, false otherwise - */ - public void setCollapsed(boolean isCollapsed) { - this.isCollapsed = isCollapsed; - } + protected TreeElement treeElement; + protected double span; + protected int depth; + protected boolean isSelected; + protected boolean isHover; + protected TreeElementType type; + protected boolean isVisible; + protected boolean isCollapsed; + + /** + * TreeElementView Constructor creates a tree puzzleElement view + * + * @param type tree puzzleElement type + * @param treeElement tree puzzleElement puzzleElement associated with this view + */ + protected TreeElementView(TreeElementType type, TreeElement treeElement) { + this.type = type; + this.treeElement = treeElement; + this.isSelected = false; + this.isHover = false; + this.isVisible = true; + } + + /** + * Draws the tree puzzleElement view + * + * @param graphics2D graphics2D object used to draw the tree puzzleElement view + */ + public abstract void draw(Graphics2D graphics2D); + + /** + * Gets the span for the sub tree rooted at this view + * + * @return span bounded y span + */ + public double getSpan() { + return span; + } + + /** + * Sets the span for the sub tree rooted at this view. + * + * @param span bounded y span + */ + public void setSpan(double span) { + this.span = span; + } + + /** + * Gets the depth of this tree puzzleElement in the tree + * + * @return depth of this tree puzzleElement + */ + public int getDepth() { + return depth; + } + + /** + * Sets the depth of this tree puzzleElement in the tree + * + * @param depth depth of this tree puzzleElement + */ + public void setDepth(int depth) { + this.depth = depth; + } + + /** + * Gets the tree puzzleElement type for this view + * + * @return tree puzzleElement type + */ + public TreeElementType getType() { + return type; + } + + /** + * Gets the tree puzzleElement associated with this view + * + * @return tree puzzleElement associated with this view + */ + public TreeElement getTreeElement() { + return treeElement; + } + + /** + * Sets the tree puzzleElement associated with this view + * + * @param treeElement tree puzzleElement associated with this view + */ + public void setTreeElement(TreeElement treeElement) { + this.treeElement = treeElement; + } + + /** + * Gets the mouse selection + * + * @return mouse selection + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets the mouse selection + * + * @param isSelected mouse selection + */ + public void setSelected(boolean isSelected) { + this.isSelected = isSelected; + } + + /** + * Gets the mouse hover + * + * @return mouse hover + */ + public boolean isHover() { + return isHover; + } + + /** + * Sets the mouse hover + * + * @param isHovered mouse hover + */ + public void setHover(boolean isHovered) { + this.isHover = isHovered; + } + + /** + * Gets the visibility of the tree puzzleElement. Tells the TreeView whether or not to draw the + * tree puzzleElement + * + * @return visibility of the tree puzzleElement + */ + public boolean isVisible() { + return isVisible; + } + + /** + * Sets the visibility of the tree puzzleElement + * + * @param isVisible visibility of the tree puzzleElement + */ + public void setVisible(boolean isVisible) { + this.isVisible = isVisible; + } + + /** + * Is this tree node view collapsed in the view + * + * @return true if the node is collapsed, false otherwise + */ + public boolean isCollapsed() { + return isCollapsed; + } + + /** + * Sets the tree node view collapsed field + * + * @param isCollapsed true if the node is collapsed, false otherwise + */ + public void setCollapsed(boolean isCollapsed) { + this.isCollapsed = isCollapsed; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java index 990d96620..dbb4dfcb4 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java @@ -8,305 +8,285 @@ import java.util.ArrayList; public class TreeNodeView extends TreeElementView { - static final int RADIUS = 25; - static final int DIAMETER = 2 * RADIUS; - - private static final Stroke MAIN_STROKE = new BasicStroke(3); - private static final Stroke SELECTION_STROKE = new BasicStroke(2); - - private static final Color NODE_COLOR_ROOT = new Color(100, 100, 100); - private static final Color NODE_MINOR_COLOR_ROOT = new Color(75, 75, 75); - - private static final Color NODE_COLOR_DEFAULT = new Color(0xFFEB3B); - private static final Color NODE_MINOR_COLOR_DEFAULT = new Color(216, 197, 52); - - private static final Color NODE_COLOR_CONTRADICTION = new Color(178, 10, 16); - private static final Color NODE_MINOR_COLOR_CONTRADICTION = new Color(119, 13, 16); - - private static final Color OUTLINE_COLOR = new Color(0x212121); - private static final Color SELECTION_COLOR = new Color(0x1E88E5); - private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); - - private static final Color HOVER_COLOR = new Color(0x90CAF9); - private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); - - private Point location; - - private TreeTransitionView parentView; - private ArrayList childrenViews; - - private boolean isCollapsed; - private boolean isContradictoryState; - - /** - * TreeNodeView Constructor creates a node for display - * - * @param treeNode treeElement associated with this transition - */ - public TreeNodeView(TreeNode treeNode) { - super(TreeElementType.NODE, treeNode); - this.treeElement = treeNode; - this.location = new Point(); - this.parentView = null; - this.childrenViews = new ArrayList<>(); - this.isCollapsed = false; - this.isContradictoryState = false; - this.isVisible = true; - } - - /** - * Draws the TreeNodeView - * - * @param graphics2D graphics2D used for drawing - */ - public void draw(Graphics2D graphics2D) { - if (isVisible() && treeElement != null) { - if (getTreeElement().getParent() != null - && getTreeElement().getParent().isJustified() - && getTreeElement().getParent().getRule().getRuleType() - == RuleType.CONTRADICTION) { - isContradictoryState = true; - graphics2D.setColor(NODE_COLOR_CONTRADICTION); - graphics2D.drawLine( - location.x - RADIUS, - location.y - RADIUS, - location.x + RADIUS, - location.y + RADIUS); - graphics2D.drawLine( - location.x + RADIUS, - location.y - RADIUS, - location.x - RADIUS, - location.y + RADIUS); - } else { - isContradictoryState = false; - graphics2D.setStroke(MAIN_STROKE); - boolean isContraBranch = getTreeElement().isContradictoryBranch(); - - if (isSelected) { - graphics2D.setColor(SELECTION_COLOR); - graphics2D.fillOval( - location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval( - location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_SELECTION_COLOR); - graphics2D.drawOval( - location.x - RADIUS - 4, - location.y - RADIUS - 4, - DIAMETER + 8, - DIAMETER + 8); - } else { - if (isHover) { - graphics2D.setColor(HOVER_COLOR); - graphics2D.fillOval( - location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval( - location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_HOVER_COLOR); - graphics2D.drawOval( - location.x - RADIUS - 4, - location.y - RADIUS - 4, - DIAMETER + 8, - DIAMETER + 8); - } else { - graphics2D.setColor( - isContraBranch ? NODE_COLOR_CONTRADICTION : NODE_COLOR_DEFAULT); - graphics2D.fillOval( - location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval( - location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - } - } - } + static final int RADIUS = 25; + static final int DIAMETER = 2 * RADIUS; + + private static final Stroke MAIN_STROKE = new BasicStroke(3); + private static final Stroke SELECTION_STROKE = new BasicStroke(2); + + private static final Color NODE_COLOR_ROOT = new Color(100, 100, 100); + private static final Color NODE_MINOR_COLOR_ROOT = new Color(75, 75, 75); + + private static final Color NODE_COLOR_DEFAULT = new Color(0xFFEB3B); + private static final Color NODE_MINOR_COLOR_DEFAULT = new Color(216, 197, 52); + + private static final Color NODE_COLOR_CONTRADICTION = new Color(178, 10, 16); + private static final Color NODE_MINOR_COLOR_CONTRADICTION = new Color(119, 13, 16); + + private static final Color OUTLINE_COLOR = new Color(0x212121); + private static final Color SELECTION_COLOR = new Color(0x1E88E5); + private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); + + private static final Color HOVER_COLOR = new Color(0x90CAF9); + private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); + + private Point location; + + private TreeTransitionView parentView; + private ArrayList childrenViews; + + private boolean isCollapsed; + private boolean isContradictoryState; + + /** + * TreeNodeView Constructor creates a node for display + * + * @param treeNode treeElement associated with this transition + */ + public TreeNodeView(TreeNode treeNode) { + super(TreeElementType.NODE, treeNode); + this.treeElement = treeNode; + this.location = new Point(); + this.parentView = null; + this.childrenViews = new ArrayList<>(); + this.isCollapsed = false; + this.isContradictoryState = false; + this.isVisible = true; + } + + /** + * Draws the TreeNodeView + * + * @param graphics2D graphics2D used for drawing + */ + public void draw(Graphics2D graphics2D) { + if (isVisible() && treeElement != null) { + if (getTreeElement().getParent() != null + && getTreeElement().getParent().isJustified() + && getTreeElement().getParent().getRule().getRuleType() == RuleType.CONTRADICTION) { + isContradictoryState = true; + graphics2D.setColor(NODE_COLOR_CONTRADICTION); + graphics2D.drawLine( + location.x - RADIUS, location.y - RADIUS, location.x + RADIUS, location.y + RADIUS); + graphics2D.drawLine( + location.x + RADIUS, location.y - RADIUS, location.x - RADIUS, location.y + RADIUS); + } else { + isContradictoryState = false; + graphics2D.setStroke(MAIN_STROKE); + boolean isContraBranch = getTreeElement().isContradictoryBranch(); + + if (isSelected) { + graphics2D.setColor(SELECTION_COLOR); + graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_SELECTION_COLOR); + graphics2D.drawOval( + location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); + } else { + if (isHover) { + graphics2D.setColor(HOVER_COLOR); + graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_HOVER_COLOR); + graphics2D.drawOval( + location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); + } else { + graphics2D.setColor(isContraBranch ? NODE_COLOR_CONTRADICTION : NODE_COLOR_DEFAULT); + graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + } } + } } - - public boolean isContradictoryState() { - return isContradictoryState; - } - - /** - * Gets the list of children views associated with this tree node - * - * @return list of children views for this tree node - */ - public ArrayList getChildrenViews() { - return childrenViews; - } - - /** - * Sets the list of children views associated with this tree node - * - * @param childrenViews list of children views for this tree node - */ - public void setChildrenViews(ArrayList childrenViews) { - this.childrenViews = childrenViews; - } - - /** - * Adds a TreeTransitionView to the list of children views - * - * @param nodeView TreeTransitionView to add to the list of children views - */ - public void addChildrenView(TreeTransitionView nodeView) { - childrenViews.add(nodeView); - } - - /** - * Removes a TreeTransitionView from the list of children views - * - * @param nodeView TreeTransitionView to remove from the list of children views - */ - public void removeChildrenView(TreeTransitionView nodeView) { - childrenViews.remove(nodeView); - } - - /** - * Sets the parent tree transition view - * - * @param parentView parent tree transition view - */ - public void setParentView(TreeTransitionView parentView) { - this.parentView = parentView; - } - - /** - * Gets the parent tree transition view - * - * @return parent tree transition view - */ - public TreeTransitionView getParentView() { - return parentView; - } - - /** - * Gets the tree node associated with this view - * - * @return tree node - */ - public TreeNode getTreeElement() { - return (TreeNode) treeElement; - } - - /** - * Gets the location of the tree node - * - * @return location of the tree node - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the tree node - * - * @param location location of the tree node - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Gets the x location of the tree node - * - * @return x location - */ - public int getX() { - return location.x; - } - - /** - * Sets the x location of the tree node - * - * @param x x location - */ - public void setX(int x) { - location.x = x; - } - - /** - * Gets the y location of the tree node - * - * @return y location - */ - public int getY() { - return location.y; - } - - /** - * Sets the y location of the tree node - * - * @param y y location - */ - public void setY(int y) { - location.y = y; - } - - /** - * Gets the radius of the tree node - * - * @return radius - */ - public int getRadius() { - return RADIUS; - } - - @Override - public Rectangle getBounds() { - return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); - } - - @Override - public Rectangle2D getBounds2D() { - return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); - } - - @Override - public boolean contains(double x, double y) { - return Math.sqrt(Math.pow(x - location.x, 2) + Math.pow(y - location.y, 2)) <= RADIUS; - } - - @Override - public boolean contains(Point2D p) { - return contains(p.getX(), p.getY()); - } - - @Override - public boolean intersects(double x, double y, double w, double h) { - return false; - } - - @Override - public boolean intersects(Rectangle2D r) { - return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); - } - - @Override - public boolean contains(double x, double y, double w, double h) { - return false; - } - - @Override - public boolean contains(Rectangle2D r) { - return false; - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return null; - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return null; - } + } + + public boolean isContradictoryState() { + return isContradictoryState; + } + + /** + * Gets the list of children views associated with this tree node + * + * @return list of children views for this tree node + */ + public ArrayList getChildrenViews() { + return childrenViews; + } + + /** + * Sets the list of children views associated with this tree node + * + * @param childrenViews list of children views for this tree node + */ + public void setChildrenViews(ArrayList childrenViews) { + this.childrenViews = childrenViews; + } + + /** + * Adds a TreeTransitionView to the list of children views + * + * @param nodeView TreeTransitionView to add to the list of children views + */ + public void addChildrenView(TreeTransitionView nodeView) { + childrenViews.add(nodeView); + } + + /** + * Removes a TreeTransitionView from the list of children views + * + * @param nodeView TreeTransitionView to remove from the list of children views + */ + public void removeChildrenView(TreeTransitionView nodeView) { + childrenViews.remove(nodeView); + } + + /** + * Sets the parent tree transition view + * + * @param parentView parent tree transition view + */ + public void setParentView(TreeTransitionView parentView) { + this.parentView = parentView; + } + + /** + * Gets the parent tree transition view + * + * @return parent tree transition view + */ + public TreeTransitionView getParentView() { + return parentView; + } + + /** + * Gets the tree node associated with this view + * + * @return tree node + */ + public TreeNode getTreeElement() { + return (TreeNode) treeElement; + } + + /** + * Gets the location of the tree node + * + * @return location of the tree node + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the tree node + * + * @param location location of the tree node + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Gets the x location of the tree node + * + * @return x location + */ + public int getX() { + return location.x; + } + + /** + * Sets the x location of the tree node + * + * @param x x location + */ + public void setX(int x) { + location.x = x; + } + + /** + * Gets the y location of the tree node + * + * @return y location + */ + public int getY() { + return location.y; + } + + /** + * Sets the y location of the tree node + * + * @param y y location + */ + public void setY(int y) { + location.y = y; + } + + /** + * Gets the radius of the tree node + * + * @return radius + */ + public int getRadius() { + return RADIUS; + } + + @Override + public Rectangle getBounds() { + return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); + } + + @Override + public Rectangle2D getBounds2D() { + return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); + } + + @Override + public boolean contains(double x, double y) { + return Math.sqrt(Math.pow(x - location.x, 2) + Math.pow(y - location.y, 2)) <= RADIUS; + } + + @Override + public boolean contains(Point2D p) { + return contains(p.getX(), p.getY()); + } + + @Override + public boolean intersects(double x, double y, double w, double h) { + return false; + } + + @Override + public boolean intersects(Rectangle2D r) { + return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); + } + + @Override + public boolean contains(double x, double y, double w, double h) { + return false; + } + + @Override + public boolean contains(Rectangle2D r) { + return false; + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return null; + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java index b6a29f2b5..f73ab02fe 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java @@ -18,123 +18,123 @@ import javax.swing.border.TitledBorder; public class TreePanel extends JPanel { - public boolean modifiedSinceSave = false; - public boolean modifiedSinceUndoPush = false; - public int updateStatusTimer = 0; + public boolean modifiedSinceSave = false; + public boolean modifiedSinceUndoPush = false; + public int updateStatusTimer = 0; - private JPanel main; - private TreeView treeView; - private TreeToolbarPanel toolbar; - // private LegupUI legupUI; + private JPanel main; + private TreeView treeView; + private TreeToolbarPanel toolbar; + // private LegupUI legupUI; - private JLabel status; + private JLabel status; - public TreePanel(/*LegupUI legupUI*/ ) { - // this.legupUI = legupUI; + public TreePanel(/*LegupUI legupUI*/ ) { + // this.legupUI = legupUI; - main = new JPanel(); + main = new JPanel(); - main.setLayout(new BorderLayout()); + main.setLayout(new BorderLayout()); - TreeController treeController = new TreeController(); - treeView = new TreeView(treeController); - treeController.setViewer(treeView); + TreeController treeController = new TreeController(); + treeView = new TreeView(treeController); + treeController.setViewer(treeView); - toolbar = new TreeToolbarPanel(this); + toolbar = new TreeToolbarPanel(this); - DynamicView dynamicTreeView = new DynamicView(treeView, DynamicViewType.PROOF_TREE); - main.add(dynamicTreeView, BorderLayout.CENTER); - dynamicTreeView.add(toolbar, BorderLayout.WEST); + DynamicView dynamicTreeView = new DynamicView(treeView, DynamicViewType.PROOF_TREE); + main.add(dynamicTreeView, BorderLayout.CENTER); + dynamicTreeView.add(toolbar, BorderLayout.WEST); - status = new JLabel(); - status.setPreferredSize(new Dimension(150, 15)); - dynamicTreeView.getZoomWrapper().add(status, BorderLayout.CENTER); + status = new JLabel(); + status.setPreferredSize(new Dimension(150, 15)); + dynamicTreeView.getZoomWrapper().add(status, BorderLayout.CENTER); - TitledBorder title = BorderFactory.createTitledBorder("Proof Tree"); - title.setTitleJustification(TitledBorder.CENTER); - main.setBorder(title); + TitledBorder title = BorderFactory.createTitledBorder("Proof Tree"); + title.setTitleJustification(TitledBorder.CENTER); + main.setBorder(title); - setLayout(new BorderLayout()); - add(main); + setLayout(new BorderLayout()); + add(main); - updateStatusTimer = 0; - } - - public void repaintTreeView(Tree tree) { - treeView.updateTreeView(tree); - } + updateStatusTimer = 0; + } - public void boardDataChanged(Board board) { - modifiedSinceSave = true; - modifiedSinceUndoPush = true; - updateStatus(); - // colorTransitions(); - } + public void repaintTreeView(Tree tree) { + treeView.updateTreeView(tree); + } - public void updateStatus() { - updateStatusTimer = ((updateStatusTimer - 1) > 0) ? (updateStatusTimer - 1) : 0; - if (updateStatusTimer > 0) { - return; - } - this.status.setText(""); - } + public void boardDataChanged(Board board) { + modifiedSinceSave = true; + modifiedSinceUndoPush = true; + updateStatus(); + // colorTransitions(); + } - public void updateStatus(String statusString) { - status.setForeground(Color.BLACK); - status.setFont(MaterialFonts.REGULAR); - status.setText(statusString); + public void updateStatus() { + updateStatusTimer = ((updateStatusTimer - 1) > 0) ? (updateStatusTimer - 1) : 0; + if (updateStatusTimer > 0) { + return; } - - public void updateError(String error) { - status.setForeground(Color.RED); - status.setFont(MaterialFonts.ITALIC); - status.setText(error); - } - - public TreeView getTreeView() { - return treeView; - } - - public void add() { - TreeViewSelection selection = treeView.getSelection(); - - AddTreeElementCommand add = new AddTreeElementCommand(selection); - if (add.canExecute()) { - add.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(add); - } else { - updateError(add.getError()); - } + this.status.setText(""); + } + + public void updateStatus(String statusString) { + status.setForeground(Color.BLACK); + status.setFont(MaterialFonts.REGULAR); + status.setText(statusString); + } + + public void updateError(String error) { + status.setForeground(Color.RED); + status.setFont(MaterialFonts.ITALIC); + status.setText(error); + } + + public TreeView getTreeView() { + return treeView; + } + + public void add() { + TreeViewSelection selection = treeView.getSelection(); + + AddTreeElementCommand add = new AddTreeElementCommand(selection); + if (add.canExecute()) { + add.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(add); + } else { + updateError(add.getError()); } + } - public void delete() { - TreeViewSelection selection = treeView.getSelection(); + public void delete() { + TreeViewSelection selection = treeView.getSelection(); - DeleteTreeElementCommand del = new DeleteTreeElementCommand(selection); - if (del.canExecute()) { - del.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(del); - } else { - updateError(del.getError()); - } + DeleteTreeElementCommand del = new DeleteTreeElementCommand(selection); + if (del.canExecute()) { + del.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(del); + } else { + updateError(del.getError()); } + } - public void merge() { - TreeViewSelection selection = treeView.getSelection(); + public void merge() { + TreeViewSelection selection = treeView.getSelection(); - ICommand merge = new MergeCommand(selection); - if (merge.canExecute()) { - merge.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(merge); - } else { - updateError(merge.getError()); - } + ICommand merge = new MergeCommand(selection); + if (merge.canExecute()) { + merge.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(merge); + } else { + updateError(merge.getError()); } + } - public void collapse() { - TreeViewSelection selection = treeView.getSelection(); - for (TreeElementView view : selection.getSelectedViews()) { - view.setCollapsed(!view.isCollapsed()); - } + public void collapse() { + TreeViewSelection selection = treeView.getSelection(); + for (TreeElementView view : selection.getSelectedViews()) { + view.setCollapsed(!view.isCollapsed()); } + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java index 002092155..45bf518b2 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java @@ -5,18 +5,18 @@ public class TreeToolBarButton extends JButton { - private TreeToolBarName name; - private final Dimension MINIMUM_DIMENSION = new Dimension(60, 60); + private TreeToolBarName name; + private final Dimension MINIMUM_DIMENSION = new Dimension(60, 60); - public TreeToolBarButton(ImageIcon imageIcon, TreeToolBarName name) { - super(imageIcon); - this.name = name; - this.setSize(MINIMUM_DIMENSION.width, MINIMUM_DIMENSION.height); - this.setMinimumSize(this.MINIMUM_DIMENSION); - this.setFocusPainted(false); - } + public TreeToolBarButton(ImageIcon imageIcon, TreeToolBarName name) { + super(imageIcon); + this.name = name; + this.setSize(MINIMUM_DIMENSION.width, MINIMUM_DIMENSION.height); + this.setMinimumSize(this.MINIMUM_DIMENSION); + this.setFocusPainted(false); + } - public TreeToolBarName getToolBarName() { - return name; - } + public TreeToolBarName getToolBarName() { + return name; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java index c805021be..d1a009b7e 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java @@ -1,8 +1,8 @@ package edu.rpi.legup.ui.proofeditorui.treeview; public enum TreeToolBarName { - ADD_CHILD, - DEL_CHILD, - MERGE, - COLLAPSE + ADD_CHILD, + DEL_CHILD, + MERGE, + COLLAPSE } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java index 8f3ebfc23..3923de25b 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java @@ -4,58 +4,50 @@ import javax.swing.*; public class TreeToolbarPanel extends JPanel { - private TreePanel treePanel; - private TreeToolBarButton addChild, delChild, merge, collapse; - - /** - * TreeToolbarPanel Constructor - creates the tree tool mBar panel - * - * @param treePanel treePanel input - */ - public TreeToolbarPanel(TreePanel treePanel) { - this.treePanel = treePanel; - this.setLayout(new GridLayout(4, 1, 0, 2)); - - addChild = - new TreeToolBarButton( - new ImageIcon( - ClassLoader.getSystemResource( - "edu/rpi/legup/images/Legup/AddChild.png")), - TreeToolBarName.ADD_CHILD); - delChild = - new TreeToolBarButton( - new ImageIcon( - ClassLoader.getSystemResource( - "edu/rpi/legup/images/Legup/DelChild.png")), - TreeToolBarName.DEL_CHILD); - merge = - new TreeToolBarButton( - new ImageIcon( - ClassLoader.getSystemResource( - "edu/rpi/legup/images/Legup/Merge.png")), - TreeToolBarName.MERGE); - collapse = - new TreeToolBarButton( - new ImageIcon( - ClassLoader.getSystemResource( - "edu/rpi/legup/images/Legup/Collapse.png")), - TreeToolBarName.COLLAPSE); - - add(addChild); - addChild.addActionListener(a -> treePanel.add()); - addChild.setToolTipText("Add tree element"); - - add(delChild); - delChild.addActionListener(a -> treePanel.delete()); - delChild.setToolTipText("Remove selected tree elements"); - - add(merge); - merge.addActionListener(a -> treePanel.merge()); - merge.setToolTipText("Merge selected tree nodes"); - - add(collapse); - collapse.addActionListener(a -> treePanel.collapse()); - collapse.setToolTipText("Collapse nodes"); - collapse.setEnabled(false); - } + private TreePanel treePanel; + private TreeToolBarButton addChild, delChild, merge, collapse; + + /** + * TreeToolbarPanel Constructor - creates the tree tool mBar panel + * + * @param treePanel treePanel input + */ + public TreeToolbarPanel(TreePanel treePanel) { + this.treePanel = treePanel; + this.setLayout(new GridLayout(4, 1, 0, 2)); + + addChild = + new TreeToolBarButton( + new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/AddChild.png")), + TreeToolBarName.ADD_CHILD); + delChild = + new TreeToolBarButton( + new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/DelChild.png")), + TreeToolBarName.DEL_CHILD); + merge = + new TreeToolBarButton( + new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Merge.png")), + TreeToolBarName.MERGE); + collapse = + new TreeToolBarButton( + new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Collapse.png")), + TreeToolBarName.COLLAPSE); + + add(addChild); + addChild.addActionListener(a -> treePanel.add()); + addChild.setToolTipText("Add tree element"); + + add(delChild); + delChild.addActionListener(a -> treePanel.delete()); + delChild.setToolTipText("Remove selected tree elements"); + + add(merge); + merge.addActionListener(a -> treePanel.merge()); + merge.setToolTipText("Merge selected tree nodes"); + + add(collapse); + collapse.addActionListener(a -> treePanel.collapse()); + collapse.setToolTipText("Collapse nodes"); + collapse.setEnabled(false); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java index b022ac596..652514be6 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java @@ -11,344 +11,344 @@ import java.util.List; public class TreeTransitionView extends TreeElementView { - static final int RADIUS = 25; - static final int DIAMETER = 2 * RADIUS; - static final int GAP = 5; - - private static final Stroke MAIN_STROKE = new BasicStroke(3); - private static final Stroke SELECTION_STROKE = new BasicStroke(2); - - private static final Color OUTLINE_COLOR = Color.BLACK; - private static final Color CORRECT_COLOR = Color.GREEN; - private static final Color INCORRECT_COLOR = Color.RED; - private static final Color DEFAULT_COLOR = Color.GRAY; - private static final Color X_COLOR = Color.RED; - - private static final Color CORRECT_COLOR_COLORBLIND = new Color(0, 0, 255); - private static final Color INCORRECT_COLOR_COLORBLIND = new Color(255, 0, 0); - - private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); - - private static final Color HOVER_COLOR = new Color(0x90CAF9); - private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); - - private TreeNodeView childView; - private ArrayList parentViews; - private Polygon arrowhead; - - private List lineStartPoints; - private Point lineEndPoint; - - private Point endPoint; - - /** - * TreeTransitionView Constructor creates a transition arrow for display - * - * @param transition tree transition associated with this view - */ - public TreeTransitionView(TreeTransition transition) { - super(TreeElementType.TRANSITION, transition); - this.parentViews = new ArrayList<>(); - this.isCollapsed = false; - this.endPoint = new Point(); - this.lineStartPoints = new ArrayList<>(); - this.lineEndPoint = new Point(); + static final int RADIUS = 25; + static final int DIAMETER = 2 * RADIUS; + static final int GAP = 5; + + private static final Stroke MAIN_STROKE = new BasicStroke(3); + private static final Stroke SELECTION_STROKE = new BasicStroke(2); + + private static final Color OUTLINE_COLOR = Color.BLACK; + private static final Color CORRECT_COLOR = Color.GREEN; + private static final Color INCORRECT_COLOR = Color.RED; + private static final Color DEFAULT_COLOR = Color.GRAY; + private static final Color X_COLOR = Color.RED; + + private static final Color CORRECT_COLOR_COLORBLIND = new Color(0, 0, 255); + private static final Color INCORRECT_COLOR_COLORBLIND = new Color(255, 0, 0); + + private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); + + private static final Color HOVER_COLOR = new Color(0x90CAF9); + private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); + + private TreeNodeView childView; + private ArrayList parentViews; + private Polygon arrowhead; + + private List lineStartPoints; + private Point lineEndPoint; + + private Point endPoint; + + /** + * TreeTransitionView Constructor creates a transition arrow for display + * + * @param transition tree transition associated with this view + */ + public TreeTransitionView(TreeTransition transition) { + super(TreeElementType.TRANSITION, transition); + this.parentViews = new ArrayList<>(); + this.isCollapsed = false; + this.endPoint = new Point(); + this.lineStartPoints = new ArrayList<>(); + this.lineEndPoint = new Point(); + } + + /** + * TreeTransitionView Constructor creates a transition arrow for display + * + * @param transition tree transition associated with this view + * @param parentView TreeNodeView of the parent associated with this transition + */ + public TreeTransitionView(TreeTransition transition, TreeNodeView parentView) { + this(transition); + this.parentViews.add(parentView); + this.lineStartPoints.add(new Point()); + } + + /** + * Draws the TreeTransitionView + * + * @param graphics2D graphics2D used for drawing + */ + public void draw(Graphics2D graphics2D) { + arrowhead = createTransitionTriangle(RADIUS); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.setStroke(MAIN_STROKE); + + for (Point lineStartPoint : lineStartPoints) { + CubicCurve2D c = new CubicCurve2D.Double(); + double ctrlx1 = lineEndPoint.x - 25; + double ctrly1 = lineStartPoint.y; + double ctrlx2 = lineEndPoint.x - 25; + double ctrly2 = lineEndPoint.y; + + c.setCurve( + lineStartPoint.x, + lineStartPoint.y, + ctrlx1, + ctrly1, + ctrlx2, + ctrly2, + lineEndPoint.x, + lineEndPoint.y); + graphics2D.draw(c); } - /** - * TreeTransitionView Constructor creates a transition arrow for display - * - * @param transition tree transition associated with this view - * @param parentView TreeNodeView of the parent associated with this transition - */ - public TreeTransitionView(TreeTransition transition, TreeNodeView parentView) { - this(transition); - this.parentViews.add(parentView); - this.lineStartPoints.add(new Point()); - } - - /** - * Draws the TreeTransitionView - * - * @param graphics2D graphics2D used for drawing - */ - public void draw(Graphics2D graphics2D) { - arrowhead = createTransitionTriangle(RADIUS); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.setStroke(MAIN_STROKE); - - for (Point lineStartPoint : lineStartPoints) { - CubicCurve2D c = new CubicCurve2D.Double(); - double ctrlx1 = lineEndPoint.x - 25; - double ctrly1 = lineStartPoint.y; - double ctrlx2 = lineEndPoint.x - 25; - double ctrly2 = lineEndPoint.y; - - c.setCurve( - lineStartPoint.x, - lineStartPoint.y, - ctrlx1, - ctrly1, - ctrlx2, - ctrly2, - lineEndPoint.x, - lineEndPoint.y); - graphics2D.draw(c); + LegupPreferences prefs = LegupPreferences.getInstance(); + boolean colorBlind = prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true"); + + if (isSelected) { + Color c = DEFAULT_COLOR; + if (getTreeElement().isJustified()) { + if (getTreeElement().isCorrect()) { + if (colorBlind) { + c = CORRECT_COLOR_COLORBLIND; + } else { + c = CORRECT_COLOR; + } + } else { + if (colorBlind) { + c = INCORRECT_COLOR_COLORBLIND; + } else { + c = INCORRECT_COLOR; + } } + } + graphics2D.setColor(c); - LegupPreferences prefs = LegupPreferences.getInstance(); - boolean colorBlind = prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true"); - - if (isSelected) { - Color c = DEFAULT_COLOR; - if (getTreeElement().isJustified()) { - if (getTreeElement().isCorrect()) { - if (colorBlind) { - c = CORRECT_COLOR_COLORBLIND; - } else { - c = CORRECT_COLOR; - } - } else { - if (colorBlind) { - c = INCORRECT_COLOR_COLORBLIND; - } else { - c = INCORRECT_COLOR; - } - } - } - graphics2D.setColor(c); - - graphics2D.fillPolygon(arrowhead); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); + graphics2D.fillPolygon(arrowhead); - Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); - selection_triangle.translate(7, 0); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_SELECTION_COLOR); - graphics2D.drawPolygon(selection_triangle); - } else { - if (isHover) { - graphics2D.setColor(HOVER_COLOR); - graphics2D.fillPolygon(arrowhead); + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); + Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); + selection_triangle.translate(7, 0); - Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); - selection_triangle.translate(7, 0); + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_SELECTION_COLOR); + graphics2D.drawPolygon(selection_triangle); + } else { + if (isHover) { + graphics2D.setColor(HOVER_COLOR); + graphics2D.fillPolygon(arrowhead); - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_HOVER_COLOR); - graphics2D.drawPolygon(selection_triangle); + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); + + Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); + selection_triangle.translate(7, 0); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_HOVER_COLOR); + graphics2D.drawPolygon(selection_triangle); + } else { + Color c = DEFAULT_COLOR; + if (getTreeElement().isJustified()) { + if (getTreeElement().isCorrect()) { + if (colorBlind) { + c = CORRECT_COLOR_COLORBLIND; } else { - Color c = DEFAULT_COLOR; - if (getTreeElement().isJustified()) { - if (getTreeElement().isCorrect()) { - if (colorBlind) { - c = CORRECT_COLOR_COLORBLIND; - } else { - c = CORRECT_COLOR; - } - } else { - if (colorBlind) { - c = INCORRECT_COLOR_COLORBLIND; - } else { - c = INCORRECT_COLOR; - } - } - } - graphics2D.setColor(c); - graphics2D.fillPolygon(arrowhead); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); + c = CORRECT_COLOR; } + } else { + if (colorBlind) { + c = INCORRECT_COLOR_COLORBLIND; + } else { + c = INCORRECT_COLOR; + } + } } - } - - /** Constructs the arrowhead shape from the start and end points */ - private Polygon createTransitionTriangle(int radius) { - double thetaArrow = Math.toRadians(30); - - int point1X = endPoint.x; - int point1Y = endPoint.y; - - int point2X = point1X - radius; - int point2Y = point1Y + (int) Math.round(radius / (2 * cos(thetaArrow))); - - int point3X = point1X - radius; - int point3Y = point1Y - (int) Math.round(radius / (2 * cos(thetaArrow))); - - lineEndPoint.x = point2X; - lineEndPoint.y = (point3Y - point2Y) / 2 + point2Y; - - Polygon tri = new Polygon(); - tri.addPoint(point1X, point1Y); - tri.addPoint(point2X, point2Y); - tri.addPoint(point3X, point3Y); - - return tri; - } - - /** - * Gets the TreeElement associated with this view - * - * @return the TreeElement associated with this view - */ - public TreeTransition getTreeElement() { - return (TreeTransition) treeElement; - } - - /** - * Gets the TreeNodeView child view - * - * @return TreeNodeView child view - */ - public TreeNodeView getChildView() { - return childView; - } - - /** - * Sets the TreeNodeView child view - * - * @param childView TreeNodeView child view - */ - public void setChildView(TreeNodeView childView) { - this.childView = childView; - } - - /** - * Gets the list of parent views associated with this tree transition view - * - * @return list of parent views for this tree transition view - */ - public ArrayList getParentViews() { - return parentViews; - } - - /** - * Sets the list of parent views associated with this tree transition view - * - * @param parentViews list of parent views for this tree transition view - */ - public void setParentViews(ArrayList parentViews) { - this.parentViews = parentViews; - this.lineStartPoints.clear(); - for (TreeNodeView parentView : this.parentViews) { - this.lineStartPoints.add(new Point()); - } - } + graphics2D.setColor(c); + graphics2D.fillPolygon(arrowhead); - /** - * Adds a TreeNodeView to the list of parent views - * - * @param nodeView TreeNodeView to add to the list of parent views - */ - public void addParentView(TreeNodeView nodeView) { - parentViews.add(nodeView); - lineStartPoints.add(new Point()); - } - - /** - * Removes a TreeNodeView from the list of parent views - * - * @param nodeView TreeNodeView to remove from the list of parent views - */ - public void removeParentView(TreeNodeView nodeView) { - int index = parentViews.indexOf(nodeView); - parentViews.remove(nodeView); - if (index != -1) { - lineStartPoints.remove(index); - } - } - - public Point getEndPoint() { - return endPoint; - } - - public void setEndPoint(Point endPoint) { - this.endPoint = endPoint; - } - - public int getEndX() { - return endPoint.x; - } - - public void setEndX(int x) { - this.endPoint.x = x; - } - - public int getEndY() { - return endPoint.y; - } - - public void setEndY(int y) { - this.endPoint.y = y; - } - - public List getLineStartPoints() { - return lineStartPoints; - } - - public void setLineStartPoints(List lineStartPoints) { - this.lineStartPoints = lineStartPoints; - } - - public Point getLineStartPoint(int index) { - return index < lineStartPoints.size() ? lineStartPoints.get(index) : null; - } - - @Override - public Rectangle getBounds() { - return arrowhead.getBounds(); - } - - @Override - public Rectangle2D getBounds2D() { - return arrowhead.getBounds2D(); - } - - @Override - public boolean contains(double x, double y) { - return arrowhead.contains(x, y); - } - - @Override - public boolean contains(Point2D p) { - return arrowhead != null && arrowhead.contains(p); - } - - @Override - public boolean intersects(double x, double y, double w, double h) { - return arrowhead.intersects(x, y, w, h); - } - - @Override - public boolean intersects(Rectangle2D r) { - return arrowhead.intersects(r); - } - - @Override - public boolean contains(double x, double y, double w, double h) { - return arrowhead.contains(x, y, w, h); - } - - @Override - public boolean contains(Rectangle2D r) { - return arrowhead.contains(r); + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); + } } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return arrowhead.getPathIterator(at); + } + + /** Constructs the arrowhead shape from the start and end points */ + private Polygon createTransitionTriangle(int radius) { + double thetaArrow = Math.toRadians(30); + + int point1X = endPoint.x; + int point1Y = endPoint.y; + + int point2X = point1X - radius; + int point2Y = point1Y + (int) Math.round(radius / (2 * cos(thetaArrow))); + + int point3X = point1X - radius; + int point3Y = point1Y - (int) Math.round(radius / (2 * cos(thetaArrow))); + + lineEndPoint.x = point2X; + lineEndPoint.y = (point3Y - point2Y) / 2 + point2Y; + + Polygon tri = new Polygon(); + tri.addPoint(point1X, point1Y); + tri.addPoint(point2X, point2Y); + tri.addPoint(point3X, point3Y); + + return tri; + } + + /** + * Gets the TreeElement associated with this view + * + * @return the TreeElement associated with this view + */ + public TreeTransition getTreeElement() { + return (TreeTransition) treeElement; + } + + /** + * Gets the TreeNodeView child view + * + * @return TreeNodeView child view + */ + public TreeNodeView getChildView() { + return childView; + } + + /** + * Sets the TreeNodeView child view + * + * @param childView TreeNodeView child view + */ + public void setChildView(TreeNodeView childView) { + this.childView = childView; + } + + /** + * Gets the list of parent views associated with this tree transition view + * + * @return list of parent views for this tree transition view + */ + public ArrayList getParentViews() { + return parentViews; + } + + /** + * Sets the list of parent views associated with this tree transition view + * + * @param parentViews list of parent views for this tree transition view + */ + public void setParentViews(ArrayList parentViews) { + this.parentViews = parentViews; + this.lineStartPoints.clear(); + for (TreeNodeView parentView : this.parentViews) { + this.lineStartPoints.add(new Point()); } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return arrowhead.getPathIterator(at, flatness); + } + + /** + * Adds a TreeNodeView to the list of parent views + * + * @param nodeView TreeNodeView to add to the list of parent views + */ + public void addParentView(TreeNodeView nodeView) { + parentViews.add(nodeView); + lineStartPoints.add(new Point()); + } + + /** + * Removes a TreeNodeView from the list of parent views + * + * @param nodeView TreeNodeView to remove from the list of parent views + */ + public void removeParentView(TreeNodeView nodeView) { + int index = parentViews.indexOf(nodeView); + parentViews.remove(nodeView); + if (index != -1) { + lineStartPoints.remove(index); } + } + + public Point getEndPoint() { + return endPoint; + } + + public void setEndPoint(Point endPoint) { + this.endPoint = endPoint; + } + + public int getEndX() { + return endPoint.x; + } + + public void setEndX(int x) { + this.endPoint.x = x; + } + + public int getEndY() { + return endPoint.y; + } + + public void setEndY(int y) { + this.endPoint.y = y; + } + + public List getLineStartPoints() { + return lineStartPoints; + } + + public void setLineStartPoints(List lineStartPoints) { + this.lineStartPoints = lineStartPoints; + } + + public Point getLineStartPoint(int index) { + return index < lineStartPoints.size() ? lineStartPoints.get(index) : null; + } + + @Override + public Rectangle getBounds() { + return arrowhead.getBounds(); + } + + @Override + public Rectangle2D getBounds2D() { + return arrowhead.getBounds2D(); + } + + @Override + public boolean contains(double x, double y) { + return arrowhead.contains(x, y); + } + + @Override + public boolean contains(Point2D p) { + return arrowhead != null && arrowhead.contains(p); + } + + @Override + public boolean intersects(double x, double y, double w, double h) { + return arrowhead.intersects(x, y, w, h); + } + + @Override + public boolean intersects(Rectangle2D r) { + return arrowhead.intersects(r); + } + + @Override + public boolean contains(double x, double y, double w, double h) { + return arrowhead.contains(x, y, w, h); + } + + @Override + public boolean contains(Rectangle2D r) { + return arrowhead.contains(r); + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return arrowhead.getPathIterator(at); + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return arrowhead.getPathIterator(at, flatness); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java index f491009b4..b46090fed 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java @@ -27,885 +27,855 @@ import org.apache.logging.log4j.Logger; public class TreeView extends ScrollView implements ITreeListener { - private static final Logger LOGGER = LogManager.getLogger(TreeView.class.getName()); - - private static final int TRANS_GAP = 5; - - private static final int NODE_GAP_WIDTH = 70; - private static final int NODE_GAP_HEIGHT = 15; - - private static final int BORDER_GAP_HEIGHT = 20; - private static final int BORDER_GAP_WIDTH = 20; - - private static final int BORDER_SPACING = 100; - - private TreeNodeView nodeHover; - - private ArrayList currentStateBoxes; - private Rectangle bounds = new Rectangle(0, 0, 0, 0); - - private Tree tree; - private TreeNodeView rootNodeView; - private Map viewMap; - private Dimension dimension; - - private TreeViewSelection selection; - - public TreeView(TreeController treeController) { - super(treeController); - currentStateBoxes = new ArrayList<>(); - setSize(dimension = new Dimension(100, 200)); - setPreferredSize(new Dimension(640, 160)); - - viewMap = new HashMap<>(); - - selection = new TreeViewSelection(); - } - - public TreeViewSelection getSelection() { - return selection; - } - - /** - * Gets the tree node puzzleElement that the mouse is hovering over - * - * @return tree node puzzleElement that the mouse is hovering over - */ - public TreeNodeView getNodeHover() { - return nodeHover; - } - - /** - * Sets the tree node puzzleElement that the mouse is hovering over - * - * @param nodeHover tree node puzzleElement the mouse is hovering over - */ - public void setNodeHover(TreeNodeView nodeHover) { - this.nodeHover = nodeHover; - } - - /** - * Gets the TreeElementView by the specified point or null if no view exists at the specified - * point - * - * @param point location to query for a view - * @return TreeElementView at the point specified, otherwise null - */ - public TreeElementView getTreeElementView(Point point) { - return getTreeElementView(point, rootNodeView); - } - - /** - * Recursively gets the TreeElementView by the specified point or null if no view exists at the - * specified point or the view specified is null - * - * @param point location to query for a view - * @param elementView view to determine if the point is contained within it - * @return TreeElementView at the point specified, otherwise null - */ - private TreeElementView getTreeElementView(Point point, TreeElementView elementView) { - if (elementView == null) { - return null; - } else { - if (elementView.contains(point) && elementView.isVisible()) { - if (elementView.getType() == NODE - && ((TreeNodeView) elementView).isContradictoryState()) { - return null; - } - return elementView; - } else { - if (elementView.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) elementView; - for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { - TreeElementView view = getTreeElementView(point, transitionView); - if (view != null) { - return view; - } - } - } else { - TreeTransitionView transitionView = (TreeTransitionView) elementView; - return getTreeElementView(point, transitionView.getChildView()); - } - } + private static final Logger LOGGER = LogManager.getLogger(TreeView.class.getName()); + + private static final int TRANS_GAP = 5; + + private static final int NODE_GAP_WIDTH = 70; + private static final int NODE_GAP_HEIGHT = 15; + + private static final int BORDER_GAP_HEIGHT = 20; + private static final int BORDER_GAP_WIDTH = 20; + + private static final int BORDER_SPACING = 100; + + private TreeNodeView nodeHover; + + private ArrayList currentStateBoxes; + private Rectangle bounds = new Rectangle(0, 0, 0, 0); + + private Tree tree; + private TreeNodeView rootNodeView; + private Map viewMap; + private Dimension dimension; + + private TreeViewSelection selection; + + public TreeView(TreeController treeController) { + super(treeController); + currentStateBoxes = new ArrayList<>(); + setSize(dimension = new Dimension(100, 200)); + setPreferredSize(new Dimension(640, 160)); + + viewMap = new HashMap<>(); + + selection = new TreeViewSelection(); + } + + public TreeViewSelection getSelection() { + return selection; + } + + /** + * Gets the tree node puzzleElement that the mouse is hovering over + * + * @return tree node puzzleElement that the mouse is hovering over + */ + public TreeNodeView getNodeHover() { + return nodeHover; + } + + /** + * Sets the tree node puzzleElement that the mouse is hovering over + * + * @param nodeHover tree node puzzleElement the mouse is hovering over + */ + public void setNodeHover(TreeNodeView nodeHover) { + this.nodeHover = nodeHover; + } + + /** + * Gets the TreeElementView by the specified point or null if no view exists at the specified + * point + * + * @param point location to query for a view + * @return TreeElementView at the point specified, otherwise null + */ + public TreeElementView getTreeElementView(Point point) { + return getTreeElementView(point, rootNodeView); + } + + /** + * Recursively gets the TreeElementView by the specified point or null if no view exists at the + * specified point or the view specified is null + * + * @param point location to query for a view + * @param elementView view to determine if the point is contained within it + * @return TreeElementView at the point specified, otherwise null + */ + private TreeElementView getTreeElementView(Point point, TreeElementView elementView) { + if (elementView == null) { + return null; + } else { + if (elementView.contains(point) && elementView.isVisible()) { + if (elementView.getType() == NODE && ((TreeNodeView) elementView).isContradictoryState()) { + return null; } - return null; - } - - public void updateTreeView(Tree tree) { - this.tree = tree; - if (selection.getSelectedViews().size() == 0) { - selection.newSelection(new TreeNodeView(tree.getRootNode())); - } - repaint(); - } - - /** - * Sets the tree associated with this TreeView - * - * @param tree tree - */ - public void setTree(Tree tree) { - this.tree = tree; - } - - public void updateTreeSize() { - if (GameBoardFacade.getInstance().getTree() == null) { - return; - } - setSize(bounds.getSize()); - } - - public void reset() { - if (bounds.x != 0 || bounds.y != 0) { - updateTreeSize(); + return elementView; + } else { + if (elementView.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) elementView; + for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { + TreeElementView view = getTreeElementView(point, transitionView); + if (view != null) { + return view; + } + } + } else { + TreeTransitionView transitionView = (TreeTransitionView) elementView; + return getTreeElementView(point, transitionView.getChildView()); } - } - - public void zoomFit() { - double fitWidth = (viewport.getWidth() - 8.0) / (getSize().width - 200); - double fitHeight = (viewport.getHeight() - 8.0) / (getSize().height - 120); - zoomTo(Math.min(fitWidth, fitHeight)); - viewport.setViewPosition(new Point(0, viewport.getHeight() / 2)); - } - - /** - * Creates a customized viewport for the scroll pane - * - * @return viewport for the scroll pane - */ - @Override - protected JViewport createViewport() { - return new JViewport() { - @Override - protected LayoutManager createLayoutManager() { - return new ViewportLayout() { - @Override - public void layoutContainer(Container parent) { - Point point = viewport.getViewPosition(); - // determine the maximum x and y view positions - int mx = getCanvas().getWidth() - viewport.getWidth(); - int my = getCanvas().getHeight() - viewport.getHeight(); - // obey edge boundaries - if (point.x < 0) { - point.x = 0; - } - if (point.x > mx) { - point.x = mx; - } - if (point.y < 0) { - point.y = 0; - } - if (point.y > my) { - point.y = my; - } - // center margins - if (mx < 0) { - point.x = 0; - } - if (my < 0) { - point.y = my / 2; - } - viewport.setViewPosition(point); - } - }; + } + } + return null; + } + + public void updateTreeView(Tree tree) { + this.tree = tree; + if (selection.getSelectedViews().size() == 0) { + selection.newSelection(new TreeNodeView(tree.getRootNode())); + } + repaint(); + } + + /** + * Sets the tree associated with this TreeView + * + * @param tree tree + */ + public void setTree(Tree tree) { + this.tree = tree; + } + + public void updateTreeSize() { + if (GameBoardFacade.getInstance().getTree() == null) { + return; + } + setSize(bounds.getSize()); + } + + public void reset() { + if (bounds.x != 0 || bounds.y != 0) { + updateTreeSize(); + } + } + + public void zoomFit() { + double fitWidth = (viewport.getWidth() - 8.0) / (getSize().width - 200); + double fitHeight = (viewport.getHeight() - 8.0) / (getSize().height - 120); + zoomTo(Math.min(fitWidth, fitHeight)); + viewport.setViewPosition(new Point(0, viewport.getHeight() / 2)); + } + + /** + * Creates a customized viewport for the scroll pane + * + * @return viewport for the scroll pane + */ + @Override + protected JViewport createViewport() { + return new JViewport() { + @Override + protected LayoutManager createLayoutManager() { + return new ViewportLayout() { + @Override + public void layoutContainer(Container parent) { + Point point = viewport.getViewPosition(); + // determine the maximum x and y view positions + int mx = getCanvas().getWidth() - viewport.getWidth(); + int my = getCanvas().getHeight() - viewport.getHeight(); + // obey edge boundaries + if (point.x < 0) { + point.x = 0; + } + if (point.x > mx) { + point.x = mx; + } + if (point.y < 0) { + point.y = 0; } + if (point.y > my) { + point.y = my; + } + // center margins + if (mx < 0) { + point.x = 0; + } + if (my < 0) { + point.y = my / 2; + } + viewport.setViewPosition(point); + } }; - } - - public void draw(Graphics2D graphics2D) { - currentStateBoxes.clear(); - Tree tree = GameBoardFacade.getInstance().getTree(); - if (tree != null) { - // setSize(bounds.getDimension()); - graphics2D.setRenderingHint( - RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics2D.setRenderingHint( - RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + } + }; + } + + public void draw(Graphics2D graphics2D) { + currentStateBoxes.clear(); + Tree tree = GameBoardFacade.getInstance().getTree(); + if (tree != null) { + // setSize(bounds.getDimension()); + graphics2D.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics2D.setRenderingHint( + RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + + drawTree(graphics2D); + + dimension.width += BORDER_SPACING; + setSize(dimension); + // graphics2D.drawRect(0,0, dimension.width, dimension.height); + + if (selection.getHover() != null) { + drawMouseOver(graphics2D); + } + } + } + + public void zoomReset() { + zoomTo(1.0); + viewport.setViewPosition(new Point(0, 0)); + } + + private void redrawTree(Graphics2D graphics2D, TreeNodeView nodeView) { + if (nodeView != null) { + nodeView.draw(graphics2D); + for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { + transitionView.draw(graphics2D); + redrawTree(graphics2D, transitionView.getChildView()); + } + } + } + + public void removeTreeElement(TreeElementView view) { + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + nodeView.getParentView().setChildView(null); + } else { + TreeTransitionView transitionView = (TreeTransitionView) view; + transitionView + .getParentViews() + .forEach((TreeNodeView n) -> n.removeChildrenView(transitionView)); + } + } + + /** + * When the edu.rpi.legup.user hovers over the transition, draws the corresponding rules image + * + * @param g the graphics to use to draw + */ + public void drawMouseOver(Graphics2D g) { + if (selection.getHover().getType() == TRANSITION + && ((TreeTransitionView) selection.getHover()).getTreeElement().isJustified()) { + TreeTransition transition = (TreeTransition) selection.getHover().treeElement; + int imgWidth = 100; + int imgHeight = 100; + + BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); + image.createGraphics().drawImage(transition.getRule().getImageIcon().getImage(), 0, 0, null); + Point mousePoint = selection.getMousePoint(); + g.drawImage(image, mousePoint.x, mousePoint.y - 50, imgWidth, imgHeight, null); + } + } + + public void resetView() { + this.tree = null; + this.rootNodeView = null; + this.selection.clearSelection(); + this.selection.clearHover(); + } + + /** + * Called when a tree puzzleElement is added to the tree + * + * @param treeElement TreeElement that was added to the tree + */ + @Override + public void onTreeElementAdded(TreeElement treeElement) { + if (treeElement.getType() == NODE) { + addTreeNode((TreeNode) treeElement); + } else { + addTreeTransition((TreeTransition) treeElement); + } + repaint(); + } + + /** + * Called when a tree puzzleElement is removed from the tree + * + * @param element TreeElement that was removed to the tree + */ + @Override + public void onTreeElementRemoved(TreeElement element) { + if (element.getType() == NODE) { + TreeNode node = (TreeNode) element; + TreeNodeView nodeView = (TreeNodeView) viewMap.get(node); + + nodeView.getParentView().setChildView(null); + removeTreeNode(node); + } else { + TreeTransition trans = (TreeTransition) element; + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + + // unlock ancestor elements if case rule deleted + Rule rule = trans.getRule(); + for (TreeNode node : trans.getParents()) { + + // only if the last case of a case rule will be deleted + if (!(rule instanceof CaseRule && node.getChildren().isEmpty())) { + continue; + } - drawTree(graphics2D); + CaseRule caseRule = (CaseRule) rule; + // set dependent elements to be modifiable by ancestors (if not dependent on others) + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + + for (PuzzleElement pelement : + caseRule.dependentElements(node.getBoard(), trans.getSelection())) { + // decrement, unlock if 0 cases depended + PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); + oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); + if (oldElement.getCasesDepended() != 0) { + continue; + } - dimension.width += BORDER_SPACING; - setSize(dimension); - // graphics2D.drawRect(0,0, dimension.width, dimension.height); + // set modifiable if started modifiable + boolean modifiable = + tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); - if (selection.getHover() != null) { - drawMouseOver(graphics2D); + // unmodifiable if already modified + TreeNode modNode = ancestor.getParent().getParents().get(0); + while (modNode.getParent() != null) { + Board modBoard = modNode.getParent().getBoard(); + if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { + modifiable = false; + break; + } + modNode = modNode.getParent().getParents().get(0); } + oldElement.setModifiable(modifiable); + } } - } + } + + transView.getParentViews().forEach(n -> n.removeChildrenView(transView)); + removeTreeTransition(trans); + } + repaint(); + } + + /** + * Called when the tree selection was changed + * + * @param selection tree selection that was changed + */ + @Override + public void onTreeSelectionChanged(TreeViewSelection selection) { + this.selection.getSelectedViews().forEach(v -> v.setSelected(false)); + selection.getSelectedViews().forEach(v -> v.setSelected(true)); + this.selection = selection; + repaint(); + } + + /** Called when the model has finished updating the tree. */ + @Override + public void onUpdateTree() { + repaint(); + } + + /** + * Gets the TreeElementView by the corresponding TreeElement associated with it + * + * @param element TreeElement of the view + * @return TreeElementView of the TreeElement associated with it + */ + public TreeElementView getElementView(TreeElement element) { + return viewMap.get(element); + } + + private void removeTreeNode(TreeNode node) { + viewMap.remove(node); + List children = node.getChildren(); + + // if child is a case rule, unlock ancestor elements + if (!children.isEmpty()) { + Rule rule = children.get(0).getRule(); + if (rule instanceof CaseRule) { + CaseRule caseRule = (CaseRule) rule; + // set dependent elements to be modifiable by ancestors (if not dependent on others) + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement pelement : + caseRule.dependentElements(node.getBoard(), children.get(0).getSelection())) { + // decrement, unlock if 0 cases depended + PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); + oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); + if (oldElement.getCasesDepended() == 0) { + continue; + } - public void zoomReset() { - zoomTo(1.0); - viewport.setViewPosition(new Point(0, 0)); - } + // set modifiable if started modifiable + boolean modifiable = + tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); - private void redrawTree(Graphics2D graphics2D, TreeNodeView nodeView) { - if (nodeView != null) { - nodeView.draw(graphics2D); - for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { - transitionView.draw(graphics2D); - redrawTree(graphics2D, transitionView.getChildView()); + // unmodifiable if already modified + TreeNode modNode = ancestor.getParent().getParents().get(0); + while (modNode.getParent() != null) { + Board modBoard = modNode.getParent().getBoard(); + if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { + modifiable = false; + break; + } + modNode = modNode.getParent().getParents().get(0); } + oldElement.setModifiable(modifiable); + } } - } - - public void removeTreeElement(TreeElementView view) { - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - nodeView.getParentView().setChildView(null); - } else { - TreeTransitionView transitionView = (TreeTransitionView) view; - transitionView - .getParentViews() - .forEach((TreeNodeView n) -> n.removeChildrenView(transitionView)); - } - } - - /** - * When the edu.rpi.legup.user hovers over the transition, draws the corresponding rules image - * - * @param g the graphics to use to draw - */ - public void drawMouseOver(Graphics2D g) { - if (selection.getHover().getType() == TRANSITION - && ((TreeTransitionView) selection.getHover()).getTreeElement().isJustified()) { - TreeTransition transition = (TreeTransition) selection.getHover().treeElement; - int imgWidth = 100; - int imgHeight = 100; - - BufferedImage image = - new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); - image.createGraphics() - .drawImage(transition.getRule().getImageIcon().getImage(), 0, 0, null); - Point mousePoint = selection.getMousePoint(); - g.drawImage(image, mousePoint.x, mousePoint.y - 50, imgWidth, imgHeight, null); + } + } + node.getChildren().forEach(t -> removeTreeTransition(t)); + } + + private void removeTreeTransition(TreeTransition trans) { + viewMap.remove(trans); + if (trans.getChildNode() != null) { + removeTreeNode(trans.getChildNode()); + } + } + + private void addTreeNode(TreeNode node) { + TreeTransition parent = node.getParent(); + + TreeNodeView nodeView = new TreeNodeView(node); + TreeTransitionView parentView = (TreeTransitionView) viewMap.get(parent); + + nodeView.setParentView(parentView); + parentView.setChildView(nodeView); + + viewMap.put(node, nodeView); + + if (!node.getChildren().isEmpty()) { + + // if adding a case rule, lock dependent ancestor elements + Rule rule = node.getChildren().get(0).getRule(); + if (rule instanceof CaseRule) { + CaseRule caseRule = (CaseRule) rule; + + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement element : + caseRule.dependentElements( + node.getBoard(), node.getChildren().get(0).getSelection())) { + // increment and lock + PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); + oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); + oldElement.setModifiable(false); + } } - } - - public void resetView() { - this.tree = null; - this.rootNodeView = null; - this.selection.clearSelection(); - this.selection.clearHover(); - } - - /** - * Called when a tree puzzleElement is added to the tree - * - * @param treeElement TreeElement that was added to the tree - */ - @Override - public void onTreeElementAdded(TreeElement treeElement) { - if (treeElement.getType() == NODE) { - addTreeNode((TreeNode) treeElement); - } else { - addTreeTransition((TreeTransition) treeElement); + } + + node.getChildren().forEach(t -> addTreeTransition(t)); + } + } + + private void addTreeTransition(TreeTransition trans) { + List parents = trans.getParents(); + + TreeTransitionView transView = new TreeTransitionView(trans); + for (TreeNode parent : parents) { + TreeNodeView parentNodeView = (TreeNodeView) viewMap.get(parent); + transView.addParentView(parentNodeView); + parentNodeView.addChildrenView(transView); + + // if transition is a new case rule, lock dependent ancestor elements + Rule rule = trans.getRule(); + if (rule instanceof CaseRule && parent.getChildren().size() == 1) { + CaseRule caseRule = (CaseRule) rule; + + List ancestors = parent.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement element : + caseRule.dependentElements(parent.getBoard(), trans.getSelection())) { + // increment and lock + PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); + oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); + oldElement.setModifiable(false); + } } - repaint(); + } } - /** - * Called when a tree puzzleElement is removed from the tree - * - * @param element TreeElement that was removed to the tree - */ - @Override - public void onTreeElementRemoved(TreeElement element) { - if (element.getType() == NODE) { - TreeNode node = (TreeNode) element; - TreeNodeView nodeView = (TreeNodeView) viewMap.get(node); - - nodeView.getParentView().setChildView(null); - removeTreeNode(node); - } else { - TreeTransition trans = (TreeTransition) element; - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - - // unlock ancestor elements if case rule deleted - Rule rule = trans.getRule(); - for (TreeNode node : trans.getParents()) { - - // only if the last case of a case rule will be deleted - if (!(rule instanceof CaseRule && node.getChildren().isEmpty())) { - continue; - } - - CaseRule caseRule = (CaseRule) rule; - // set dependent elements to be modifiable by ancestors (if not dependent on others) - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - - for (PuzzleElement pelement : - caseRule.dependentElements(node.getBoard(), trans.getSelection())) { - // decrement, unlock if 0 cases depended - PuzzleElement oldElement = - ancestor.getParent().getBoard().getPuzzleElement(pelement); - oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); - if (oldElement.getCasesDepended() != 0) { - continue; - } - - // set modifiable if started modifiable - boolean modifiable = - tree.getRootNode() - .getBoard() - .getPuzzleElement(oldElement) - .isModifiable(); - - // unmodifiable if already modified - TreeNode modNode = ancestor.getParent().getParents().get(0); - while (modNode.getParent() != null) { - Board modBoard = modNode.getParent().getBoard(); - if (modBoard.getModifiedData() - .contains(modBoard.getPuzzleElement(oldElement))) { - modifiable = false; - break; - } - modNode = modNode.getParent().getParents().get(0); - } - oldElement.setModifiable(modifiable); - } - } - } + viewMap.put(trans, transView); - transView.getParentViews().forEach(n -> n.removeChildrenView(transView)); - removeTreeTransition(trans); - } - repaint(); + if (trans.getChildNode() != null) { + addTreeNode(trans.getChildNode()); } + } - /** - * Called when the tree selection was changed - * - * @param selection tree selection that was changed - */ - @Override - public void onTreeSelectionChanged(TreeViewSelection selection) { - this.selection.getSelectedViews().forEach(v -> v.setSelected(false)); - selection.getSelectedViews().forEach(v -> v.setSelected(true)); - this.selection = selection; - repaint(); - } + /// New Draw Methods - /** Called when the model has finished updating the tree. */ - @Override - public void onUpdateTree() { - repaint(); - } + public void drawTree(Graphics2D graphics2D) { + if (tree == null) { + LOGGER.error("Unable to draw tree."); + } else { + if (rootNodeView == null) { + rootNodeView = new TreeNodeView(tree.getRootNode()); - /** - * Gets the TreeElementView by the corresponding TreeElement associated with it - * - * @param element TreeElement of the view - * @return TreeElementView of the TreeElement associated with it - */ - public TreeElementView getElementView(TreeElement element) { - return viewMap.get(element); - } + LOGGER.debug("Creating new views for tree view."); + createViews(rootNodeView); - private void removeTreeNode(TreeNode node) { - viewMap.remove(node); - List children = node.getChildren(); - - // if child is a case rule, unlock ancestor elements - if (!children.isEmpty()) { - Rule rule = children.get(0).getRule(); - if (rule instanceof CaseRule) { - CaseRule caseRule = (CaseRule) rule; - // set dependent elements to be modifiable by ancestors (if not dependent on others) - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement pelement : - caseRule.dependentElements( - node.getBoard(), children.get(0).getSelection())) { - // decrement, unlock if 0 cases depended - PuzzleElement oldElement = - ancestor.getParent().getBoard().getPuzzleElement(pelement); - oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); - if (oldElement.getCasesDepended() == 0) { - continue; - } - - // set modifiable if started modifiable - boolean modifiable = - tree.getRootNode() - .getBoard() - .getPuzzleElement(oldElement) - .isModifiable(); - - // unmodifiable if already modified - TreeNode modNode = ancestor.getParent().getParents().get(0); - while (modNode.getParent() != null) { - Board modBoard = modNode.getParent().getBoard(); - if (modBoard.getModifiedData() - .contains(modBoard.getPuzzleElement(oldElement))) { - modifiable = false; - break; - } - modNode = modNode.getParent().getParents().get(0); - } - oldElement.setModifiable(modifiable); - } - } - } - } - node.getChildren().forEach(t -> removeTreeTransition(t)); - } + selection.newSelection(rootNodeView); + } - private void removeTreeTransition(TreeTransition trans) { - viewMap.remove(trans); - if (trans.getChildNode() != null) { - removeTreeNode(trans.getChildNode()); - } - } + dimension = new Dimension(0, 0); + calcSpan(rootNodeView); + rootNodeView.setSpan(rootNodeView.getSpan() + DIAMETER + BORDER_SPACING); - private void addTreeNode(TreeNode node) { - TreeTransition parent = node.getParent(); - - TreeNodeView nodeView = new TreeNodeView(node); - TreeTransitionView parentView = (TreeTransitionView) viewMap.get(parent); - - nodeView.setParentView(parentView); - parentView.setChildView(nodeView); - - viewMap.put(node, nodeView); - - if (!node.getChildren().isEmpty()) { - - // if adding a case rule, lock dependent ancestor elements - Rule rule = node.getChildren().get(0).getRule(); - if (rule instanceof CaseRule) { - CaseRule caseRule = (CaseRule) rule; - - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement element : - caseRule.dependentElements( - node.getBoard(), node.getChildren().get(0).getSelection())) { - // increment and lock - PuzzleElement oldElement = - ancestor.getParent().getBoard().getPuzzleElement(element); - oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); - oldElement.setModifiable(false); - } - } - } + calculateViewLocations(rootNodeView, 0); + dimension.height = (int) rootNodeView.getSpan(); - node.getChildren().forEach(t -> addTreeTransition(t)); - } + redrawTree(graphics2D, rootNodeView); + LOGGER.debug("DrawTree: dimensions - " + dimension.width + "x" + dimension.height); } + } - private void addTreeTransition(TreeTransition trans) { - List parents = trans.getParents(); - - TreeTransitionView transView = new TreeTransitionView(trans); - for (TreeNode parent : parents) { - TreeNodeView parentNodeView = (TreeNodeView) viewMap.get(parent); - transView.addParentView(parentNodeView); - parentNodeView.addChildrenView(transView); - - // if transition is a new case rule, lock dependent ancestor elements - Rule rule = trans.getRule(); - if (rule instanceof CaseRule && parent.getChildren().size() == 1) { - CaseRule caseRule = (CaseRule) rule; - - List ancestors = parent.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement element : - caseRule.dependentElements(parent.getBoard(), trans.getSelection())) { - // increment and lock - PuzzleElement oldElement = - ancestor.getParent().getBoard().getPuzzleElement(element); - oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); - oldElement.setModifiable(false); - } - } - } - } + public void createViews(TreeNodeView nodeView) { + if (nodeView != null) { + viewMap.put(nodeView.getTreeElement(), nodeView); - viewMap.put(trans, transView); - - if (trans.getChildNode() != null) { - addTreeNode(trans.getChildNode()); + TreeNode node = nodeView.getTreeElement(); + for (TreeTransition trans : node.getChildren()) { + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + if (transView != null) { + nodeView.addChildrenView(transView); + transView.addParentView(nodeView); + break; } - } + transView = new TreeTransitionView(trans); - /// New Draw Methods + viewMap.put(transView.getTreeElement(), transView); - public void drawTree(Graphics2D graphics2D) { - if (tree == null) { - LOGGER.error("Unable to draw tree."); - } else { - if (rootNodeView == null) { - rootNodeView = new TreeNodeView(tree.getRootNode()); + transView.addParentView(nodeView); + nodeView.addChildrenView(transView); - LOGGER.debug("Creating new views for tree view."); - createViews(rootNodeView); + TreeNode childNode = trans.getChildNode(); + if (childNode != null) { + TreeNodeView childNodeView = new TreeNodeView(childNode); + viewMap.put(childNodeView.getTreeElement(), childNodeView); - selection.newSelection(rootNodeView); - } - - dimension = new Dimension(0, 0); - calcSpan(rootNodeView); - rootNodeView.setSpan(rootNodeView.getSpan() + DIAMETER + BORDER_SPACING); + childNodeView.setParentView(transView); + transView.setChildView(childNodeView); - calculateViewLocations(rootNodeView, 0); - dimension.height = (int) rootNodeView.getSpan(); - - redrawTree(graphics2D, rootNodeView); - LOGGER.debug("DrawTree: dimensions - " + dimension.width + "x" + dimension.height); + createViews(childNodeView); } + } } + } - public void createViews(TreeNodeView nodeView) { - if (nodeView != null) { - viewMap.put(nodeView.getTreeElement(), nodeView); + public void calculateViewLocations(TreeNodeView nodeView, int depth) { + nodeView.setDepth(depth); + int xLoc = (NODE_GAP_WIDTH + DIAMETER) * depth + DIAMETER; + nodeView.setX(xLoc); + dimension.width = Math.max(dimension.width, xLoc); - TreeNode node = nodeView.getTreeElement(); - for (TreeTransition trans : node.getChildren()) { - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - if (transView != null) { - nodeView.addChildrenView(transView); - transView.addParentView(nodeView); - break; - } - transView = new TreeTransitionView(trans); + TreeTransitionView parentTransView = nodeView.getParentView(); + int yLoc = parentTransView == null ? (int) nodeView.getSpan() / 2 : parentTransView.getEndY(); + nodeView.setY(yLoc); - viewMap.put(transView.getTreeElement(), transView); + ArrayList children = nodeView.getChildrenViews(); + switch (children.size()) { + case 0: + break; + case 1: + { + TreeTransitionView childView = children.get(0); - transView.addParentView(nodeView); - nodeView.addChildrenView(transView); + List parentsViews = childView.getParentViews(); + if (parentsViews.size() == 1) { + childView.setEndY(yLoc); - TreeNode childNode = trans.getChildNode(); - if (childNode != null) { - TreeNodeView childNodeView = new TreeNodeView(childNode); - viewMap.put(childNodeView.getTreeElement(), childNodeView); + childView.setDepth(depth); - childNodeView.setParentView(transView); - transView.setChildView(childNodeView); + Point lineStartPoint = childView.getLineStartPoint(0); + lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = yLoc; + childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - createViews(childNodeView); - } + dimension.width = Math.max(dimension.width, childView.getEndX()); + + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } + } else { + if (parentsViews.size() > 1 && parentsViews.get(parentsViews.size() - 1) == nodeView) { + int yAvg = 0; + for (int i = 0; i < parentsViews.size(); i++) { + TreeNodeView parentNodeView = parentsViews.get(i); + depth = Math.max(depth, parentNodeView.getDepth()); + yAvg += parentNodeView.getY(); + + Point lineStartPoint = childView.getLineStartPoint(i); + lineStartPoint.x = parentNodeView.getX() + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = parentNodeView.getY(); + } + yAvg /= parentsViews.size(); + childView.setEndY(yAvg); + + childView.setDepth(depth); + + childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + + dimension.width = Math.max(dimension.width, childView.getEndX()); + + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } } + } + break; } - } - - public void calculateViewLocations(TreeNodeView nodeView, int depth) { - nodeView.setDepth(depth); - int xLoc = (NODE_GAP_WIDTH + DIAMETER) * depth + DIAMETER; - nodeView.setX(xLoc); - dimension.width = Math.max(dimension.width, xLoc); - - TreeTransitionView parentTransView = nodeView.getParentView(); - int yLoc = - parentTransView == null ? (int) nodeView.getSpan() / 2 : parentTransView.getEndY(); - nodeView.setY(yLoc); - - ArrayList children = nodeView.getChildrenViews(); - switch (children.size()) { - case 0: - break; - case 1: - { - TreeTransitionView childView = children.get(0); - - List parentsViews = childView.getParentViews(); - if (parentsViews.size() == 1) { - childView.setEndY(yLoc); - - childView.setDepth(depth); - - Point lineStartPoint = childView.getLineStartPoint(0); - lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = yLoc; - childView.setEndX( - (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - - dimension.width = Math.max(dimension.width, childView.getEndX()); - - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } else { - if (parentsViews.size() > 1 - && parentsViews.get(parentsViews.size() - 1) == nodeView) { - int yAvg = 0; - for (int i = 0; i < parentsViews.size(); i++) { - TreeNodeView parentNodeView = parentsViews.get(i); - depth = Math.max(depth, parentNodeView.getDepth()); - yAvg += parentNodeView.getY(); - - Point lineStartPoint = childView.getLineStartPoint(i); - lineStartPoint.x = parentNodeView.getX() + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = parentNodeView.getY(); - } - yAvg /= parentsViews.size(); - childView.setEndY(yAvg); - - childView.setDepth(depth); - - childView.setEndX( - (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) - + RADIUS - - TRANS_GAP / 2); - - dimension.width = Math.max(dimension.width, childView.getEndX()); - - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } - } - break; - } - default: - { - int span = 0; - for (TreeTransitionView childView : children) { - span += childView.getSpan(); - } - - span = (int) ((nodeView.getSpan() - span) / 2); - for (int i = 0; i < children.size(); i++) { - TreeTransitionView childView = children.get(i); - - childView.setDepth(depth); - - Point lineStartPoint = childView.getLineStartPoint(0); - lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = yLoc; - childView.setEndX( - (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - childView.setEndY( - yLoc - - (int) (nodeView.getSpan() / 2) - + span - + (int) (childView.getSpan() / 2)); - - span += childView.getSpan(); - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } - break; - } + default: + { + int span = 0; + for (TreeTransitionView childView : children) { + span += childView.getSpan(); + } + + span = (int) ((nodeView.getSpan() - span) / 2); + for (int i = 0; i < children.size(); i++) { + TreeTransitionView childView = children.get(i); + + childView.setDepth(depth); + + Point lineStartPoint = childView.getLineStartPoint(0); + lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = yLoc; + childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + childView.setEndY( + yLoc - (int) (nodeView.getSpan() / 2) + span + (int) (childView.getSpan() / 2)); + + span += childView.getSpan(); + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } + } + break; } } + } + + public void calcSpan(TreeElementView view) { + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + TreeNode node = nodeView.getTreeElement(); + if (nodeView.getChildrenViews().size() == 0) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + if (nodeView.getChildrenViews().size() == 1) { + TreeTransitionView childView = nodeView.getChildrenViews().get(0); + calcSpan(childView); + if (childView.getParentViews().size() > 1) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + nodeView.setSpan(childView.getSpan()); + } + } else { + DisjointSets branches = node.findMergingBranches(); + List children = node.getChildren(); - public void calcSpan(TreeElementView view) { - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - TreeNode node = nodeView.getTreeElement(); - if (nodeView.getChildrenViews().size() == 0) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - if (nodeView.getChildrenViews().size() == 1) { - TreeTransitionView childView = nodeView.getChildrenViews().get(0); - calcSpan(childView); - if (childView.getParentViews().size() > 1) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - nodeView.setSpan(childView.getSpan()); - } - } else { - DisjointSets branches = node.findMergingBranches(); - List children = node.getChildren(); - - if (node == children.get(0).getParents().get(0)) { - reorderBranches(node, branches); - ArrayList newChildrenViews = new ArrayList<>(); - for (TreeTransition trans : node.getChildren()) { - newChildrenViews.add((TreeTransitionView) viewMap.get(trans)); - } - nodeView.setChildrenViews(newChildrenViews); - } - - List> mergingSets = branches.getAllSets(); - - double span = 0.0; - for (Set mergeSet : mergingSets) { - if (mergeSet.size() > 1) { - TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); - TreeTransitionView mergePointView = - (TreeTransitionView) viewMap.get(mergePoint); - double subSpan = 0.0; - for (TreeTransition branch : mergeSet) { - TreeTransitionView branchView = - (TreeTransitionView) viewMap.get(branch); - subCalcSpan(branchView, mergePointView); - subSpan += branchView.getSpan(); - } - calcSpan(mergePointView); - span += Math.max(mergePointView.getSpan(), subSpan); - } else { - TreeTransition trans = mergeSet.iterator().next(); - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - calcSpan(transView); - span += transView.getSpan(); - } - } - nodeView.setSpan(span); - } + if (node == children.get(0).getParents().get(0)) { + reorderBranches(node, branches); + ArrayList newChildrenViews = new ArrayList<>(); + for (TreeTransition trans : node.getChildren()) { + newChildrenViews.add((TreeTransitionView) viewMap.get(trans)); } - } else { - TreeTransitionView transView = (TreeTransitionView) view; - TreeNodeView nodeView = transView.getChildView(); - if (nodeView == null) { - transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + nodeView.setChildrenViews(newChildrenViews); + } + + List> mergingSets = branches.getAllSets(); + + double span = 0.0; + for (Set mergeSet : mergingSets) { + if (mergeSet.size() > 1) { + TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); + TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); + double subSpan = 0.0; + for (TreeTransition branch : mergeSet) { + TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); + subCalcSpan(branchView, mergePointView); + subSpan += branchView.getSpan(); + } + calcSpan(mergePointView); + span += Math.max(mergePointView.getSpan(), subSpan); } else { - calcSpan(nodeView); - transView.setSpan(nodeView.getSpan()); + TreeTransition trans = mergeSet.iterator().next(); + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + calcSpan(transView); + span += transView.getSpan(); } + } + nodeView.setSpan(span); } - } - - /** - * Calculates the sub span of a given sub tree rooted at the specified view and stops at the - * tree puzzleElement view specified as stop. Stop tree puzzleElement is NOT included in the - * span calculation - * - * @param view - * @param stop - */ - private void subCalcSpan(TreeElementView view, TreeElementView stop) { - // safe-guard for infinite loop - if (view == stop) { - return; - } - - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - TreeNode node = nodeView.getTreeElement(); - if (nodeView.getChildrenViews().size() == 0) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } + } else { + TreeTransitionView transView = (TreeTransitionView) view; + TreeNodeView nodeView = transView.getChildView(); + if (nodeView == null) { + transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + calcSpan(nodeView); + transView.setSpan(nodeView.getSpan()); + } + } + } + + /** + * Calculates the sub span of a given sub tree rooted at the specified view and stops at the tree + * puzzleElement view specified as stop. Stop tree puzzleElement is NOT included in the span + * calculation + * + * @param view + * @param stop + */ + private void subCalcSpan(TreeElementView view, TreeElementView stop) { + // safe-guard for infinite loop + if (view == stop) { + return; + } + + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + TreeNode node = nodeView.getTreeElement(); + if (nodeView.getChildrenViews().size() == 0) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + if (nodeView.getChildrenViews().size() == 1) { + TreeTransitionView childView = nodeView.getChildrenViews().get(0); + if (childView == stop) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + subCalcSpan(childView, stop); + if (childView.getParentViews().size() > 1) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); } else { - if (nodeView.getChildrenViews().size() == 1) { - TreeTransitionView childView = nodeView.getChildrenViews().get(0); - if (childView == stop) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - subCalcSpan(childView, stop); - if (childView.getParentViews().size() > 1) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - nodeView.setSpan(childView.getSpan()); - } - } - } else { - DisjointSets branches = node.findMergingBranches(); - List children = node.getChildren(); - - if (node == children.get(0).getParents().get(0)) { - reorderBranches(node, branches); - } - - List> mergingSets = branches.getAllSets(); - - double span = 0.0; - for (Set mergeSet : mergingSets) { - if (mergeSet.size() > 1) { - TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); - TreeTransitionView mergePointView = - (TreeTransitionView) viewMap.get(mergePoint); - double subSpan = 0.0; - for (TreeTransition branch : mergeSet) { - TreeTransitionView branchView = - (TreeTransitionView) viewMap.get(branch); - subCalcSpan(branchView, mergePointView); - subSpan += branchView.getSpan(); - } - subCalcSpan(mergePointView, stop); - span += Math.max(mergePointView.getSpan(), subSpan); - } else { - TreeTransition trans = mergeSet.iterator().next(); - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - subCalcSpan(transView, stop); - span += transView.getSpan(); - } - } - - nodeView.setSpan(span); - } + nodeView.setSpan(childView.getSpan()); } + } } else { - TreeTransitionView transView = (TreeTransitionView) view; - TreeNodeView nodeView = transView.getChildView(); - if (nodeView == null || nodeView == stop) { - transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + DisjointSets branches = node.findMergingBranches(); + List children = node.getChildren(); + + if (node == children.get(0).getParents().get(0)) { + reorderBranches(node, branches); + } + + List> mergingSets = branches.getAllSets(); + + double span = 0.0; + for (Set mergeSet : mergingSets) { + if (mergeSet.size() > 1) { + TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); + TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); + double subSpan = 0.0; + for (TreeTransition branch : mergeSet) { + TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); + subCalcSpan(branchView, mergePointView); + subSpan += branchView.getSpan(); + } + subCalcSpan(mergePointView, stop); + span += Math.max(mergePointView.getSpan(), subSpan); } else { - calcSpan(nodeView); - transView.setSpan(nodeView.getSpan()); + TreeTransition trans = mergeSet.iterator().next(); + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + subCalcSpan(transView, stop); + span += transView.getSpan(); } - } - } + } - /** - * Reorders branches such that merging branches are sequentially grouped together and - * transitions are kept in relative order in the list of child transitions of the specified node - * - * @param node root node of the branches - * @param branches DisjointSets of the child branches of the specified node which determine - * which branches merge - */ - private void reorderBranches(TreeNode node, DisjointSets branches) { - List children = node.getChildren(); - List> mergingSets = branches.getAllSets(); - - List> newOrder = new ArrayList<>(); - for (Set set : mergingSets) { - List mergeBranch = new ArrayList<>(); - newOrder.add(mergeBranch); - children.forEach( - t -> { - if (set.contains(t)) { - mergeBranch.add(t); - } - }); - mergeBranch.sort( - (TreeTransition t1, TreeTransition t2) -> - children.indexOf(t1) <= children.indexOf(t2) ? -1 : 1); + nodeView.setSpan(span); } - - newOrder.sort( - (List b1, List b2) -> { - int low1 = -1; - int low2 = -1; - for (TreeTransition t1 : b1) { - int curIndex = children.indexOf(t1); - if (low1 == -1 || curIndex < low1) { - low1 = curIndex; - } - } - for (TreeTransition t1 : b2) { - int curIndex = children.indexOf(t1); - if (low1 == -1 || curIndex < low1) { - low1 = curIndex; - } - } - return low1 < low2 ? -1 : 1; - }); - - List newChildren = new ArrayList<>(); - newOrder.forEach(l -> newChildren.addAll(l)); - node.setChildren(newChildren); - } + } + } else { + TreeTransitionView transView = (TreeTransitionView) view; + TreeNodeView nodeView = transView.getChildView(); + if (nodeView == null || nodeView == stop) { + transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + calcSpan(nodeView); + transView.setSpan(nodeView.getSpan()); + } + } + } + + /** + * Reorders branches such that merging branches are sequentially grouped together and transitions + * are kept in relative order in the list of child transitions of the specified node + * + * @param node root node of the branches + * @param branches DisjointSets of the child branches of the specified node which determine which + * branches merge + */ + private void reorderBranches(TreeNode node, DisjointSets branches) { + List children = node.getChildren(); + List> mergingSets = branches.getAllSets(); + + List> newOrder = new ArrayList<>(); + for (Set set : mergingSets) { + List mergeBranch = new ArrayList<>(); + newOrder.add(mergeBranch); + children.forEach( + t -> { + if (set.contains(t)) { + mergeBranch.add(t); + } + }); + mergeBranch.sort( + (TreeTransition t1, TreeTransition t2) -> + children.indexOf(t1) <= children.indexOf(t2) ? -1 : 1); + } + + newOrder.sort( + (List b1, List b2) -> { + int low1 = -1; + int low2 = -1; + for (TreeTransition t1 : b1) { + int curIndex = children.indexOf(t1); + if (low1 == -1 || curIndex < low1) { + low1 = curIndex; + } + } + for (TreeTransition t1 : b2) { + int curIndex = children.indexOf(t1); + if (low1 == -1 || curIndex < low1) { + low1 = curIndex; + } + } + return low1 < low2 ? -1 : 1; + }); + + List newChildren = new ArrayList<>(); + newOrder.forEach(l -> newChildren.addAll(l)); + node.setChildren(newChildren); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java index 71a65b49e..e8eddaa6c 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java @@ -5,161 +5,160 @@ import java.util.List; public class TreeViewSelection { - private ArrayList selectedViews; - private TreeElementView hover; - private Point mousePoint; - - /** TreeViewSelection Constructor creates a tree view selection */ - public TreeViewSelection() { - this.selectedViews = new ArrayList<>(); - this.hover = null; - this.mousePoint = null; + private ArrayList selectedViews; + private TreeElementView hover; + private Point mousePoint; + + /** TreeViewSelection Constructor creates a tree view selection */ + public TreeViewSelection() { + this.selectedViews = new ArrayList<>(); + this.hover = null; + this.mousePoint = null; + } + + /** + * TreeViewSelection Constructor creates a tree view selection with a selected view + * + * @param view selected view + */ + public TreeViewSelection(TreeElementView view) { + this(); + this.selectedViews.add(view); + } + + /** + * TreeViewSelection Constructor creates a tree view selection with a list of selected views + * + * @param views list of selected views + */ + public TreeViewSelection(List views) { + this(); + this.selectedViews.addAll(views); + } + + /** + * Gets the list of selected tree puzzleElement views + * + * @return list of selected tree puzzleElement views + */ + public List getSelectedViews() { + return selectedViews; + } + + /** + * Gets the first selectedViews in the list of views + * + * @return first selectedViews in the list of views + */ + public TreeElementView getFirstSelection() { + return selectedViews.size() == 0 ? null : selectedViews.get(0); + } + + /** + * Toggles a tree puzzleElement view selectedViews + * + * @param treeElementView a tree puzzleElement view to toggle + */ + public void toggleSelection(TreeElementView treeElementView) { + if (selectedViews.contains(treeElementView)) { + selectedViews.remove(treeElementView); + treeElementView.setSelected(false); + } else { + selectedViews.add(treeElementView); + treeElementView.setSelected(true); } - - /** - * TreeViewSelection Constructor creates a tree view selection with a selected view - * - * @param view selected view - */ - public TreeViewSelection(TreeElementView view) { - this(); - this.selectedViews.add(view); - } - - /** - * TreeViewSelection Constructor creates a tree view selection with a list of selected views - * - * @param views list of selected views - */ - public TreeViewSelection(List views) { - this(); - this.selectedViews.addAll(views); - } - - /** - * Gets the list of selected tree puzzleElement views - * - * @return list of selected tree puzzleElement views - */ - public List getSelectedViews() { - return selectedViews; - } - - /** - * Gets the first selectedViews in the list of views - * - * @return first selectedViews in the list of views - */ - public TreeElementView getFirstSelection() { - return selectedViews.size() == 0 ? null : selectedViews.get(0); - } - - /** - * Toggles a tree puzzleElement view selectedViews - * - * @param treeElementView a tree puzzleElement view to toggle - */ - public void toggleSelection(TreeElementView treeElementView) { - if (selectedViews.contains(treeElementView)) { - selectedViews.remove(treeElementView); - treeElementView.setSelected(false); - } else { - selectedViews.add(treeElementView); - treeElementView.setSelected(true); - } - } - - /** - * Adds a tree puzzleElement view selectedViews - * - * @param treeElementView a tree puzzleElement view to add - */ - public void addToSelection(TreeElementView treeElementView) { - if (!selectedViews.contains(treeElementView)) { - selectedViews.add(treeElementView); - treeElementView.setSelected(true); - } - } - - /** - * Creates a new selectedViews and add the specified tree puzzleElement view - * - * @param treeElementView tree puzzleElement view - */ - public void newSelection(TreeElementView treeElementView) { - clearSelection(); - selectedViews.add(treeElementView); - treeElementView.setSelected(true); - } - - /** Clears all selected views */ - public void clearSelection() { - for (TreeElementView treeElementView : selectedViews) { - treeElementView.setSelected(false); - } - selectedViews.clear(); - } - - /** - * Gets tree puzzleElement view that the mouse is hovering over or null is no such view exists - * - * @return tree puzzleElement view that the mouse is hovering over or null is no such view - * exists - */ - public TreeElementView getHover() { - return hover; - } - - /** - * Clears the previous hover and sets the specified tree puzzleElement view to the new hover - * - * @param newHovered tree puzzleElement view for the new hover - */ - public void newHover(TreeElementView newHovered) { - newHovered.setHover(true); - if (hover != null) { - hover.setHover(false); - } - hover = newHovered; - } - - /** Clears the current hover tree puzzleElement view */ - public void clearHover() { - if (hover != null) { - hover.setHover(false); - hover = null; - } + } + + /** + * Adds a tree puzzleElement view selectedViews + * + * @param treeElementView a tree puzzleElement view to add + */ + public void addToSelection(TreeElementView treeElementView) { + if (!selectedViews.contains(treeElementView)) { + selectedViews.add(treeElementView); + treeElementView.setSelected(true); } - - /** - * Gets the current mouse location relative to the tree view - * - * @return the current mouse location relative to the tree view - */ - public Point getMousePoint() { - return mousePoint; + } + + /** + * Creates a new selectedViews and add the specified tree puzzleElement view + * + * @param treeElementView tree puzzleElement view + */ + public void newSelection(TreeElementView treeElementView) { + clearSelection(); + selectedViews.add(treeElementView); + treeElementView.setSelected(true); + } + + /** Clears all selected views */ + public void clearSelection() { + for (TreeElementView treeElementView : selectedViews) { + treeElementView.setSelected(false); } - - /** - * Sets the current mouse location relative to the tree view - * - * @param point the current mouse location relative to the tree view - */ - public void setMousePoint(Point point) { - this.mousePoint = point; + selectedViews.clear(); + } + + /** + * Gets tree puzzleElement view that the mouse is hovering over or null is no such view exists + * + * @return tree puzzleElement view that the mouse is hovering over or null is no such view exists + */ + public TreeElementView getHover() { + return hover; + } + + /** + * Clears the previous hover and sets the specified tree puzzleElement view to the new hover + * + * @param newHovered tree puzzleElement view for the new hover + */ + public void newHover(TreeElementView newHovered) { + newHovered.setHover(true); + if (hover != null) { + hover.setHover(false); } - - /** - * Copies the TreeViewSelection - * - * @return a copy of this TreeViewSelection - */ - @SuppressWarnings("unchecked") - public TreeViewSelection copy() { - TreeViewSelection cpy = new TreeViewSelection(); - cpy.selectedViews = (ArrayList) selectedViews.clone(); - cpy.hover = hover; - cpy.mousePoint = mousePoint; - return cpy; + hover = newHovered; + } + + /** Clears the current hover tree puzzleElement view */ + public void clearHover() { + if (hover != null) { + hover.setHover(false); + hover = null; } + } + + /** + * Gets the current mouse location relative to the tree view + * + * @return the current mouse location relative to the tree view + */ + public Point getMousePoint() { + return mousePoint; + } + + /** + * Sets the current mouse location relative to the tree view + * + * @param point the current mouse location relative to the tree view + */ + public void setMousePoint(Point point) { + this.mousePoint = point; + } + + /** + * Copies the TreeViewSelection + * + * @return a copy of this TreeViewSelection + */ + @SuppressWarnings("unchecked") + public TreeViewSelection copy() { + TreeViewSelection cpy = new TreeViewSelection(); + cpy.selectedViews = (ArrayList) selectedViews.clone(); + cpy.hover = hover; + cpy.mousePoint = mousePoint; + return cpy; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java index 552d517b9..4c7098765 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java @@ -7,31 +7,31 @@ public class ElementButton extends JButton { - private Element element; - private final Border originalBorder; - - ElementButton(Element e) { - super(e.getImageIcon()); - this.element = e; - this.originalBorder = this.getBorder(); - this.setFocusPainted(false); - } - - public Element getElement() { - return element; - } - - public void setElement(Element e) { - this.element = e; - } - - public void setBorderToSelected() { - Border newBorderIn = BorderFactory.createLineBorder(new Color(20, 140, 70), 2, true); - Border newBorder = BorderFactory.createCompoundBorder(newBorderIn, this.originalBorder); - this.setBorder(newBorder); - } - - public void resetBorder() { - this.setBorder(this.originalBorder); - } + private Element element; + private final Border originalBorder; + + ElementButton(Element e) { + super(e.getImageIcon()); + this.element = e; + this.originalBorder = this.getBorder(); + this.setFocusPainted(false); + } + + public Element getElement() { + return element; + } + + public void setElement(Element e) { + this.element = e; + } + + public void setBorderToSelected() { + Border newBorderIn = BorderFactory.createLineBorder(new Color(20, 140, 70), 2, true); + Border newBorder = BorderFactory.createCompoundBorder(newBorderIn, this.originalBorder); + this.setBorder(newBorder); + } + + public void resetBorder() { + this.setBorder(this.originalBorder); + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java index e0524f84d..2a7119abb 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java @@ -8,92 +8,91 @@ import javax.swing.border.TitledBorder; public class ElementFrame extends JPanel { - private static final String checkBox = " \u2714 "; - private static final String xBox = " \u2718 "; - private static final String htmlHead = ""; - private static final String htmlTail = ""; - - private PlaceableElementPanel placeableElementPanel; - private NonPlaceableElementPanel nonPlaceableElementPanel; - private JTabbedPane tabbedPane; - private ButtonGroup buttonGroup; - - private EditorElementController controller; - - public ElementFrame(EditorElementController controller) { - this.controller = controller; - MaterialTabbedPaneUI tabOverride = - new MaterialTabbedPaneUI() { - // this prevents the tabs from moving around when you select them - @Override - protected boolean shouldRotateTabRuns(int i) { - return false; - } - }; - - this.tabbedPane = new JTabbedPane(); - tabbedPane.setUI(tabOverride); - JLabel status = new JLabel("", SwingConstants.CENTER); - this.buttonGroup = new ButtonGroup(); - - nonPlaceableElementPanel = new NonPlaceableElementPanel(this); - // nonPlaceableElementPanel.setMinimumSize(new Dimension(100,200)); - tabbedPane.addTab( - nonPlaceableElementPanel.getName(), - nonPlaceableElementPanel.getIcon(), - new JScrollPane(nonPlaceableElementPanel), - nonPlaceableElementPanel.getToolTip()); - - placeableElementPanel = new PlaceableElementPanel(this); - // placeableElementPanel.setMinimuSize(new Dimension(100,200)); - tabbedPane.addTab( - placeableElementPanel.getName(), - placeableElementPanel.getIcon(), - new JScrollPane(placeableElementPanel), - placeableElementPanel.getToolTip()); - tabbedPane.setTabPlacement(JTabbedPane.TOP); - - setLayout(new BorderLayout()); - setMinimumSize(new Dimension(250, 256)); - setPreferredSize(new Dimension(330, 256)); - - add(tabbedPane); - add(status, BorderLayout.SOUTH); - - TitledBorder title = BorderFactory.createTitledBorder("Elements"); - title.setTitleJustification(TitledBorder.CENTER); - setBorder(title); - } - - public ButtonGroup getButtonGroup() { - return buttonGroup; - } - - public void resetSize() { - int buttonWidth = - ((ElementPanel) tabbedPane.getSelectedComponent()) - .getElementButtons()[0].getWidth(); - this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); - } - - public void setElements(Puzzle puzzle) { - nonPlaceableElementPanel.setElements(puzzle.getNonPlaceableElements()); - placeableElementPanel.setElements(puzzle.getPlaceableElements()); - } - - public EditorElementController getController() { - return controller; - } - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - public NonPlaceableElementPanel getNonPlaceableElementPanel() { - return nonPlaceableElementPanel; - } - - public PlaceableElementPanel getPlaceableElementPanel() { - return placeableElementPanel; - } + private static final String checkBox = " \u2714 "; + private static final String xBox = " \u2718 "; + private static final String htmlHead = ""; + private static final String htmlTail = ""; + + private PlaceableElementPanel placeableElementPanel; + private NonPlaceableElementPanel nonPlaceableElementPanel; + private JTabbedPane tabbedPane; + private ButtonGroup buttonGroup; + + private EditorElementController controller; + + public ElementFrame(EditorElementController controller) { + this.controller = controller; + MaterialTabbedPaneUI tabOverride = + new MaterialTabbedPaneUI() { + // this prevents the tabs from moving around when you select them + @Override + protected boolean shouldRotateTabRuns(int i) { + return false; + } + }; + + this.tabbedPane = new JTabbedPane(); + tabbedPane.setUI(tabOverride); + JLabel status = new JLabel("", SwingConstants.CENTER); + this.buttonGroup = new ButtonGroup(); + + nonPlaceableElementPanel = new NonPlaceableElementPanel(this); + // nonPlaceableElementPanel.setMinimumSize(new Dimension(100,200)); + tabbedPane.addTab( + nonPlaceableElementPanel.getName(), + nonPlaceableElementPanel.getIcon(), + new JScrollPane(nonPlaceableElementPanel), + nonPlaceableElementPanel.getToolTip()); + + placeableElementPanel = new PlaceableElementPanel(this); + // placeableElementPanel.setMinimuSize(new Dimension(100,200)); + tabbedPane.addTab( + placeableElementPanel.getName(), + placeableElementPanel.getIcon(), + new JScrollPane(placeableElementPanel), + placeableElementPanel.getToolTip()); + tabbedPane.setTabPlacement(JTabbedPane.TOP); + + setLayout(new BorderLayout()); + setMinimumSize(new Dimension(250, 256)); + setPreferredSize(new Dimension(330, 256)); + + add(tabbedPane); + add(status, BorderLayout.SOUTH); + + TitledBorder title = BorderFactory.createTitledBorder("Elements"); + title.setTitleJustification(TitledBorder.CENTER); + setBorder(title); + } + + public ButtonGroup getButtonGroup() { + return buttonGroup; + } + + public void resetSize() { + int buttonWidth = + ((ElementPanel) tabbedPane.getSelectedComponent()).getElementButtons()[0].getWidth(); + this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); + } + + public void setElements(Puzzle puzzle) { + nonPlaceableElementPanel.setElements(puzzle.getNonPlaceableElements()); + placeableElementPanel.setElements(puzzle.getPlaceableElements()); + } + + public EditorElementController getController() { + return controller; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public NonPlaceableElementPanel getNonPlaceableElementPanel() { + return nonPlaceableElementPanel; + } + + public PlaceableElementPanel getPlaceableElementPanel() { + return placeableElementPanel; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java index 46198e226..725bafe3b 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java @@ -7,75 +7,74 @@ import javax.swing.*; public abstract class ElementPanel extends JPanel { - protected ImageIcon icon; - protected String name; - protected String toolTip; - protected ElementButton[] elementButtons; - protected ElementFrame elementFrame; - protected List elements; + protected ImageIcon icon; + protected String name; + protected String toolTip; + protected ElementButton[] elementButtons; + protected ElementFrame elementFrame; + protected List elements; - public ElementPanel(ElementFrame eFrame) { - this.elementFrame = eFrame; - this.elements = new ArrayList<>(); - setLayout(new WrapLayout()); - } + public ElementPanel(ElementFrame eFrame) { + this.elementFrame = eFrame; + this.elements = new ArrayList<>(); + setLayout(new WrapLayout()); + } - public void setElements(List elements) { - this.elements = elements; - clearButtons(); + public void setElements(List elements) { + this.elements = elements; + clearButtons(); - elementButtons = new ElementButton[elements.size()]; - System.out.println("adding " + elements.size() + " elements to panel"); - for (int i = 0; i < elements.size(); i++) { - Element element = elements.get(i); - elementButtons[i] = new ElementButton(element); - elementFrame.getButtonGroup().add(elementButtons[i]); - System.out.printf("added button: %d, element %s\n", i, element.getElementName()); + elementButtons = new ElementButton[elements.size()]; + System.out.println("adding " + elements.size() + " elements to panel"); + for (int i = 0; i < elements.size(); i++) { + Element element = elements.get(i); + elementButtons[i] = new ElementButton(element); + elementFrame.getButtonGroup().add(elementButtons[i]); + System.out.printf("added button: %d, element %s\n", i, element.getElementName()); - elementButtons[i].setToolTipText( - element.getElementName() + ": " + element.getDescription()); - elementButtons[i].addActionListener(elementFrame.getController()); - add(elementButtons[i]); - } - revalidate(); + elementButtons[i].setToolTipText(element.getElementName() + ": " + element.getDescription()); + elementButtons[i].addActionListener(elementFrame.getController()); + add(elementButtons[i]); } + revalidate(); + } - protected void clearButtons() { - if (elementButtons != null) { - removeAll(); - for (int x = 0; x < elementButtons.length; ++x) { - elementButtons[x].removeActionListener(elementFrame.getController()); - } - } + protected void clearButtons() { + if (elementButtons != null) { + removeAll(); + for (int x = 0; x < elementButtons.length; ++x) { + elementButtons[x].removeActionListener(elementFrame.getController()); + } } + } - public ElementButton[] getElementButtons() { - return elementButtons; - } + public ElementButton[] getElementButtons() { + return elementButtons; + } - public ImageIcon getIcon() { - return icon; - } + public ImageIcon getIcon() { + return icon; + } - public void setIcon(ImageIcon icon) { - this.icon = icon; - } + public void setIcon(ImageIcon icon) { + this.icon = icon; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public void setName(String name) { - this.name = name; - } + @Override + public void setName(String name) { + this.name = name; + } - public String getToolTip() { - return toolTip; - } + public String getToolTip() { + return toolTip; + } - public void setToolTip(String toolTip) { - this.toolTip = toolTip; - } + public void setToolTip(String toolTip) { + this.toolTip = toolTip; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java index 00b4f5379..b6d447c8f 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java @@ -3,13 +3,13 @@ import javax.swing.*; public class NonPlaceableElementPanel extends ElementPanel { - public NonPlaceableElementPanel(ElementFrame elementFrame) { - super(elementFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Non-Placeable Elements"; - this.toolTip = "Non-Placeable Elements"; - } + public NonPlaceableElementPanel(ElementFrame elementFrame) { + super(elementFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Non-Placeable Elements"; + this.toolTip = "Non-Placeable Elements"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java index 088e18f8c..2d9a09962 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java @@ -3,13 +3,13 @@ import javax.swing.*; public class PlaceableElementPanel extends ElementPanel { - public PlaceableElementPanel(ElementFrame elementFrame) { - super(elementFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Placeable Elements"; - this.toolTip = "Placeable Elements"; - } + public PlaceableElementPanel(ElementFrame elementFrame) { + super(elementFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Placeable Elements"; + this.toolTip = "Placeable Elements"; + } } diff --git a/src/main/java/edu/rpi/legup/user/Submission.java b/src/main/java/edu/rpi/legup/user/Submission.java index 42373d2ec..2fe174946 100644 --- a/src/main/java/edu/rpi/legup/user/Submission.java +++ b/src/main/java/edu/rpi/legup/user/Submission.java @@ -3,7 +3,7 @@ import edu.rpi.legup.model.gameboard.Board; public class Submission { - public Submission(Board board) {} + public Submission(Board board) {} - public void submit() {} + public void submit() {} } diff --git a/src/main/java/edu/rpi/legup/user/UsageStatistics.java b/src/main/java/edu/rpi/legup/user/UsageStatistics.java index 0bc5d1c62..80867e445 100644 --- a/src/main/java/edu/rpi/legup/user/UsageStatistics.java +++ b/src/main/java/edu/rpi/legup/user/UsageStatistics.java @@ -11,43 +11,43 @@ public class UsageStatistics { - private static final String url = "https://legup-3b4a5.firebaseio.com/databases/test.json"; + private static final String url = "https://legup-3b4a5.firebaseio.com/databases/test.json"; - public UsageStatistics() {} + public UsageStatistics() {} + + public boolean sendErrorReport() { + try { + HttpClient httpclient = new DefaultHttpClient(); + + HttpPost httppost = new HttpPost(url); + + // Request parameters and other properties. + httppost.setEntity(new StringEntity("{\"test\": \"jeff\"}")); + // List params = new ArrayList<>(2); + // params.add(new BasicNameValuePair("param-1", "12345")); + // params.add(new BasicNameValuePair("param-2", "Hello!")); + // httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + + // Execute and get the response. + HttpResponse response = httpclient.execute(httppost); + HttpEntity entity = response.getEntity(); + + if (entity != null) { + InputStream instream = entity.getContent(); - public boolean sendErrorReport() { try { - HttpClient httpclient = new DefaultHttpClient(); - - HttpPost httppost = new HttpPost(url); - - // Request parameters and other properties. - httppost.setEntity(new StringEntity("{\"test\": \"jeff\"}")); - // List params = new ArrayList<>(2); - // params.add(new BasicNameValuePair("param-1", "12345")); - // params.add(new BasicNameValuePair("param-2", "Hello!")); - // httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); - - // Execute and get the response. - HttpResponse response = httpclient.execute(httppost); - HttpEntity entity = response.getEntity(); - - if (entity != null) { - InputStream instream = entity.getContent(); - - try { - // System.err.println(new String(instream.readAllBytes())); - } finally { - instream.close(); - } - } - } catch (IOException e) { - return false; + // System.err.println(new String(instream.readAllBytes())); + } finally { + instream.close(); } - return false; + } + } catch (IOException e) { + return false; } + return false; + } - public static void main(String[] args) { - new UsageStatistics().sendErrorReport(); - } + public static void main(String[] args) { + new UsageStatistics().sendErrorReport(); + } } diff --git a/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java b/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java index 14b68ba40..c52264674 100644 --- a/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java +++ b/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java @@ -7,72 +7,66 @@ import java.util.Set; public final class ConnectedRegions { - public static List> getConnectedRegions( - int boundaryCell, int[][] cells, int width, int height) { - Set boundaryCells = new HashSet<>(); - boundaryCells.add(boundaryCell); - return getConnectedRegions(boundaryCells, cells, width, height); - } + public static List> getConnectedRegions( + int boundaryCell, int[][] cells, int width, int height) { + Set boundaryCells = new HashSet<>(); + boundaryCells.add(boundaryCell); + return getConnectedRegions(boundaryCells, cells, width, height); + } - public static List> getConnectedRegions( - Set boundaryCells, int[][] cells, int width, int height) { - boolean[][] visited = new boolean[height][width]; - List> results = new ArrayList<>(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - Set region = floodfill(boundaryCells, cells, visited, width, height, x, y); - if (region.size() > 0) { - results.add(region); - } - } + public static List> getConnectedRegions( + Set boundaryCells, int[][] cells, int width, int height) { + boolean[][] visited = new boolean[height][width]; + List> results = new ArrayList<>(); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + Set region = floodfill(boundaryCells, cells, visited, width, height, x, y); + if (region.size() > 0) { + results.add(region); } - return results; + } } + return results; + } - public static boolean regionContains(int toFind, int[][] cells, Set region) { - for (Point p : region) { - if (cells[p.y][p.x] == toFind) { - return true; - } - } - return false; + public static boolean regionContains(int toFind, int[][] cells, Set region) { + for (Point p : region) { + if (cells[p.y][p.x] == toFind) { + return true; + } } + return false; + } - public static Set getRegionAroundPoint( - Point p, int boundaryCell, int[][] cells, int width, int height) { - Set boundaryCells = new HashSet<>(); - boundaryCells.add(boundaryCell); - return getRegionAroundPoint(p, boundaryCells, cells, width, height); - } + public static Set getRegionAroundPoint( + Point p, int boundaryCell, int[][] cells, int width, int height) { + Set boundaryCells = new HashSet<>(); + boundaryCells.add(boundaryCell); + return getRegionAroundPoint(p, boundaryCells, cells, width, height); + } - public static Set getRegionAroundPoint( - Point p, Set boundaryCells, int[][] cells, int width, int height) { - return floodfill(boundaryCells, cells, new boolean[height][width], width, height, p.x, p.y); - } + public static Set getRegionAroundPoint( + Point p, Set boundaryCells, int[][] cells, int width, int height) { + return floodfill(boundaryCells, cells, new boolean[height][width], width, height, p.x, p.y); + } - private static Set floodfill( - Set boundaryCells, - int[][] cells, - boolean[][] visited, - int w, - int h, - int x, - int y) { - HashSet result = new HashSet<>(); - if ((x < 0) || (x >= w)) { - return result; - } - if ((y < 0) || (y >= h)) { - return result; - } - if (!visited[y][x] && (!boundaryCells.contains(cells[y][x]))) { - result.add(new Point(x, y)); - visited[y][x] = true; - for (int delta = -1; delta < 2; delta += 2) { - result.addAll(floodfill(boundaryCells, cells, visited, w, h, x + delta, y)); - result.addAll(floodfill(boundaryCells, cells, visited, w, h, x, y + delta)); - } - } - return result; + private static Set floodfill( + Set boundaryCells, int[][] cells, boolean[][] visited, int w, int h, int x, int y) { + HashSet result = new HashSet<>(); + if ((x < 0) || (x >= w)) { + return result; + } + if ((y < 0) || (y >= h)) { + return result; + } + if (!visited[y][x] && (!boundaryCells.contains(cells[y][x]))) { + result.add(new Point(x, y)); + visited[y][x] = true; + for (int delta = -1; delta < 2; delta += 2) { + result.addAll(floodfill(boundaryCells, cells, visited, w, h, x + delta, y)); + result.addAll(floodfill(boundaryCells, cells, visited, w, h, x, y + delta)); + } } + return result; + } } diff --git a/src/main/java/edu/rpi/legup/utility/DisjointSets.java b/src/main/java/edu/rpi/legup/utility/DisjointSets.java index f33b8993c..da2dcb408 100644 --- a/src/main/java/edu/rpi/legup/utility/DisjointSets.java +++ b/src/main/java/edu/rpi/legup/utility/DisjointSets.java @@ -3,164 +3,164 @@ import java.util.*; public class DisjointSets { - private Map parents; - private Map depths; - private Map> sets; + private Map parents; + private Map depths; + private Map> sets; - /** DisjointSets Constructor creates an empty DisjointSets */ - public DisjointSets() { - this.parents = new HashMap<>(); - this.depths = new HashMap<>(); - this.sets = new HashMap<>(); - } + /** DisjointSets Constructor creates an empty DisjointSets */ + public DisjointSets() { + this.parents = new HashMap<>(); + this.depths = new HashMap<>(); + this.sets = new HashMap<>(); + } - /** - * Creates a unique set that contains the specified puzzleElement. If the specified - * puzzleElement is null or another set already contains that puzzleElement, this method returns - * false, indicating that a set was not created - * - * @param u puzzleElement to create the set from - * @return true if the set was created, false otherwise - */ - public boolean createSet(T u) { - if (u == null || parents.containsKey(u)) { - return false; - } else { - parents.put(u, u); - depths.put(u, 0); - Set newSet = new HashSet<>(); - newSet.add(u); - sets.put(u, newSet); - return true; - } + /** + * Creates a unique set that contains the specified puzzleElement. If the specified puzzleElement + * is null or another set already contains that puzzleElement, this method returns false, + * indicating that a set was not created + * + * @param u puzzleElement to create the set from + * @return true if the set was created, false otherwise + */ + public boolean createSet(T u) { + if (u == null || parents.containsKey(u)) { + return false; + } else { + parents.put(u, u); + depths.put(u, 0); + Set newSet = new HashSet<>(); + newSet.add(u); + sets.put(u, newSet); + return true; } + } - /** - * Finds and returns the representative set puzzleElement of the set that the specified - * puzzleElement contains - * - * @param p puzzleElement of the set of which to find - * @return representative set puzzleElement or null if the specified puzzleElement is null or is - * not in the DisjointSets - */ - public T find(T p) { - if (p == null || parents.get(p) == null) { - return null; - } else { - if (p != parents.get(p)) { - parents.put(p, find(parents.get(p))); - } - } - return parents.get(p); + /** + * Finds and returns the representative set puzzleElement of the set that the specified + * puzzleElement contains + * + * @param p puzzleElement of the set of which to find + * @return representative set puzzleElement or null if the specified puzzleElement is null or is + * not in the DisjointSets + */ + public T find(T p) { + if (p == null || parents.get(p) == null) { + return null; + } else { + if (p != parents.get(p)) { + parents.put(p, find(parents.get(p))); + } } + return parents.get(p); + } - /** - * Unions two sets together. If the set are non-null and disjoint, then it returns true, false - * otherwise - * - * @param p set one - * @param q set two - * @return returns true if sets are non-null and disjoint, false otherwise - */ - public boolean union(T p, T q) { - T pid = find(p); - T qid = find(q); - if (pid == null || qid == null || pid == qid) { - return false; - } else { - if (depths.get(pid) > depths.get(qid)) { - parents.put(qid, pid); - sets.get(pid).addAll(sets.get(qid)); - sets.remove(qid); - } else { - parents.put(pid, qid); - sets.get(qid).addAll(sets.get(pid)); - sets.remove(pid); - if (depths.get(pid) == depths.get(qid)) { - depths.put(qid, depths.get(qid) + 1); - } - } - return true; + /** + * Unions two sets together. If the set are non-null and disjoint, then it returns true, false + * otherwise + * + * @param p set one + * @param q set two + * @return returns true if sets are non-null and disjoint, false otherwise + */ + public boolean union(T p, T q) { + T pid = find(p); + T qid = find(q); + if (pid == null || qid == null || pid == qid) { + return false; + } else { + if (depths.get(pid) > depths.get(qid)) { + parents.put(qid, pid); + sets.get(pid).addAll(sets.get(qid)); + sets.remove(qid); + } else { + parents.put(pid, qid); + sets.get(qid).addAll(sets.get(pid)); + sets.remove(pid); + if (depths.get(pid) == depths.get(qid)) { + depths.put(qid, depths.get(qid) + 1); } + } + return true; } + } - /** - * Unions to elements together, if either puzzleElement is not already in the DisjointSets, it - * creates a set for the puzzleElement then unions the sets together. If either puzzleElement is - * null, no action is taken. - * - * @param p puzzleElement one - * @param q puzzleElement two - */ - public void addAndUnion(T p, T q) { - if (p != null && q != null) { - T pid = find(p); - if (pid == null) { - createSet(p); - } - T qid = find(q); - if (qid == null) { - createSet(q); - } - union(p, q); - } + /** + * Unions to elements together, if either puzzleElement is not already in the DisjointSets, it + * creates a set for the puzzleElement then unions the sets together. If either puzzleElement is + * null, no action is taken. + * + * @param p puzzleElement one + * @param q puzzleElement two + */ + public void addAndUnion(T p, T q) { + if (p != null && q != null) { + T pid = find(p); + if (pid == null) { + createSet(p); + } + T qid = find(q); + if (qid == null) { + createSet(q); + } + union(p, q); } + } - /** - * Determines whether the specified puzzleElement is in the DisjointSets - * - * @param u puzzleElement to check - * @return true if the DisjointSets contains the specified puzzleElement, false otherwise - */ - public boolean contains(T u) { - return parents.containsKey(u); - } + /** + * Determines whether the specified puzzleElement is in the DisjointSets + * + * @param u puzzleElement to check + * @return true if the DisjointSets contains the specified puzzleElement, false otherwise + */ + public boolean contains(T u) { + return parents.containsKey(u); + } - /** - * Gets the set of elements that the specified puzzleElement is contained in, or null if no such - * set exists. - * - * @param p puzzleElement to get the set of - * @return the set of elements that the specified puzzleElement if contained in, or null if no - * such set exists - */ - public Set getSet(T p) { - T pid = find(p); - if (pid != null) { - return new HashSet<>(sets.get(pid)); - } else { - return null; - } + /** + * Gets the set of elements that the specified puzzleElement is contained in, or null if no such + * set exists. + * + * @param p puzzleElement to get the set of + * @return the set of elements that the specified puzzleElement if contained in, or null if no + * such set exists + */ + public Set getSet(T p) { + T pid = find(p); + if (pid != null) { + return new HashSet<>(sets.get(pid)); + } else { + return null; } + } - /** - * Gets a list of all of the sets in the DisjointSets - * - * @return list of the sets in the DisjointSets - */ - public List> getAllSets() { - ArrayList> list = new ArrayList<>(); - for (T e : sets.keySet()) { - list.add(new HashSet<>(sets.get(e))); - } - return list; + /** + * Gets a list of all of the sets in the DisjointSets + * + * @return list of the sets in the DisjointSets + */ + public List> getAllSets() { + ArrayList> list = new ArrayList<>(); + for (T e : sets.keySet()) { + list.add(new HashSet<>(sets.get(e))); } + return list; + } - /** - * Gets the number of disjoint sets - * - * @return the number of disjoint sets - */ - public int setCount() { - return sets.size(); - } + /** + * Gets the number of disjoint sets + * + * @return the number of disjoint sets + */ + public int setCount() { + return sets.size(); + } - /** - * Gets the total number of elements among all sets in the DisjointSets - * - * @return the number of elements in the DisjointSets - */ - public int size() { - return parents.size(); - } + /** + * Gets the total number of elements among all sets in the DisjointSets + * + * @return the number of elements in the DisjointSets + */ + public int size() { + return parents.size(); + } } diff --git a/src/main/java/edu/rpi/legup/utility/Entry.java b/src/main/java/edu/rpi/legup/utility/Entry.java index 0686f0dbf..9cff78750 100644 --- a/src/main/java/edu/rpi/legup/utility/Entry.java +++ b/src/main/java/edu/rpi/legup/utility/Entry.java @@ -1,53 +1,53 @@ package edu.rpi.legup.utility; public class Entry { - private K key; - private V value; + private K key; + private V value; - /** - * Entry Constructor creates a key value pair - * - * @param key key - * @param value value - */ - public Entry(K key, V value) { - this.key = key; - this.value = value; - } + /** + * Entry Constructor creates a key value pair + * + * @param key key + * @param value value + */ + public Entry(K key, V value) { + this.key = key; + this.value = value; + } - /** - * Gets the key - * - * @return key - */ - public K getKey() { - return key; - } + /** + * Gets the key + * + * @return key + */ + public K getKey() { + return key; + } - /** - * Sets the key - * - * @param key key - */ - public void setKey(K key) { - this.key = key; - } + /** + * Sets the key + * + * @param key key + */ + public void setKey(K key) { + this.key = key; + } - /** - * Gets the value - * - * @return value - */ - public V getValue() { - return value; - } + /** + * Gets the value + * + * @return value + */ + public V getValue() { + return value; + } - /** - * Set the value - * - * @param value value - */ - public void setValue(V value) { - this.value = value; - } + /** + * Set the value + * + * @param value value + */ + public void setValue(V value) { + this.value = value; + } } diff --git a/src/main/java/edu/rpi/legup/utility/LegupUtils.java b/src/main/java/edu/rpi/legup/utility/LegupUtils.java index 94f119a5e..cde415f6a 100644 --- a/src/main/java/edu/rpi/legup/utility/LegupUtils.java +++ b/src/main/java/edu/rpi/legup/utility/LegupUtils.java @@ -14,91 +14,85 @@ public class LegupUtils { - private static final Logger LOGGER = Logger.getLogger(LegupUtils.class.getName()); + private static final Logger LOGGER = Logger.getLogger(LegupUtils.class.getName()); - /** - * Scans all classes accessible from the context class loader which belong to the given package - * and subpackages. - * - * @param packageName The base package - * @return The classes - * @throws ClassNotFoundException if class is not in package - * @throws IOException if file is not found - */ - public static Class[] getClasses(String packageName) - throws ClassNotFoundException, IOException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - assert classLoader != null; - String path = packageName.replace('.', '/'); + /** + * Scans all classes accessible from the context class loader which belong to the given package + * and subpackages. + * + * @param packageName The base package + * @return The classes + * @throws ClassNotFoundException if class is not in package + * @throws IOException if file is not found + */ + public static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + assert classLoader != null; + String path = packageName.replace('.', '/'); - URL url = LegupUtils.class.getProtectionDomain().getCodeSource().getLocation(); - String jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); - if (jarPath.contains(".jar")) { - List css = findClassesZip(jarPath, path); - return css.toArray(new Class[css.size()]); - } + URL url = LegupUtils.class.getProtectionDomain().getCodeSource().getLocation(); + String jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); + if (jarPath.contains(".jar")) { + List css = findClassesZip(jarPath, path); + return css.toArray(new Class[css.size()]); + } - Enumeration resources = classLoader.getResources(path); - List dirs = new ArrayList<>(); - while (resources.hasMoreElements()) { - URL resource = resources.nextElement(); - dirs.add(new File(resource.getFile())); - } + Enumeration resources = classLoader.getResources(path); + List dirs = new ArrayList<>(); + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + dirs.add(new File(resource.getFile())); + } - ArrayList classes = new ArrayList<>(); - for (File directory : dirs) { - classes.addAll(findClasses(directory, packageName)); - } - return classes.toArray(new Class[classes.size()]); + ArrayList classes = new ArrayList<>(); + for (File directory : dirs) { + classes.addAll(findClasses(directory, packageName)); } + return classes.toArray(new Class[classes.size()]); + } - /** - * Recursive method used to find all classes in a given directory and subdirs. - * - * @param directory The base directory - * @param packageName The package name for classes found inside the base directory - * @return The classes - * @throws ClassNotFoundException - */ - private static List findClasses(File directory, String packageName) - throws ClassNotFoundException { - List classes = new ArrayList<>(); - if (!directory.exists()) { - return classes; - } - File[] files = directory.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - assert !file.getName().contains("."); - classes.addAll(findClasses(file, packageName + "." + file.getName())); - } else { - if (file.getName().endsWith(".class")) { - classes.add( - Class.forName( - packageName - + '.' - + file.getName() - .substring(0, file.getName().length() - 6))); - } - } + /** + * Recursive method used to find all classes in a given directory and subdirs. + * + * @param directory The base directory + * @param packageName The package name for classes found inside the base directory + * @return The classes + * @throws ClassNotFoundException + */ + private static List findClasses(File directory, String packageName) + throws ClassNotFoundException { + List classes = new ArrayList<>(); + if (!directory.exists()) { + return classes; + } + File[] files = directory.listFiles(); + for (File file : files) { + if (file.isDirectory()) { + assert !file.getName().contains("."); + classes.addAll(findClasses(file, packageName + "." + file.getName())); + } else { + if (file.getName().endsWith(".class")) { + classes.add( + Class.forName( + packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); } - return classes; + } } + return classes; + } - private static List findClassesZip(String path, String packageName) - throws IOException, ClassNotFoundException { - List classes = new ArrayList<>(); - ZipInputStream zip = new ZipInputStream(new FileInputStream(path)); - for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { - if (!entry.isDirectory() - && entry.getName().endsWith(".class") - && entry.getName().startsWith(packageName)) { - String className = entry.getName().replace('/', '.'); - classes.add( - Class.forName( - className.substring(0, className.length() - ".class".length()))); - } - } - return classes; + private static List findClassesZip(String path, String packageName) + throws IOException, ClassNotFoundException { + List classes = new ArrayList<>(); + ZipInputStream zip = new ZipInputStream(new FileInputStream(path)); + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + if (!entry.isDirectory() + && entry.getName().endsWith(".class") + && entry.getName().startsWith(packageName)) { + String className = entry.getName().replace('/', '.'); + classes.add(Class.forName(className.substring(0, className.length() - ".class".length()))); + } } + return classes; + } } diff --git a/src/main/java/edu/rpi/legup/utility/Logger.java b/src/main/java/edu/rpi/legup/utility/Logger.java index 67048e5b4..d423043e7 100644 --- a/src/main/java/edu/rpi/legup/utility/Logger.java +++ b/src/main/java/edu/rpi/legup/utility/Logger.java @@ -12,35 +12,33 @@ public class Logger { - private static final String LEGUP_HOME = - System.getProperty("user.home") + File.separator + ".legup" + File.separator; + private static final String LEGUP_HOME = + System.getProperty("user.home") + File.separator + ".legup" + File.separator; - public static void initLogger() { - LoggerContext context = (LoggerContext) LogManager.getContext(false); - Configuration config = context.getConfiguration(); - ConsoleAppender consoleAppender = config.getAppender("console"); - PatternLayout consolePattern = (PatternLayout) consoleAppender.getLayout(); - TimeBasedTriggeringPolicy triggeringPolicy = - TimeBasedTriggeringPolicy.newBuilder().withInterval(1).withModulate(true).build(); - PatternLayout patternLayout = - PatternLayout.newBuilder() - .withPattern(consolePattern.getConversionPattern()) - .build(); - RollingFileAppender rollingFileAppender = - RollingFileAppender.newBuilder() - .setName("fileLogger") - .withFileName(LEGUP_HOME + "legup.log") - .withFilePattern(LEGUP_HOME + "legup-%d{yyyy-MM-dd}.log.gz") - .withPolicy(triggeringPolicy) - .setLayout(patternLayout) - .setConfiguration(config) - .build(); - rollingFileAppender.start(); - config.addAppender(rollingFileAppender); - LoggerConfig rootLogger = config.getRootLogger(); - rootLogger.addAppender(config.getAppender("fileLogger"), null, null); - context.updateLoggers(); + public static void initLogger() { + LoggerContext context = (LoggerContext) LogManager.getContext(false); + Configuration config = context.getConfiguration(); + ConsoleAppender consoleAppender = config.getAppender("console"); + PatternLayout consolePattern = (PatternLayout) consoleAppender.getLayout(); + TimeBasedTriggeringPolicy triggeringPolicy = + TimeBasedTriggeringPolicy.newBuilder().withInterval(1).withModulate(true).build(); + PatternLayout patternLayout = + PatternLayout.newBuilder().withPattern(consolePattern.getConversionPattern()).build(); + RollingFileAppender rollingFileAppender = + RollingFileAppender.newBuilder() + .setName("fileLogger") + .withFileName(LEGUP_HOME + "legup.log") + .withFilePattern(LEGUP_HOME + "legup-%d{yyyy-MM-dd}.log.gz") + .withPolicy(triggeringPolicy) + .setLayout(patternLayout) + .setConfiguration(config) + .build(); + rollingFileAppender.start(); + config.addAppender(rollingFileAppender); + LoggerConfig rootLogger = config.getRootLogger(); + rootLogger.addAppender(config.getAppender("fileLogger"), null, null); + context.updateLoggers(); - System.setProperty("sun.java2d.noddraw", Boolean.TRUE.toString()); - } + System.setProperty("sun.java2d.noddraw", Boolean.TRUE.toString()); + } } diff --git a/src/test/java/legup/MockGameBoardFacade.java b/src/test/java/legup/MockGameBoardFacade.java index f4f1db938..a1505455c 100644 --- a/src/test/java/legup/MockGameBoardFacade.java +++ b/src/test/java/legup/MockGameBoardFacade.java @@ -6,37 +6,37 @@ import edu.rpi.legup.model.Puzzle; public class MockGameBoardFacade extends GameBoardFacade { - protected MockGameBoardFacade() { - super(); - Config config = null; - try { - config = new Config(); - } catch (InvalidConfigException e) { - System.exit(1); - } - setConfig(config); + protected MockGameBoardFacade() { + super(); + Config config = null; + try { + config = new Config(); + } catch (InvalidConfigException e) { + System.exit(1); } + setConfig(config); + } - /** - * Gets the singleton instance of GameBoardFacade - * - * @return single instance of GameBoardFacade - */ - public static synchronized GameBoardFacade getInstance() { - if (instance == null) { - instance = new MockGameBoardFacade(); - } - return instance; + /** + * Gets the singleton instance of GameBoardFacade + * + * @return single instance of GameBoardFacade + */ + public static synchronized GameBoardFacade getInstance() { + if (instance == null) { + instance = new MockGameBoardFacade(); } + return instance; + } - @Override - public void initializeUI() {} + @Override + public void initializeUI() {} - @Override - public void setPuzzle(Puzzle puzzle) { - this.puzzle = puzzle; - } + @Override + public void setPuzzle(Puzzle puzzle) { + this.puzzle = puzzle; + } - @Override - public void setWindowTitle(String puzzleName, String fileName) {} + @Override + public void setWindowTitle(String puzzleName, String fileName) {} } diff --git a/src/test/java/legup/TestRunner.java b/src/test/java/legup/TestRunner.java index 40cc5fa6c..c8c43bcda 100644 --- a/src/test/java/legup/TestRunner.java +++ b/src/test/java/legup/TestRunner.java @@ -11,96 +11,96 @@ /** This class runs all of the tests for the project without needing to run build scripts. */ public class TestRunner { - public static void main(String[] args) { - // Battleship Tests - Result result1 = JUnitCore.runClasses(AdjacentShipsContradictionRuleTest.class); - printTestResults(result1); - Result result2 = JUnitCore.runClasses(FinishWithShipsDirectRuleTests.class); - printTestResults(result2); + public static void main(String[] args) { + // Battleship Tests + Result result1 = JUnitCore.runClasses(AdjacentShipsContradictionRuleTest.class); + printTestResults(result1); + Result result2 = JUnitCore.runClasses(FinishWithShipsDirectRuleTests.class); + printTestResults(result2); - // Lightup Tests - Result result3 = JUnitCore.runClasses(BulbsInPathContradictionRuleTest.class); - printTestResults(result3); - Result result4 = JUnitCore.runClasses(CannotLightACellContradictionRuleTest.class); - printTestResults(result4); - Result result5 = JUnitCore.runClasses(EmptyCellinLightDirectRuleTest.class); - printTestResults(result5); - Result result6 = JUnitCore.runClasses(EmptyCornersDirectRuleTest.class); - printTestResults(result6); - Result result7 = JUnitCore.runClasses(FinishWithBulbsDirectRuleTest.class); - printTestResults(result7); - Result result8 = JUnitCore.runClasses(LightOrEmptyCaseRuleTest.class); - printTestResults(result8); - Result result9 = JUnitCore.runClasses(MustLightDirectRuleTest.class); - printTestResults(result9); - Result result10 = JUnitCore.runClasses(SatisfyNumberCaseRuleTest.class); - printTestResults(result10); - Result result11 = JUnitCore.runClasses(TooFewBulbsContradictionRuleTest.class); - printTestResults(result11); - Result result12 = JUnitCore.runClasses(TooManyBulbsContradictionRuleTest.class); - printTestResults(result12); + // Lightup Tests + Result result3 = JUnitCore.runClasses(BulbsInPathContradictionRuleTest.class); + printTestResults(result3); + Result result4 = JUnitCore.runClasses(CannotLightACellContradictionRuleTest.class); + printTestResults(result4); + Result result5 = JUnitCore.runClasses(EmptyCellinLightDirectRuleTest.class); + printTestResults(result5); + Result result6 = JUnitCore.runClasses(EmptyCornersDirectRuleTest.class); + printTestResults(result6); + Result result7 = JUnitCore.runClasses(FinishWithBulbsDirectRuleTest.class); + printTestResults(result7); + Result result8 = JUnitCore.runClasses(LightOrEmptyCaseRuleTest.class); + printTestResults(result8); + Result result9 = JUnitCore.runClasses(MustLightDirectRuleTest.class); + printTestResults(result9); + Result result10 = JUnitCore.runClasses(SatisfyNumberCaseRuleTest.class); + printTestResults(result10); + Result result11 = JUnitCore.runClasses(TooFewBulbsContradictionRuleTest.class); + printTestResults(result11); + Result result12 = JUnitCore.runClasses(TooManyBulbsContradictionRuleTest.class); + printTestResults(result12); - // nurikabe tests - Result result13 = JUnitCore.runClasses(BlackBetweenRegionsDirectRuleTest.class); - printTestResults(result13); - Result result14 = JUnitCore.runClasses(BlackBottleNeckDirectRuleTest.class); - printTestResults(result14); - Result result15 = JUnitCore.runClasses(BlackOrWhiteCaseRuleTest.class); - printTestResults(result15); - Result result16 = JUnitCore.runClasses(BlackSquareContradictionRuleTest.class); - printTestResults(result16); - Result result17 = JUnitCore.runClasses(CornerBlackDirectRuleTest.class); - printTestResults(result17); - Result result18 = JUnitCore.runClasses(FillinBlackDirectRuleTest.class); - printTestResults(result18); - Result result19 = JUnitCore.runClasses(FillinWhiteDirectRuleTest.class); - printTestResults(result19); - Result result20 = JUnitCore.runClasses(IsolateBlackContradictionRuleTest.class); - printTestResults(result20); - Result result21 = JUnitCore.runClasses(MultipleNumbersContradictionRuleTest.class); - printTestResults(result21); - Result result22 = JUnitCore.runClasses(NoNumbersContradictionRuleTest.class); - printTestResults(result22); - Result result23 = JUnitCore.runClasses(PreventBlackSquareDirectRuleTest.class); - printTestResults(result23); - Result result24 = JUnitCore.runClasses(SurroundRegionDirectRuleTest.class); - printTestResults(result24); - Result result25 = JUnitCore.runClasses(TooFewSpacesContradictionRuleTest.class); - printTestResults(result25); - Result result26 = JUnitCore.runClasses(TooManySpacesContradictionRuleTest.class); - printTestResults(result26); - Result result27 = JUnitCore.runClasses(WhiteBottleNeckDirectRuleTest.class); - printTestResults(result27); + // nurikabe tests + Result result13 = JUnitCore.runClasses(BlackBetweenRegionsDirectRuleTest.class); + printTestResults(result13); + Result result14 = JUnitCore.runClasses(BlackBottleNeckDirectRuleTest.class); + printTestResults(result14); + Result result15 = JUnitCore.runClasses(BlackOrWhiteCaseRuleTest.class); + printTestResults(result15); + Result result16 = JUnitCore.runClasses(BlackSquareContradictionRuleTest.class); + printTestResults(result16); + Result result17 = JUnitCore.runClasses(CornerBlackDirectRuleTest.class); + printTestResults(result17); + Result result18 = JUnitCore.runClasses(FillinBlackDirectRuleTest.class); + printTestResults(result18); + Result result19 = JUnitCore.runClasses(FillinWhiteDirectRuleTest.class); + printTestResults(result19); + Result result20 = JUnitCore.runClasses(IsolateBlackContradictionRuleTest.class); + printTestResults(result20); + Result result21 = JUnitCore.runClasses(MultipleNumbersContradictionRuleTest.class); + printTestResults(result21); + Result result22 = JUnitCore.runClasses(NoNumbersContradictionRuleTest.class); + printTestResults(result22); + Result result23 = JUnitCore.runClasses(PreventBlackSquareDirectRuleTest.class); + printTestResults(result23); + Result result24 = JUnitCore.runClasses(SurroundRegionDirectRuleTest.class); + printTestResults(result24); + Result result25 = JUnitCore.runClasses(TooFewSpacesContradictionRuleTest.class); + printTestResults(result25); + Result result26 = JUnitCore.runClasses(TooManySpacesContradictionRuleTest.class); + printTestResults(result26); + Result result27 = JUnitCore.runClasses(WhiteBottleNeckDirectRuleTest.class); + printTestResults(result27); - // Treetent - Result result28 = JUnitCore.runClasses(EmptyFieldDirectRuleTest.class); - printTestResults(result28); - Result result29 = JUnitCore.runClasses(FinishWithGrassDirectRuleTest.class); - printTestResults(result29); - Result result30 = JUnitCore.runClasses(FinishWithTentsDirectRuleTest.class); - printTestResults(result30); - Result result31 = JUnitCore.runClasses(LastCampingSpotDirectRuleTest.class); - printTestResults(result31); - Result result32 = JUnitCore.runClasses(NoTentForTreeContradictionRuleTest.class); - printTestResults(result32); - Result result33 = JUnitCore.runClasses(NoTreeForTentContradictionRuleTest.class); - printTestResults(result33); - Result result34 = JUnitCore.runClasses(SurroundTentWithGrassDirectRuleTest.class); - printTestResults(result34); - Result result35 = JUnitCore.runClasses(TreeForTentDirectRuleTest.class); - printTestResults(result35); - Result result36 = JUnitCore.runClasses(TentOrGrassCaseRuleTest.class); - printTestResults(result36); - } - - private static void printTestResults(Result result) { - for (Failure failure : result.getFailures()) { - System.out.println(failure.toString()); - } + // Treetent + Result result28 = JUnitCore.runClasses(EmptyFieldDirectRuleTest.class); + printTestResults(result28); + Result result29 = JUnitCore.runClasses(FinishWithGrassDirectRuleTest.class); + printTestResults(result29); + Result result30 = JUnitCore.runClasses(FinishWithTentsDirectRuleTest.class); + printTestResults(result30); + Result result31 = JUnitCore.runClasses(LastCampingSpotDirectRuleTest.class); + printTestResults(result31); + Result result32 = JUnitCore.runClasses(NoTentForTreeContradictionRuleTest.class); + printTestResults(result32); + Result result33 = JUnitCore.runClasses(NoTreeForTentContradictionRuleTest.class); + printTestResults(result33); + Result result34 = JUnitCore.runClasses(SurroundTentWithGrassDirectRuleTest.class); + printTestResults(result34); + Result result35 = JUnitCore.runClasses(TreeForTentDirectRuleTest.class); + printTestResults(result35); + Result result36 = JUnitCore.runClasses(TentOrGrassCaseRuleTest.class); + printTestResults(result36); + } - System.out.println("Tests run: " + result.getRunCount()); - System.out.println("Tests failed: " + result.getFailureCount()); - System.out.println("All tests passed: " + result.wasSuccessful()); - System.out.println(); + private static void printTestResults(Result result) { + for (Failure failure : result.getFailures()) { + System.out.println(failure.toString()); } + + System.out.println("Tests run: " + result.getRunCount()); + System.out.println("Tests failed: " + result.getFailureCount()); + System.out.println("All tests passed: " + result.wasSuccessful()); + System.out.println(); + } } diff --git a/src/test/java/legup/TestUtilities.java b/src/test/java/legup/TestUtilities.java index 83ce773d4..a5349197c 100644 --- a/src/test/java/legup/TestUtilities.java +++ b/src/test/java/legup/TestUtilities.java @@ -8,13 +8,13 @@ import edu.rpi.legup.save.InvalidFileFormatException; public final class TestUtilities { - public static void importTestBoard(String fileName, Puzzle puzzle) - throws InvalidFileFormatException { - puzzle.importPuzzle(ClassLoader.getSystemResourceAsStream(fileName)); - Tree tree = puzzle.getTree(); - TreeNode rootNode = tree.getRootNode(); - Board board = rootNode.getBoard().copy(); - TreeTransition transition = new TreeTransition(rootNode, board); - rootNode.getChildren().add(transition); - } + public static void importTestBoard(String fileName, Puzzle puzzle) + throws InvalidFileFormatException { + puzzle.importPuzzle(ClassLoader.getSystemResourceAsStream(fileName)); + Tree tree = puzzle.getTree(); + TreeNode rootNode = tree.getRootNode(); + Board board = rootNode.getBoard().copy(); + TreeTransition transition = new TreeTransition(rootNode, board); + rootNode.getChildren().add(transition); + } } diff --git a/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java b/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java index 08b6633db..350b6b0e7 100644 --- a/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java +++ b/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java @@ -14,60 +14,57 @@ import org.junit.Test; public class AdjacentShipsContradictionRuleTest { - private static final AdjacentShipsContradictionRule RULE = new AdjacentShipsContradictionRule(); + private static final AdjacentShipsContradictionRule RULE = new AdjacentShipsContradictionRule(); - private static Battleship battleship; + private static Battleship battleship; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - battleship = new Battleship(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + battleship = new Battleship(); + } - @Test - public void OrthogonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" - + "/AdjacentShipsContradictionRule/OrthogonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void OrthogonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/AdjacentShipsContradictionRule/OrthogonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - } + Assert.assertNotNull(RULE.checkContradiction(board)); + } - @Test - public void InvalidOrthogonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" - + "/AdjacentShipsContradictionRule" - + "/InvalidOrthogonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void InvalidOrthogonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/AdjacentShipsContradictionRule" + + "/InvalidOrthogonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - } + Assert.assertNull(RULE.checkContradiction(board)); + } - @Test - public void DiagonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" - + "/AdjacentShipsContradictionRule" - + "/DiagonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void DiagonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/AdjacentShipsContradictionRule" + "/DiagonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - } + Assert.assertNull(RULE.checkContradiction(board)); + } } diff --git a/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java b/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java index 1548445fd..a0cf6dc61 100644 --- a/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java +++ b/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java @@ -10,62 +10,61 @@ import org.junit.*; public class FinishWithShipsDirectRuleTests { - private static final FinishWithShipsDirectRule RULE = new FinishWithShipsDirectRule(); + private static final FinishWithShipsDirectRule RULE = new FinishWithShipsDirectRule(); - private static Battleship battleship; + private static Battleship battleship; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - battleship = new Battleship(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + battleship = new Battleship(); + } - // @Test - public void HorizontalValidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalValidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void HorizontalValidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalValidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } + Assert.assertNull(RULE.checkRule(transition)); + } - // @Test - public void VerticaValidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalValidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void VerticaValidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalValidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } + Assert.assertNull(RULE.checkRule(transition)); + } - // @Test - public void HorizontalInvalidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" - + "/FinishWithShipsBasicRuleTests/HorizontalInvalidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void HorizontalInvalidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalInvalidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - } + Assert.assertNotNull(RULE.checkRule(transition)); + } - // @Test - public void VerticalInvalidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalInvalidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void VerticalInvalidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalInvalidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - } + Assert.assertNotNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java index 316a86f43..b2357b157 100644 --- a/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java @@ -12,82 +12,78 @@ import org.junit.Test; public class BulbsInPathContradictionRuleTest { - private static final BulbsInPathContradictionRule RULE = new BulbsInPathContradictionRule(); - private static LightUp lightUp; + private static final BulbsInPathContradictionRule RULE = new BulbsInPathContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void BulbsInPathContradictionRule_LightInHorizontalPath() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInHorizontalPath", - lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_LightInHorizontalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInHorizontalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + } - @Test - public void BulbsInPathContradictionRule_LightInVerticalPath() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInVerticalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_LightInVerticalPath() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInVerticalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } - @Test - public void BulbsInPathContradictionRule_BlockInVerticalPath() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInVerticalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_BlockInVerticalPath() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInVerticalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } - @Test - public void BulbsInPathContradictionRule_BlockInHorizontalPath() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInHorizontalPath", - lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_BlockInHorizontalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInHorizontalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } } diff --git a/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java index 6db42d39b..84dc80c83 100644 --- a/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java @@ -12,83 +12,83 @@ import org.junit.Test; public class CannotLightACellContradictionRuleTest { - private static final CannotLightACellContradictionRule RULE = - new CannotLightACellContradictionRule(); - private static LightUp lightUp; + private static final CannotLightACellContradictionRule RULE = + new CannotLightACellContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - // extensive full testing of null and non-null in a 5x5 board - public void FullLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/FullLightTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // extensive full testing of null and non-null in a 5x5 board + public void FullLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/FullLightTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm it is impossible to light up these squares - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); + // confirm it is impossible to light up these squares + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); - // confirm these are not required to be lit because they are already lit or unable to be - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); - } + // confirm these are not required to be lit because they are already lit or unable to be + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); + } - @Test - // simple contradiction testing for null and non-null in a 3x3 board - public void CannotLightMiddleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/CannotLight", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // simple contradiction testing for null and non-null in a 3x3 board + public void CannotLightMiddleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/CannotLight", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm it is impossible to light up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to light up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } - @Test - public void CanLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/CanLightTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void CanLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/CanLightTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is not a contradiction somewhere on the board - Assert.assertNotNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is not a contradiction somewhere on the board + Assert.assertNotNull(RULE.checkContradiction(board)); - // confirm that these cells can be lit, are already lit, or that they are just black blocks - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); - } + // confirm that these cells can be lit, are already lit, or that they are just black blocks + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); + } } diff --git a/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java index 264cf928c..74ece1cad 100644 --- a/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java @@ -14,92 +14,92 @@ import org.junit.Test; public class EmptyCellinLightDirectRuleTest { - private static final EmptyCellinLightDirectRule RULE = new EmptyCellinLightDirectRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - @Test - // tests a 3x3 board with with a 0 black tile in the center and lightbulbs in top left and - // bototm - // right - // confirms the rest of the tiles must be empty - public void EmptyCellinLightDirectRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/EmptyCellinLightDirectRule/EmptyCells", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); - - // change the board's cells considering the emptycellinlight rule - LightUpCell cell2 = board.getCell(1, 0); - cell2.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell2); - - LightUpCell cell3 = board.getCell(0, 1); - cell3.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell3); - - LightUpCell cell4 = board.getCell(2, 0); - cell4.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell4); - - LightUpCell cell5 = board.getCell(0, 2); - cell5.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell5); - - LightUpCell cell6 = board.getCell(1, 2); - cell6.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell6); - - LightUpCell cell7 = board.getCell(2, 1); - cell7.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell7); - - LightUpCell cell8 = board.getCell(3, 0); - cell8.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell8); - - LightUpCell cell9 = board.getCell(3, 2); - cell9.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell9); - - LightUpCell cell10 = board.getCell(2, 3); - cell10.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell10); - - LightUpCell cell11 = board.getCell(0, 3); - cell11.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell11); - - // confirm there is a logical following of the EmptyCellinLight rule - Assert.assertNull(RULE.checkRule(transition)); - - // cells (0,0) and (2,2) are not empty because they have lightbulbs, (1,1) - // because it is a black tile, and (1,3),(3,1),(3,3) because they are not lit. Confirm the - // rest - // are empty - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 0 && j == 0) - || (i == 2 && j == 2) - || (i == 1 && j == 1) - || (i == 1 && j == 3) - || (i == 3 && j == 1) - || (i == 3 && j == 3)) { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - } + private static final EmptyCellinLightDirectRule RULE = new EmptyCellinLightDirectRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + // tests a 3x3 board with with a 0 black tile in the center and lightbulbs in top left and + // bototm + // right + // confirms the rest of the tiles must be empty + public void EmptyCellinLightDirectRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/EmptyCellinLightDirectRule/EmptyCells", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); + + // change the board's cells considering the emptycellinlight rule + LightUpCell cell2 = board.getCell(1, 0); + cell2.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell2); + + LightUpCell cell3 = board.getCell(0, 1); + cell3.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell3); + + LightUpCell cell4 = board.getCell(2, 0); + cell4.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell4); + + LightUpCell cell5 = board.getCell(0, 2); + cell5.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell5); + + LightUpCell cell6 = board.getCell(1, 2); + cell6.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell6); + + LightUpCell cell7 = board.getCell(2, 1); + cell7.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell7); + + LightUpCell cell8 = board.getCell(3, 0); + cell8.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell8); + + LightUpCell cell9 = board.getCell(3, 2); + cell9.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell9); + + LightUpCell cell10 = board.getCell(2, 3); + cell10.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell10); + + LightUpCell cell11 = board.getCell(0, 3); + cell11.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell11); + + // confirm there is a logical following of the EmptyCellinLight rule + Assert.assertNull(RULE.checkRule(transition)); + + // cells (0,0) and (2,2) are not empty because they have lightbulbs, (1,1) + // because it is a black tile, and (1,3),(3,1),(3,3) because they are not lit. Confirm the + // rest + // are empty + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 0 && j == 0) + || (i == 2 && j == 2) + || (i == 1 && j == 1) + || (i == 1 && j == 3) + || (i == 3 && j == 1) + || (i == 3 && j == 3)) { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, c)); } + } } + } } diff --git a/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java index a4f958860..0af76baeb 100644 --- a/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java @@ -14,65 +14,65 @@ import org.junit.Test; public class EmptyCornersDirectRuleTest { - private static final EmptyCornersDirectRule RULE = new EmptyCornersDirectRule(); - private static LightUp lightUp; + private static final EmptyCornersDirectRule RULE = new EmptyCornersDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void EmptyCornersTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/EmptyCornersDirectRule/EmptyCorners", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void EmptyCornersTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/EmptyCornersDirectRule/EmptyCorners", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the EmptyCorners rule to empty - LightUpCell cell1 = board.getCell(2, 2); - cell1.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell1); + // change the board's cells considering the EmptyCorners rule to empty + LightUpCell cell1 = board.getCell(2, 2); + cell1.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell1); - LightUpCell cell2 = board.getCell(0, 2); - cell2.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell2); + LightUpCell cell2 = board.getCell(0, 2); + cell2.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell2); - LightUpCell cell3 = board.getCell(4, 3); - cell3.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell3); + LightUpCell cell3 = board.getCell(4, 3); + cell3.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell3); - // confirm there is a logical following of the EmptyCorners rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the EmptyCorners rule + Assert.assertNull(RULE.checkRule(transition)); - // this should not be accepted, the cell should remain unknown - LightUpCell cell4 = board.getCell(4, 5); - cell4.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell4); + // this should not be accepted, the cell should remain unknown + LightUpCell cell4 = board.getCell(4, 5); + cell4.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell4); - // this should not be accepted, the cell should be empty but not because of this rule - LightUpCell cell5 = board.getCell(4, 1); - cell5.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell5); + // this should not be accepted, the cell should be empty but not because of this rule + LightUpCell cell5 = board.getCell(4, 1); + cell5.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell5); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - // confirm the two expected cells are emptied USING THE RULE - // and none of the rest are (others can be empty just not by the same rule) - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 2 && j == 0) || (i == 2 && j == 2) || (i == 3 && j == 4)) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + // confirm the two expected cells are emptied USING THE RULE + // and none of the rest are (others can be empty just not by the same rule) + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 2 && j == 0) || (i == 2 && j == 2) || (i == 3 && j == 4)) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } + } } diff --git a/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java index 59cbfdbf9..d1b0422f9 100644 --- a/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java @@ -14,92 +14,91 @@ import org.junit.Test; public class FinishWithBulbsDirectRuleTest { - private static final FinishWithBulbsDirectRule RULE = new FinishWithBulbsDirectRule(); - private static LightUp lightUp; + private static final FinishWithBulbsDirectRule RULE = new FinishWithBulbsDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void FinishBulbTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbs", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void FinishBulbTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbs", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the FinishWithBulbs rule to empty - LightUpCell cell1 = board.getCell(1, 0); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); + // change the board's cells considering the FinishWithBulbs rule to empty + LightUpCell cell1 = board.getCell(1, 0); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - // check every square except the top center (2,0) - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if (i == 0 && j == 1) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + // check every square except the top center (2,0) + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if (i == 0 && j == 1) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } + } - // even though this test isnt a completely filled board because it is unsolveable, it tests - // FinishBulbs properly - @Test - public void FinishBulbTestWithThree() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbsWithThree", - lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // even though this test isnt a completely filled board because it is unsolveable, it tests + // FinishBulbs properly + @Test + public void FinishBulbTestWithThree() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbsWithThree", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the FinishWithBulbs rule to empty - LightUpCell cell1 = board.getCell(1, 2); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); + // change the board's cells considering the FinishWithBulbs rule to empty + LightUpCell cell1 = board.getCell(1, 2); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); - LightUpCell cell2 = board.getCell(0, 1); - cell2.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell2); + LightUpCell cell2 = board.getCell(0, 1); + cell2.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell2); - LightUpCell cell3 = board.getCell(2, 1); - cell3.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell3); + LightUpCell cell3 = board.getCell(2, 1); + cell3.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell3); - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - // check every square for logical following - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 1 && j == 2) || (i == 2 && j == 1) || (i == 1 && j == 0)) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + // check every square for logical following + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 1 && j == 2) || (i == 2 && j == 1) || (i == 1 && j == 0)) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } + } } diff --git a/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java b/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java index fa0698edb..3a782dfe7 100644 --- a/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java @@ -16,60 +16,60 @@ import org.junit.Test; public class LightOrEmptyCaseRuleTest { - private static final LightOrEmptyCaseRule RULE = new LightOrEmptyCaseRule(); - private static LightUp lightUp; + private static final LightOrEmptyCaseRule RULE = new LightOrEmptyCaseRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - // creates boards for what is expected output, and checks that the getcases function produces - // the - // correct boards - // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) - @Test - public void LightOrEmptyTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/LightOrEmptyCaseRule/LightOrEmpty", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // creates boards for what is expected output, and checks that the getcases function produces + // the + // correct boards + // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) + @Test + public void LightOrEmptyTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/LightOrEmptyCaseRule/LightOrEmpty", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(0, 0); // the focus cell - ArrayList cases = RULE.getCases(b, numbered_cell); + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(0, 0); // the focus cell + ArrayList cases = RULE.getCases(b, numbered_cell); - // assert correct number of cases - Assert.assertEquals(2, cases.size()); + // assert correct number of cases + Assert.assertEquals(2, cases.size()); - // make a list of boards that I expect - LightUpCell change_cell; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + // make a list of boards that I expect + LightUpCell change_cell; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - // change the cells of the first new case board - change_cell = case1.getCell(0, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); + // change the cells of the first new case board + change_cell = case1.getCell(0, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); - change_cell = case1.getCell(1, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); + change_cell = case1.getCell(1, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); - // change the cells of the second new case board - change_cell = case2.getCell(0, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); + // change the cells of the second new case board + change_cell = case2.getCell(0, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); - change_cell = case2.getCell(1, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); + change_cell = case2.getCell(1, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); - // check each board I expect and make sure it exists in returned board list - // currently cases is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - } + // check each board I expect and make sure it exists in returned board list + // currently cases is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + } } diff --git a/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java index e0e1434c3..1602b8135 100644 --- a/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java @@ -14,46 +14,45 @@ import org.junit.Test; public class MustLightDirectRuleTest { - private static final MustLightDirectRule RULE = new MustLightDirectRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - @Test - public void MustLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/MustLightDirectRule/MustLight", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); - - // change the board's cells considering the MustLight rule - LightUpCell cell1 = board.getCell(1, 2); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); - - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if (i == 2 && j == 1) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final MustLightDirectRule RULE = new MustLightDirectRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + public void MustLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/lightup/rules/MustLightDirectRule/MustLight", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); + + // change the board's cells considering the MustLight rule + LightUpCell cell1 = board.getCell(1, 2); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); + + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if (i == 2 && j == 1) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } + } } diff --git a/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java b/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java index a04f1c520..238419c71 100644 --- a/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java @@ -16,148 +16,146 @@ import org.junit.Test; public class SatisfyNumberCaseRuleTest { - private static final SatisfyNumberCaseRule RULE = new SatisfyNumberCaseRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - // creates two boards for what is expected output, and checks that the getcases function - // produces - // the correct boards - // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) - @Test - public void SatisfyNumberTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumber", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(1, 0); // the tile cell - ArrayList cases = - RULE.getCases( - b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE - - // assert correct number of cases - Assert.assertEquals(2, cases.size()); - - // make a list of boards that I expect - LightUpCell change_cell; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - - // change the cells of the first new case board - change_cell = case1.getCell(0, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); - - change_cell = case1.getCell(1, 1); - change_cell.setData(LightUpCellType.EMPTY.value); - // case1.addModifiedData(change_cell); - - // change the cells of the second new case board - change_cell = case2.getCell(0, 0); - change_cell.setData(LightUpCellType.EMPTY.value); - // case2.addModifiedData(change_cell); - - change_cell = case2.getCell(1, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); - - // check each board I expect and make sure it exists in returned board list - // currently cases is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - } - - @Test - public void SatisfyNumberTestTwo() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumberTwo", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(1, 1); // the tile cell - ArrayList cases = - RULE.getCases( - b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE - - // assert correct number of cases - Assert.assertEquals(6, cases.size()); - - // make a list of boards that I expect - LightUpCell change_cell1; - LightUpCell change_cell2; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case3 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case4 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case5 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case6 = ((LightUpBoard) transition.getBoard()).copy(); - - // case 1: lights in (1,0) and (0,1) - change_cell1 = case1.getCell(1, 0); - change_cell2 = case1.getCell(0, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case1.addModifiedData(change_cell1); - case1.addModifiedData(change_cell2); - - // case 2: lights in (1,0) and (1,2) - change_cell1 = case2.getCell(1, 0); - change_cell2 = case2.getCell(1, 2); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case2.addModifiedData(change_cell1); - case2.addModifiedData(change_cell2); - - // case 3: lights in (1,0) and (2,1) - change_cell1 = case3.getCell(1, 0); - change_cell2 = case3.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case3.addModifiedData(change_cell1); - case3.addModifiedData(change_cell2); - - // case 4: lights in (0,1) and (2,1) - change_cell1 = case4.getCell(0, 1); - change_cell2 = case4.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case4.addModifiedData(change_cell1); - case4.addModifiedData(change_cell2); - - // case 5: lights in (0,1) and (1,2) - change_cell1 = case5.getCell(0, 1); - change_cell2 = case5.getCell(1, 2); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case5.addModifiedData(change_cell1); - case5.addModifiedData(change_cell2); - - // case 6: lights in (1,2) and (2,1) - change_cell1 = case6.getCell(1, 2); - change_cell2 = case6.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case6.addModifiedData(change_cell1); - case6.addModifiedData(change_cell2); - - // check each board I expect and make sure it exists in returned board list - // currently the cases list is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - // Assert.assertTrue(cases.contains((Board) case3)); - // Assert.assertTrue(cases.contains((Board) case4)); - // Assert.assertTrue(cases.contains((Board) case5)); - // Assert.assertTrue(cases.contains((Board) case6)); - } + private static final SatisfyNumberCaseRule RULE = new SatisfyNumberCaseRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + // creates two boards for what is expected output, and checks that the getcases function + // produces + // the correct boards + // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) + @Test + public void SatisfyNumberTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumber", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(1, 0); // the tile cell + ArrayList cases = + RULE.getCases(b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE + + // assert correct number of cases + Assert.assertEquals(2, cases.size()); + + // make a list of boards that I expect + LightUpCell change_cell; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + + // change the cells of the first new case board + change_cell = case1.getCell(0, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); + + change_cell = case1.getCell(1, 1); + change_cell.setData(LightUpCellType.EMPTY.value); + // case1.addModifiedData(change_cell); + + // change the cells of the second new case board + change_cell = case2.getCell(0, 0); + change_cell.setData(LightUpCellType.EMPTY.value); + // case2.addModifiedData(change_cell); + + change_cell = case2.getCell(1, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); + + // check each board I expect and make sure it exists in returned board list + // currently cases is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + } + + @Test + public void SatisfyNumberTestTwo() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumberTwo", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(1, 1); // the tile cell + ArrayList cases = + RULE.getCases(b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE + + // assert correct number of cases + Assert.assertEquals(6, cases.size()); + + // make a list of boards that I expect + LightUpCell change_cell1; + LightUpCell change_cell2; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case3 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case4 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case5 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case6 = ((LightUpBoard) transition.getBoard()).copy(); + + // case 1: lights in (1,0) and (0,1) + change_cell1 = case1.getCell(1, 0); + change_cell2 = case1.getCell(0, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case1.addModifiedData(change_cell1); + case1.addModifiedData(change_cell2); + + // case 2: lights in (1,0) and (1,2) + change_cell1 = case2.getCell(1, 0); + change_cell2 = case2.getCell(1, 2); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case2.addModifiedData(change_cell1); + case2.addModifiedData(change_cell2); + + // case 3: lights in (1,0) and (2,1) + change_cell1 = case3.getCell(1, 0); + change_cell2 = case3.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case3.addModifiedData(change_cell1); + case3.addModifiedData(change_cell2); + + // case 4: lights in (0,1) and (2,1) + change_cell1 = case4.getCell(0, 1); + change_cell2 = case4.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case4.addModifiedData(change_cell1); + case4.addModifiedData(change_cell2); + + // case 5: lights in (0,1) and (1,2) + change_cell1 = case5.getCell(0, 1); + change_cell2 = case5.getCell(1, 2); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case5.addModifiedData(change_cell1); + case5.addModifiedData(change_cell2); + + // case 6: lights in (1,2) and (2,1) + change_cell1 = case6.getCell(1, 2); + change_cell2 = case6.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case6.addModifiedData(change_cell1); + case6.addModifiedData(change_cell2); + + // check each board I expect and make sure it exists in returned board list + // currently the cases list is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + // Assert.assertTrue(cases.contains((Board) case3)); + // Assert.assertTrue(cases.contains((Board) case4)); + // Assert.assertTrue(cases.contains((Board) case5)); + // Assert.assertTrue(cases.contains((Board) case6)); + } } diff --git a/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java index fe994baa6..25389f299 100644 --- a/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java @@ -12,57 +12,57 @@ import org.junit.Test; public class TooFewBulbsContradictionRuleTest { - private static final TooFewBulbsContradictionRule RULE = new TooFewBulbsContradictionRule(); - private static LightUp lightUp; + private static final TooFewBulbsContradictionRule RULE = new TooFewBulbsContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooFewBulbsContradictionRule/FullTooFewTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooFewBulbsContradictionRule/FullTooFewTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm that there arent enough bulbs around the black tiles - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(4, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); + // confirm that there arent enough bulbs around the black tiles + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(4, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); - // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(4, 4))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); - } + // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(4, 4))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); + } - @Test - public void TooFewSimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooFewBulbsContradictionRule/TooFew", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void TooFewSimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooFewBulbsContradictionRule/TooFew", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm it is impossible to satisfy up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to satisfy up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } } diff --git a/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java index e27fa3323..0ee6fdb5e 100644 --- a/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java @@ -12,57 +12,57 @@ import org.junit.Test; public class TooManyBulbsContradictionRuleTest { - private static final TooManyBulbsContradictionRule RULE = new TooManyBulbsContradictionRule(); - private static LightUp lightUp; + private static final TooManyBulbsContradictionRule RULE = new TooManyBulbsContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - // complex extensive toofew test - public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooManyBulbsContradictionRule/FullTooManyTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // complex extensive toofew test + public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooManyBulbsContradictionRule/FullTooManyTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm that there are too many bulbs around the black tiles - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); + // confirm that there are too many bulbs around the black tiles + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); - // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); - } + // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); + } - @Test - // tests a 3x3 board with a 3 in the center and 4 surrounding lightbulbs - public void TooManySimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooManyBulbsContradictionRule/TooMany", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // tests a 3x3 board with a 3 in the center and 4 surrounding lightbulbs + public void TooManySimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooManyBulbsContradictionRule/TooMany", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm it is impossible to satisfy up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to satisfy up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java index d87398303..3fda4956d 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java @@ -19,186 +19,184 @@ public class BlackBetweenRegionsDirectRuleTest { - private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other - * (diagonal going from top left to bottom right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(2, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(1, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Black Between Regions direct rule for regions that are diagonal to each other + * (diagonal going from top left to bottom right) + */ + @Test + public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell1 = board.getCell(2, 1); + cell1.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell2 = board.getCell(1, 2); + cell2.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other - * (diagonal going from bottom left to top right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(1, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(2, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Black Between Regions direct rule for regions that are diagonal to each other + * (diagonal going from bottom left to top right) + */ + @Test + public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell1 = board.getCell(1, 1); + cell1.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell2 = board.getCell(2, 2); + cell2.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Black Between Regions direct rule for regions that are horizontally opposite each - * other - */ - @Test - public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Black Between Regions direct rule for regions that are horizontally opposite each + * other + */ + @Test + public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Black Between Regions direct rule for regions that are vertically opposite each - * other - */ - @Test - public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Black Between Regions direct rule for regions that are vertically opposite each other + */ + @Test + public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Black Between Regions direct rule for a false application of the rule, where a - * black tile is enclosed by one region - */ - @Test - public void BlackBetweenRegionsDirectRule_FalseBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/FalseBlackBetweenRegions", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Black Between Regions direct rule for a false application of the rule, where a black + * tile is enclosed by one region + */ + @Test + public void BlackBetweenRegionsDirectRule_FalseBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/FalseBlackBetweenRegions", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java index 262a4bdbd..cddcd7871 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java @@ -17,94 +17,94 @@ public class BlackBottleNeckDirectRuleTest { - private static final BlackBottleNeckDirectRule RULE = new BlackBottleNeckDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** Tests the Black BottleNeck direct rule for a bottleneck in the center of the board */ - @Test - public void BlackBottleNeckDirectRule_TwoSurroundBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/SimpleBlackBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final BlackBottleNeckDirectRule RULE = new BlackBottleNeckDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** Tests the Black BottleNeck direct rule for a bottleneck in the center of the board */ + @Test + public void BlackBottleNeckDirectRule_TwoSurroundBlackTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/SimpleBlackBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** Tests the Black BottleNeck direct rule for a bottleneck in the corner of the board */ - @Test - public void BlackBottleNeckDirectRule_CornerBottleneck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/CornerBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** Tests the Black BottleNeck direct rule for a bottleneck in the corner of the board */ + @Test + public void BlackBottleNeckDirectRule_CornerBottleneck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/CornerBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Black BottleNeck direct rule for a false bottleneck */ - @Test - public void BlackBottleNeckDirectRule_FalseBottleneck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/FalseBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black BottleNeck direct rule for a false bottleneck */ + @Test + public void BlackBottleNeckDirectRule_FalseBottleneck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/FalseBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.BLACK.toValue()); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java index d8f353393..65f42ac6e 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java @@ -19,57 +19,56 @@ public class BlackOrWhiteCaseRuleTest { - private static final BlackOrWhiteCaseRule RULE = new BlackOrWhiteCaseRule(); - private static Nurikabe nurikabe; + private static final BlackOrWhiteCaseRule RULE = new BlackOrWhiteCaseRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Black Or White case rule by ensuring that it results in two children, that contain - * a modified cell that is either black or white - */ - @Test - public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackOrWhiteCaseRule/SimpleBlackOrWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Black Or White case rule by ensuring that it results in two children, that contain a + * modified cell that is either black or white + */ + @Test + public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackOrWhiteCaseRule/SimpleBlackOrWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, cell); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, cell); - Assert.assertEquals(2, cases.size()); + Assert.assertEquals(2, cases.size()); - NurikabeBoard caseBoard = (NurikabeBoard) cases.get(0); - NurikabeBoard caseBoard2 = (NurikabeBoard) cases.get(1); + NurikabeBoard caseBoard = (NurikabeBoard) cases.get(0); + NurikabeBoard caseBoard2 = (NurikabeBoard) cases.get(1); - NurikabeType board1Type = caseBoard.getCell(0, 0).getType(); - NurikabeType board2Type = caseBoard2.getCell(0, 0).getType(); + NurikabeType board1Type = caseBoard.getCell(0, 0).getType(); + NurikabeType board2Type = caseBoard2.getCell(0, 0).getType(); - Assert.assertTrue( - (board1Type.equals(NurikabeType.BLACK) || board1Type.equals(NurikabeType.WHITE)) - && (board2Type.equals(NurikabeType.BLACK) - || board2Type.equals(NurikabeType.WHITE))); - Assert.assertFalse(board1Type.equals(board2Type)); + Assert.assertTrue( + (board1Type.equals(NurikabeType.BLACK) || board1Type.equals(NurikabeType.WHITE)) + && (board2Type.equals(NurikabeType.BLACK) || board2Type.equals(NurikabeType.WHITE))); + Assert.assertFalse(board1Type.equals(board2Type)); - Assert.assertEquals(caseBoard.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard.getWidth(), caseBoard2.getWidth(), board.getWidth()); + Assert.assertEquals(caseBoard.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard.getWidth(), caseBoard2.getWidth(), board.getWidth()); - for (int i = 0; i < caseBoard.getHeight(); i++) { - for (int k = 0; k < caseBoard.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(caseBoard.getCell(k, i).getLocation())) { - continue; - } - Assert.assertTrue(caseBoard.getCell(k, i).equals(caseBoard2.getCell(k, i))); - } + for (int i = 0; i < caseBoard.getHeight(); i++) { + for (int k = 0; k < caseBoard.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(caseBoard.getCell(k, i).getLocation())) { + continue; } + Assert.assertTrue(caseBoard.getCell(k, i).equals(caseBoard2.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java index d27e546bc..d317a7835 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java @@ -15,97 +15,97 @@ import org.junit.Test; public class BlackSquareContradictionRuleTest { - private static final BlackSquareContradictionRule RULE = new BlackSquareContradictionRule(); - private static Nurikabe nurikabe; + private static final BlackSquareContradictionRule RULE = new BlackSquareContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Black Square contradiction rule for a black square in the middle of the board */ - @Test - public void BlackSquareContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/SimpleBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a black square in the middle of the board */ + @Test + public void BlackSquareContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/SimpleBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); - NurikabeCell cell2 = board.getCell(1, 2); - NurikabeCell cell3 = board.getCell(2, 1); - NurikabeCell cell4 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); + NurikabeCell cell2 = board.getCell(1, 2); + NurikabeCell cell3 = board.getCell(2, 1); + NurikabeCell cell4 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Black Square contradiction rule for a square in the corner of the board */ - @Test - public void BlackSquareContradictionRule_CornerSquareTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/CornerBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a square in the corner of the board */ + @Test + public void BlackSquareContradictionRule_CornerSquareTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/CornerBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 2); - NurikabeCell cell2 = board.getCell(2, 3); - NurikabeCell cell3 = board.getCell(3, 2); - NurikabeCell cell4 = board.getCell(3, 3); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(2, 2); + NurikabeCell cell2 = board.getCell(2, 3); + NurikabeCell cell3 = board.getCell(3, 2); + NurikabeCell cell4 = board.getCell(3, 3); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Black Square contradiction rule for a false contradiction */ - @Test - public void BlackSquareContradictionRule_FalseBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/FalseBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a false contradiction */ + @Test + public void BlackSquareContradictionRule_FalseBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/FalseBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java index 164e08e38..deb93c43f 100644 --- a/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java @@ -17,76 +17,75 @@ public class CannotReachCellDirectRuleTest { - private static final CannotReachCellDirectRule RULE = new CannotReachCellDirectRule(); - private static Nurikabe nurikabe; + private static final CannotReachCellDirectRule RULE = new CannotReachCellDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Cannot Reach Cell direct rule for a simple unreachable cell */ - @Test - public void CannotReachCellDirectRule_SimpleUnreachableCell() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CannotReachCellDirectRule/SimpleUnreachableCell", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); + /** Tests the Cannot Reach Cell direct rule for a simple unreachable cell */ + @Test + public void CannotReachCellDirectRule_SimpleUnreachableCell() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CannotReachCellDirectRule/SimpleUnreachableCell", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Cannot Reach Cell direct rule for a more complex board with all cells reachable */ - @Test - public void CannotReachCellDirectRule_AllCellsReachable() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CannotReachCellDirectRule/AllCellsReachable", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); + /** Tests the Cannot Reach Cell direct rule for a more complex board with all cells reachable */ + @Test + public void CannotReachCellDirectRule_AllCellsReachable() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CannotReachCellDirectRule/AllCellsReachable", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 3); - NurikabeCell cell2 = board.getCell(0, 1); - NurikabeCell cell3 = board.getCell(4, 1); + NurikabeCell cell1 = board.getCell(2, 3); + NurikabeCell cell2 = board.getCell(0, 1); + NurikabeCell cell3 = board.getCell(4, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (!(point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()))) { - NurikabeCell newCell = board.getCell(k, i); - newCell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(newCell); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (!(point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()))) { + NurikabeCell newCell = board.getCell(k, i); + newCell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(newCell); } + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java index 196a1ac2f..567d663e8 100644 --- a/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java @@ -17,65 +17,65 @@ public class CornerBlackDirectRuleTest { - private static final CornerBlackDirectRule RULE = new CornerBlackDirectRule(); - private static Nurikabe nurikabe; + private static final CornerBlackDirectRule RULE = new CornerBlackDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Corner Black direct rule for a simple corner black tile */ - @Test - public void CornerBlackContradictionRule_SimpleCornerBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CornerBlackDirectRule/SimpleCornerBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); + /** Tests the Corner Black direct rule for a simple corner black tile */ + @Test + public void CornerBlackContradictionRule_SimpleCornerBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CornerBlackDirectRule/SimpleCornerBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); - NurikabeCell cell = board.getCell(2, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeCell cell = board.getCell(2, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Corner Black direct rule for a false application of the rule */ - @Test - public void CornerBlackContradictionRule_FalseCornerBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CornerBlackDirectRule/FalseCornerBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); + /** Tests the Corner Black direct rule for a false application of the rule */ + @Test + public void CornerBlackContradictionRule_FalseCornerBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CornerBlackDirectRule/FalseCornerBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); - NurikabeCell cell = board.getCell(2, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeCell cell = board.getCell(2, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java index 5238411b2..c4ed751b0 100644 --- a/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java @@ -17,126 +17,125 @@ public class FillinBlackDirectRuleTest { - private static final FillinBlackDirectRule RULE = new FillinBlackDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the middle of the - * board - */ - @Test - public void FillinBlackDirectRule_UnknownSurroundBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/UnknownSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final FillinBlackDirectRule RULE = new FillinBlackDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the middle of the board + */ + @Test + public void FillinBlackDirectRule_UnknownSurroundBlackTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/UnknownSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the top left corner of - * the board - */ - @Test - public void FillinBlackDirectRule_CornerTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the top left corner of + * the board + */ + @Test + public void FillinBlackDirectRule_CornerTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the bottom right - * corner of the board - */ - @Test - public void FillinBlackDirectRule_CornerTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 2); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the bottom right corner + * of the board + */ + @Test + public void FillinBlackDirectRule_CornerTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 2); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** Tests the Fillin Black direct rule for a false application of the rule */ - @Test - public void FillinBlackDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/FalseFillinBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** Tests the Fillin Black direct rule for a false application of the rule */ + @Test + public void FillinBlackDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/FalseFillinBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java index e6aea12b9..317f44521 100644 --- a/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java @@ -16,128 +16,127 @@ import org.junit.Test; public class FillinWhiteDirectRuleTest { - private static final FillinWhiteDirectRule RULE = new FillinWhiteDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the middle of the - * board - */ - @Test - public void FillinWhiteDirectRule_UnknownSurroundWhiteTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/UnknownSurroundWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final FillinWhiteDirectRule RULE = new FillinWhiteDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the middle of the board + */ + @Test + public void FillinWhiteDirectRule_UnknownSurroundWhiteTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/UnknownSurroundWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the top left corner of - * the board - */ - @Test - public void FillinWhiteDirectRule_CornerTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the top left corner of + * the board + */ + @Test + public void FillinWhiteDirectRule_CornerTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the bottom right - * corner of the board - */ - @Test - public void FillinWhiteDirectRule_CornerTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 2); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the bottom right corner + * of the board + */ + @Test + public void FillinWhiteDirectRule_CornerTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 2); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** Tests the Fillin White direct rule for a false application of the rule */ - @Test - public void FillinWhiteDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/FalseFillinWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** Tests the Fillin White direct rule for a false application of the rule */ + @Test + public void FillinWhiteDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/FalseFillinWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java index 660542d79..1c6773e35 100644 --- a/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java @@ -16,96 +16,93 @@ public class IsolateBlackContradictionRuleTest { - private static final IsolateBlackContradictionRule RULE = new IsolateBlackContradictionRule(); - private static Nurikabe nurikabe; + private static final IsolateBlackContradictionRule RULE = new IsolateBlackContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Isolate Black contradiction rule for a black square in the corner, separated by a - * diagonal of white squares - */ - @Test - public void IsolateBlackContradictionRule_SimpleIsolateBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/SimpleIsolateBlack", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Isolate Black contradiction rule for a black square in the corner, separated by a + * diagonal of white squares + */ + @Test + public void IsolateBlackContradictionRule_SimpleIsolateBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/SimpleIsolateBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Isolate Black contradiction rule for diagonally connected black squares */ - @Test - public void IsolateBlackContradictionRule_DiagonalBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/DiagonalIsolateBlack", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Isolate Black contradiction rule for diagonally connected black squares */ + @Test + public void IsolateBlackContradictionRule_DiagonalBlackTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/DiagonalIsolateBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(1, 1); - NurikabeCell cell3 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(1, 1); + NurikabeCell cell3 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Isolate Black contradiction rule for a false contradiction */ - @Test - public void IsolateBlackContradictionRule_FalseIsolateBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/FalseIsolateBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Isolate Black contradiction rule for a false contradiction */ + @Test + public void IsolateBlackContradictionRule_FalseIsolateBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/FalseIsolateBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java index 0ca30c136..4bc98a9ac 100644 --- a/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java @@ -16,99 +16,96 @@ public class MultipleNumbersContradictionRuleTest { - private static final MultipleNumbersContradictionRule RULE = - new MultipleNumbersContradictionRule(); - private static Nurikabe nurikabe; + private static final MultipleNumbersContradictionRule RULE = + new MultipleNumbersContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Multiple Numbers contradiction rule for a single region with multiple numbers */ - @Test - public void MultipleNumbersContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/MultipleNumbers", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Multiple Numbers contradiction rule for a single region with multiple numbers */ + @Test + public void MultipleNumbersContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/MultipleNumbers", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(0, 0)) || point.equals(new Point(2, 0))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(0, 0)) || point.equals(new Point(2, 0))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** - * Tests the Multiple Numbers contradiction rule for a more complex regions with multiple - * numbers - */ - @Test - public void MultipleNumbersContradictionRule_ComplexRegion() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/ComplexRegion", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Multiple Numbers contradiction rule for a more complex regions with multiple numbers + */ + @Test + public void MultipleNumbersContradictionRule_ComplexRegion() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/ComplexRegion", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(2, 0); - NurikabeCell cell3 = board.getCell(4, 0); - NurikabeCell cell4 = board.getCell(2, 3); - NurikabeCell cell5 = board.getCell(4, 4); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(2, 0); + NurikabeCell cell3 = board.getCell(4, 0); + NurikabeCell cell4 = board.getCell(2, 3); + NurikabeCell cell5 = board.getCell(4, 4); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation()) - || point.equals(cell5.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation()) + || point.equals(cell5.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** - * Tests the Multiple Numbers contradiction rule for two regions with one number each, separated - * diagonally - */ - @Test - public void MultipleNumbersContradictionRule_FalseContradiction() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/FalseContradiction", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Multiple Numbers contradiction rule for two regions with one number each, separated + * diagonally + */ + @Test + public void MultipleNumbersContradictionRule_FalseContradiction() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/FalseContradiction", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java index c5293880f..2b032e650 100644 --- a/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java @@ -15,73 +15,72 @@ public class NoNumbersContradictionRuleTest { - private static final NoNumberContradictionRule RULE = new NoNumberContradictionRule(); - private static Nurikabe nurikabe; + private static final NoNumberContradictionRule RULE = new NoNumberContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the No Number contradiction rule for a white region enclosed by black squares */ - @Test - public void NoNumberContradictionRule_NoNumberSurroundBlack() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/SimpleNoNumber", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the No Number contradiction rule for a white region enclosed by black squares */ + @Test + public void NoNumberContradictionRule_NoNumberSurroundBlack() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/SimpleNoNumber", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the No Number contradiction rule for a false contradiction */ - @Test - public void NoNumberContradictionRule_FalseNoNumber() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the No Number contradiction rule for a false contradiction */ + @Test + public void NoNumberContradictionRule_FalseNoNumber() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } - @Test - public void NoNumberContradictionRule_FalseNoNumber2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void NoNumberContradictionRule_FalseNoNumber2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java index c529c81cc..67f87e751 100644 --- a/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java @@ -17,162 +17,157 @@ public class PreventBlackSquareDirectRuleTest { - private static final PreventBlackSquareDirectRule RULE = new PreventBlackSquareDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the bottom left corner - * missing - */ - @Test - public void PreventBlackSquareDirectRule_BottomLeftWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomLeftWhiteBlackSquare", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final PreventBlackSquareDirectRule RULE = new PreventBlackSquareDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Prevent Black Square direct rule for a black square with the bottom left corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_BottomLeftWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomLeftWhiteBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Prevent Black Square direct rule for a black square with the bottom right corner - * missing - */ - @Test - public void PreventBlackSquareDirectRule_BottomRightWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomRightWhiteBlackSquare", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Prevent Black Square direct rule for a black square with the bottom right corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_BottomRightWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomRightWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Prevent Black Square direct rule for a black square with the top left corner - * missing - */ - @Test - public void PreventBlackSquareDirectRule_TopLeftWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopLeftWhiteBlackSquare", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Prevent Black Square direct rule for a black square with the top left corner missing + */ + @Test + public void PreventBlackSquareDirectRule_TopLeftWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopLeftWhiteBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * Tests the Prevent Black Square direct rule for a black square with the top right corner - * missing - */ - @Test - public void PreventBlackSquareDirectRule_TopRightWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopRightWhiteBlackSquare", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * Tests the Prevent Black Square direct rule for a black square with the top right corner missing + */ + @Test + public void PreventBlackSquareDirectRule_TopRightWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopRightWhiteBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** Tests the Prevent Black Square direct rule for a false contradiction */ - @Test - public void PreventBlackSquareDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/FalseBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** Tests the Prevent Black Square direct rule for a false contradiction */ + @Test + public void PreventBlackSquareDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/FalseBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java index a09475cff..6520e1221 100644 --- a/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java @@ -17,105 +17,103 @@ public class SurroundRegionDirectRuleTest { - private static final SurroundRegionDirectRule RULE = new SurroundRegionDirectRule(); - private static Nurikabe nurikabe; + private static final SurroundRegionDirectRule RULE = new SurroundRegionDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Surround Region direct rule for a white square in the middle of the board */ - @Test - public void SurroundRegionDirectRule_SurroundRegionBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a white square in the middle of the board */ + @Test + public void SurroundRegionDirectRule_SurroundRegionBlackTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 0); - cell1.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell1); - NurikabeCell cell2 = board.getCell(0, 1); - cell2.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell2); - NurikabeCell cell3 = board.getCell(2, 1); - cell3.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell3); - NurikabeCell cell4 = board.getCell(1, 2); - cell4.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell4); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 0); + cell1.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell1); + NurikabeCell cell2 = board.getCell(0, 1); + cell2.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell2); + NurikabeCell cell3 = board.getCell(2, 1); + cell3.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell3); + NurikabeCell cell4 = board.getCell(1, 2); + cell4.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell4); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Surround Region direct rule for a white square in the corner of the board */ - @Test - public void SurroundRegionDirectRule_SurroundRegionBlackInCornerTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlackInCorner", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a white square in the corner of the board */ + @Test + public void SurroundRegionDirectRule_SurroundRegionBlackInCornerTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlackInCorner", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 0); - cell1.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell1); - NurikabeCell cell2 = board.getCell(0, 1); - cell2.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 0); + cell1.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell1); + NurikabeCell cell2 = board.getCell(0, 1); + cell2.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell2); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Surround Region direct rule for a false application of the rule */ - @Test - public void SurroundRegionDirectRule_FalseSurroundRegionBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/FalseSurroundRegion", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a false application of the rule */ + @Test + public void SurroundRegionDirectRule_FalseSurroundRegionBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/FalseSurroundRegion", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java index 89b1a29a7..b5774e3dd 100644 --- a/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java @@ -16,85 +16,84 @@ public class TooFewSpacesContradictionRuleTest { - private static final TooFewSpacesContradictionRule RULE = new TooFewSpacesContradictionRule(); - private static Nurikabe nurikabe; + private static final TooFewSpacesContradictionRule RULE = new TooFewSpacesContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Too Few Spaces contradiction rule for an isolated completely enclosed number */ - @Test - public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for an isolated completely enclosed number */ + @Test + public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(1, 1))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(1, 1))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Too Few Spaces contradiction rule for a region with insufficient space */ - @Test - public void TooFewSpacesContradictionRule_InsufficientSpaceTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for a region with insufficient space */ + @Test + public void TooFewSpacesContradictionRule_InsufficientSpaceTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Too Few Spaces contradiction rule for a false contradiction */ - @Test - public void TooFewSpacesContradictionRule_FalseTooFewSpaces() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/FalseTooFewSpaces", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for a false contradiction */ + @Test + public void TooFewSpacesContradictionRule_FalseTooFewSpaces() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/FalseTooFewSpaces", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java index 31fb92f5d..1a3280653 100644 --- a/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java @@ -15,94 +15,92 @@ public class TooManySpacesContradictionRuleTest { - private static final TooManySpacesContradictionRule RULE = new TooManySpacesContradictionRule(); - private static Nurikabe nurikabe; + private static final TooManySpacesContradictionRule RULE = new TooManySpacesContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Too Many Spaces contradiction rule for a 2 in the center surrounded by 4 white - * squares - */ - @Test - public void TooManySpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/TwoSurroundWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Too Many Spaces contradiction rule for a 2 in the center surrounded by 4 white + * squares + */ + @Test + public void TooManySpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/TwoSurroundWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(1, 0)) - || point.equals(new Point(1, 1)) - || point.equals(new Point(2, 1)) - || point.equals(new Point(1, 2)) - || point.equals(new Point(0, 1))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(1, 0)) + || point.equals(new Point(1, 1)) + || point.equals(new Point(2, 1)) + || point.equals(new Point(1, 2)) + || point.equals(new Point(0, 1))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** Tests the Too Many Spaces contradiction rule for an extra diagonal space */ - @Test - public void TooManySpacesContradictionRule_ExtraDiagonalSpace() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/ExtraDiagonalSpace", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Many Spaces contradiction rule for an extra diagonal space */ + @Test + public void TooManySpacesContradictionRule_ExtraDiagonalSpace() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/ExtraDiagonalSpace", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } - /** - * Tests the Too Many Spaces contradiction rule for a contradiction.with multiple numbers, - * wherein one of the numbers is larger than the region - */ - @Test - public void TooManySpacesContradictionRule_MultipleNumberRegion() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/MultipleNumberRegion", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Too Many Spaces contradiction rule for a contradiction.with multiple numbers, wherein + * one of the numbers is larger than the region + */ + @Test + public void TooManySpacesContradictionRule_MultipleNumberRegion() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/MultipleNumberRegion", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(board.getCell(2, 1).getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNull(RULE.checkContradiction(board)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(board.getCell(2, 1).getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java index da94d7598..58470d6b0 100644 --- a/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java @@ -16,69 +16,67 @@ public class UnreachableWhiteCellContradictionRuleTest { - private static final UnreachableWhiteCellContradictionRule RULE = - new UnreachableWhiteCellContradictionRule(); - private static Nurikabe nurikabe; + private static final UnreachableWhiteCellContradictionRule RULE = + new UnreachableWhiteCellContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Unreachable White Cell contradiction rule for a simple case of an unreachable white - * cell - */ - @Test - public void UnreachableWhiteCellContradictionRule_SimpleTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/SimpleUnreachableTest", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Unreachable White Cell contradiction rule for a simple case of an unreachable white + * cell + */ + @Test + public void UnreachableWhiteCellContradictionRule_SimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/SimpleUnreachableTest", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(2, 2); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } - /** - * Tests the Unreachable White Cell contradiction rule for a variety of white square that should - * all be reachable in some manner - */ - @Test - public void UnreachableWhiteCellContradictionRule_AllCellsReachable() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/AllCellsReachable", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Unreachable White Cell contradiction rule for a variety of white square that should + * all be reachable in some manner + */ + @Test + public void UnreachableWhiteCellContradictionRule_AllCellsReachable() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/AllCellsReachable", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java index ce9144879..4ad9267bd 100644 --- a/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java @@ -17,87 +17,87 @@ public class WhiteBottleNeckDirectRuleTest { - private static final WhiteBottleNeckDirectRule RULE = new WhiteBottleNeckDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** Tests the White BottleNeck direct rule for a bottleneck in the middle of the board */ - @Test - public void WhiteBottleNeckDirectRule_SimpleWhiteBottleNeckTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/SimpleWhiteBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final WhiteBottleNeckDirectRule RULE = new WhiteBottleNeckDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** Tests the White BottleNeck direct rule for a bottleneck in the middle of the board */ + @Test + public void WhiteBottleNeckDirectRule_SimpleWhiteBottleNeckTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/SimpleWhiteBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** Tests the White BottleNeck direct rule for a more complex board */ - @Test - public void WhiteBottleNeckDirectRule_NurikabeBoard1Test() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/NurikabeBoard1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** Tests the White BottleNeck direct rule for a more complex board */ + @Test + public void WhiteBottleNeckDirectRule_NurikabeBoard1Test() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/NurikabeBoard1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - /** Tests the White BottleNeck direct rule for a more false bottle neck */ - @Test - public void WhiteBottleNeckDirectRule_FalseBottleNeck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/FalseBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** Tests the White BottleNeck direct rule for a more false bottle neck */ + @Test + public void WhiteBottleNeckDirectRule_FalseBottleNeck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/FalseBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java index 58fc67824..693acc682 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java @@ -18,142 +18,142 @@ public class AndCaseRuleTest { - private static final CaseRuleAnd RULE = new CaseRuleAnd(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - private void falseAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); - - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); - ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); - - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); - ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); - - // Assert that the corresponding cells for the different case rules do not - // match with each other - Assert.assertNotEquals(board1A, board2A); - Assert.assertNotEquals(board1B, board2B); - - // First assert the two cells are not equal, then verify that they are either - // unknown or false. - Assert.assertNotEquals(board1A, board1B); - Assert.assertTrue( - board1A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - board1B.equals(ShortTruthTableCellType.UNKNOWN) - || board1B.equals(ShortTruthTableCellType.FALSE)); - - Assert.assertNotEquals(board2A, board2B); - Assert.assertTrue( - board2A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - board2B.equals(ShortTruthTableCellType.UNKNOWN) - || board2B.equals(ShortTruthTableCellType.FALSE)); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the two cells that should be different - if (!((i == aX && j == aY) || (i == bX && j == bY))) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); - } - } + private static final CaseRuleAnd RULE = new CaseRuleAnd(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + private void falseAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); + + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); + ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); + + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); + ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); + + // Assert that the corresponding cells for the different case rules do not + // match with each other + Assert.assertNotEquals(board1A, board2A); + Assert.assertNotEquals(board1B, board2B); + + // First assert the two cells are not equal, then verify that they are either + // unknown or false. + Assert.assertNotEquals(board1A, board1B); + Assert.assertTrue( + board1A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + board1B.equals(ShortTruthTableCellType.UNKNOWN) + || board1B.equals(ShortTruthTableCellType.FALSE)); + + Assert.assertNotEquals(board2A, board2B); + Assert.assertTrue( + board2A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + board2B.equals(ShortTruthTableCellType.UNKNOWN) + || board2B.equals(ShortTruthTableCellType.FALSE)); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the two cells that should be different + if (!((i == aX && j == aY) || (i == bX && j == bY))) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); } + } } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches - * are created: one where A is false and one where B is false. - */ - @Test - public void SimpleStatement1FalseTest() throws InvalidFileFormatException { - falseAndTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring - * that two branches are created: one where ~ is false and one where the second ^ is false. - */ - @Test - public void ComplexStatement1FalseTest() throws InvalidFileFormatException { - falseAndTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); - } - - private void trueAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // There should only be 1 branch - Assert.assertEquals(1, cases.size()); - - ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); - ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); - - // Both cells should be true - Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.TRUE); - Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.TRUE); - Assert.assertEquals(caseBoardAType, caseBoardBType); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is - * created where A and B are both true. - */ - @Test - public void SimpleStatement1AndTest() throws InvalidFileFormatException { - trueAndTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring - * that one branch is created where both ~ and the second ^ are true. - */ - @Test - public void ComplexStatement1TrueTest() throws InvalidFileFormatException { - trueAndTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); - } + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches + * are created: one where A is false and one where B is false. + */ + @Test + public void SimpleStatement1FalseTest() throws InvalidFileFormatException { + falseAndTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring + * that two branches are created: one where ~ is false and one where the second ^ is false. + */ + @Test + public void ComplexStatement1FalseTest() throws InvalidFileFormatException { + falseAndTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); + } + + private void trueAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // There should only be 1 branch + Assert.assertEquals(1, cases.size()); + + ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); + ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); + + // Both cells should be true + Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.TRUE); + Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.TRUE); + Assert.assertEquals(caseBoardAType, caseBoardBType); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is + * created where A and B are both true. + */ + @Test + public void SimpleStatement1AndTest() throws InvalidFileFormatException { + trueAndTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring that + * one branch is created where both ~ and the second ^ are true. + */ + @Test + public void ComplexStatement1TrueTest() throws InvalidFileFormatException { + trueAndTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java index 61f29a669..94b99801b 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java @@ -15,205 +15,198 @@ import org.junit.Test; public class AndEliminationDirectRuleTest { - private static final DirectRuleAndElimination RULE = new DirectRuleAndElimination(); - private static ShortTruthTable stt; + private static final DirectRuleAndElimination RULE = new DirectRuleAndElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: B^C where ^ is true + * + *

Checks all possible combinations of true, false, and unknown for B and C except for where + * both B and C are true and asserts that each one of them is not a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void trueAndTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.TRUE) { + continue; + } - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); - /** - * Given one statement: B^C where ^ is true - * - *

Checks all possible combinations of true, false, and unknown for B and C except for where - * both B and C are true and asserts that each one of them is not a valid application of the - * rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void trueAndTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.TRUE) { - continue; - } - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); - - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); - } - - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } - - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); } - } - /** - * Given one statement: B^C where ^ is true - * - *

Checks all possible combinations of true and unknown for B and C except for where both B - * and C are unknown and asserts that each one of them is a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void trueAndTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.UNKNOWN) { - continue; - } - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); - - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); - } - - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } - - Assert.assertNull(RULE.checkRule(transition)); - } + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); } - } - /** - * Given one statement: B^C where ^ is false - * - *

Checks all possible combinations of true, false, and unknown for B and C and asserts that - * each one of them is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithUnknownsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); - - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); - } - - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); + } } - - /** - * Given one statement: B^C where both B and ^ are false - * - *

Asserts that this is not a valid application of the rule if C is set to either true or - * false. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithKnownFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownFalse", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + } + + /** + * Given one statement: B^C where ^ is true + * + *

Checks all possible combinations of true and unknown for B and C except for where both B and + * C are unknown and asserts that each one of them is a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void trueAndTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.UNKNOWN) { + continue; + } ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - + ShortTruthTableCell bonnie = board.getCell(0, 0); ShortTruthTableCell clyde = board.getCell(2, 0); - clyde.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - clyde.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } - /** - * Given one statement: B^C where B is true and ^ is false - * - *

Asserts that this is a valid application of the rule if and only if C is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithKnownTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownTrue", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + Assert.assertNull(RULE.checkRule(transition)); + } + } + } + + /** + * Given one statement: B^C where ^ is false + * + *

Checks all possible combinations of true, false, and unknown for B and C and asserts that + * each one of them is not a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithUnknownsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - + ShortTruthTableCell bonnie = board.getCell(0, 0); ShortTruthTableCell clyde = board.getCell(2, 0); - clyde.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - clyde.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(clyde); - Assert.assertNull(RULE.checkRule(transition)); + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } + + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } + + /** + * Given one statement: B^C where both B and ^ are false + * + *

Asserts that this is not a valid application of the rule if C is set to either true or + * false. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithKnownFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownFalse", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell clyde = board.getCell(2, 0); + clyde.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); + + clyde.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: B^C where B is true and ^ is false + * + *

Asserts that this is a valid application of the rule if and only if C is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithKnownTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownTrue", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell clyde = board.getCell(2, 0); + clyde.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); + + clyde.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(clyde); + Assert.assertNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java index ec03919ae..d17ffd6cf 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java @@ -15,91 +15,91 @@ import org.junit.Test; public class AndIntroductionDirectRuleTest { - private static final DirectRuleAndIntroduction RULE = new DirectRuleAndIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleAndIntroduction RULE = new DirectRuleAndIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A ^ B - * - *

Asserts that if at least 1 of A or B is false, then this is a valid application of the - * rule if and only if ^ is false. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseAndTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; - falseAndTestHelper(path + "FUF"); - falseAndTestHelper(path + "FUU"); - falseAndTestHelper(path + "UUF"); - falseAndTestHelper(path + "FUT"); - falseAndTestHelper(path + "TUF"); - } + /** + * Given a statement: A ^ B + * + *

Asserts that if at least 1 of A or B is false, then this is a valid application of the rule + * if and only if ^ is false. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseAndTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; + falseAndTestHelper(path + "FUF"); + falseAndTestHelper(path + "FUU"); + falseAndTestHelper(path + "UUF"); + falseAndTestHelper(path + "FUT"); + falseAndTestHelper(path + "TUF"); + } - private void falseAndTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseAndTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell and = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell and = board.getCell(1, 0); - and.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(and); - Assert.assertNotNull(RULE.checkRule(transition)); + and.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(and); + Assert.assertNotNull(RULE.checkRule(transition)); - and.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(and); - Assert.assertNull(RULE.checkRule(transition)); - } + and.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(and); + Assert.assertNull(RULE.checkRule(transition)); + } - /** - * Given a statement: A ^ B - * - *

Asserts that setting ^ to true is a valid application of the rule if and only if both A - * and B are true. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String first : letters) { - for (String second : letters) { - trueAndTestHelper(path + first + "U" + second); - } - } + /** + * Given a statement: A ^ B + * + *

Asserts that setting ^ to true is a valid application of the rule if and only if both A and + * B are true. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; + String[] letters = {"T", "F", "U"}; + for (String first : letters) { + for (String second : letters) { + trueAndTestHelper(path + first + "U" + second); + } } + } - private void trueAndTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueAndTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - ShortTruthTableCell and = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell and = board.getCell(1, 0); - and.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(and); + and.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(and); - if (a.getType() == ShortTruthTableCellType.TRUE - && b.getType() == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (a.getType() == ShortTruthTableCellType.TRUE + && b.getType() == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java index c631db613..2126fc60d 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java @@ -15,156 +15,156 @@ import org.junit.Test; public class AtomicDirectRuleTest { - private static final DirectRuleAtomic RULE = new DirectRuleAtomic(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given two statements: A A where the first A is set to false. - * - *

This test sets the second A to false and then asserts that this is a valid application of - * the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MatchingFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: A A where the first A is set to false. - * - *

This test sets the second A to true and then asserts that this is not a valid application - * of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MismatchingFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: B B where the first B is set to true. - * - *

This test sets the second B to true and then asserts that this is a valid application of - * the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MatchingTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: B B where the first B is set to true. - * - *

This test sets the second B to false and then asserts that this is not a valid application - * of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MismatchingTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: C C where neither statement is set to anything. - * - *

This test sets the second C to false and then asserts that this is not a valid application - * of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void NothingPreviouslyMarkedTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: C C where neither statement is set to anything. - * - *

This test sets the second C to true and then asserts that this is not a valid application - * of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void NothingPreviouslyMarkedTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } + private static final DirectRuleAtomic RULE = new DirectRuleAtomic(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given two statements: A A where the first A is set to false. + * + *

This test sets the second A to false and then asserts that this is a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MatchingFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: A A where the first A is set to false. + * + *

This test sets the second A to true and then asserts that this is not a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MismatchingFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: B B where the first B is set to true. + * + *

This test sets the second B to true and then asserts that this is a valid application of the + * rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MatchingTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: B B where the first B is set to true. + * + *

This test sets the second B to false and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MismatchingTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: C C where neither statement is set to anything. + * + *

This test sets the second C to false and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void NothingPreviouslyMarkedTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: C C where neither statement is set to anything. + * + *

This test sets the second C to true and then asserts that this is not a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void NothingPreviouslyMarkedTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java index 987d194f9..36824faee 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java @@ -15,385 +15,380 @@ import org.junit.Test; public class BiconditionalEliminationTest { - private static final DirectRuleBiconditionalElimination RULE = - new DirectRuleBiconditionalElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: A <-> B where both A and <-> are true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where both B and <-> are true - * - *

Asserts that this is a valid application of the rule if and only if A is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + private static final DirectRuleBiconditionalElimination RULE = + new DirectRuleBiconditionalElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: A <-> B where both A and <-> are true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where both B and <-> are true + * + *

Asserts that this is a valid application of the rule if and only if A is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A is false and <-> is true + * + *

Asserts that this is a valid application of the rule if and only if B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B is false and <-> is true + * + *

Asserts that this is a valid application of the rule if and only if A is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A is true and <-> is false + * + *

Asserts that this is a valid application of the rule if and only if B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B is true and <-> is false + * + *

Asserts that this is a valid application of the rule if and only if A is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A and <-> are false + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B and <-> are false + * + *

Asserts that this is a valid application of the rule if and only if A is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where <-> is true + * + *

Asserts that setting any combination of A and B at the same time is not a valid application + * of this rule + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalSetBothAtOnceTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A is false and <-> is true - * - *

Asserts that this is a valid application of the rule if and only if B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell morty = board.getCell(2, 0); - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - } + rick.setData(cellType1); + morty.setData(cellType2); - /** - * Given one statement: A <-> B where B is false and <-> is true - * - *

Asserts that this is a valid application of the rule if and only if A is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A is true and <-> is false - * - *

Asserts that this is a valid application of the rule if and only if B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - // Asserts that this is not a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); + } } - - /** - * Given one statement: A <-> B where B is true and <-> is false - * - *

Asserts that this is a valid application of the rule if and only if A is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + } + + /** + * Asserts that setting any combination of A and B at the same time is not a valid application of + * this rule. This is tested on multiple files. + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAandBAtOnceTest() throws InvalidFileFormatException { + String directory = "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/"; + setAandBBothAtOnceTest(directory + "FalseBiconditional"); + setAandBBothAtOnceTest(directory + "TrueBiconditional"); + setAandBBothAtOnceTest(directory + "FalseBiconditionalWithFalseA"); + setAandBBothAtOnceTest(directory + "TrueBiconditionalWithFalseA"); + setAandBBothAtOnceTest(directory + "FalseBiconditionalWithTrueA"); + setAandBBothAtOnceTest(directory + "TrueBiconditionalWithTrueA"); + } + + /** + * Helper function to test biconditional elimination rule with given file path. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + private void setAandBBothAtOnceTest(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A and <-> are false - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell morty = board.getCell(2, 0); - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B and <-> are false - * - *

Asserts that this is a valid application of the rule if and only if A is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); + rick.setData(cellType1); + morty.setData(cellType2); - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); + board.addModifiedData(morty); - // Asserts that this is not a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where <-> is true - * - *

Asserts that setting any combination of A and B at the same time is not a valid - * application of this rule - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalSetBothAtOnceTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditional", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - ShortTruthTableCell morty = board.getCell(2, 0); - - rick.setData(cellType1); - morty.setData(cellType2); - - board.addModifiedData(rick); - board.addModifiedData(morty); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - - /** - * Asserts that setting any combination of A and B at the same time is not a valid application - * of this rule. This is tested on multiple files. - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAandBAtOnceTest() throws InvalidFileFormatException { - String directory = "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/"; - setAandBBothAtOnceTest(directory + "FalseBiconditional"); - setAandBBothAtOnceTest(directory + "TrueBiconditional"); - setAandBBothAtOnceTest(directory + "FalseBiconditionalWithFalseA"); - setAandBBothAtOnceTest(directory + "TrueBiconditionalWithFalseA"); - setAandBBothAtOnceTest(directory + "FalseBiconditionalWithTrueA"); - setAandBBothAtOnceTest(directory + "TrueBiconditionalWithTrueA"); - } - - /** - * Helper function to test biconditional elimination rule with given file path. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - private void setAandBBothAtOnceTest(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - ShortTruthTableCell morty = board.getCell(2, 0); - - rick.setData(cellType1); - morty.setData(cellType2); - - board.addModifiedData(rick); - board.addModifiedData(morty); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + } } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java index e1c5cf957..99a86c6f1 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java @@ -15,103 +15,103 @@ import org.junit.Test; public class BiconditionalIntroductionTest { - private static final DirectRuleBiconditionalIntroduction RULE = - new DirectRuleBiconditionalIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleBiconditionalIntroduction RULE = + new DirectRuleBiconditionalIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A <-> B - * - *

Asserts that if setting <-> to false is a valid application of this rule if and only if A - * and B do not match. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; + /** + * Given a statement: A <-> B + * + *

Asserts that if setting <-> to false is a valid application of this rule if and only if A + * and B do not match. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - System.out.println(a + b); - falseConditionalHelper(path + a + "U" + b); - } - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + System.out.println(a + b); + falseConditionalHelper(path + a + "U" + b); + } } + } - private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() != b.getType()) { - // Not valid if they don't match but at least one of the values of A or B is unknown - if (a.getType() == ShortTruthTableCellType.UNKNOWN - || b.getType() == ShortTruthTableCellType.UNKNOWN) { - Assert.assertNotNull(RULE.checkRule(transition)); - } else { - Assert.assertNull(RULE.checkRule(transition)); - } - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() != b.getType()) { + // Not valid if they don't match but at least one of the values of A or B is unknown + if (a.getType() == ShortTruthTableCellType.UNKNOWN + || b.getType() == ShortTruthTableCellType.UNKNOWN) { + Assert.assertNotNull(RULE.checkRule(transition)); + } else { + Assert.assertNull(RULE.checkRule(transition)); + } + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } - /** - * Given a statement: A <-> B - * - *

Asserts that if setting <-> to true is a valid application of this rule if and only if A - * and B match. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; + /** + * Given a statement: A <-> B + * + *

Asserts that if setting <-> to true is a valid application of this rule if and only if A and + * B match. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - System.out.println(a + b); - trueConditionalHelper(path + a + "U" + b); - } - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + System.out.println(a + b); + trueConditionalHelper(path + a + "U" + b); + } } + } - private void trueConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == b.getType() && a.getType() != ShortTruthTableCellType.UNKNOWN) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == b.getType() && a.getType() != ShortTruthTableCellType.UNKNOWN) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java index 0f95906f2..7574ce337 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java @@ -15,237 +15,229 @@ import org.junit.Test; public class ConditionalEliminationTest { - private static final DirectRuleConditionalElimination RULE = - new DirectRuleConditionalElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that the only valid combination of A and B that is a valid application of this - * rule is when A is true and B is false - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - ShortTruthTableCell boniato = board.getCell(2, 0); - - aubergine.setData(cellType1); - boniato.setData(cellType2); - - board.addModifiedData(aubergine); - board.addModifiedData(boniato); - - if (cellType1 == ShortTruthTableCellType.TRUE - && cellType2 == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that this is a valid application of the rule if and only if A is set to true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + private static final DirectRuleConditionalElimination RULE = + new DirectRuleConditionalElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that the only valid combination of A and B that is a valid application of this rule + * is when A is true and B is false + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell aubergine = board.getCell(0, 0); - - aubergine.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(aubergine); - Assert.assertNull(RULE.checkRule(transition)); - - aubergine.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(aubergine); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that this is a valid application of the rule if and only if B is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell boniato = board.getCell(2, 0); - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNull(RULE.checkRule(transition)); + aubergine.setData(cellType1); + boniato.setData(cellType2); - boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(aubergine); board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } - /** - * Given one statement: A -> B where -> is true - * - *

Asserts that you cannot set any combination of both A and B at the same time. - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAandBTrueConditionalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditional", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - ShortTruthTableCell boniato = board.getCell(2, 0); - - aubergine.setData(cellType1); - boniato.setData(cellType2); - - board.addModifiedData(aubergine); - board.addModifiedData(boniato); - - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType1 == ShortTruthTableCellType.TRUE + && cellType2 == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } } - - /** - * Given one statement: A -> B where A and -> are true - * - *

Asserts that this is a valid application of this rule if and only if B is set to true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueAMeansTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(boniato); - Assert.assertNull(RULE.checkRule(transition)); - - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where B is false and -> is true - * - *

Asserts that this is a valid application of this rule if and only if A is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBMeansFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that this is a valid application of the rule if and only if A is set to true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); + + aubergine.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(aubergine); + Assert.assertNull(RULE.checkRule(transition)); + + aubergine.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(aubergine); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that this is a valid application of the rule if and only if B is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where -> is true + * + *

Asserts that you cannot set any combination of both A and B at the same time. + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAandBTrueConditionalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditional", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell aubergine = board.getCell(0, 0); + ShortTruthTableCell boniato = board.getCell(2, 0); - aubergine.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(aubergine); - Assert.assertNull(RULE.checkRule(transition)); + aubergine.setData(cellType1); + boniato.setData(cellType2); - aubergine.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(aubergine); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where B and -> are true - * - *

Asserts that this is not a valid application of this rule no matter what A is set to. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBCannotDetermineA() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); Assert.assertNotNull(RULE.checkRule(transition)); + } } + } + + /** + * Given one statement: A -> B where A and -> are true + * + *

Asserts that this is a valid application of this rule if and only if B is set to true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueAMeansTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(boniato); + Assert.assertNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where B is false and -> is true + * + *

Asserts that this is a valid application of this rule if and only if A is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBMeansFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); + + aubergine.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(aubergine); + Assert.assertNull(RULE.checkRule(transition)); + + aubergine.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(aubergine); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where B and -> are true + * + *

Asserts that this is not a valid application of this rule no matter what A is set to. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBCannotDetermineA() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java index 1bc28373d..5eea810a7 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java @@ -15,97 +15,97 @@ import org.junit.Test; public class ConditionalIntroductionTest { - private static final DirectRuleConditionalIntroduction RULE = - new DirectRuleConditionalIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleConditionalIntroduction RULE = + new DirectRuleConditionalIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A -> B - * - *

Asserts that if setting -> to false is a valid application of this rule if and only if A - * is true and B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; + /** + * Given a statement: A -> B + * + *

Asserts that if setting -> to false is a valid application of this rule if and only if A is + * true and B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - falseConditionalHelper(path + a + "U" + b); - } - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + falseConditionalHelper(path + a + "U" + b); + } } + } - private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == ShortTruthTableCellType.TRUE - && b.getType() == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == ShortTruthTableCellType.TRUE + && b.getType() == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } - /** - * Given a statement: A -> B - * - *

Asserts that if setting -> to true is a valid application of this rule if and only if A is - * false or B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; + /** + * Given a statement: A -> B + * + *

Asserts that if setting -> to true is a valid application of this rule if and only if A is + * false or B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - trueConditionalTestHelper(path + a + "U" + b); - } - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + trueConditionalTestHelper(path + a + "U" + b); + } } + } - private void trueConditionalTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueConditionalTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == ShortTruthTableCellType.FALSE - || b.getType() == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == ShortTruthTableCellType.FALSE + || b.getType() == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java index 589e3cfb9..9caf2414a 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java @@ -15,120 +15,116 @@ import org.junit.Test; public class NotEliminationTest { - private static final DirectRuleNotElimination RULE = new DirectRuleNotElimination(); - private static ShortTruthTable stt; + private static final DirectRuleNotElimination RULE = new DirectRuleNotElimination(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given one statement: ¬A where ¬ is false - * - *

Asserts that this is a valid application of this rule if and only if A is true - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotEliminationDirectRule/FalseNot", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Given one statement: ¬A where ¬ is false + * + *

Asserts that this is a valid application of this rule if and only if A is true + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotEliminationDirectRule/FalseNot", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(1, 0); - a.setData(cellType); - board.addModifiedData(a); + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(1, 0); + a.setData(cellType); + board.addModifiedData(a); - if (cellType == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + if (cellType == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } - /** - * Given one statement: ¬A where ¬ is true - * - *

Asserts that this is a valid application of this rule if and only if A is false - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotEliminationDirectRule/TrueNot", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Given one statement: ¬A where ¬ is true + * + *

Asserts that this is a valid application of this rule if and only if A is false + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotEliminationDirectRule/TrueNot", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(1, 0); - a.setData(cellType); - board.addModifiedData(a); + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(1, 0); + a.setData(cellType); + board.addModifiedData(a); - if (cellType == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + if (cellType == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } - // /** - // * Given one statement: ¬A - // * - // * Asserts that setting both ¬ and A to any values would not be a valid - // * application of this rule - // * - // * @throws InvalidFileFormatException - // */ - // @Test - // public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { - // - // TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/BlankNot", stt); - // TreeNode rootNode = stt.getTree().getRootNode(); - // TreeTransition transition = rootNode.getChildren().get(0); - // transition.setRule(RULE); - // - // ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, - // ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - // - // for (ShortTruthTableCellType cellType1 : cellTypes) { - // for (ShortTruthTableCellType cellType2 : cellTypes) { - // ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - // ShortTruthTableCell not = board.getCell(0, 0); - // ShortTruthTableCell a = board.getCell(1, 0); - // - // not.setData(cellType1); - // a.setData(cellType2); - // - // board.addModifiedData(not); - // board.addModifiedData(a); - // - // System.out.println("TYPE1:" + cellType1); - // System.out.println("TYPE2:" + cellType2); - // Assert.assertNotNull(RULE.checkRule(transition)); - // } - // } - // } + // /** + // * Given one statement: ¬A + // * + // * Asserts that setting both ¬ and A to any values would not be a valid + // * application of this rule + // * + // * @throws InvalidFileFormatException + // */ + // @Test + // public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { + // + // TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/BlankNot", stt); + // TreeNode rootNode = stt.getTree().getRootNode(); + // TreeTransition transition = rootNode.getChildren().get(0); + // transition.setRule(RULE); + // + // ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, + // ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; + // + // for (ShortTruthTableCellType cellType1 : cellTypes) { + // for (ShortTruthTableCellType cellType2 : cellTypes) { + // ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + // ShortTruthTableCell not = board.getCell(0, 0); + // ShortTruthTableCell a = board.getCell(1, 0); + // + // not.setData(cellType1); + // a.setData(cellType2); + // + // board.addModifiedData(not); + // board.addModifiedData(a); + // + // System.out.println("TYPE1:" + cellType1); + // System.out.println("TYPE2:" + cellType2); + // Assert.assertNotNull(RULE.checkRule(transition)); + // } + // } + // } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java index e338fb9bd..9949651eb 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java @@ -15,121 +15,115 @@ import org.junit.Test; public class NotIntroductionTest { - private static final DirectRuleNotIntroduction RULE = new DirectRuleNotIntroduction(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); + private static final DirectRuleNotIntroduction RULE = new DirectRuleNotIntroduction(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: ¬A where A is false + * + *

Asserts that this is a valid application of this rule if and only if ¬ is true + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + not.setData(cellType); + board.addModifiedData(not); + + if (cellType == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - - /** - * Given one statement: ¬A where A is false - * - *

Asserts that this is a valid application of this rule if and only if ¬ is true - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - not.setData(cellType); - board.addModifiedData(not); - - if (cellType == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + } + + /** + * Given one statement: ¬A where A is true + * + *

Asserts that this is a valid application of this rule if and only if ¬ is false + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/TrueA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + not.setData(cellType); + board.addModifiedData(not); + + if (cellType == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - - /** - * Given one statement: ¬A where A is true - * - *

Asserts that this is a valid application of this rule if and only if ¬ is false - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/TrueA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - not.setData(cellType); - board.addModifiedData(not); - - if (cellType == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - - /** - * Given one statement: ¬A - * - *

Asserts that setting both ¬ and A to any values would not be a valid application of this - * rule - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/BlankA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - ShortTruthTableCell a = board.getCell(1, 0); - - not.setData(cellType1); - a.setData(cellType2); - - board.addModifiedData(not); - board.addModifiedData(a); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + } + + /** + * Given one statement: ¬A + * + *

Asserts that setting both ¬ and A to any values would not be a valid application of this + * rule + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/BlankA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + ShortTruthTableCell a = board.getCell(1, 0); + + not.setData(cellType1); + a.setData(cellType2); + + board.addModifiedData(not); + board.addModifiedData(a); + + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java index 0bfa6fc6e..a2cc2abc0 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java @@ -18,142 +18,142 @@ public class OrCaseRuleTest { - private static final CaseRuleOr RULE = new CaseRuleOr(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - private void trueOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); - - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); - ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); - - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); - ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); - - // Assert that the corresponding cells for the different case rules do not - // match with each other - Assert.assertNotEquals(board1A, board2A); - Assert.assertNotEquals(board1B, board2B); - - // First assert the two cells are not equal, then verify that they are either - // unknown or false. - Assert.assertNotEquals(board1A, board1B); - Assert.assertTrue( - board1A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.TRUE)); - Assert.assertTrue( - board1B.equals(ShortTruthTableCellType.UNKNOWN) - || board1B.equals(ShortTruthTableCellType.TRUE)); - - Assert.assertNotEquals(board2A, board2B); - Assert.assertTrue( - board2A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.TRUE)); - Assert.assertTrue( - board2B.equals(ShortTruthTableCellType.UNKNOWN) - || board2B.equals(ShortTruthTableCellType.TRUE)); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the two cells that should be different - if (!((i == aX && j == aY) || (i == bX && j == bY))) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); - } - } + private static final CaseRuleOr RULE = new CaseRuleOr(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + private void trueOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); + + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); + ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); + + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); + ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); + + // Assert that the corresponding cells for the different case rules do not + // match with each other + Assert.assertNotEquals(board1A, board2A); + Assert.assertNotEquals(board1B, board2B); + + // First assert the two cells are not equal, then verify that they are either + // unknown or false. + Assert.assertNotEquals(board1A, board1B); + Assert.assertTrue( + board1A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.TRUE)); + Assert.assertTrue( + board1B.equals(ShortTruthTableCellType.UNKNOWN) + || board1B.equals(ShortTruthTableCellType.TRUE)); + + Assert.assertNotEquals(board2A, board2B); + Assert.assertTrue( + board2A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.TRUE)); + Assert.assertTrue( + board2B.equals(ShortTruthTableCellType.UNKNOWN) + || board2B.equals(ShortTruthTableCellType.TRUE)); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the two cells that should be different + if (!((i == aX && j == aY) || (i == bX && j == bY))) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); } + } } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches - * are created: one where A is false and one where B is false. - */ - @Test - public void SimpleStatement1TrueTest() throws InvalidFileFormatException { - trueOrTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring - * that two branches are created: one where ~ is false and one where the second ^ is false. - */ - @Test - public void ComplexStatement1TrueTest() throws InvalidFileFormatException { - trueOrTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); - } - - private void falseOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // There should only be 1 branch - Assert.assertEquals(1, cases.size()); - - ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); - ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); - - // Both cells should be true - Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.FALSE); - Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.FALSE); - Assert.assertEquals(caseBoardAType, caseBoardBType); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is - * created where A and B are both true. - */ - @Test - public void SimpleStatement1FalseTest() throws InvalidFileFormatException { - falseOrTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring - * that one branch is created where both ~ and the second ^ are true. - */ - @Test - public void ComplexStatement1FalseTest() throws InvalidFileFormatException { - falseOrTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); - } + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches + * are created: one where A is false and one where B is false. + */ + @Test + public void SimpleStatement1TrueTest() throws InvalidFileFormatException { + trueOrTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring + * that two branches are created: one where ~ is false and one where the second ^ is false. + */ + @Test + public void ComplexStatement1TrueTest() throws InvalidFileFormatException { + trueOrTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); + } + + private void falseOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // There should only be 1 branch + Assert.assertEquals(1, cases.size()); + + ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); + ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); + + // Both cells should be true + Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.FALSE); + Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.FALSE); + Assert.assertEquals(caseBoardAType, caseBoardBType); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is + * created where A and B are both true. + */ + @Test + public void SimpleStatement1FalseTest() throws InvalidFileFormatException { + falseOrTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring that + * one branch is created where both ~ and the second ^ are true. + */ + @Test + public void ComplexStatement1FalseTest() throws InvalidFileFormatException { + falseOrTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java index e4efad465..b678b6610 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java @@ -15,148 +15,139 @@ import org.junit.Test; public class OrEliminationTest { - private static final DirectRuleOrElimination RULE = new DirectRuleOrElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given a statement: A V B, where A is false and V is true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FTUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/OrEliminationDirectRule/FTU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - + private static final DirectRuleOrElimination RULE = new DirectRuleOrElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given a statement: A V B, where A is false and V is true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FTUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/FTU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(2, 0); + + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + Assert.assertNull(RULE.checkRule(transition)); + + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given a statement: A V B, where B is false and V is true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void UTFTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTF", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(0, 0); + + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + Assert.assertNull(RULE.checkRule(transition)); + + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given a statement: A V B, where V is false + * + *

Asserts that this is a valid application of the rule if and only if both A and B are false. + * + * @throws InvalidFileFormatException + */ + @Test + public void UFUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UFU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(2, 0); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + a.setData(cellType1); + b.setData(cellType2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given a statement: A V B, where B is false and V is true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void UTFTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTF", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + board.addModifiedData(a); + board.addModifiedData(b); + if (cellType1 == ShortTruthTableCellType.FALSE + && cellType2 == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + } + + /** + * Given a statement: A V B, where V is true + * + *

Asserts that setting both A and B is not a valid application of this rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void UTUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(0, 0); - - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); - } + a.setData(cellType1); + b.setData(cellType2); - /** - * Given a statement: A V B, where V is false - * - *

Asserts that this is a valid application of the rule if and only if both A and B are - * false. - * - * @throws InvalidFileFormatException - */ - @Test - public void UFUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UFU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - - a.setData(cellType1); - b.setData(cellType2); - - board.addModifiedData(a); - board.addModifiedData(b); - - if (cellType1 == ShortTruthTableCellType.FALSE - && cellType2 == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - } + board.addModifiedData(a); + board.addModifiedData(b); - /** - * Given a statement: A V B, where V is true - * - *

Asserts that setting both A and B is not a valid application of this rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void UTUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, - ShortTruthTableCellType.FALSE, - ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - - a.setData(cellType1); - b.setData(cellType2); - - board.addModifiedData(a); - board.addModifiedData(b); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java index d5f9387eb..67a111da7 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java @@ -15,91 +15,91 @@ import org.junit.Test; public class OrIntroductionTest { - private static final DirectRuleOrIntroduction RULE = new DirectRuleOrIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleOrIntroduction RULE = new DirectRuleOrIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A V B - * - *

Asserts that if at least 1 of A or B is true, then this is a valid application of the rule - * if and only if V is true. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void TrueOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; - trueOrTestHelper(path + "TUT"); - trueOrTestHelper(path + "TUU"); - trueOrTestHelper(path + "UUT"); - trueOrTestHelper(path + "TUF"); - trueOrTestHelper(path + "FUT"); - } + /** + * Given a statement: A V B + * + *

Asserts that if at least 1 of A or B is true, then this is a valid application of the rule + * if and only if V is true. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void TrueOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; + trueOrTestHelper(path + "TUT"); + trueOrTestHelper(path + "TUU"); + trueOrTestHelper(path + "UUT"); + trueOrTestHelper(path + "TUF"); + trueOrTestHelper(path + "FUT"); + } - private void trueOrTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueOrTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell or = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell or = board.getCell(1, 0); - or.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(or); - Assert.assertNull(RULE.checkRule(transition)); + or.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(or); + Assert.assertNull(RULE.checkRule(transition)); - or.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(or); - Assert.assertNotNull(RULE.checkRule(transition)); - } + or.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(or); + Assert.assertNotNull(RULE.checkRule(transition)); + } - /** - * Given a statement: A V B - * - *

Asserts that setting V to false is a valid application of the rule if and only if both A - * and B are false. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String first : letters) { - for (String second : letters) { - falseOrTestHelper(path + first + "U" + second); - } - } + /** + * Given a statement: A V B + * + *

Asserts that setting V to false is a valid application of the rule if and only if both A and + * B are false. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; + String[] letters = {"T", "F", "U"}; + for (String first : letters) { + for (String second : letters) { + falseOrTestHelper(path + first + "U" + second); + } } + } - private void falseOrTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseOrTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - ShortTruthTableCell or = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell or = board.getCell(1, 0); - or.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(or); + or.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(or); - if (a.getType() == ShortTruthTableCellType.FALSE - && b.getType() == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (a.getType() == ShortTruthTableCellType.FALSE + && b.getType() == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java index d0c390785..3a9c749e7 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java @@ -18,66 +18,66 @@ public class TrueOrFalseCaseRuleTest { - private static final CaseRuleAtomic RULE = new CaseRuleAtomic(); - private static ShortTruthTable stt; + private static final CaseRuleAtomic RULE = new CaseRuleAtomic(); + private static ShortTruthTable stt; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Tests the True or False case rule by ensuring that it results in two children, one that - * contains Statement as true and one that contains Statement as false. - */ - @Test - public void TwoBranchesTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/TrueOrFalseCaseRule/Statement", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the True or False case rule by ensuring that it results in two children, one that + * contains Statement as true and one that contains Statement as false. + */ + @Test + public void TwoBranchesTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/TrueOrFalseCaseRule/Statement", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, cell); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, cell); - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType cellType1 = caseBoard1.getCell(0, 0).getType(); - ShortTruthTableCellType cellType2 = caseBoard2.getCell(0, 0).getType(); + ShortTruthTableCellType cellType1 = caseBoard1.getCell(0, 0).getType(); + ShortTruthTableCellType cellType2 = caseBoard2.getCell(0, 0).getType(); - // First assert the two cells are not equal, then verify that they are true - // or false. - Assert.assertNotEquals(cellType1, cellType2); - Assert.assertTrue( - cellType1.equals(ShortTruthTableCellType.TRUE) - || cellType1.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - cellType2.equals(ShortTruthTableCellType.TRUE) - || cellType2.equals(ShortTruthTableCellType.FALSE)); + // First assert the two cells are not equal, then verify that they are true + // or false. + Assert.assertNotEquals(cellType1, cellType2); + Assert.assertTrue( + cellType1.equals(ShortTruthTableCellType.TRUE) + || cellType1.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + cellType2.equals(ShortTruthTableCellType.TRUE) + || cellType2.equals(ShortTruthTableCellType.FALSE)); - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the one cell that should be different - if (i != 0 && j != 0) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); - } - } + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the one cell that should be different + if (i != 0 && j != 0) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); } + } } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java b/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java index 1fce24cf1..598e9fd9c 100644 --- a/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java @@ -17,242 +17,238 @@ public class CellForNumberCaseRuleTest { - private static final CellForNumberCaseRule RULE = new CellForNumberCaseRule(); - private static Skyscrapers skyscrapers; + private static final CellForNumberCaseRule RULE = new CellForNumberCaseRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // basic, max cases - @Test - public void CellForNumberCaseRule_BasicEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // basic, max cases + @Test + public void CellForNumberCaseRule_BasicEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(false); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); + board.setDupeFlag(false); + board.setViewFlag(false); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, i); - changedCell.setData(1); - expected.addModifiedData(changedCell); + Assert.assertEquals(board.getWidth(), cases.size()); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, i); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(exists); + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; } - } + } - // dupe, max cases - @Test - public void CellForNumberCaseRule_DupeEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + Assert.assertTrue(exists); + } + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // dupe, max cases + @Test + public void CellForNumberCaseRule_DupeEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(true); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, i); - changedCell.setData(1); - expected.addModifiedData(changedCell); + Assert.assertEquals(board.getWidth(), cases.size()); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, i); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(exists); + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; } - } + } - // dupe, 1 case - @Test - public void CellForNumberCaseRule_DupeSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + Assert.assertTrue(exists); + } + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // dupe, 1 case + @Test + public void CellForNumberCaseRule_DupeSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(true); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(1, cases.size()); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + Assert.assertEquals(1, cases.size()); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - // dupe, no cases - @Test - public void CellForNumberCaseRule_DupeNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", - skyscrapers); + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // dupe, no cases + @Test + public void CellForNumberCaseRule_DupeNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(true); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(0, cases.size()); - } + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - // visibility, max cases - @Test - public void CellForNumberCaseRule_ViewEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + Assert.assertEquals(0, cases.size()); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // visibility, max cases + @Test + public void CellForNumberCaseRule_ViewEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(false); - board.setViewFlag(true); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(1), 1); + board.setDupeFlag(false); + board.setViewFlag(true); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(1), 1); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(i, 1); - changedCell.setData(1); - expected.addModifiedData(changedCell); + Assert.assertEquals(board.getWidth(), cases.size()); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(i, 1); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(exists); + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; } + } + + Assert.assertTrue(exists); } + } - // visibility, 1 Case, direct - @Test - public void CellForNumberCaseRule_ViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // visibility, 1 Case, direct + @Test + public void CellForNumberCaseRule_ViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, 1 Case, implied - @Test - public void CellForNumberCaseRule_ImpliedViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // visibility, 1 Case, implied + @Test + public void CellForNumberCaseRule_ImpliedViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(0), 5); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(0), 5); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(4, 0); - changedCell.setData(5); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(4, 0); + changedCell.setData(5); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, no cases - @Test - public void CellForNumberCaseRule_ViewNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", - skyscrapers); + // visibility, no cases + @Test + public void CellForNumberCaseRule_ViewNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - Assert.assertEquals(0, cases.size()); - } + Assert.assertEquals(0, cases.size()); + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java index a7bb63a08..cf74604f8 100644 --- a/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java @@ -14,149 +14,143 @@ public class DuplicateNumberContradictionTest { - private static final DuplicateNumberContradictionRule RULE = - new DuplicateNumberContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); + private static final DuplicateNumberContradictionRule RULE = + new DuplicateNumberContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // empty + @Test + public void DuplicateNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } - // empty - @Test - public void DuplicateNumberContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // correct board, no cont + @Test + public void DuplicateNumberContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - // correct board, no cont - @Test - public void DuplicateNumberContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // invalid board, no cont + @Test + public void DuplicateNumberContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - // invalid board, no cont - @Test - public void DuplicateNumberContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + } + + // on row + @Test + public void DuplicateNumberContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if ((k == 0 || k == 1) && i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // on row - @Test - public void DuplicateNumberContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if ((k == 0 || k == 1) && i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - } - - // on col - @Test - public void DuplicateNumberContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/ColContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 0 && (i == 0 || i == 1)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // on col + @Test + public void DuplicateNumberContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/ColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 0 && (i == 0 || i == 1)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // multitudes - @Test - public void DuplicateNumberContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/AllContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // multitudes + @Test + public void DuplicateNumberContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/AllContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java index a5a07f997..5fbadf555 100644 --- a/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java @@ -14,137 +14,133 @@ public class ExceedingVisibilityContradictionTest { - private static final ExceedingVisibilityContradictionRule RULE = - new ExceedingVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); + private static final ExceedingVisibilityContradictionRule RULE = + new ExceedingVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // empty + @Test + public void ExceedingVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // empty - @Test - public void ExceedingVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // correct board, no cont + @Test + public void ExceedingVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // correct board, no cont - @Test - public void ExceedingVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // invalid board, no cont + @Test + public void ExceedingVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } - - // invalid board, no cont - @Test - public void ExceedingVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + } + + // on row + @Test + public void ExceedingVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - // on row - @Test - public void ExceedingVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } - } - - // on col - @Test - public void ExceedingVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on col + @Test + public void ExceedingVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } + } - // multitudes - @Test - public void ExceedingVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", - skyscrapers); + // multitudes + @Test + public void ExceedingVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java index ee0f3349a..a59fa3746 100644 --- a/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java @@ -14,137 +14,133 @@ public class InsufficientVisibilityContradictionTest { - private static final InsufficientVisibilityContradictionRule RULE = - new InsufficientVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); + private static final InsufficientVisibilityContradictionRule RULE = + new InsufficientVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // empty + @Test + public void InsufficientVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // empty - @Test - public void InsufficientVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // correct board, no cont + @Test + public void InsufficientVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // correct board, no cont - @Test - public void InsufficientVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // invalid board, no cont + @Test + public void InsufficientVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } - - // invalid board, no cont - @Test - public void InsufficientVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + } + + // on row + @Test + public void InsufficientVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - // on row - @Test - public void InsufficientVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } - } - - // on col - @Test - public void InsufficientVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on col + @Test + public void InsufficientVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } + } - // multitudes - @Test - public void InsufficientVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", - skyscrapers); + // multitudes + @Test + public void InsufficientVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java index 76540f010..78ba581b9 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java @@ -16,215 +16,213 @@ public class LastSingularCellDirectTest { - private static final LastSingularCellDirectRule RULE = new LastSingularCellDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastSingularCellDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastSingularCellDirectRule RULE = new LastSingularCellDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastSingularCellDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // full col - @Test - public void LastSingularCellDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // full col + @Test + public void LastSingularCellDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // empty row/col - @Test - public void LastSingularCellDirectRule_EmptyTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/0-3Opening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 1); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty row/col + @Test + public void LastSingularCellDirectRule_EmptyTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/0-3Opening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 1); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2-1 row - @Test - public void LastSingularCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 row + @Test + public void LastSingularCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2-1 col - @Test - public void LastSingularCellDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 col + @Test + public void LastSingularCellDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 1-2 row - @Test - public void LastSingularCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 row + @Test + public void LastSingularCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 1-2 col - @Test - public void LastSingularCellDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 0); - cell.setData(4); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 col + @Test + public void LastSingularCellDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 0); + cell.setData(4); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java index 6b99994a2..5cecb9b4c 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java @@ -16,132 +16,126 @@ public class LastSingularNumberDirectTest { - private static final LastSingularNumberDirectRule RULE = new LastSingularNumberDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row / empty col - @Test - public void LastSingularNumberDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastSingularNumberDirectRule RULE = new LastSingularNumberDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row / empty col + @Test + public void LastSingularNumberDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // full col / empty row - @Test - public void LastSingularNumberDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // full col / empty row + @Test + public void LastSingularNumberDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2-1 row / 1-2 col - @Test - public void LastSingularNumberDirectRule_PartialRowColTest1() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1RowOpening", - skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 1); - cell.setData(4); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 row / 1-2 col + @Test + public void LastSingularNumberDirectRule_PartialRowColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 1); + cell.setData(4); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2-1 col / 1-2 row - @Test - public void LastSingularNumberDirectRule_PartialRowColTest2() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1ColOpening", - skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 col / 1-2 row + @Test + public void LastSingularNumberDirectRule_PartialRowColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java index 756ff7468..3fe530a32 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java @@ -16,238 +16,236 @@ public class LastVisibleCellDirectTest { - private static final LastVisibleCellDirectRule RULE = new LastVisibleCellDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastVisibleCellDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastVisibleCellDirectRule RULE = new LastVisibleCellDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastVisibleCellDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // full col - @Test - public void LastVisibleCellDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // full col + @Test + public void LastVisibleCellDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // empty row - @Test - public void LastVisibleCellDirectRule_EmptyRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty row + @Test + public void LastVisibleCellDirectRule_EmptyRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // empty col - @Test - public void LastVisibleCellDirectRule_EmptyColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 4); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty col + @Test + public void LastVisibleCellDirectRule_EmptyColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 4); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 1-2 row - public void LastVisibleCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 row + public void LastVisibleCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 1-2 col - public void LastVisibleCellDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 2); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 col + public void LastVisibleCellDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 2); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2-1 row - public void LastVisibleCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 row + public void LastVisibleCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2-1 col - public void LastVisibleCellDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 col + public void LastVisibleCellDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java index c628b89da..65311f2ca 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java @@ -16,238 +16,236 @@ public class LastVisibleNumberDirectTest { - private static final LastVisibleNumberDirectRule RULE = new LastVisibleNumberDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastVisibleNumberDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastVisibleNumberDirectRule RULE = new LastVisibleNumberDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastVisibleNumberDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // full col - @Test - public void LastVisibleNumberDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // full col + @Test + public void LastVisibleNumberDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // empty row - @Test - public void LastVisibleNumberDirectRule_EmptyRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty row + @Test + public void LastVisibleNumberDirectRule_EmptyRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // empty col - @Test - public void LastVisibleNumberDirectRule_EmptyColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 4); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // empty col + @Test + public void LastVisibleNumberDirectRule_EmptyColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 4); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 1-2 row - public void LastVisibleNumberDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 row + public void LastVisibleNumberDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 1-2 col - public void LastVisibleNumberDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 2); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 1-2 col + public void LastVisibleNumberDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 2); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2-1 row - public void LastVisibleNumberDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 row + public void LastVisibleNumberDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2-1 col - public void LastVisibleNumberDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2-1 col + public void LastVisibleNumberDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java index ed70fce40..2ba6d7ad7 100644 --- a/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java @@ -16,127 +16,127 @@ public class NEdgeDirectTest { - private static final NEdgeDirectRule RULE = new NEdgeDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); + private static final NEdgeDirectRule RULE = new NEdgeDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // -> row, empty -> full + @Test + public void NEdgeDirectRule_RightRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < 5; i++) { + SkyscrapersCell cell = board.getCell(i, 0); + cell.setData(i + 1); + board.addModifiedData(cell); } - // -> row, empty -> full - @Test - public void NEdgeDirectRule_RightRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < 5; i++) { - SkyscrapersCell cell = board.getCell(i, 0); - cell.setData(i + 1); - board.addModifiedData(cell); - } - - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // <-row, partial -> partial - @Test - public void NEdgeDirectRule_LeftRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/LeftRowPartial", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 3); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // <-row, partial -> partial + @Test + public void NEdgeDirectRule_LeftRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/LeftRowPartial", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 3); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } + } + } + + // up col, partial -> full + @Test + public void NEdgeDirectRule_UpColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/UpColPartial", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < 2; i++) { + SkyscrapersCell cell = board.getCell(1, i); + cell.setData(i + 1); + board.addModifiedData(cell); } - // up col, partial -> full - @Test - public void NEdgeDirectRule_UpColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/UpColPartial", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < 2; i++) { - SkyscrapersCell cell = board.getCell(1, i); - cell.setData(i + 1); - board.addModifiedData(cell); - } - - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 1 && i < 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 1 && i < 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } + } + } + + // down col, empty -> partial + @Test + public void NEdgeDirectRule_DownColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/DownColEmpty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 1; i < 5; i++) { + SkyscrapersCell cell = board.getCell(3, i); + cell.setData(5 - i); + board.addModifiedData(cell); } - // down col, empty -> partial - @Test - public void NEdgeDirectRule_DownColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/DownColEmpty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 1; i < 5; i++) { - SkyscrapersCell cell = board.getCell(3, i); - cell.setData(5 - i); - board.addModifiedData(cell); - } - - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 3 && i > 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 3 && i > 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java b/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java index b417a5227..f4a298c7c 100644 --- a/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java @@ -17,216 +17,212 @@ public class NumberForCellCaseRuleTest { - private static final NumberForCellCaseRule RULE = new NumberForCellCaseRule(); - private static Skyscrapers skyscrapers; + private static final NumberForCellCaseRule RULE = new NumberForCellCaseRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // basic, max cases - @Test - public void NumberForCellCaseRule_BasicEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // basic, max cases + @Test + public void NumberForCellCaseRule_BasicEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(false); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); + board.setDupeFlag(false); + board.setViewFlag(false); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, 0); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + Assert.assertEquals(board.getWidth(), cases.size()); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, 0); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - Assert.assertTrue(exists); + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; } - } + } - // dupe, max cases - @Test - public void NumberForCellCaseRule_DupeEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + Assert.assertTrue(exists); + } + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // dupe, max cases + @Test + public void NumberForCellCaseRule_DupeEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(true); - board.setViewFlag(false); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); + board.setDupeFlag(true); + board.setViewFlag(false); - Assert.assertEquals(board.getWidth(), cases.size()); + ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, 0); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + Assert.assertEquals(board.getWidth(), cases.size()); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, 0); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - Assert.assertTrue(exists); + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; } + } + + Assert.assertTrue(exists); } + } - // dupe, 1 case - @Test - public void NumberForCellCaseRule_DupeSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // dupe, 1 case + @Test + public void NumberForCellCaseRule_DupeSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // dupe, no cases - @Test - public void NumberForCellCaseRule_DupeNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", - skyscrapers); + // dupe, no cases + @Test + public void NumberForCellCaseRule_DupeNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(0, cases.size()); - } - - // visibility, max cases - @Test - public void NumberForCellCaseRule_ViewEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + Assert.assertEquals(0, cases.size()); + } - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // visibility, max cases + @Test + public void NumberForCellCaseRule_ViewEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.setDupeFlag(false); - board.setViewFlag(true); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - ArrayList cases = RULE.getCases(board, board.getCell(1, 4)); + board.setDupeFlag(false); + board.setViewFlag(true); - Assert.assertEquals(4, cases.size()); + ArrayList cases = RULE.getCases(board, board.getCell(1, 4)); - for (int i = 0; i < board.getWidth() - 1; i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(1, 4); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + Assert.assertEquals(4, cases.size()); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + for (int i = 0; i < board.getWidth() - 1; i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(1, 4); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - Assert.assertTrue(exists); + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; } + } + + Assert.assertTrue(exists); } + } - // visibility, 1 case - @Test - public void NumberForCellCaseRule_ViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // visibility, 1 case + @Test + public void NumberForCellCaseRule_ViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, no cases - @Test - public void NumberForCellCaseRule_ViewNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", - skyscrapers); + // visibility, no cases + @Test + public void NumberForCellCaseRule_ViewNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(0, cases.size()); - } + Assert.assertEquals(0, cases.size()); + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java index ec49a8194..b615ce7fb 100644 --- a/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java @@ -14,157 +14,155 @@ public class PreemptiveVisibilityContradictionTest { - private static final PreemptiveVisibilityContradictionRule RULE = - new PreemptiveVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); + private static final PreemptiveVisibilityContradictionRule RULE = + new PreemptiveVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // empty + @Test + public void PreemptiveVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // empty - @Test - public void PreemptiveVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // correct board, no cont + @Test + public void PreemptiveVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // correct board, no cont - @Test - public void PreemptiveVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // invalid board, no cont + @Test + public void PreemptiveVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } - - // invalid board, no cont - @Test - public void PreemptiveVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + } + + // on row + @Test + public void PreemptiveVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - // on row - @Test - public void PreemptiveVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedRowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } - } - - // on col - @Test - public void PreemptiveVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedColContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // on col + @Test + public void PreemptiveVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } + } - // multitudes - @Test - public void PreemptiveVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", - skyscrapers); + // multitudes + @Test + public void PreemptiveVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // multitudes - preemptive - @Test - public void PreemptiveVisibilityContradictionRule_ImpliedAllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); + // multitudes - preemptive + @Test + public void PreemptiveVisibilityContradictionRule_ImpliedAllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java index 398bba6e5..f9509990a 100644 --- a/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java @@ -14,152 +14,147 @@ public class UnresolvedCellContradictionTest { - private static final UnresolvedCellContradictionRule RULE = - new UnresolvedCellContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); + private static final UnresolvedCellContradictionRule RULE = new UnresolvedCellContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // empty + @Test + public void UnresolvedCellContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } - // empty - @Test - public void UnresolvedCellContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // correct board, no cont + @Test + public void UnresolvedCellContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - - // correct board, no cont - @Test - public void UnresolvedCellContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - // invalid board, no cont - @Test - public void UnresolvedCellContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // invalid board, no cont + @Test + public void UnresolvedCellContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - // 3 in a row, 1 in col creates contradiction - @Test - public void UnresolvedCellContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 2 && i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 3 in a row, 1 in col creates contradiction + @Test + public void UnresolvedCellContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 2 && i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 3 in a col, 1 in row creates contradiction - @Test - public void UnresolvedCellContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 1 && i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 3 in a col, 1 in row creates contradiction + @Test + public void UnresolvedCellContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 1 && i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - // 2 in a col, 2 in row creates cell contradiction - @Test - public void UnresolvedCellContradictionRule_MixedContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 2 && i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + // 2 in a col, 2 in row creates cell contradiction + @Test + public void UnresolvedCellContradictionRule_MixedContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 2 && i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java index 17139fb60..eb6cf566c 100644 --- a/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java @@ -14,165 +14,162 @@ public class UnresolvedNumberContradictionTest { - private static final UnresolvedNumberContradictionRule RULE = - new UnresolvedNumberContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); + private static final UnresolvedNumberContradictionRule RULE = + new UnresolvedNumberContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // empty + @Test + public void UnresolvedNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // empty - @Test - public void UnresolvedNumberContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // correct board, no cont + @Test + public void UnresolvedNumberContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } + } - // correct board, no cont - @Test - public void UnresolvedNumberContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // invalid board, no cont + @Test + public void UnresolvedNumberContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); } - - // invalid board, no cont - @Test - public void UnresolvedNumberContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + } + + // 3 in a row, 1 in col creates contradiction + @Test + public void UnresolvedNumberContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - // 3 in a row, 1 in col creates contradiction - @Test - public void UnresolvedNumberContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // 3 in a col, 1 in row creates contradiction + @Test + public void UnresolvedNumberContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - // 3 in a col, 1 in row creates contradiction - @Test - public void UnresolvedNumberContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } - } - - // 2 in a row/col, 2 in other row/cols creates number contradiction - @Test - public void UnresolvedNumberContradictionRule_TwoContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2NumberContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // 2 in a row/col, 2 in other row/cols creates number contradiction + @Test + public void UnresolvedNumberContradictionRule_TwoContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2NumberContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - - // 1 in a row/col, 3 in other row/cols creates number contradiction - @Test - public void UnresolvedNumberContradictionRule_ThreeContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/1-3NumberContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } - } + } + + // 1 in a row/col, 3 in other row/cols creates number contradiction + @Test + public void UnresolvedNumberContradictionRule_ThreeContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/1-3NumberContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java index 38284c410..df343b6b9 100644 --- a/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java @@ -17,259 +17,259 @@ public class EmptyFieldDirectRuleTest { - private static final EmptyFieldDirectRule RULE = new EmptyFieldDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - // creates a 3x3 puzzle with no trees - // make the (1,1) tile GRASS - // checks if tiles logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyField", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final EmptyFieldDirectRule RULE = new EmptyFieldDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + // creates a 3x3 puzzle with no trees + // make the (1,1) tile GRASS + // checks if tiles logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyField", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - // creates a 3x3 puzzle with 4 trees - // trees are at (0,0), (2,0), (0,2), and (2,2) - // make the (1,1) tile GRASS. - // checks if tiles logically follow the EmptyFieldDirectRule - @Test - public void DiagonalTreeTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/DiagonalTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 4 trees + // trees are at (0,0), (2,0), (0,2), and (2,2) + // make the (1,1) tile GRASS. + // checks if tiles logically follow the EmptyFieldDirectRule + @Test + public void DiagonalTreeTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/DiagonalTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - // creates a 3x3 puzzle with 4 trees - // trees are at (0,1), (1,0), (1,2), and (2,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFail() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 4 trees + // trees are at (0,1), (1,0), (1,2), and (2,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFail() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - - // creates a 3x3 puzzle with 1 tree - // tree is at (1,0) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailTop() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailTop", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 1 tree + // tree is at (1,0) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailTop() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailTop", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - - // creates a 3x3 puzzle with 1 tree - // tree is at (1,2) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailTopBottom() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailBottom", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 1 tree + // tree is at (1,2) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailTopBottom() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailBottom", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - - // creates a 3x3 puzzle with 1 tree - // tree is at (0,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 1 tree + // tree is at (0,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - - // creates a 3x3 puzzle with 1 tree - // tree is at (2,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + // creates a 3x3 puzzle with 1 tree + // tree is at (2,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java index 0783ab8b8..45a1add86 100644 --- a/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java @@ -19,350 +19,350 @@ public class FinishWithGrassDirectRuleTest { - private static final FinishWithGrassDirectRule RULE = new FinishWithGrassDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles - * horizontal of the tent at (1,0) and (2,0) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassHorizontalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final FinishWithGrassDirectRule RULE = new FinishWithGrassDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles + * horizontal of the tent at (1,0) and (2,0) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassHorizontalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles - * vertical of the tent at (0,1) and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassVerticalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles + * vertical of the tent at (0,1) and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassVerticalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles at - * (1,0), (2,0), (0,1), and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.GRASS); - TreeTentCell cell3 = board.getCell(0, 1); - cell3.setData(TreeTentType.GRASS); - TreeTentCell cell4 = board.getCell(0, 2); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles at + * (1,0), (2,0), (0,1), and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.GRASS); + TreeTentCell cell3 = board.getCell(0, 1); + cell3.setData(TreeTentType.GRASS); + TreeTentCell cell4 = board.getCell(0, 2); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } + } + } + + /** + * 3x3 TreeTent puzzle with no tents Tests FinishWithGrassDirectRule on GRASS tiles GRASS tiles + * fill entire board + * + * @throws InvalidFileFormatException + */ + @Test + public void NoTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/NoTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + List cells = new ArrayList(); + for (int i = 0; i < board.getWidth(); i++) { + for (int k = 0; k < board.getHeight(); k++) { + TreeTentCell c = board.getCell(i, k); + c.setData(TreeTentType.GRASS); + cells.add(c); + } } - /** - * 3x3 TreeTent puzzle with no tents Tests FinishWithGrassDirectRule on GRASS tiles GRASS tiles - * fill entire board - * - * @throws InvalidFileFormatException - */ - @Test - public void NoTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/NoTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - List cells = new ArrayList(); - for (int i = 0; i < board.getWidth(); i++) { - for (int k = 0; k < board.getHeight(); k++) { - TreeTentCell c = board.getCell(i, k); - c.setData(TreeTentType.GRASS); - cells.add(c); - } - } - - for (TreeTentCell c : cells) { - board.addModifiedData(c); - } + for (TreeTentCell c : cells) { + board.addModifiedData(c); + } - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); - // all cells should change following the rule - for (TreeTentCell c : cells) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } + // all cells should change following the rule + for (TreeTentCell c : cells) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); } - - /** - * 3x3 TreeTent puzzle with a tent at (1,1) Tests FinishWithGrassDirectRule on GRASS tiles - * surrounding the tent at (1,0), (0,1), (2,1), and (1,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void MiddleTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/MiddleTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(0, 1); - TreeTentCell cell3 = board.getCell(2, 1); - TreeTentCell cell4 = board.getCell(1, 2); - - cell1.setData(TreeTentType.GRASS); - cell2.setData(TreeTentType.GRASS); - cell3.setData(TreeTentType.GRASS); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a tent at (1,1) Tests FinishWithGrassDirectRule on GRASS tiles + * surrounding the tent at (1,0), (0,1), (2,1), and (1,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void MiddleTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/MiddleTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(0, 1); + TreeTentCell cell3 = board.getCell(2, 1); + TreeTentCell cell4 = board.getCell(1, 2); + + cell1.setData(TreeTentType.GRASS); + cell2.setData(TreeTentType.GRASS); + cell3.setData(TreeTentType.GRASS); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } + } + } + + /** + * 3x3 TreeTent puzzle with missing tents Tests FinishWithGrassDirectRule on GRASS tiles filling + * the puzzle all GRASS tiles should fail the FinishWithGrassDirectRule + * + * @throws InvalidFileFormatException + */ + @Test + public void FailTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/FailTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells not following the FinishWithGrass rule + List cells = new ArrayList(); + for (int i = 0; i < board.getWidth(); i++) { + for (int k = 0; k < board.getHeight(); k++) { + TreeTentCell c = board.getCell(i, k); + c.setData(TreeTentType.GRASS); + cells.add(c); + } } - /** - * 3x3 TreeTent puzzle with missing tents Tests FinishWithGrassDirectRule on GRASS tiles filling - * the puzzle all GRASS tiles should fail the FinishWithGrassDirectRule - * - * @throws InvalidFileFormatException - */ - @Test - public void FailTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/FailTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells not following the FinishWithGrass rule - List cells = new ArrayList(); - for (int i = 0; i < board.getWidth(); i++) { - for (int k = 0; k < board.getHeight(); k++) { - TreeTentCell c = board.getCell(i, k); - c.setData(TreeTentType.GRASS); - cells.add(c); - } - } - - for (TreeTentCell c : cells) { - board.addModifiedData(c); - } + for (TreeTentCell c : cells) { + board.addModifiedData(c); + } - // confirm there is a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); + // confirm there is a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); - // all cells should fail the rule test - for (TreeTentCell c : cells) { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + // all cells should fail the rule test + for (TreeTentCell c : cells) { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } - - /** - * 7x7 TreeTent puzzle with multiple tents spaced out Tests FinishWithGrassDirectRule on GRASS - * tiles between the tents at (0,3), (2,3), (4,3), and (6,3) - * - * @throws InvalidFileFormatException - */ - @Test - public void SpacedOutTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/SpacedOutTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(0, 3); - TreeTentCell cell2 = board.getCell(2, 3); - TreeTentCell cell3 = board.getCell(4, 3); - TreeTentCell cell4 = board.getCell(6, 3); - - cell1.setData(TreeTentType.GRASS); - cell2.setData(TreeTentType.GRASS); - cell3.setData(TreeTentType.GRASS); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 7x7 TreeTent puzzle with multiple tents spaced out Tests FinishWithGrassDirectRule on GRASS + * tiles between the tents at (0,3), (2,3), (4,3), and (6,3) + * + * @throws InvalidFileFormatException + */ + @Test + public void SpacedOutTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/SpacedOutTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(0, 3); + TreeTentCell cell2 = board.getCell(2, 3); + TreeTentCell cell3 = board.getCell(4, 3); + TreeTentCell cell4 = board.getCell(6, 3); + + cell1.setData(TreeTentType.GRASS); + cell2.setData(TreeTentType.GRASS); + cell3.setData(TreeTentType.GRASS); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java index 652af615f..9903a9685 100644 --- a/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java @@ -18,337 +18,335 @@ public class FinishWithTentsDirectRuleTest { - private static final FinishWithTentsDirectRule RULE = new FinishWithTentsDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles - * horizontal of the GRASS tile at (1,0) and (2,0) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithHorizontalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithHorizontalTents", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.TENT); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final FinishWithTentsDirectRule RULE = new FinishWithTentsDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles + * horizontal of the GRASS tile at (1,0) and (2,0) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithHorizontalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithHorizontalTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.TENT); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles - * vertical of the GRASS tile at (0,1) and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithVerticalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithVerticalTents", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.TENT); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles + * vertical of the GRASS tile at (0,1) and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithVerticalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithVerticalTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.TENT); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the GRASS tile at (1,0), (1,2), (0,1), and (2,1) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 2); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(2, 1); - - cell1.setData(TreeTentType.TENT); - cell2.setData(TreeTentType.TENT); - cell3.setData(TreeTentType.TENT); - cell4.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation()) - || (c.getLocation()).equals(cell3.getLocation()) - || (c.getLocation()).equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the GRASS tile at (1,0), (1,2), (0,1), and (2,1) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 2); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(2, 1); + + cell1.setData(TreeTentType.TENT); + cell2.setData(TreeTentType.TENT); + cell3.setData(TreeTentType.TENT); + cell4.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation()) + || (c.getLocation()).equals(cell3.getLocation()) + || (c.getLocation()).equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) - * - * @throws InvalidFileFormatException - */ - @Test - public void AdditionalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/AdditionalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 2); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(2, 1); - - cell1.setData(TreeTentType.TENT); - cell2.setData(TreeTentType.TENT); - cell3.setData(TreeTentType.TENT); - cell4.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation()) - || (c.getLocation()).equals(cell3.getLocation()) - || (c.getLocation()).equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + } + + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) + * + * @throws InvalidFileFormatException + */ + @Test + public void AdditionalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/AdditionalTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 2); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(2, 1); + + cell1.setData(TreeTentType.TENT); + cell2.setData(TreeTentType.TENT); + cell3.setData(TreeTentType.TENT); + cell4.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation()) + || (c.getLocation()).equals(cell3.getLocation()) + || (c.getLocation()).equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); } + } + } + } + + /** + * Empty 3x3 TreeTent puzzle Tests FinishWithTentsDirectRule on TENT tiles of entire puzzle all + * TENT tiles should fail FinishWithTentsDirectRule as no TENT tiles should be there + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithTentsFailTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTentsFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + ArrayList cells = new ArrayList(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + c.setData(TreeTentType.TENT); + board.addModifiedData(c); + cells.add(c); + } } - /** - * Empty 3x3 TreeTent puzzle Tests FinishWithTentsDirectRule on TENT tiles of entire puzzle all - * TENT tiles should fail FinishWithTentsDirectRule as no TENT tiles should be there - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithTentsFailTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTentsFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - ArrayList cells = new ArrayList(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - c.setData(TreeTentType.TENT); - board.addModifiedData(c); - cells.add(c); - } - } - - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail - * FinishWithTentsDirectRule as there were already sufficient number of TENT tiles - * - * @throws InvalidFileFormatException - */ - @Test - public void TooManyTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/TooManyTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - ArrayList cells = new ArrayList(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if ((k == 1) && (i == 1)) { - continue; - } - TreeTentCell c = board.getCell(k, i); - c.setData(TreeTentType.TENT); - board.addModifiedData(c); - cells.add(c); - } + } + + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail + * FinishWithTentsDirectRule as there were already sufficient number of TENT tiles + * + * @throws InvalidFileFormatException + */ + @Test + public void TooManyTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/TooManyTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + ArrayList cells = new ArrayList(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if ((k == 1) && (i == 1)) { + continue; } + TreeTentCell c = board.getCell(k, i); + c.setData(TreeTentType.TENT); + board.addModifiedData(c); + cells.add(c); + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } + } + + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail + * FinishWithTentsDirectRule as there are multiple configurations of the placement of the TENT + * tiles + * + * @throws InvalidFileFormatException + */ + @Test + public void AmbiguousTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/AmbiguousTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell = board.getCell(0, 1); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail - * FinishWithTentsDirectRule as there are multiple configurations of the placement of the TENT - * tiles - * - * @throws InvalidFileFormatException - */ - @Test - public void AmbiguousTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/AmbiguousTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell = board.getCell(0, 1); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(1, 0); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(1, 0); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(2, 1); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(2, 1); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(1, 2); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(1, 2); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java index 92d6e4a59..b3a1de6d5 100644 --- a/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java @@ -17,148 +17,148 @@ public class LastCampingSpotDirectRuleTest { - private static final LastCampingSpotDirectRule RULE = new LastCampingSpotDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square above a tree which is surrounded on all - * other sides. - */ - @Test - public void EmptyFieldTest_Up() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotUp", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final LastCampingSpotDirectRule RULE = new LastCampingSpotDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square above a tree which is surrounded on all other + * sides. + */ + @Test + public void EmptyFieldTest_Up() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotUp", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square below a tree which is surrounded on all - * other sides. - */ - @Test - public void EmptyFieldTest_Down() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotDown", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 2); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square below a tree which is surrounded on all other + * sides. + */ + @Test + public void EmptyFieldTest_Down() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotDown", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 2); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square to the left of a tree which is surrounded - * on all other sides. - */ - @Test - public void EmptyFieldTest_Left() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square to the left of a tree which is surrounded on + * all other sides. + */ + @Test + public void EmptyFieldTest_Left() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square to the right of a tree which is surrounded - * on all other sides. - */ - @Test - public void EmptyFieldTest_Right() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(2, 1); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square to the right of a tree which is surrounded on + * all other sides. + */ + @Test + public void EmptyFieldTest_Right() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(2, 1); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java index b17c92486..8d099f283 100644 --- a/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java @@ -15,99 +15,96 @@ public class NoTentForTreeContradictionRuleTest { - private static final NoTentForTreeContradictionRule RULE = new NoTentForTreeContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Tests if a tree is next to only grass in a 2x2 grid - * triggers the contradiction - */ - @Test - public void NoTentForTreeContradictionRule_Basic() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally - * next to the tree, which should still contradict - */ - @Test - public void NoTentForTreeContradictionRule_Diagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeDiagonal", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests that adjacent trees do not allow a pass - */ - @Test - public void NoTentForTreeContradictionRule_TwoTrees() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTrees", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally - * next to two trees, which should still contradict on one. - */ - @Test - public void NoTentForTreeContradictionRule_TwoTreesDiagonal() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTreesDiagonal", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } + private static final NoTentForTreeContradictionRule RULE = new NoTentForTreeContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Tests if a tree is next to only grass in a 2x2 grid triggers + * the contradiction + */ + @Test + public void NoTentForTreeContradictionRule_Basic() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally + * next to the tree, which should still contradict + */ + @Test + public void NoTentForTreeContradictionRule_Diagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeDiagonal", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests that adjacent trees do not allow a pass + */ + @Test + public void NoTentForTreeContradictionRule_TwoTrees() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTrees", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally + * next to two trees, which should still contradict on one. + */ + @Test + public void NoTentForTreeContradictionRule_TwoTreesDiagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTreesDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } } diff --git a/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java index fd6be92de..c639b2a25 100644 --- a/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java @@ -14,204 +14,201 @@ public class NoTreeForTentContradictionRuleTest { - private static final NoTreeForTentContradictionRule RULE = new NoTreeForTentContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_NW() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNW", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NE corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_NE() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNE", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_SW() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSW", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the SE corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_SE() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSE", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with no trees, a Tent in the - * center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_3x3() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTent3x3", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with diagonal trees, a Tent in the - * center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_3x3WithDiagonalTrees() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentDiagonals", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with an adjacent tree, test does - * not assert null. - */ - @Test - public void NoTreeForTentContradictionRule_YesTree() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentYesTree", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with touching tents, a Tent in the - * center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_JustTent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentJustTent", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } + private static final NoTreeForTentContradictionRule RULE = new NoTreeForTentContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_NW() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNW", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NE corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_NE() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNE", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_SW() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSW", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the SE corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_SE() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSE", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with no trees, a Tent in the center + * cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_3x3() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTent3x3", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with diagonal trees, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_3x3WithDiagonalTrees() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentDiagonals", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with an adjacent tree, test does not + * assert null. + */ + @Test + public void NoTreeForTentContradictionRule_YesTree() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentYesTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with touching tents, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_JustTent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentJustTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } } diff --git a/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java index 7ff57a052..e48fd0979 100644 --- a/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java @@ -17,140 +17,138 @@ public class SurroundTentWithGrassDirectRuleTest { - private static final SurroundTentWithGrassDirectRule RULE = - new SurroundTentWithGrassDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Test to check if all adjacent and diagonals not filled - * with a tree are filled with grass - */ - @Test - public void SurroundTentWithGrassBasicRuleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrass", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final SurroundTentWithGrassDirectRule RULE = new SurroundTentWithGrassDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Test to check if all adjacent and diagonals not filled with + * a tree are filled with grass + */ + @Test + public void SurroundTentWithGrassBasicRuleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrass", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - *

Test with a 3x3 board with an absolutely empty area aside from a tent in the middle - * While such a situation is an illegal treetent setup, this direct rule doesn't consider - * that aspect, so its ok in this context - */ - @Test - public void SurroundTentWithGrassBasicRuleTest_BadBoard() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassBad", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(1, 0); - cell2.setData(TreeTentType.GRASS); - TreeTentCell cell3 = board.getCell(2, 0); - cell3.setData(TreeTentType.GRASS); - TreeTentCell cell4 = board.getCell(0, 1); - cell4.setData(TreeTentType.GRASS); - // Skip (1,1) due to being the Tent - TreeTentCell cell5 = board.getCell(2, 1); - cell5.setData(TreeTentType.GRASS); - TreeTentCell cell6 = board.getCell(0, 2); - cell6.setData(TreeTentType.GRASS); - TreeTentCell cell7 = board.getCell(1, 2); - cell7.setData(TreeTentType.GRASS); - TreeTentCell cell8 = board.getCell(2, 2); - cell8.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - // board.addModifiedData(cell4); - board.addModifiedData(cell5); - board.addModifiedData(cell6); - board.addModifiedData(cell7); - board.addModifiedData(cell8); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || // point.equals(cell4.getLocation()) || - point.equals(cell5.getLocation()) - || point.equals(cell6.getLocation()) - || point.equals(cell7.getLocation()) - || point.equals(cell8.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Test with a 3x3 board with an absolutely empty area aside from a tent in the middle + * While such a situation is an illegal treetent setup, this direct rule doesn't consider that + * aspect, so its ok in this context + */ + @Test + public void SurroundTentWithGrassBasicRuleTest_BadBoard() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassBad", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(1, 0); + cell2.setData(TreeTentType.GRASS); + TreeTentCell cell3 = board.getCell(2, 0); + cell3.setData(TreeTentType.GRASS); + TreeTentCell cell4 = board.getCell(0, 1); + cell4.setData(TreeTentType.GRASS); + // Skip (1,1) due to being the Tent + TreeTentCell cell5 = board.getCell(2, 1); + cell5.setData(TreeTentType.GRASS); + TreeTentCell cell6 = board.getCell(0, 2); + cell6.setData(TreeTentType.GRASS); + TreeTentCell cell7 = board.getCell(1, 2); + cell7.setData(TreeTentType.GRASS); + TreeTentCell cell8 = board.getCell(2, 2); + cell8.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + // board.addModifiedData(cell4); + board.addModifiedData(cell5); + board.addModifiedData(cell6); + board.addModifiedData(cell7); + board.addModifiedData(cell8); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || // point.equals(cell4.getLocation()) || + point.equals(cell5.getLocation()) + || point.equals(cell6.getLocation()) + || point.equals(cell7.getLocation()) + || point.equals(cell8.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException - *

Test to see if the rule passes even if no grass was able to be placed due to the - * presence of trees. - */ - @Test - public void SurroundTentWithGrassBasicRuleTest_FullBoard() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassTrees", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException + *

Test to see if the rule passes even if no grass was able to be placed due to the + * presence of trees. + */ + @Test + public void SurroundTentWithGrassBasicRuleTest_FullBoard() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassTrees", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java index 68dbeaf48..237013212 100644 --- a/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java @@ -3,12 +3,12 @@ // This feature is no longer supported public class TentForTreeDirectRuleTest { - // private static final TentForTreeBasicRule RULE = new TentForTreeBasicRule(); - // private static TreeTent treetent; - // - // @BeforeClass - // public static void setUp() { - // MockGameBoardFacade.getInstance(); - // treetent = new TreeTent(); - // } + // private static final TentForTreeBasicRule RULE = new TentForTreeBasicRule(); + // private static TreeTent treetent; + // + // @BeforeClass + // public static void setUp() { + // MockGameBoardFacade.getInstance(); + // treetent = new TreeTent(); + // } } diff --git a/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java b/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java index 1fe7e4bd0..1f08fa597 100644 --- a/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java @@ -18,62 +18,62 @@ import org.junit.Test; public class TentOrGrassCaseRuleTest { - private static final TentOrGrassCaseRule RULE = new TentOrGrassCaseRule(); - private static TreeTent treetent; + private static final TentOrGrassCaseRule RULE = new TentOrGrassCaseRule(); + private static TreeTent treetent; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * empty 3x3 TreeTent puzzle Tests TentOrGrassCaseRule on UNKOWN tile at (0,0) - * - *

checks 2 cases are created checks first case is TENT tile checks second case is GRASS tile - * checks other cells have not been modified - * - * @throws InvalidFileFormatException - */ - @Test - public void TentOrTreeTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TentOrGrassCaseRule/TestPuzzle", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentCell testing_cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, testing_cell); + /** + * empty 3x3 TreeTent puzzle Tests TentOrGrassCaseRule on UNKOWN tile at (0,0) + * + *

checks 2 cases are created checks first case is TENT tile checks second case is GRASS tile + * checks other cells have not been modified + * + * @throws InvalidFileFormatException + */ + @Test + public void TentOrTreeTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TentOrGrassCaseRule/TestPuzzle", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // assert correct number of cases created - Assert.assertEquals(2, cases.size()); + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentCell testing_cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, testing_cell); - // TENT case - TreeTentBoard tentCase = (TreeTentBoard) cases.get(0); - Assert.assertEquals(tentCase.getCell(0, 0).getType(), TreeTentType.TENT); + // assert correct number of cases created + Assert.assertEquals(2, cases.size()); - // GRASS case - TreeTentBoard grassCase = (TreeTentBoard) cases.get(1); - Assert.assertEquals(grassCase.getCell(0, 0).getType(), TreeTentType.GRASS); + // TENT case + TreeTentBoard tentCase = (TreeTentBoard) cases.get(0); + Assert.assertEquals(tentCase.getCell(0, 0).getType(), TreeTentType.TENT); - // checks other cells have not been modified - TreeTentCell original_cell; - TreeTentCell case_cell; + // GRASS case + TreeTentBoard grassCase = (TreeTentBoard) cases.get(1); + Assert.assertEquals(grassCase.getCell(0, 0).getType(), TreeTentType.GRASS); - for (int w = 0; w < board.getWidth(); w++) { - for (int h = 0; h < board.getHeight(); h++) { - if (w == 0 && h == 0) { - continue; - } - original_cell = board.getCell(w, h); - case_cell = tentCase.getCell(w, h); - Assert.assertEquals(original_cell.getType(), case_cell.getType()); + // checks other cells have not been modified + TreeTentCell original_cell; + TreeTentCell case_cell; - case_cell = grassCase.getCell(w, h); - Assert.assertEquals(original_cell.getType(), case_cell.getType()); - } + for (int w = 0; w < board.getWidth(); w++) { + for (int h = 0; h < board.getHeight(); h++) { + if (w == 0 && h == 0) { + continue; } + original_cell = board.getCell(w, h); + case_cell = tentCase.getCell(w, h); + Assert.assertEquals(original_cell.getType(), case_cell.getType()); + + case_cell = grassCase.getCell(w, h); + Assert.assertEquals(original_cell.getType(), case_cell.getType()); + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java index e1773827d..f08d87a3b 100644 --- a/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java @@ -16,231 +16,225 @@ public class TooFewTentsContradictionRuleTest { - private static final TooFewTentsContradictionRule RULE = new TooFewTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if - * the fact it expects a tent on the y-axis is caught. - */ - @Test - public void TooFewTentsContradictionRule_JustY() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsJustY", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just a tent, checks if - * the fact it expects 2 tents on the y-axis is caught. (This is an impossible situation - * given the constraints, but for the purposes of the test it is fine) - */ - @Test - public void TooFewTentsContradictionRule_WithTent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsWithTent", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if - * the fact it expects a tent on both x and y is caught. - */ - @Test - public void TooFewTentsContradictionRule_DoubleBad() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsDoubleBad", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: [] Tr [] Gr Column 2 - * is checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_2x2ColumnOnly() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Column", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 1); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final TooFewTentsContradictionRule RULE = new TooFewTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if the + * fact it expects a tent on the y-axis is caught. + */ + @Test + public void TooFewTentsContradictionRule_JustY() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsJustY", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just a tent, checks if the + * fact it expects 2 tents on the y-axis is caught. (This is an impossible situation given the + * constraints, but for the purposes of the test it is fine) + */ + @Test + public void TooFewTentsContradictionRule_WithTent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsWithTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if the + * fact it expects a tent on both x and y is caught. + */ + @Test + public void TooFewTentsContradictionRule_DoubleBad() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsDoubleBad", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: [] Tr [] Gr Column 2 is + * checked to have 1 Tent (which is not present, thus producing a contradiction) + */ + @Test + public void TooFewTentsContradictionRule_2x2ColumnOnly() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Column", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 1); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tr Gr [] [] Row 1 is - * checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_2x2RowOnly() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Row", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(1, 0); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tr Gr [] [] Row 1 is + * checked to have 1 Tent (which is not present, thus producing a contradiction) + */ + @Test + public void TooFewTentsContradictionRule_2x2RowOnly() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Row", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(1, 0); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: [] Tr [] [] Gr [] [] - * Gr [] Column 2 is checked to have 1 Tent (which is not present, thus producing a - * contradiction) - */ - @Test - public void TooFewTentsContradictionRule_3x3OneColumn() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3Column", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 1); - TreeTentCell cell3 = board.getCell(1, 2); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: [] Tr [] [] Gr [] [] Gr + * [] Column 2 is checked to have 1 Tent (which is not present, thus producing a + * contradiction) + */ + @Test + public void TooFewTentsContradictionRule_3x3OneColumn() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3Column", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 1); + TreeTentCell cell3 = board.getCell(1, 2); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: Gr Tr Gr Gr [] Gr Gr - * Tr Gr Column 1 and 3 are checked to have 1 Tent (which is not present, thus producing a - * contradiction) - */ - @Test - public void TooFewTentsContradictionRule_3x3TwoColumn() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3DoubleColumn", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(0, 1); - TreeTentCell cell3 = board.getCell(0, 2); - TreeTentCell cell4 = board.getCell(2, 0); - TreeTentCell cell5 = board.getCell(2, 1); - TreeTentCell cell6 = board.getCell(2, 2); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation()) - || point.equals(cell5.getLocation()) - || point.equals(cell6.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: Gr Tr Gr Gr [] Gr Gr Tr + * Gr Column 1 and 3 are checked to have 1 Tent (which is not present, thus producing a + * contradiction) + */ + @Test + public void TooFewTentsContradictionRule_3x3TwoColumn() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3DoubleColumn", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(0, 1); + TreeTentCell cell3 = board.getCell(0, 2); + TreeTentCell cell4 = board.getCell(2, 0); + TreeTentCell cell5 = board.getCell(2, 1); + TreeTentCell cell6 = board.getCell(2, 2); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation()) + || point.equals(cell5.getLocation()) + || point.equals(cell6.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tn [] Tr [] This - * should fail the contradiction as it is a legal board. - */ - @Test - public void TooFewTentsContradictionRule_NoContradiction() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsNoContradiction", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tn [] Tr [] This should + * fail the contradiction as it is a legal board. + */ + @Test + public void TooFewTentsContradictionRule_NoContradiction() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsNoContradiction", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java index 2e542b3d2..fb94aa006 100644 --- a/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java @@ -16,253 +16,246 @@ public class TooManyTentsContradictionRuleTest { - private static final TooManyTentsContradictionRule RULE = new TooManyTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /* - TESTING BASIS: - All test in this Rule use a 3x3 table. - There is a Tree at (1,1) - There are tents at (0,1) and (2,2) - All Tent Counts are listed left to right or top to bottom - */ - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_TotalFail() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTotalFail", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + private static final TooManyTentsContradictionRule RULE = new TooManyTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /* + TESTING BASIS: + All test in this Rule use a 3x3 table. + There is a Tree at (1,1) + There are tents at (0,1) and (2,2) + All Tent Counts are listed left to right or top to bottom + */ + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_TotalFail() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTotalFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 1,0,0 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_TopRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopRight", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(0, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 1,0,0 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_TopRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(0, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Tests for TooManyTests if: Row Tent Counts: 0,0,1 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_BottomRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomRight", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(0, 2); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTests if: Row Tent Counts: 0,0,1 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_BottomRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(0, 2); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,1,0 - */ - @Test - public void TooManyTentsContradictionRule_TopDown() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopDown", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(1, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,1,0 + */ + @Test + public void TooManyTentsContradictionRule_TopDown() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopDown", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(1, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,0,1 - */ - @Test - public void TooManyTentsContradictionRule_BottomDown() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomDown", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(2, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,0,1 + */ + @Test + public void TooManyTentsContradictionRule_BottomDown() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomDown", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(2, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if the Top Tent is completely - * accounted for, but not the bottom Row Tent Counts: 1,0,0 Column Tent Counts: 0,1,0 - */ - @Test - public void TooManyTentsContradictionRule_TopAccount() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopAccount", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(1, 0); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(1, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if the Top Tent is completely + * accounted for, but not the bottom Row Tent Counts: 1,0,0 Column Tent Counts: 0,1,0 + */ + @Test + public void TooManyTentsContradictionRule_TopAccount() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopAccount", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(1, 0); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(1, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if the Bottom Tent is completely - * accounted for, but not the Top Row Tent Counts: 0,0,1 Column Tent Counts: 0,0,1 - */ - @Test - public void TooManyTentsContradictionRule_BottomAccount() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomAccount", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(2, 1); - TreeTentCell cell3 = board.getCell(0, 2); - TreeTentCell cell4 = board.getCell(2, 2); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + } + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if the Bottom Tent is completely + * accounted for, but not the Top Row Tent Counts: 0,0,1 Column Tent Counts: 0,0,1 + */ + @Test + public void TooManyTentsContradictionRule_BottomAccount() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomAccount", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(2, 1); + TreeTentCell cell3 = board.getCell(0, 2); + TreeTentCell cell4 = board.getCell(2, 2); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); } + } } + } } diff --git a/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java index 9f5455a92..6018b6853 100644 --- a/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java @@ -14,246 +14,239 @@ public class TouchingTentsContradictionRuleTest { - private static final TouchingTentsContradictionRule RULE = new TouchingTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - // DIAGONAL TESTS - /** - * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_DiagonalUpLeftToDownRight() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonal", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - - /** - * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_DiagonalDownLeftToUpRight() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonalAlt", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - // ADJACENT TESTS - /** - * @throws InvalidFileFormatException Tests a tent adjacent of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_AdjacentVertical() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacent", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent adjacent of orientation TT - */ - @Test - public void TouchingTentsContradictionRule_AdjacentHorizontal() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacentAlt", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - // MIXED TESTS - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT TT - */ - @Test - public void TouchingTentsContradictionRule_2By2Square() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsFull2By2", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT T - */ - @Test - public void TouchingTentsContradictionRule_UpLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpLeft", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT T - */ - @Test - public void TouchingTentsContradictionRule_UpRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpRight", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation T TT - */ - @Test - public void TouchingTentsContradictionRule_DownLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownLeft", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation T TT - */ - @Test - public void TouchingTentsContradictionRule_DownRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownRight", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Tests if tree adjacent triggers a null - */ - @Test - public void TouchingTentsContradictionRule_TreeAdjacent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeAdjacent", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if tree diagonal triggers a null - */ - @Test - public void TouchingTentsContradictionRule_TreeDiagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeDiagonal", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } + private static final TouchingTentsContradictionRule RULE = new TouchingTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + // DIAGONAL TESTS + /** + * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_DiagonalUpLeftToDownRight() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonal", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } + + /** + * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_DiagonalDownLeftToUpRight() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonalAlt", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + // ADJACENT TESTS + /** + * @throws InvalidFileFormatException Tests a tent adjacent of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_AdjacentVertical() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent adjacent of orientation TT + */ + @Test + public void TouchingTentsContradictionRule_AdjacentHorizontal() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacentAlt", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + // MIXED TESTS + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT TT + */ + @Test + public void TouchingTentsContradictionRule_2By2Square() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsFull2By2", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT T + */ + @Test + public void TouchingTentsContradictionRule_UpLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT T + */ + @Test + public void TouchingTentsContradictionRule_UpRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation T TT + */ + @Test + public void TouchingTentsContradictionRule_DownLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownLeft", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation T TT + */ + @Test + public void TouchingTentsContradictionRule_DownRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Tests if tree adjacent triggers a null + */ + @Test + public void TouchingTentsContradictionRule_TreeAdjacent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeAdjacent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if tree diagonal triggers a null + */ + @Test + public void TouchingTentsContradictionRule_TreeDiagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } } diff --git a/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java index f4ea6703b..2aecd0f0a 100644 --- a/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java @@ -3,12 +3,12 @@ // This feature is no longer supported public class TreeForTentDirectRuleTest { - // private static final TreeForTentBasicRule RULE = new TreeForTentBasicRule(); - // private static TreeTent treetent; + // private static final TreeForTentBasicRule RULE = new TreeForTentBasicRule(); + // private static TreeTent treetent; - // @BeforeClass - // public static void setUp() { - // MockGameBoardFacade.getInstance(); - // treetent = new TreeTent(); - // } + // @BeforeClass + // public static void setUp() { + // MockGameBoardFacade.getInstance(); + // treetent = new TreeTent(); + // } } From 969d4f759823d528784fdf4a341cec067ada04b4 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 18:39:28 -0500 Subject: [PATCH 43/54] Comments and reordering styles --- build.gradle | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index ac8abd443..14c85f0a8 100644 --- a/build.gradle +++ b/build.gradle @@ -25,15 +25,15 @@ spotless{ } java{ + // Use the default importOrder configuration importOrder() - removeUnusedImports() - + // Cleanthat will refactor your code, but it may break your style: apply it before your formatter cleanthat() - formatAnnotations() - googleJavaFormat('1.19.2') + + formatAnnotations() } } From 4e0ef24cc1152025a51b0b08a1ff8a1fe63a86ea Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 18:45:07 -0500 Subject: [PATCH 44/54] Adding extra newlines --- src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java index 2f9c3e553..289f66032 100644 --- a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java @@ -26,6 +26,9 @@ public AddTreeElementCommand(TreeViewSelection selection) { this.addChild = new HashMap<>(); } + + + /** Executes an command */ @Override public void executeCommand() { From 4c4b6fa52b6067e1c4a6704b1ebfca56453b03e2 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln Date: Tue, 13 Feb 2024 23:46:32 +0000 Subject: [PATCH 45/54] Automated Java code formatting changes --- src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java index 289f66032..2f9c3e553 100644 --- a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java @@ -26,9 +26,6 @@ public AddTreeElementCommand(TreeViewSelection selection) { this.addChild = new HashMap<>(); } - - - /** Executes an command */ @Override public void executeCommand() { From 76904a2eca987c20bd9e2cd0a01fb9f07a8b2a3c Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 19:07:45 -0500 Subject: [PATCH 46/54] Changing tabs from 2 to 4 spaces Supposedly the only difference that aosp makes is the 2 spaces? Hopefully it doesn't break anything else --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 14c85f0a8..dc06993ec 100644 --- a/build.gradle +++ b/build.gradle @@ -31,7 +31,7 @@ spotless{ // Cleanthat will refactor your code, but it may break your style: apply it before your formatter cleanthat() - googleJavaFormat('1.19.2') + googleJavaFormat('1.19.2').aosp() formatAnnotations() } From e8ae4dbc9c7aea4169b2a5281c9a59d645045e3f Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Tue, 13 Feb 2024 19:08:51 -0500 Subject: [PATCH 47/54] Remove solo } requirement and reactivate checkstyle --- build.gradle | 2 +- config/checkstyle/checkstyle.xml | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index dc06993ec..49829e473 100644 --- a/build.gradle +++ b/build.gradle @@ -37,7 +37,7 @@ spotless{ } } -//apply plugin: 'checkstyle' +apply plugin: 'checkstyle' mainClassName = 'edu.rpi.legup.Legup' diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index a5dfea0af..0cd09a2ae 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -9,9 +9,6 @@ - - From a7db9811e24792c093b871a97d0ae1852061112b Mon Sep 17 00:00:00 2001 From: Bram van Heuveln Date: Wed, 14 Feb 2024 00:09:44 +0000 Subject: [PATCH 48/54] Automated Java code formatting changes --- src/main/java/edu/rpi/legup/Legup.java | 20 +- src/main/java/edu/rpi/legup/app/Config.java | 253 +-- .../edu/rpi/legup/app/GameBoardFacade.java | 912 ++++---- .../rpi/legup/app/InvalidConfigException.java | 6 +- .../edu/rpi/legup/app/LegupPreferences.java | 229 +- .../rpi/legup/app/PuzzleKeyAccelerator.java | 140 +- .../rpi/legup/controller/BoardController.java | 150 +- .../edu/rpi/legup/controller/Controller.java | 196 +- .../legup/controller/CursorController.java | 80 +- .../controller/EditorElementController.java | 66 +- .../legup/controller/ElementController.java | 571 ++--- .../rpi/legup/controller/RuleController.java | 181 +- .../legup/controller/ToolbarController.java | 34 +- .../rpi/legup/controller/TreeController.java | 267 +-- .../legup/history/AddTreeElementCommand.java | 167 +- .../ApplyDefaultDirectRuleCommand.java | 206 +- .../legup/history/AutoCaseRuleCommand.java | 235 +- .../edu/rpi/legup/history/CommandError.java | 44 +- .../edu/rpi/legup/history/CommandState.java | 24 +- .../history/DeleteTreeElementCommand.java | 153 +- .../rpi/legup/history/EditDataCommand.java | 272 +-- .../java/edu/rpi/legup/history/History.java | 154 +- .../java/edu/rpi/legup/history/ICommand.java | 38 +- .../rpi/legup/history/IHistoryListener.java | 44 +- .../rpi/legup/history/IHistorySubject.java | 36 +- .../InvalidCommandStateTransition.java | 20 +- .../edu/rpi/legup/history/MergeCommand.java | 224 +- .../edu/rpi/legup/history/PuzzleCommand.java | 144 +- .../history/ValidateCaseRuleCommand.java | 212 +- .../ValidateContradictionRuleCommand.java | 279 +-- .../history/ValidateDirectRuleCommand.java | 222 +- src/main/java/edu/rpi/legup/model/Puzzle.java | 1209 +++++----- .../edu/rpi/legup/model/PuzzleExporter.java | 233 +- .../edu/rpi/legup/model/PuzzleImporter.java | 717 +++--- .../edu/rpi/legup/model/elements/Element.java | 109 +- .../rpi/legup/model/elements/ElementType.java | 4 +- .../model/elements/NonPlaceableElement.java | 10 +- .../model/elements/PlaceableElement.java | 10 +- .../edu/rpi/legup/model/gameboard/Board.java | 410 ++-- .../rpi/legup/model/gameboard/CaseBoard.java | 90 +- .../legup/model/gameboard/ElementFactory.java | 38 +- .../rpi/legup/model/gameboard/GridBoard.java | 281 +-- .../rpi/legup/model/gameboard/GridCell.java | 100 +- .../legup/model/gameboard/PuzzleElement.java | 354 +-- .../legup/model/observer/IBoardListener.java | 36 +- .../legup/model/observer/IBoardSubject.java | 36 +- .../legup/model/observer/ITreeListener.java | 40 +- .../legup/model/observer/ITreeSubject.java | 36 +- .../edu/rpi/legup/model/rules/CaseRule.java | 246 +- .../legup/model/rules/ContradictionRule.java | 178 +- .../edu/rpi/legup/model/rules/DirectRule.java | 169 +- .../edu/rpi/legup/model/rules/MergeRule.java | 152 +- .../java/edu/rpi/legup/model/rules/Rule.java | 300 +-- .../edu/rpi/legup/model/rules/RuleType.java | 8 +- .../java/edu/rpi/legup/model/tree/Tree.java | 345 +-- .../edu/rpi/legup/model/tree/TreeElement.java | 114 +- .../rpi/legup/model/tree/TreeElementType.java | 4 +- .../edu/rpi/legup/model/tree/TreeNode.java | 606 ++--- .../rpi/legup/model/tree/TreeTransition.java | 781 ++++--- .../legup/puzzle/battleship/Battleship.java | 294 +-- .../puzzle/battleship/BattleshipBoard.java | 256 +-- .../puzzle/battleship/BattleshipCell.java | 58 +- .../battleship/BattleshipCellController.java | 64 +- .../battleship/BattleshipCellFactory.java | 112 +- .../puzzle/battleship/BattleshipClue.java | 124 +- .../puzzle/battleship/BattleshipClueView.java | 98 +- .../battleship/BattleshipElementView.java | 179 +- .../puzzle/battleship/BattleshipExporter.java | 100 +- .../puzzle/battleship/BattleshipImporter.java | 341 +-- .../puzzle/battleship/BattleshipType.java | 86 +- .../puzzle/battleship/BattleshipView.java | 31 +- .../rules/AdjacentShipsContradictionRule.java | 126 +- .../rules/ContinueShipDirectRule.java | 63 +- .../rules/FinishWithShipsDirectRule.java | 159 +- .../rules/FinishWithWaterDirectRule.java | 63 +- .../IncompleteShipContradictionRule.java | 40 +- .../battleship/rules/SegmentTypeCaseRule.java | 110 +- .../rules/SegmentTypeDirectRule.java | 63 +- .../rules/ShipLocationCaseRule.java | 110 +- .../battleship/rules/ShipOrWaterCaseRule.java | 110 +- .../rules/SurroundShipDirectRule.java | 63 +- .../rules/TooFewInFleetContradictionRule.java | 40 +- .../rules/TooFewRowColContradictionRule.java | 40 +- .../TooManyInFleetContradictionRule.java | 40 +- .../rules/TooManyRowColContradiction.java | 40 +- .../rpi/legup/puzzle/fillapix/Fillapix.java | 94 +- .../legup/puzzle/fillapix/FillapixBoard.java | 98 +- .../legup/puzzle/fillapix/FillapixCell.java | 162 +- .../fillapix/FillapixCellController.java | 70 +- .../puzzle/fillapix/FillapixCellFactory.java | 107 +- .../puzzle/fillapix/FillapixCellType.java | 20 +- .../puzzle/fillapix/FillapixElementView.java | 97 +- .../puzzle/fillapix/FillapixExporter.java | 52 +- .../puzzle/fillapix/FillapixImporter.java | 190 +- .../puzzle/fillapix/FillapixUtilities.java | 415 ++-- .../legup/puzzle/fillapix/FillapixView.java | 23 +- .../puzzle/fillapix/elements/BlackTile.java | 14 +- .../puzzle/fillapix/elements/NumberTile.java | 42 +- .../puzzle/fillapix/elements/UnknownTile.java | 14 +- .../puzzle/fillapix/elements/WhiteTile.java | 14 +- .../fillapix/rules/BlackOrWhiteCaseRule.java | 130 +- .../rules/FinishWithBlackDirectRule.java | 91 +- .../rules/FinishWithWhiteDirectRule.java | 91 +- .../fillapix/rules/MirrorDirectRule.java | 156 +- .../rules/NonTouchingSharedDirectRule.java | 149 +- .../fillapix/rules/SatisfyClueCaseRule.java | 383 ++-- .../TooFewBlackCellsContradictionRule.java | 78 +- .../TooManyBlackCellsContradictionRule.java | 72 +- .../rules/TouchingCornersDirectRule.java | 165 +- .../rules/TouchingSidesDirectRule.java | 189 +- .../rpi/legup/puzzle/heyawake/Heyawake.java | 102 +- .../legup/puzzle/heyawake/HeyawakeBoard.java | 80 +- .../legup/puzzle/heyawake/HeyawakeCell.java | 32 +- .../puzzle/heyawake/HeyawakeElementView.java | 73 +- .../puzzle/heyawake/HeyawakeExporter.java | 52 +- .../puzzle/heyawake/HeyawakeFactory.java | 113 +- .../puzzle/heyawake/HeyawakeImporter.java | 170 +- .../legup/puzzle/heyawake/HeyawakeView.java | 69 +- .../AdjacentBlacksContradictionRule.java | 40 +- .../heyawake/rules/BlackOrWhiteCaseRule.java | 110 +- .../heyawake/rules/BlackPathDirectRule.java | 6 +- .../heyawake/rules/BottleNeckDirectRule.java | 6 +- .../rules/FillRoomBlackDirectRule.java | 63 +- .../rules/FillRoomWhiteDirectRule.java | 63 +- .../heyawake/rules/OneRowDirectRule.java | 6 +- .../rules/PreventWhiteLineDirectRule.java | 6 +- .../rules/RoomTooEmptyContradictionRule.java | 40 +- .../rules/RoomTooFullContradictionRule.java | 40 +- .../rules/ThreeByThreeDirectRule.java | 6 +- .../heyawake/rules/TwoInCornerDirectRule.java | 6 +- .../rules/WhiteAreaContradictionRule.java | 40 +- .../rules/WhiteAroundBlackDirectRule.java | 63 +- .../heyawake/rules/WhiteEscapeDirectRule.java | 6 +- .../rules/WhiteLineContradictionRule.java | 40 +- .../puzzle/heyawake/rules/ZigZagCaseRule.java | 6 +- .../heyawake/rules/ZigZagWhiteDirectRule.java | 6 +- .../edu/rpi/legup/puzzle/lightup/LightUp.java | 133 +- .../legup/puzzle/lightup/LightUpBoard.java | 292 +-- .../rpi/legup/puzzle/lightup/LightUpCell.java | 128 +- .../puzzle/lightup/LightUpCellController.java | 66 +- .../puzzle/lightup/LightUpCellFactory.java | 106 +- .../legup/puzzle/lightup/LightUpCellType.java | 18 +- .../puzzle/lightup/LightUpElementView.java | 145 +- .../legup/puzzle/lightup/LightUpExporter.java | 52 +- .../legup/puzzle/lightup/LightUpImporter.java | 192 +- .../rpi/legup/puzzle/lightup/LightUpView.java | 144 +- .../puzzle/lightup/elements/BlackTile.java | 11 +- .../puzzle/lightup/elements/BulbTile.java | 10 +- .../puzzle/lightup/elements/NumberTile.java | 32 +- .../puzzle/lightup/elements/UnknownTile.java | 14 +- .../rules/BulbsInPathContradictionRule.java | 122 +- .../CannotLightACellContradictionRule.java | 140 +- .../rules/EmptyCellinLightDirectRule.java | 99 +- .../lightup/rules/EmptyCornersDirectRule.java | 182 +- .../rules/FinishWithBulbsDirectRule.java | 170 +- .../rules/FinishWithEmptyDirectRule.java | 193 +- .../lightup/rules/LightOrEmptyCaseRule.java | 171 +- .../lightup/rules/MustLightDirectRule.java | 249 +- .../lightup/rules/SatisfyNumberCaseRule.java | 598 ++--- .../rules/TooFewBulbsContradictionRule.java | 58 +- .../rules/TooManyBulbsContradictionRule.java | 90 +- .../legup/puzzle/masyu/EditLineCommand.java | 271 +-- .../edu/rpi/legup/puzzle/masyu/Masyu.java | 102 +- .../rpi/legup/puzzle/masyu/MasyuBoard.java | 90 +- .../edu/rpi/legup/puzzle/masyu/MasyuCell.java | 28 +- .../legup/puzzle/masyu/MasyuCellFactory.java | 104 +- .../legup/puzzle/masyu/MasyuController.java | 154 +- .../legup/puzzle/masyu/MasyuElementView.java | 80 +- .../rpi/legup/puzzle/masyu/MasyuExporter.java | 47 +- .../rpi/legup/puzzle/masyu/MasyuImporter.java | 168 +- .../edu/rpi/legup/puzzle/masyu/MasyuLine.java | 72 +- .../rpi/legup/puzzle/masyu/MasyuLineView.java | 36 +- .../edu/rpi/legup/puzzle/masyu/MasyuType.java | 30 +- .../edu/rpi/legup/puzzle/masyu/MasyuView.java | 76 +- .../rules/BadLoopingContradictionRule.java | 40 +- .../masyu/rules/BlackContradictionRule.java | 32 +- .../masyu/rules/BlackEdgeDirectRule.java | 55 +- .../masyu/rules/BlackSplitCaseRule.java | 102 +- .../masyu/rules/BlockedBlackDirectRule.java | 59 +- .../masyu/rules/ConnectedCellsDirectRule.java | 63 +- .../masyu/rules/FinishPathDirectRule.java | 59 +- .../masyu/rules/NearWhiteDirectRule.java | 55 +- .../rules/NoOptionsContradictionRule.java | 40 +- .../masyu/rules/NormalSplitCaseRule.java | 106 +- .../masyu/rules/OnlyOneChoiceDirectRule.java | 63 +- .../masyu/rules/OnlyTwoContradictionRule.java | 36 +- .../masyu/rules/WhiteContradictionRule.java | 32 +- .../masyu/rules/WhiteEdgeDirectRule.java | 55 +- .../masyu/rules/WhiteSplitCaseRule.java | 102 +- .../rpi/legup/puzzle/nurikabe/Nurikabe.java | 126 +- .../legup/puzzle/nurikabe/NurikabeBoard.java | 84 +- .../legup/puzzle/nurikabe/NurikabeCell.java | 150 +- .../puzzle/nurikabe/NurikabeCellFactory.java | 107 +- .../puzzle/nurikabe/NurikabeController.java | 66 +- .../puzzle/nurikabe/NurikabeElementView.java | 103 +- .../puzzle/nurikabe/NurikabeExporter.java | 52 +- .../puzzle/nurikabe/NurikabeImporter.java | 192 +- .../legup/puzzle/nurikabe/NurikabeType.java | 14 +- .../puzzle/nurikabe/NurikabeUtilities.java | 522 ++--- .../legup/puzzle/nurikabe/NurikabeView.java | 23 +- .../puzzle/nurikabe/elements/BlackTile.java | 14 +- .../puzzle/nurikabe/elements/NumberTile.java | 42 +- .../puzzle/nurikabe/elements/UnknownTile.java | 14 +- .../puzzle/nurikabe/elements/WhiteTile.java | 14 +- .../rules/BlackBetweenRegionsDirectRule.java | 177 +- .../rules/BlackBottleNeckDirectRule.java | 90 +- .../nurikabe/rules/BlackOrWhiteCaseRule.java | 173 +- .../rules/BlackSquareContradictionRule.java | 88 +- .../rules/CannotReachCellDirectRule.java | 86 +- .../nurikabe/rules/CornerBlackDirectRule.java | 210 +- .../nurikabe/rules/FillinBlackDirectRule.java | 83 +- .../nurikabe/rules/FillinWhiteDirectRule.java | 83 +- .../rules/IsolateBlackContradictionRule.java | 82 +- .../MultipleNumbersContradictionRule.java | 67 +- .../rules/NoNumberContradictionRule.java | 101 +- .../rules/PreventBlackSquareDirectRule.java | 87 +- .../rules/SurroundRegionDirectRule.java | 139 +- .../rules/TooFewSpacesContradictionRule.java | 88 +- .../rules/TooManySpacesContradictionRule.java | 85 +- ...UnreachableWhiteCellContradictionRule.java | 159 +- .../rules/WhiteBottleNeckDirectRule.java | 93 +- .../shorttruthtable/ShortTruthTable.java | 186 +- .../shorttruthtable/ShortTruthTableBoard.java | 196 +- .../shorttruthtable/ShortTruthTableCell.java | 391 ++-- .../ShortTruthTableCellFactory.java | 95 +- .../ShortTruthTableCellType.java | 100 +- .../ShortTruthTableController.java | 42 +- .../ShortTruthTableElementView.java | 119 +- .../ShortTruthTableExporter.java | 67 +- .../ShortTruthTableImporter.java | 630 +++--- .../ShortTruthTableOperation.java | 74 +- .../ShortTruthTableStatement.java | 516 ++--- .../shorttruthtable/ShortTruthTableView.java | 25 +- .../elements/ArgumentElement.java | 14 +- .../elements/GreenElement.java | 14 +- .../elements/LogicSymbolElement.java | 14 +- .../shorttruthtable/elements/RedElement.java | 14 +- .../elements/UnknownElement.java | 14 +- .../rules/basic/DirectRuleAtomic.java | 18 +- .../rules/basic/DirectRule_Generic.java | 129 +- .../elimination/DirectRuleAndElimination.java | 6 +- .../DirectRuleBiconditionalElimination.java | 6 +- .../DirectRuleConditionalElimination.java | 6 +- .../elimination/DirectRuleNotElimination.java | 6 +- .../elimination/DirectRuleOrElimination.java | 6 +- .../DirectRule_GenericElimination.java | 20 +- .../DirectRuleAndIntroduction.java | 6 +- .../DirectRuleBiconditionalIntroduction.java | 6 +- .../DirectRuleConditionalIntroduction.java | 6 +- .../DirectRuleNotIntroduction.java | 6 +- .../DirectRuleOrIntroduction.java | 6 +- .../DirectRule_GenericIntroduction.java | 20 +- .../rules/caserule/CaseRuleAnd.java | 16 +- .../rules/caserule/CaseRuleAtomic.java | 92 +- .../rules/caserule/CaseRuleBiconditional.java | 32 +- .../rules/caserule/CaseRuleConditional.java | 30 +- .../rules/caserule/CaseRuleOr.java | 20 +- .../rules/caserule/CaseRule_Generic.java | 100 +- .../caserule/CaseRule_GenericStatement.java | 259 +-- .../contradiction/ContradictionRuleAnd.java | 28 +- .../ContradictionRuleAtomic.java | 84 +- .../ContradictionRuleBiconditional.java | 28 +- .../ContradictionRuleConditional.java | 26 +- .../contradiction/ContradictionRuleNot.java | 24 +- .../contradiction/ContradictionRuleOr.java | 26 +- .../ContradictionRule_GenericStatement.java | 131 +- .../legup/puzzle/skyscrapers/Skyscrapers.java | 128 +- .../puzzle/skyscrapers/SkyscrapersBoard.java | 448 ++-- .../puzzle/skyscrapers/SkyscrapersCell.java | 94 +- .../skyscrapers/SkyscrapersCellFactory.java | 106 +- .../puzzle/skyscrapers/SkyscrapersClue.java | 94 +- .../skyscrapers/SkyscrapersClueView.java | 96 +- .../skyscrapers/SkyscrapersController.java | 42 +- .../skyscrapers/SkyscrapersElementView.java | 51 +- .../skyscrapers/SkyscrapersExporter.java | 104 +- .../skyscrapers/SkyscrapersImporter.java | 390 ++-- .../puzzle/skyscrapers/SkyscrapersType.java | 62 +- .../puzzle/skyscrapers/SkyscrapersView.java | 333 +-- .../puzzle/skyscrapers/elements/ClueTile.java | 14 +- .../skyscrapers/elements/NumberTile.java | 14 +- .../skyscrapers/elements/UnknownTile.java | 14 +- .../rules/CellForNumberCaseRule.java | 343 +-- .../DuplicateNumberContradictionRule.java | 96 +- .../ExceedingVisibilityContradictionRule.java | 221 +- ...sufficientVisibilityContradictionRule.java | 223 +- .../rules/LastSingularCellDirectRule.java | 201 +- .../rules/LastSingularNumberDirectRule.java | 157 +- .../rules/LastVisibleCellDirectRule.java | 207 +- .../rules/LastVisibleNumberDirectRule.java | 159 +- .../skyscrapers/rules/NEdgeDirectRule.java | 162 +- .../rules/NumberForCellCaseRule.java | 298 +-- ...PreemptiveVisibilityContradictionRule.java | 346 +-- .../UnresolvedCellContradictionRule.java | 50 +- .../UnresolvedNumberContradictionRule.java | 160 +- .../rpi/legup/puzzle/sudoku/GroupType.java | 6 +- .../sudoku/PossibleNumberCaseBoard.java | 118 +- .../edu/rpi/legup/puzzle/sudoku/Sudoku.java | 178 +- .../rpi/legup/puzzle/sudoku/SudokuBoard.java | 306 +-- .../rpi/legup/puzzle/sudoku/SudokuCell.java | 106 +- .../puzzle/sudoku/SudokuCellController.java | 52 +- .../puzzle/sudoku/SudokuCellFactory.java | 106 +- .../puzzle/sudoku/SudokuElementView.java | 114 +- .../legup/puzzle/sudoku/SudokuExporter.java | 50 +- .../legup/puzzle/sudoku/SudokuImporter.java | 214 +- .../rpi/legup/puzzle/sudoku/SudokuView.java | 286 +-- .../puzzle/sudoku/elements/NumberTile.java | 34 +- .../rules/AdvancedDeductionDirectRule.java | 153 +- .../rules/LastCellForNumberDirectRule.java | 143 +- .../rules/LastNumberForCellDirectRule.java | 124 +- .../rules/NoSolutionContradictionRule.java | 90 +- .../sudoku/rules/PossibleCellCaseRule.java | 166 +- .../sudoku/rules/PossibleNumberCaseRule.java | 200 +- .../RepeatedNumberContradictionRule.java | 98 +- .../legup/puzzle/treetent/ClueCommand.java | 317 +-- .../puzzle/treetent/EditLineCommand.java | 378 ++-- .../rpi/legup/puzzle/treetent/TreeTent.java | 136 +- .../legup/puzzle/treetent/TreeTentBoard.java | 430 ++-- .../legup/puzzle/treetent/TreeTentCell.java | 80 +- .../puzzle/treetent/TreeTentCellFactory.java | 152 +- .../legup/puzzle/treetent/TreeTentClue.java | 98 +- .../puzzle/treetent/TreeTentClueView.java | 88 +- .../puzzle/treetent/TreeTentController.java | 199 +- .../puzzle/treetent/TreeTentElementView.java | 104 +- .../puzzle/treetent/TreeTentExporter.java | 114 +- .../puzzle/treetent/TreeTentImporter.java | 379 ++-- .../legup/puzzle/treetent/TreeTentLine.java | 72 +- .../puzzle/treetent/TreeTentLineView.java | 38 +- .../legup/puzzle/treetent/TreeTentType.java | 38 +- .../legup/puzzle/treetent/TreeTentView.java | 403 ++-- .../puzzle/treetent/elements/GrassTile.java | 14 +- .../puzzle/treetent/elements/TentTile.java | 10 +- .../puzzle/treetent/elements/TreeTile.java | 10 +- .../puzzle/treetent/elements/UnknownTile.java | 14 +- .../treetent/rules/EmptyFieldDirectRule.java | 135 +- .../treetent/rules/FillinRowCaseRule.java | 358 +-- .../rules/FinishWithGrassDirectRule.java | 125 +- .../rules/FinishWithTentsDirectRule.java | 130 +- .../rules/LastCampingSpotDirectRule.java | 155 +- .../treetent/rules/LinkTentCaseRule.java | 292 +-- .../treetent/rules/LinkTreeCaseRule.java | 307 +-- .../rules/NoTentForTreeContradictionRule.java | 98 +- .../rules/NoTreeForTentContradictionRule.java | 86 +- .../SurroundTentWithGrassDirectRule.java | 127 +- .../treetent/rules/TentForTreeDirectRule.java | 194 +- .../treetent/rules/TentOrGrassCaseRule.java | 172 +- .../rules/TooFewTentsContradictionRule.java | 62 +- .../rules/TooManyTentsContradictionRule.java | 58 +- .../rules/TouchingTentsContradictionRule.java | 60 +- .../treetent/rules/TreeForTentDirectRule.java | 194 +- .../rpi/legup/save/ExportFileException.java | 6 +- .../save/InvalidFileFormatException.java | 6 +- .../java/edu/rpi/legup/save/SavableBoard.java | 14 +- .../edu/rpi/legup/ui/CreatePuzzleDialog.java | 378 ++-- .../java/edu/rpi/legup/ui/DynamicView.java | 397 ++-- .../edu/rpi/legup/ui/DynamicViewType.java | 4 +- src/main/java/edu/rpi/legup/ui/HomePanel.java | 1218 +++++----- .../java/edu/rpi/legup/ui/LegupPanel.java | 6 +- src/main/java/edu/rpi/legup/ui/LegupUI.java | 372 +-- .../legup/ui/ManualPuzzleCreatorDialog.java | 2 +- .../java/edu/rpi/legup/ui/PickGameDialog.java | 260 +-- .../edu/rpi/legup/ui/PreferencesDialog.java | 803 +++---- .../edu/rpi/legup/ui/ProofEditorPanel.java | 2002 +++++++++-------- .../edu/rpi/legup/ui/PuzzleEditorPanel.java | 988 ++++---- .../java/edu/rpi/legup/ui/ScrollView.java | 559 ++--- .../java/edu/rpi/legup/ui/ToolbarName.java | 48 +- .../java/edu/rpi/legup/ui/WrapLayout.java | 294 +-- .../java/edu/rpi/legup/ui/ZoomWidget.java | 78 +- .../java/edu/rpi/legup/ui/ZoomablePane.java | 56 +- .../edu/rpi/legup/ui/boardview/BoardView.java | 386 ++-- .../legup/ui/boardview/DataSelectionView.java | 8 +- .../legup/ui/boardview/ElementSelection.java | 104 +- .../rpi/legup/ui/boardview/ElementView.java | 661 +++--- .../rpi/legup/ui/boardview/GridBoardView.java | 134 +- .../legup/ui/boardview/GridElementView.java | 6 +- .../legup/ui/boardview/SelectionItemView.java | 38 +- .../ui/lookandfeel/LegupLookAndFeel.java | 664 +++--- .../animation/MaterialUIMovement.java | 14 +- .../animation/MaterialUITimer.java | 184 +- .../components/MaterialButtonUI.java | 50 +- .../MaterialCheckBoxMenuItemUI.java | 80 +- .../components/MaterialCheckBoxUI.java | 34 +- .../components/MaterialComboBoxRenderer.java | 29 +- .../components/MaterialComboBoxUI.java | 74 +- .../components/MaterialEditorPaneUI.java | 14 +- .../components/MaterialFileChooserUI.java | 88 +- .../components/MaterialLabelUI.java | 34 +- .../components/MaterialMenuBarUI.java | 32 +- .../components/MaterialMenuItemUI.java | 36 +- .../components/MaterialMenuUI.java | 34 +- .../components/MaterialPanelUI.java | 32 +- .../components/MaterialPasswordFieldUI.java | 343 +-- .../components/MaterialPopupMenuUI.java | 30 +- .../components/MaterialProgressBarUI.java | 30 +- .../MaterialRadioButtonMenuItemUI.java | 86 +- .../components/MaterialRadioButtonUI.java | 34 +- .../components/MaterialScrollBarUI.java | 72 +- .../components/MaterialSeparatorUI.java | 22 +- .../components/MaterialSliderUI.java | 236 +- .../components/MaterialSpinnerUI.java | 108 +- .../components/MaterialSplitPaneDivider.java | 32 +- .../components/MaterialSplitPaneUI.java | 36 +- .../components/MaterialTabbedPaneUI.java | 134 +- .../components/MaterialTableCellEditor.java | 35 +- .../components/MaterialTableCellRenderer.java | 25 +- .../MaterialTableHeaderCellRenderer.java | 27 +- .../components/MaterialTableHeaderUI.java | 26 +- .../components/MaterialTableUI.java | 60 +- .../components/MaterialTextFieldUI.java | 351 +-- .../components/MaterialTextPaneUI.java | 14 +- .../components/MaterialToggleButtonUI.java | 38 +- .../components/MaterialToolBarUI.java | 40 +- .../components/MaterialToolTipUI.java | 22 +- .../components/MaterialTreeCellEditor.java | 78 +- .../components/MaterialTreeCellRenderer.java | 66 +- .../components/MaterialTreeUI.java | 58 +- .../materialdesign/DropShadowBorder.java | 745 +++--- .../materialdesign/MaterialBorders.java | 18 +- .../materialdesign/MaterialColors.java | 528 ++--- .../materialdesign/MaterialDrawingUtils.java | 40 +- .../materialdesign/MaterialFonts.java | 89 +- .../materialdesign/MaterialImages.java | 70 +- .../rulesview/CaseRulePanel.java | 28 +- .../rulesview/CaseRuleSelectionView.java | 20 +- .../rulesview/ContradictionRulePanel.java | 28 +- .../rulesview/DirectRulePanel.java | 30 +- .../proofeditorui/rulesview/RuleButton.java | 58 +- .../ui/proofeditorui/rulesview/RuleFrame.java | 325 +-- .../ui/proofeditorui/rulesview/RulePanel.java | 633 +++--- .../rulesview/SearchBarPanel.java | 30 +- .../treeview/TreeElementView.java | 330 +-- .../proofeditorui/treeview/TreeNodeView.java | 578 ++--- .../ui/proofeditorui/treeview/TreePanel.java | 188 +- .../treeview/TreeToolBarButton.java | 24 +- .../treeview/TreeToolBarName.java | 8 +- .../treeview/TreeToolbarPanel.java | 100 +- .../treeview/TreeTransitionView.java | 650 +++--- .../ui/proofeditorui/treeview/TreeView.java | 1612 ++++++------- .../treeview/TreeViewSelection.java | 303 +-- .../elementsview/ElementButton.java | 54 +- .../elementsview/ElementFrame.java | 175 +- .../elementsview/ElementPanel.java | 113 +- .../NonPlaceableElementPanel.java | 18 +- .../elementsview/PlaceableElementPanel.java | 18 +- .../java/edu/rpi/legup/user/Submission.java | 4 +- .../edu/rpi/legup/user/UsageStatistics.java | 66 +- .../rpi/legup/utility/ConnectedRegions.java | 112 +- .../edu/rpi/legup/utility/DisjointSets.java | 286 +-- .../java/edu/rpi/legup/utility/Entry.java | 88 +- .../edu/rpi/legup/utility/LegupUtils.java | 148 +- .../java/edu/rpi/legup/utility/Logger.java | 56 +- src/test/java/legup/MockGameBoardFacade.java | 54 +- src/test/java/legup/TestRunner.java | 174 +- src/test/java/legup/TestUtilities.java | 18 +- .../AdjacentShipsContradictionRuleTest.java | 87 +- .../rules/FinishWithShipsDirectRuleTests.java | 95 +- .../BulbsInPathContradictionRuleTest.java | 128 +- ...CannotLightACellContradictionRuleTest.java | 134 +- .../rules/EmptyCellinLightDirectRuleTest.java | 172 +- .../rules/EmptyCornersDirectRuleTest.java | 96 +- .../rules/FinishWithBulbsDirectRuleTest.java | 141 +- .../rules/LightOrEmptyCaseRuleTest.java | 92 +- .../rules/MustLightDirectRuleTest.java | 79 +- .../rules/SatisfyNumberCaseRuleTest.java | 286 +-- .../TooFewBulbsContradictionRuleTest.java | 88 +- .../TooManyBulbsContradictionRuleTest.java | 88 +- .../BlackBetweenRegionsDirectRuleTest.java | 344 +-- .../rules/BlackBottleNeckDirectRuleTest.java | 160 +- .../rules/BlackOrWhiteCaseRuleTest.java | 83 +- .../BlackSquareContradictionRuleTest.java | 152 +- .../rules/CannotReachCellDirectRuleTest.java | 113 +- .../rules/CornerBlackDirectRuleTest.java | 98 +- .../rules/FillinBlackDirectRuleTest.java | 229 +- .../rules/FillinWhiteDirectRuleTest.java | 233 +- .../IsolateBlackContradictionRuleTest.java | 147 +- .../MultipleNumbersContradictionRuleTest.java | 157 +- .../rules/NoNumbersContradictionRuleTest.java | 113 +- .../PreventBlackSquareDirectRuleTest.java | 293 +-- .../rules/SurroundRegionDirectRuleTest.java | 166 +- .../TooFewSpacesContradictionRuleTest.java | 129 +- .../TooManySpacesContradictionRuleTest.java | 144 +- ...achableWhiteCellContradictionRuleTest.java | 104 +- .../rules/WhiteBottleNeckDirectRuleTest.java | 158 +- .../rules/AndCaseRuleTest.java | 272 +-- .../rules/AndEliminationDirectRuleTest.java | 361 +-- .../rules/AndIntroductionDirectRuleTest.java | 148 +- .../rules/AtomicDirectRuleTest.java | 304 +-- .../rules/BiconditionalEliminationTest.java | 719 +++--- .../rules/BiconditionalIntroductionTest.java | 164 +- .../rules/ConditionalEliminationTest.java | 422 ++-- .../rules/ConditionalIntroductionTest.java | 152 +- .../rules/NotEliminationTest.java | 204 +- .../rules/NotIntroductionTest.java | 222 +- .../shorttruthtable/rules/OrCaseRuleTest.java | 272 +-- .../rules/OrEliminationTest.java | 261 +-- .../rules/OrIntroductionTest.java | 148 +- .../rules/TrueOrFalseCaseRuleTest.java | 100 +- .../rules/CellForNumberCaseRuleTest.java | 338 +-- .../DuplicateNumberContradictionTest.java | 260 +-- .../ExceedingVisibilityContradictionTest.java | 226 +- ...sufficientVisibilityContradictionTest.java | 226 +- .../rules/LastSingularCellDirectTest.java | 392 ++-- .../rules/LastSingularNumberDirectTest.java | 234 +- .../rules/LastVisibleCellDirectTest.java | 434 ++-- .../rules/LastVisibleNumberDirectTest.java | 434 ++-- .../skyscrapers/rules/NEdgeDirectTest.java | 216 +- .../rules/NumberForCellCaseRuleTest.java | 302 +-- ...PreemptiveVisibilityContradictionTest.java | 258 +-- .../UnresolvedCellContradictionTest.java | 265 +-- .../UnresolvedNumberContradictionTest.java | 289 +-- .../rules/EmptyFieldDirectRuleTest.java | 492 ++-- .../rules/FinishWithGrassDirectRuleTest.java | 656 +++--- .../rules/FinishWithTentsDirectRuleTest.java | 614 ++--- .../rules/LastCampingSpotDirectRuleTest.java | 272 +-- .../NoTentForTreeContradictionRuleTest.java | 187 +- .../NoTreeForTentContradictionRuleTest.java | 397 ++-- .../SurroundTentWithGrassDirectRuleTest.java | 260 +-- .../rules/TentForTreeDirectRuleTest.java | 16 +- .../rules/TentOrGrassCaseRuleTest.java | 96 +- .../TooFewTentsContradictionRuleTest.java | 430 ++-- .../TooManyTentsContradictionRuleTest.java | 463 ++-- .../TouchingTentsContradictionRuleTest.java | 477 ++-- .../rules/TreeForTentDirectRuleTest.java | 14 +- 522 files changed, 40888 insertions(+), 40056 deletions(-) diff --git a/src/main/java/edu/rpi/legup/Legup.java b/src/main/java/edu/rpi/legup/Legup.java index 0ea5b638a..79471286b 100644 --- a/src/main/java/edu/rpi/legup/Legup.java +++ b/src/main/java/edu/rpi/legup/Legup.java @@ -5,14 +5,14 @@ public class Legup { - /** - * Starts the Legup Program - * - * @param args arguments to Legup - */ - public static void main(String[] args) { - Logger.initLogger(); - GameBoardFacade.getInstance(); - GameBoardFacade.setupConfig(); - } + /** + * Starts the Legup Program + * + * @param args arguments to Legup + */ + public static void main(String[] args) { + Logger.initLogger(); + GameBoardFacade.getInstance(); + GameBoardFacade.setupConfig(); + } } diff --git a/src/main/java/edu/rpi/legup/app/Config.java b/src/main/java/edu/rpi/legup/app/Config.java index baaeb1dbd..8a8e9665d 100644 --- a/src/main/java/edu/rpi/legup/app/Config.java +++ b/src/main/java/edu/rpi/legup/app/Config.java @@ -13,139 +13,140 @@ import org.xml.sax.SAXException; public class Config { - private static final Logger Logger = LogManager.getLogger(Config.class.getName()); - - private Map puzzles; - private Map fileCreationDisabledStatuses; - private static final String CONFIG_LOCATION = "edu/rpi/legup/legup/config"; - - /** - * Config Constructor for logic puzzles - * - * @throws InvalidConfigException if configuration is invalid - */ - public Config() throws InvalidConfigException { - this.puzzles = new Hashtable<>(); - this.fileCreationDisabledStatuses = new Hashtable<>(); - loadConfig(this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION)); - } - - /** - * Gets a list of all available Puzzle names - * - * @return Vector of Puzzle names which are Strings - */ - public List getPuzzleClassNames() { - return new LinkedList<>(puzzles.keySet()); - } - - /** - * Returns a list of the names of the puzzles which can have puzzles created and edited within the - * proof editor. - * - * @return the aforementioned list of Strings - */ - public List getFileCreationEnabledPuzzles() { - LinkedList puzzles = new LinkedList(); - for (String puzzle : this.getPuzzleClassNames()) { - if (!this.fileCreationDisabledStatuses.get(puzzle)) { - puzzles.add(puzzle); - } + private static final Logger Logger = LogManager.getLogger(Config.class.getName()); + + private Map puzzles; + private Map fileCreationDisabledStatuses; + private static final String CONFIG_LOCATION = "edu/rpi/legup/legup/config"; + + /** + * Config Constructor for logic puzzles + * + * @throws InvalidConfigException if configuration is invalid + */ + public Config() throws InvalidConfigException { + this.puzzles = new Hashtable<>(); + this.fileCreationDisabledStatuses = new Hashtable<>(); + loadConfig(this.getClass().getClassLoader().getResourceAsStream(CONFIG_LOCATION)); } - return puzzles; - } - - /** - * Converts the class name of the puzzles to their display names. Some examples of the conversion: - * convertClassNameToDisplayName("TreeTent") will return "Tree Tent" - * convertClassNameToDisplayName("Nurikabe") will return "Nurikabe" - * - * @param className the name of the class - * @return displayName the name of the puzzle - */ - public static String convertClassNameToDisplayName(String className) { - String displayName = ""; - for (int i = 0; i < className.length(); i++) { - if (Character.isUpperCase(className.charAt(i)) && i != 0) { - displayName += " "; - } - displayName += className.charAt(i); + + /** + * Gets a list of all available Puzzle names + * + * @return Vector of Puzzle names which are Strings + */ + public List getPuzzleClassNames() { + return new LinkedList<>(puzzles.keySet()); + } + + /** + * Returns a list of the names of the puzzles which can have puzzles created and edited within + * the proof editor. + * + * @return the aforementioned list of Strings + */ + public List getFileCreationEnabledPuzzles() { + LinkedList puzzles = new LinkedList(); + for (String puzzle : this.getPuzzleClassNames()) { + if (!this.fileCreationDisabledStatuses.get(puzzle)) { + puzzles.add(puzzle); + } + } + return puzzles; + } + + /** + * Converts the class name of the puzzles to their display names. Some examples of the + * conversion: convertClassNameToDisplayName("TreeTent") will return "Tree Tent" + * convertClassNameToDisplayName("Nurikabe") will return "Nurikabe" + * + * @param className the name of the class + * @return displayName the name of the puzzle + */ + public static String convertClassNameToDisplayName(String className) { + String displayName = ""; + for (int i = 0; i < className.length(); i++) { + if (Character.isUpperCase(className.charAt(i)) && i != 0) { + displayName += " "; + } + displayName += className.charAt(i); + } + return displayName; } - return displayName; - } - - public static String convertDisplayNameToClassName(String displayName) { - String className = ""; - for (int i = 0; i < displayName.length(); i++) { - if (displayName.charAt(i) != ' ') { - className += displayName.charAt(i); - } + + public static String convertDisplayNameToClassName(String displayName) { + String className = ""; + for (int i = 0; i < displayName.length(); i++) { + if (displayName.charAt(i) != ' ') { + className += displayName.charAt(i); + } + } + return className; } - return className; - } - public List getPuzzleNames() { - List names = new LinkedList(); - for (String puzzle : this.getPuzzleClassNames()) { - names.add(Config.convertClassNameToDisplayName(puzzle)); + public List getPuzzleNames() { + List names = new LinkedList(); + for (String puzzle : this.getPuzzleClassNames()) { + names.add(Config.convertClassNameToDisplayName(puzzle)); + } + return names; } - return names; - } - public List getFileCreationEnabledPuzzleNames() { - List names = new LinkedList(); - for (String puzzle : this.getFileCreationEnabledPuzzles()) { - names.add(Config.convertClassNameToDisplayName(puzzle)); + public List getFileCreationEnabledPuzzleNames() { + List names = new LinkedList(); + for (String puzzle : this.getFileCreationEnabledPuzzles()) { + names.add(Config.convertClassNameToDisplayName(puzzle)); + } + return names; } - return names; - } - - /** - * Gets a {@link edu.rpi.legup.model.Puzzle} class for a puzzle name - * - * @param puzzleName puzzle name of the class - * @return class name for the puzzle name - */ - public String getPuzzleClassForName(String puzzleName) { - if (puzzles.containsKey(puzzleName)) { - return puzzles.get(puzzleName); + + /** + * Gets a {@link edu.rpi.legup.model.Puzzle} class for a puzzle name + * + * @param puzzleName puzzle name of the class + * @return class name for the puzzle name + */ + public String getPuzzleClassForName(String puzzleName) { + if (puzzles.containsKey(puzzleName)) { + return puzzles.get(puzzleName); + } + return null; } - return null; - } - - /** - * Loads the config object from the config xml file - * - * @param stream file stream for the config xml file - */ - private void loadConfig(InputStream stream) throws InvalidConfigException { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.parse(stream); - Element configNode = document.getDocumentElement(); - - if (!configNode.getNodeName().equalsIgnoreCase("Legup")) { - throw new InvalidConfigException("Config is not formatted correctly"); - } - - Element puzzleList = (Element) configNode.getElementsByTagName("puzzles").item(0); - Logger.debug(puzzleList); - NodeList puzzleNodes = puzzleList.getElementsByTagName("puzzle"); - - for (int i = 0; i < puzzleNodes.getLength(); i++) { - Element puzzle = (Element) puzzleNodes.item(i); - String name = puzzle.getAttribute("name"); - String className = puzzle.getAttribute("qualifiedClassName"); - boolean status = - Boolean.parseBoolean(puzzle.getAttribute("fileCreationDisabled").toLowerCase()); - Logger.debug("Class Name: " + className); - this.puzzles.put(name, className); - this.fileCreationDisabledStatuses.put(name, Boolean.valueOf(status)); - } - - } catch (ParserConfigurationException | SAXException | IOException e) { - throw new InvalidConfigException(e.getMessage()); + + /** + * Loads the config object from the config xml file + * + * @param stream file stream for the config xml file + */ + private void loadConfig(InputStream stream) throws InvalidConfigException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(stream); + Element configNode = document.getDocumentElement(); + + if (!configNode.getNodeName().equalsIgnoreCase("Legup")) { + throw new InvalidConfigException("Config is not formatted correctly"); + } + + Element puzzleList = (Element) configNode.getElementsByTagName("puzzles").item(0); + Logger.debug(puzzleList); + NodeList puzzleNodes = puzzleList.getElementsByTagName("puzzle"); + + for (int i = 0; i < puzzleNodes.getLength(); i++) { + Element puzzle = (Element) puzzleNodes.item(i); + String name = puzzle.getAttribute("name"); + String className = puzzle.getAttribute("qualifiedClassName"); + boolean status = + Boolean.parseBoolean( + puzzle.getAttribute("fileCreationDisabled").toLowerCase()); + Logger.debug("Class Name: " + className); + this.puzzles.put(name, className); + this.fileCreationDisabledStatuses.put(name, Boolean.valueOf(status)); + } + + } catch (ParserConfigurationException | SAXException | IOException e) { + throw new InvalidConfigException(e.getMessage()); + } } - } } diff --git a/src/main/java/edu/rpi/legup/app/GameBoardFacade.java b/src/main/java/edu/rpi/legup/app/GameBoardFacade.java index 8babbbfa3..c928c1209 100644 --- a/src/main/java/edu/rpi/legup/app/GameBoardFacade.java +++ b/src/main/java/edu/rpi/legup/app/GameBoardFacade.java @@ -32,491 +32,495 @@ import org.xml.sax.SAXException; public class GameBoardFacade implements IHistorySubject { - private static final Logger LOGGER = LogManager.getLogger(GameBoardFacade.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(GameBoardFacade.class.getName()); - protected static volatile GameBoardFacade instance; + protected static volatile GameBoardFacade instance; - private Config config; + private Config config; - protected Puzzle puzzle; + protected Puzzle puzzle; - private LegupUI legupUI; + private LegupUI legupUI; - private ProofEditorPanel puzzleSolver; + private ProofEditorPanel puzzleSolver; - private PuzzleEditorPanel puzzleEditor; + private PuzzleEditorPanel puzzleEditor; - private String curFileName; + private String curFileName; - private History history; - private List historyListeners; + private History history; + private List historyListeners; - /** Private GameBoardFacade Constructor creates a game board facade */ - protected GameBoardFacade() { - history = new History(); - historyListeners = new ArrayList<>(); - curFileName = null; - LegupPreferences.getInstance(); - initializeUI(); - } - - /** - * Gets the singleton instance of GameBoardFacade - * - * @return single instance of GameBoardFacade - */ - public static synchronized GameBoardFacade getInstance() { - if (instance == null) { - instance = new GameBoardFacade(); - } - return instance; - } - - public void initializeUI() { - EventQueue.invokeLater( - () -> { - legupUI = new LegupUI(); - puzzleSolver = legupUI.getProofEditor(); - puzzleEditor = legupUI.getPuzzleEditor(); - addHistoryListener(legupUI.getProofEditor()); - addHistoryListener(legupUI.getPuzzleEditor()); - }); - } - - public void setPuzzle(Puzzle puzzle) { - this.puzzle = puzzle; - this.puzzleSolver.setPuzzleView(puzzle); - this.history.clear(); - } - - public void clearPuzzle() { - this.puzzle = null; - this.curFileName = null; - this.history.clear(); - } - - public static void setupConfig() { - Config config = null; - try { - config = new Config(); - } catch (InvalidConfigException e) { - System.exit(1); + /** Private GameBoardFacade Constructor creates a game board facade */ + protected GameBoardFacade() { + history = new History(); + historyListeners = new ArrayList<>(); + curFileName = null; + LegupPreferences.getInstance(); + initializeUI(); } - GameBoardFacade.getInstance().setConfig(config); - } - - public void setPuzzleEditor(Puzzle puzzle) { - this.puzzle = puzzle; - this.puzzleEditor.setPuzzleView(puzzle); - } - - public void setConfig(Config config) { - this.config = config; - } - - /** - * Validates the given dimensions for the given puzzle - * - * @param game name of the puzzle - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @return true if it is possible to create a board for the given game with the given number of - * rows and columns, false otherwise - * @throws RuntimeException if any of the given input is invalid - */ - public boolean validateDimensions(String game, int rows, int columns) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - try { - Class c = Class.forName(qualifiedClassName); - Constructor constructor = c.getConstructor(); - Puzzle puzzle = (Puzzle) constructor.newInstance(); - return puzzle.isValidDimensions(rows, columns); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Error validating puzzle dimensions"); + + /** + * Gets the singleton instance of GameBoardFacade + * + * @return single instance of GameBoardFacade + */ + public static synchronized GameBoardFacade getInstance() { + if (instance == null) { + instance = new GameBoardFacade(); + } + return instance; } - } - - /** - * Validates the given text input for the given puzzle - * - * @param game the name of the puzzle - * @param statements an array of statements - * @return true if it is possible to create a board for the given game with the given statements, - * false otherwise - * @throws RuntimeException if any of the input is invalid - */ - public boolean validateTextInput(String game, String[] statements) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - try { - Class c = Class.forName(qualifiedClassName); - Constructor constructor = c.getConstructor(); - Puzzle puzzle = (Puzzle) constructor.newInstance(); - return puzzle.isValidTextInput(statements); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Error validating puzzle text input"); + + public void initializeUI() { + EventQueue.invokeLater( + () -> { + legupUI = new LegupUI(); + puzzleSolver = legupUI.getProofEditor(); + puzzleEditor = legupUI.getPuzzleEditor(); + addHistoryListener(legupUI.getProofEditor()); + addHistoryListener(legupUI.getPuzzleEditor()); + }); } - } - - /** - * Loads an empty puzzle - * - * @param game name of the puzzle - * @param rows the number of rows on the board - * @param columns the number of columns on the board - */ - public void loadPuzzle(String game, int rows, int columns) throws RuntimeException { - String qualifiedClassName = config.getPuzzleClassForName(game); - LOGGER.debug("Loading " + qualifiedClassName); - - try { - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new RuntimeException("Puzzle importer null"); - } - - // Theoretically, this exception should never be thrown, since LEGUP should not be - // allowing the user to give row/column input for a puzzle that doesn't support it - if (!importer.acceptsRowsAndColumnsInput()) { - throw new IllegalArgumentException( - puzzle.getName() + " does not accept rows and columns input"); - } - - setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); - importer.initializePuzzle(rows, columns); - - puzzle.initializeView(); - // - // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Puzzle creation error"); + + public void setPuzzle(Puzzle puzzle) { + this.puzzle = puzzle; + this.puzzleSolver.setPuzzleView(puzzle); + this.history.clear(); } - } - - public void loadPuzzle(String game, String[] statements) { - String qualifiedClassName = config.getPuzzleClassForName(game); - LOGGER.debug("Loading " + qualifiedClassName); - - try { - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); - - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new RuntimeException("Puzzle importer null"); - } - - // Theoretically, this exception should never be thrown, since LEGUP should not be - // allowing the user to give text input for a puzzle that doesn't support it - if (!importer.acceptsTextInput()) { - throw new IllegalArgumentException(puzzle.getName() + " does not accept text input"); - } - - setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); - importer.initializePuzzle(statements); - - puzzle.initializeView(); - // - // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new RuntimeException("Puzzle creation error"); + + public void clearPuzzle() { + this.puzzle = null; + this.curFileName = null; + this.history.clear(); } - } - - /** - * Loads a puzzle file - * - * @param fileName file name of the board file - * @throws InvalidFileFormatException if input is invalid - */ - public void loadPuzzle(String fileName) throws InvalidFileFormatException { - try { - loadPuzzle(new FileInputStream(fileName)); - curFileName = fileName; - setWindowTitle(puzzle.getName(), fileName); - } catch (IOException e) { - LOGGER.error("Invalid file " + fileName, e); - throw new InvalidFileFormatException("Could not find file"); + + public static void setupConfig() { + Config config = null; + try { + config = new Config(); + } catch (InvalidConfigException e) { + System.exit(1); + } + GameBoardFacade.getInstance().setConfig(config); } - } - - public void loadPuzzleEditor(String fileName) throws InvalidFileFormatException { - try { - loadPuzzleEditor(new FileInputStream(fileName)); - curFileName = fileName; - setWindowTitle(puzzle.getName(), fileName); - } catch (IOException e) { - LOGGER.error("Invalid file " + fileName, e); - throw new InvalidFileFormatException("Could not find file"); + + public void setPuzzleEditor(Puzzle puzzle) { + this.puzzle = puzzle; + this.puzzleEditor.setPuzzleView(puzzle); } - } - - public void loadPuzzleEditor(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Invalid file", e); - throw new InvalidFileFormatException("Could not find file"); + + public void setConfig(Config config) { + this.config = config; } - Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - try { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - String qualifiedClassName = - config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); - if (qualifiedClassName == null) { - throw new InvalidFileFormatException( - "Puzzle creation error: cannot find puzzle with that name"); + /** + * Validates the given dimensions for the given puzzle + * + * @param game name of the puzzle + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @return true if it is possible to create a board for the given game with the given number of + * rows and columns, false otherwise + * @throws RuntimeException if any of the given input is invalid + */ + public boolean validateDimensions(String game, int rows, int columns) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + try { + Class c = Class.forName(qualifiedClassName); + Constructor constructor = c.getConstructor(); + Puzzle puzzle = (Puzzle) constructor.newInstance(); + return puzzle.isValidDimensions(rows, columns); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Error validating puzzle dimensions"); } - // Check if puzzle is a "FileCreationEnabled" puzzle (meaning it is editable). - String[] editablePuzzles = config.getFileCreationEnabledPuzzles().toArray(new String[0]); - boolean isEditablePuzzle = false; - for (int i = 0; i < editablePuzzles.length; i++) { - if (qualifiedClassName.contains(editablePuzzles[i])) { - isEditablePuzzle = true; - break; - } + } + + /** + * Validates the given text input for the given puzzle + * + * @param game the name of the puzzle + * @param statements an array of statements + * @return true if it is possible to create a board for the given game with the given + * statements, false otherwise + * @throws RuntimeException if any of the input is invalid + */ + public boolean validateTextInput(String game, String[] statements) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + try { + Class c = Class.forName(qualifiedClassName); + Constructor constructor = c.getConstructor(); + Puzzle puzzle = (Puzzle) constructor.newInstance(); + return puzzle.isValidTextInput(statements); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Error validating puzzle text input"); } - if (!isEditablePuzzle) { - LOGGER.error("Puzzle is not editable"); - throw new InvalidFileFormatException("Puzzle is not editable"); + } + + /** + * Loads an empty puzzle + * + * @param game name of the puzzle + * @param rows the number of rows on the board + * @param columns the number of columns on the board + */ + public void loadPuzzle(String game, int rows, int columns) throws RuntimeException { + String qualifiedClassName = config.getPuzzleClassForName(game); + LOGGER.debug("Loading " + qualifiedClassName); + + try { + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new RuntimeException("Puzzle importer null"); + } + + // Theoretically, this exception should never be thrown, since LEGUP should not be + // allowing the user to give row/column input for a puzzle that doesn't support it + if (!importer.acceptsRowsAndColumnsInput()) { + throw new IllegalArgumentException( + puzzle.getName() + " does not accept rows and columns input"); + } + + setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); + importer.initializePuzzle(rows, columns); + + puzzle.initializeView(); + // + // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Puzzle creation error"); } - // If it is editable, start loading it + } + + public void loadPuzzle(String game, String[] statements) { + String qualifiedClassName = config.getPuzzleClassForName(game); LOGGER.debug("Loading " + qualifiedClassName); - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); + try { + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new RuntimeException("Puzzle importer null"); + } + + // Theoretically, this exception should never be thrown, since LEGUP should not be + // allowing the user to give text input for a puzzle that doesn't support it + if (!importer.acceptsTextInput()) { + throw new IllegalArgumentException( + puzzle.getName() + " does not accept text input"); + } + + setWindowTitle(puzzle.getName(), "New " + puzzle.getName() + " Puzzle"); + importer.initializePuzzle(statements); + + puzzle.initializeView(); + // + // puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new RuntimeException("Puzzle creation error"); + } + } - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new InvalidFileFormatException("Puzzle importer null"); + /** + * Loads a puzzle file + * + * @param fileName file name of the board file + * @throws InvalidFileFormatException if input is invalid + */ + public void loadPuzzle(String fileName) throws InvalidFileFormatException { + try { + loadPuzzle(new FileInputStream(fileName)); + curFileName = fileName; + setWindowTitle(puzzle.getName(), fileName); + } catch (IOException e) { + LOGGER.error("Invalid file " + fileName, e); + throw new InvalidFileFormatException("Could not find file"); } - importer.initializePuzzle(node); - puzzle.initializeView(); - puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzleEditor(puzzle); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new InvalidFileFormatException("Puzzle creation error"); - } - } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - } - - /** - * Loads a puzzle file from the input stream - * - * @throws InvalidFileFormatException if input is invalid - * @param inputStream input stream for the puzzle file - */ - public void loadPuzzle(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Invalid file", e); - throw new InvalidFileFormatException("Could not find file"); + + public void loadPuzzleEditor(String fileName) throws InvalidFileFormatException { + try { + loadPuzzleEditor(new FileInputStream(fileName)); + curFileName = fileName; + setWindowTitle(puzzle.getName(), fileName); + } catch (IOException e) { + LOGGER.error("Invalid file " + fileName, e); + throw new InvalidFileFormatException("Could not find file"); + } } - Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - try { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - String qualifiedClassName = - config.getPuzzleClassForName(node.getAttributes().getNamedItem("name").getNodeValue()); - if (qualifiedClassName == null) { - throw new InvalidFileFormatException( - "Puzzle creation error: cannot find puzzle with that name"); + public void loadPuzzleEditor(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Invalid file", e); + throw new InvalidFileFormatException("Could not find file"); } - LOGGER.debug("Loading " + qualifiedClassName); - Class c = Class.forName(qualifiedClassName); - Constructor cons = c.getConstructor(); - Puzzle puzzle = (Puzzle) cons.newInstance(); + Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + try { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + String qualifiedClassName = + config.getPuzzleClassForName( + node.getAttributes().getNamedItem("name").getNodeValue()); + if (qualifiedClassName == null) { + throw new InvalidFileFormatException( + "Puzzle creation error: cannot find puzzle with that name"); + } + // Check if puzzle is a "FileCreationEnabled" puzzle (meaning it is editable). + String[] editablePuzzles = + config.getFileCreationEnabledPuzzles().toArray(new String[0]); + boolean isEditablePuzzle = false; + for (int i = 0; i < editablePuzzles.length; i++) { + if (qualifiedClassName.contains(editablePuzzles[i])) { + isEditablePuzzle = true; + break; + } + } + if (!isEditablePuzzle) { + LOGGER.error("Puzzle is not editable"); + throw new InvalidFileFormatException("Puzzle is not editable"); + } + // If it is editable, start loading it + LOGGER.debug("Loading " + qualifiedClassName); + + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new InvalidFileFormatException("Puzzle importer null"); + } + importer.initializePuzzle(node); + puzzle.initializeView(); + puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzleEditor(puzzle); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new InvalidFileFormatException("Puzzle creation error"); + } + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); + } + } + + /** + * Loads a puzzle file from the input stream + * + * @throws InvalidFileFormatException if input is invalid + * @param inputStream input stream for the puzzle file + */ + public void loadPuzzle(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Invalid file", e); + throw new InvalidFileFormatException("Could not find file"); + } - PuzzleImporter importer = puzzle.getImporter(); - if (importer == null) { - LOGGER.error("Puzzle importer is null"); - throw new InvalidFileFormatException("Puzzle importer null"); + Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + try { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + String qualifiedClassName = + config.getPuzzleClassForName( + node.getAttributes().getNamedItem("name").getNodeValue()); + if (qualifiedClassName == null) { + throw new InvalidFileFormatException( + "Puzzle creation error: cannot find puzzle with that name"); + } + LOGGER.debug("Loading " + qualifiedClassName); + + Class c = Class.forName(qualifiedClassName); + Constructor cons = c.getConstructor(); + Puzzle puzzle = (Puzzle) cons.newInstance(); + + PuzzleImporter importer = puzzle.getImporter(); + if (importer == null) { + LOGGER.error("Puzzle importer is null"); + throw new InvalidFileFormatException("Puzzle importer null"); + } + importer.initializePuzzle(node); + puzzle.initializeView(); + puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); + setPuzzle(puzzle); + } catch (ClassNotFoundException + | NoSuchMethodException + | InvocationTargetException + | IllegalAccessException + | InstantiationException e) { + LOGGER.error(e); + throw new InvalidFileFormatException("Puzzle creation error"); + } + } else { + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - importer.initializePuzzle(node); - puzzle.initializeView(); - puzzle.getBoardView().onTreeElementChanged(puzzle.getTree().getRootNode()); - setPuzzle(puzzle); - } catch (ClassNotFoundException - | NoSuchMethodException - | InvocationTargetException - | IllegalAccessException - | InstantiationException e) { - LOGGER.error(e); - throw new InvalidFileFormatException("Puzzle creation error"); - } - } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - } - - /** - * Sets the window title to 'PuzzleName - FileName' Removes the extension - * - * @param puzzleName puzzle name for the file - * @param fileName file name of the edu.rpi.legup.puzzle - */ - public void setWindowTitle(String puzzleName, String fileName) { - File file = new File(fileName); - legupUI.setTitle(puzzleName + " - " + file.getName()); - } - - /** - * Gets the Config info - * - * @return Config object - */ - public Config getConfig() { - return config; - } - - /** - * Gets the LegupUI - * - * @return LegupUI - */ - public LegupUI getLegupUI() { - return legupUI; - } - - /** - * Gets the initial board state - * - * @return the initial board state - */ - public Board getBoard() { - return puzzle == null ? null : puzzle.getCurrentBoard(); - } - - /** - * Sets the initial board state and the tree - * - * @param board initial board - */ - public void setBoard(Board board) { - puzzle.setCurrentBoard(board); - } - - /** - * Gets the rules tree - * - * @return rules tree - */ - public Tree getTree() { - return puzzle == null ? null : puzzle.getTree(); - } - - /** - * Gets the Puzzle for the board - * - * @return the Puzzle for the board - */ - public Puzzle getPuzzleModule() { - return puzzle; - } - - /** - * Sets the Puzzle for the board - * - * @param puzzle the PuzzleModule for the board - */ - public void setPuzzleModule(Puzzle puzzle) { - this.puzzle = puzzle; - } - - public String getCurFileName() { - return this.curFileName; - } - - /** - * Adds a {@link IHistoryListener} - * - * @param listener listener to add - */ - @Override - public void addHistoryListener(IHistoryListener listener) { - historyListeners.add(listener); - } - - /** - * Adds a {@link IHistoryListener} - * - * @param listener listener to remove - */ - @Override - public void removeHistoryListener(IHistoryListener listener) { - historyListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyHistoryListeners(Consumer algorithm) { - historyListeners.forEach(algorithm); - } - - /** - * Gets the History object for storing changes to the board states - * - * @return History object - */ - public History getHistory() { - return history; - } + + /** + * Sets the window title to 'PuzzleName - FileName' Removes the extension + * + * @param puzzleName puzzle name for the file + * @param fileName file name of the edu.rpi.legup.puzzle + */ + public void setWindowTitle(String puzzleName, String fileName) { + File file = new File(fileName); + legupUI.setTitle(puzzleName + " - " + file.getName()); + } + + /** + * Gets the Config info + * + * @return Config object + */ + public Config getConfig() { + return config; + } + + /** + * Gets the LegupUI + * + * @return LegupUI + */ + public LegupUI getLegupUI() { + return legupUI; + } + + /** + * Gets the initial board state + * + * @return the initial board state + */ + public Board getBoard() { + return puzzle == null ? null : puzzle.getCurrentBoard(); + } + + /** + * Sets the initial board state and the tree + * + * @param board initial board + */ + public void setBoard(Board board) { + puzzle.setCurrentBoard(board); + } + + /** + * Gets the rules tree + * + * @return rules tree + */ + public Tree getTree() { + return puzzle == null ? null : puzzle.getTree(); + } + + /** + * Gets the Puzzle for the board + * + * @return the Puzzle for the board + */ + public Puzzle getPuzzleModule() { + return puzzle; + } + + /** + * Sets the Puzzle for the board + * + * @param puzzle the PuzzleModule for the board + */ + public void setPuzzleModule(Puzzle puzzle) { + this.puzzle = puzzle; + } + + public String getCurFileName() { + return this.curFileName; + } + + /** + * Adds a {@link IHistoryListener} + * + * @param listener listener to add + */ + @Override + public void addHistoryListener(IHistoryListener listener) { + historyListeners.add(listener); + } + + /** + * Adds a {@link IHistoryListener} + * + * @param listener listener to remove + */ + @Override + public void removeHistoryListener(IHistoryListener listener) { + historyListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyHistoryListeners(Consumer algorithm) { + historyListeners.forEach(algorithm); + } + + /** + * Gets the History object for storing changes to the board states + * + * @return History object + */ + public History getHistory() { + return history; + } } diff --git a/src/main/java/edu/rpi/legup/app/InvalidConfigException.java b/src/main/java/edu/rpi/legup/app/InvalidConfigException.java index 03120dffe..a570e7d44 100644 --- a/src/main/java/edu/rpi/legup/app/InvalidConfigException.java +++ b/src/main/java/edu/rpi/legup/app/InvalidConfigException.java @@ -1,7 +1,7 @@ package edu.rpi.legup.app; public class InvalidConfigException extends Exception { - public InvalidConfigException(String message) { - super(message); - } + public InvalidConfigException(String message) { + super(message); + } } diff --git a/src/main/java/edu/rpi/legup/app/LegupPreferences.java b/src/main/java/edu/rpi/legup/app/LegupPreferences.java index eb5ea5981..12433d7e4 100644 --- a/src/main/java/edu/rpi/legup/app/LegupPreferences.java +++ b/src/main/java/edu/rpi/legup/app/LegupPreferences.java @@ -6,120 +6,125 @@ public class LegupPreferences { - private static LegupPreferences instance; - - private static String SAVED_PATH = ""; - - private static final Preferences preferences = - Preferences.userNodeForPackage(LegupPreferences.class); - - private static final Map preferencesMap = new HashMap<>(); - private static final Map defaultPreferencesMap = new HashMap<>(); - - public static final String WORK_DIRECTORY = "work-directory"; - public static final String START_FULL_SCREEN = "start-full-screen"; - public static final String AUTO_UPDATE = "auto-update"; - public static final String DARK_MODE = "night-mode"; - public static final String SHOW_MISTAKES = "show-mistakes"; - public static final String SHOW_ANNOTATIONS = "show-annotations"; - public static final String ALLOW_DEFAULT_RULES = "allow-default-rules"; - public static final String AUTO_GENERATE_CASES = "auto-generate-cases"; - public static final String IMMEDIATE_FEEDBACK = "immediate-feedback"; - public static final String COLOR_BLIND = "color-blind"; - - static { - defaultPreferencesMap.put(WORK_DIRECTORY, System.getProperty("user.home")); - defaultPreferencesMap.put(START_FULL_SCREEN, Boolean.toString(false)); - defaultPreferencesMap.put(AUTO_UPDATE, Boolean.toString(true)); - defaultPreferencesMap.put(DARK_MODE, Boolean.toString(false)); - defaultPreferencesMap.put(SHOW_MISTAKES, Boolean.toString(true)); - defaultPreferencesMap.put(SHOW_ANNOTATIONS, Boolean.toString(false)); - defaultPreferencesMap.put(ALLOW_DEFAULT_RULES, Boolean.toString(false)); - defaultPreferencesMap.put(AUTO_GENERATE_CASES, Boolean.toString(true)); - defaultPreferencesMap.put(IMMEDIATE_FEEDBACK, Boolean.toString(true)); - defaultPreferencesMap.put(COLOR_BLIND, Boolean.toString(false)); - } - - static { - preferencesMap.put( - WORK_DIRECTORY, preferences.get(WORK_DIRECTORY, defaultPreferencesMap.get(WORK_DIRECTORY))); - preferencesMap.put( - START_FULL_SCREEN, - preferences.get(START_FULL_SCREEN, defaultPreferencesMap.get(START_FULL_SCREEN))); - preferencesMap.put( - AUTO_UPDATE, preferences.get(AUTO_UPDATE, defaultPreferencesMap.get(AUTO_UPDATE))); - preferencesMap.put(DARK_MODE, preferences.get(DARK_MODE, defaultPreferencesMap.get(DARK_MODE))); - preferencesMap.put( - SHOW_MISTAKES, preferences.get(SHOW_MISTAKES, defaultPreferencesMap.get(SHOW_MISTAKES))); - preferencesMap.put( - SHOW_ANNOTATIONS, - preferences.get(SHOW_ANNOTATIONS, defaultPreferencesMap.get(SHOW_ANNOTATIONS))); - preferencesMap.put( - ALLOW_DEFAULT_RULES, - preferences.get(ALLOW_DEFAULT_RULES, defaultPreferencesMap.get(ALLOW_DEFAULT_RULES))); - preferencesMap.put( - AUTO_GENERATE_CASES, - preferences.get(AUTO_GENERATE_CASES, defaultPreferencesMap.get(AUTO_GENERATE_CASES))); - preferencesMap.put( - IMMEDIATE_FEEDBACK, - preferences.get(IMMEDIATE_FEEDBACK, defaultPreferencesMap.get(IMMEDIATE_FEEDBACK))); - preferencesMap.put( - COLOR_BLIND, preferences.get(COLOR_BLIND, defaultPreferencesMap.get(COLOR_BLIND))); - } - - /** - * Gets the legup preferences singleton instance. - * - * @return legup preferences - */ - public static LegupPreferences getInstance() { - if (instance == null) { - instance = new LegupPreferences(); + private static LegupPreferences instance; + + private static String SAVED_PATH = ""; + + private static final Preferences preferences = + Preferences.userNodeForPackage(LegupPreferences.class); + + private static final Map preferencesMap = new HashMap<>(); + private static final Map defaultPreferencesMap = new HashMap<>(); + + public static final String WORK_DIRECTORY = "work-directory"; + public static final String START_FULL_SCREEN = "start-full-screen"; + public static final String AUTO_UPDATE = "auto-update"; + public static final String DARK_MODE = "night-mode"; + public static final String SHOW_MISTAKES = "show-mistakes"; + public static final String SHOW_ANNOTATIONS = "show-annotations"; + public static final String ALLOW_DEFAULT_RULES = "allow-default-rules"; + public static final String AUTO_GENERATE_CASES = "auto-generate-cases"; + public static final String IMMEDIATE_FEEDBACK = "immediate-feedback"; + public static final String COLOR_BLIND = "color-blind"; + + static { + defaultPreferencesMap.put(WORK_DIRECTORY, System.getProperty("user.home")); + defaultPreferencesMap.put(START_FULL_SCREEN, Boolean.toString(false)); + defaultPreferencesMap.put(AUTO_UPDATE, Boolean.toString(true)); + defaultPreferencesMap.put(DARK_MODE, Boolean.toString(false)); + defaultPreferencesMap.put(SHOW_MISTAKES, Boolean.toString(true)); + defaultPreferencesMap.put(SHOW_ANNOTATIONS, Boolean.toString(false)); + defaultPreferencesMap.put(ALLOW_DEFAULT_RULES, Boolean.toString(false)); + defaultPreferencesMap.put(AUTO_GENERATE_CASES, Boolean.toString(true)); + defaultPreferencesMap.put(IMMEDIATE_FEEDBACK, Boolean.toString(true)); + defaultPreferencesMap.put(COLOR_BLIND, Boolean.toString(false)); } - return instance; - } - - /** Private LegupPreferences Singleton Constructor */ - private LegupPreferences() {} - - /** - * Gets the user preference by the string key - * - * @param key key name of the preference - * @return value of the preference - */ - public String getUserPref(String key) { - return preferencesMap.get(key); - } - - /** - * Gets the user preference by the string key, value pair - * - * @param key key name of the preference - * @param value value of the preference - */ - public void setUserPref(String key, String value) { - preferences.put(key, value); - preferencesMap.put(key, value); - } - - public boolean getUserPrefAsBool(String key) { - if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(true))) { - return true; - } else { - if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(false))) { - return false; - } else { - throw new RuntimeException("Cannot get user preference - " + key); - } + + static { + preferencesMap.put( + WORK_DIRECTORY, + preferences.get(WORK_DIRECTORY, defaultPreferencesMap.get(WORK_DIRECTORY))); + preferencesMap.put( + START_FULL_SCREEN, + preferences.get(START_FULL_SCREEN, defaultPreferencesMap.get(START_FULL_SCREEN))); + preferencesMap.put( + AUTO_UPDATE, preferences.get(AUTO_UPDATE, defaultPreferencesMap.get(AUTO_UPDATE))); + preferencesMap.put( + DARK_MODE, preferences.get(DARK_MODE, defaultPreferencesMap.get(DARK_MODE))); + preferencesMap.put( + SHOW_MISTAKES, + preferences.get(SHOW_MISTAKES, defaultPreferencesMap.get(SHOW_MISTAKES))); + preferencesMap.put( + SHOW_ANNOTATIONS, + preferences.get(SHOW_ANNOTATIONS, defaultPreferencesMap.get(SHOW_ANNOTATIONS))); + preferencesMap.put( + ALLOW_DEFAULT_RULES, + preferences.get( + ALLOW_DEFAULT_RULES, defaultPreferencesMap.get(ALLOW_DEFAULT_RULES))); + preferencesMap.put( + AUTO_GENERATE_CASES, + preferences.get( + AUTO_GENERATE_CASES, defaultPreferencesMap.get(AUTO_GENERATE_CASES))); + preferencesMap.put( + IMMEDIATE_FEEDBACK, + preferences.get(IMMEDIATE_FEEDBACK, defaultPreferencesMap.get(IMMEDIATE_FEEDBACK))); + preferencesMap.put( + COLOR_BLIND, preferences.get(COLOR_BLIND, defaultPreferencesMap.get(COLOR_BLIND))); + } + + /** + * Gets the legup preferences singleton instance. + * + * @return legup preferences + */ + public static LegupPreferences getInstance() { + if (instance == null) { + instance = new LegupPreferences(); + } + return instance; } - } - public String getSavedPath() { - return SAVED_PATH; - } + /** Private LegupPreferences Singleton Constructor */ + private LegupPreferences() {} + + /** + * Gets the user preference by the string key + * + * @param key key name of the preference + * @return value of the preference + */ + public String getUserPref(String key) { + return preferencesMap.get(key); + } + + /** + * Gets the user preference by the string key, value pair + * + * @param key key name of the preference + * @param value value of the preference + */ + public void setUserPref(String key, String value) { + preferences.put(key, value); + preferencesMap.put(key, value); + } - public void setSavedPath(String path) { - SAVED_PATH = path; - } + public boolean getUserPrefAsBool(String key) { + if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(true))) { + return true; + } else { + if (preferencesMap.get(key).equalsIgnoreCase(Boolean.toString(false))) { + return false; + } else { + throw new RuntimeException("Cannot get user preference - " + key); + } + } + } + + public String getSavedPath() { + return SAVED_PATH; + } + + public void setSavedPath(String path) { + SAVED_PATH = path; + } } diff --git a/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java b/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java index 4a055ab3a..f3945be22 100644 --- a/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java +++ b/src/main/java/edu/rpi/legup/app/PuzzleKeyAccelerator.java @@ -19,85 +19,87 @@ public class PuzzleKeyAccelerator implements KeyListener { - private Map keyStrokeMap; + private Map keyStrokeMap; - public PuzzleKeyAccelerator() { - this.keyStrokeMap = new HashMap<>(); - } + public PuzzleKeyAccelerator() { + this.keyStrokeMap = new HashMap<>(); + } - public void addKeyAccelerator(KeyStroke keyStroke, Rule rule) { - keyStrokeMap.put(keyStroke, rule); - } + public void addKeyAccelerator(KeyStroke keyStroke, Rule rule) { + keyStrokeMap.put(keyStroke, rule); + } - public Map getKeyStrokeMap() { - return this.keyStrokeMap; - } + public Map getKeyStrokeMap() { + return this.keyStrokeMap; + } - public void clearKeyMap() { - this.keyStrokeMap.clear(); - } + public void clearKeyMap() { + this.keyStrokeMap.clear(); + } - /** - * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a - * definition of a key typed event. - * - * @param e the event to be processed - */ - @Override - public void keyTyped(KeyEvent e) {} + /** + * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a + * definition of a key typed event. + * + * @param e the event to be processed + */ + @Override + public void keyTyped(KeyEvent e) {} - /** - * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a - * definition of a key pressed event. - * - * @param e the event to be processed - */ - @Override - public void keyPressed(KeyEvent e) { - KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); - Rule rule = keyStrokeMap.get(keyStroke); - if (rule != null) { - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + /** + * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a + * definition of a key pressed event. + * + * @param e the event to be processed + */ + @Override + public void keyPressed(KeyEvent e) { + KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e); + Rule rule = keyStrokeMap.get(keyStroke); + if (rule != null) { + TreeView treeView = + GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - String update = ""; - if (rule.getRuleType() == RuleType.CASE) { - // TODO: review this line of code and figure out what it's supposed to do (remove if - // necessary) - // handleCaseRule((CaseRule)rule); - } else { - if (rule.getRuleType() == RuleType.CONTRADICTION) { - TreeViewSelection selection = treeView.getSelection(); + String update = ""; + if (rule.getRuleType() == RuleType.CASE) { + // TODO: review this line of code and figure out what it's supposed to do (remove if + // necessary) + // handleCaseRule((CaseRule)rule); + } else { + if (rule.getRuleType() == RuleType.CONTRADICTION) { + TreeViewSelection selection = treeView.getSelection(); - ICommand validate = - new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - update = validate.getError(); - } - } else { - TreeViewSelection selection = treeView.getSelection(); + ICommand validate = + new ValidateContradictionRuleCommand( + selection, (ContradictionRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + update = validate.getError(); + } + } else { + TreeViewSelection selection = treeView.getSelection(); - ICommand validate = new ValidateDirectRuleCommand(selection, (DirectRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - update = validate.getError(); - } + ICommand validate = new ValidateDirectRuleCommand(selection, (DirectRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + update = validate.getError(); + } + } + } + GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(update); } - } - GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(update); } - } - /** - * Invoked when a key has been released. See the class description for {@link KeyEvent} for a - * definition of a key released event. - * - * @param e the event to be processed - */ - @Override - public void keyReleased(KeyEvent e) {} + /** + * Invoked when a key has been released. See the class description for {@link KeyEvent} for a + * definition of a key released event. + * + * @param e the event to be processed + */ + @Override + public void keyReleased(KeyEvent e) {} } diff --git a/src/main/java/edu/rpi/legup/controller/BoardController.java b/src/main/java/edu/rpi/legup/controller/BoardController.java index f672961d2..eaae3851d 100644 --- a/src/main/java/edu/rpi/legup/controller/BoardController.java +++ b/src/main/java/edu/rpi/legup/controller/BoardController.java @@ -4,88 +4,88 @@ import java.awt.event.*; public class BoardController extends Controller { - protected Point lastLeftMousePoint; - protected Point lastRightMousePoint; + protected Point lastLeftMousePoint; + protected Point lastRightMousePoint; - /** - * BoardController Constructor creates a controller object to listen to ui events from a - * ScrollView - */ - public BoardController() { - super(); - lastLeftMousePoint = null; - lastRightMousePoint = null; - } + /** + * BoardController Constructor creates a controller object to listen to ui events from a + * ScrollView + */ + public BoardController() { + super(); + lastLeftMousePoint = null; + lastRightMousePoint = null; + } - /** - * Mouse Clicked event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event - sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); - } + /** + * Mouse Pressed event - sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); + } - /** - * Mouse Released event - sets the cursor back to the default cursor and reset info for panning - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - } + /** + * Mouse Released event - sets the cursor back to the default cursor and reset info for panning + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + } - /** - * Mouse Entered event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) {} + /** + * Mouse Entered event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) {} - /** - * Mouse Exited event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) {} + /** + * Mouse Exited event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) {} - /** - * Mouse Dragged event - adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - super.mouseDragged(e); - } + /** + * Mouse Dragged event - adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + super.mouseDragged(e); + } - /** - * Mouse Moved event - no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) {} + /** + * Mouse Moved event - no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) {} - /** - * Mouse Wheel Moved event - zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - super.mouseWheelMoved(e); - } + /** + * Mouse Wheel Moved event - zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + super.mouseWheelMoved(e); + } } diff --git a/src/main/java/edu/rpi/legup/controller/Controller.java b/src/main/java/edu/rpi/legup/controller/Controller.java index cd281fc21..57ce107ac 100644 --- a/src/main/java/edu/rpi/legup/controller/Controller.java +++ b/src/main/java/edu/rpi/legup/controller/Controller.java @@ -6,116 +6,116 @@ import javax.swing.*; public abstract class Controller implements MouseMotionListener, MouseListener, MouseWheelListener { - protected ScrollView viewer; - private int x, y; - private boolean pan; + protected ScrollView viewer; + private int x, y; + private boolean pan; - /** - * Controller Constructor creates a controller object to listen to ui events from a {@link - * ScrollView} - */ - public Controller() { - x = y = -1; - pan = false; - } + /** + * Controller Constructor creates a controller object to listen to ui events from a {@link + * ScrollView} + */ + public Controller() { + x = y = -1; + pan = false; + } - public void setViewer(ScrollView viewer) { - this.viewer = viewer; - } + public void setViewer(ScrollView viewer) { + this.viewer = viewer; + } - /** - * Mouse Clicked event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON2) { - pan = true; - x = e.getX(); - y = e.getY(); - viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); + /** + * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON2) { + pan = true; + x = e.getX(); + y = e.getY(); + viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); + } } - } - /** - * Mouse Released event sets the cursor back to the default cursor and reset info for panning - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON2) { - pan = false; - viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + /** + * Mouse Released event sets the cursor back to the default cursor and reset info for panning + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON2) { + pan = false; + viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } } - } - /** - * Mouse Entered event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) {} + /** + * Mouse Entered event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) {} - /** - * Mouse Exited event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) {} + /** + * Mouse Exited event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) {} - /** - * Mouse Dragged event adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - if (pan) { - JViewport viewport = viewer.getViewport(); - Point position = viewer.getViewport().getViewPosition(); - position.x += (x - e.getX()); - position.y += (y - e.getY()); - viewport.setViewPosition(position); - viewer.revalidate(); + /** + * Mouse Dragged event adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + if (pan) { + JViewport viewport = viewer.getViewport(); + Point position = viewer.getViewport().getViewPosition(); + position.x += (x - e.getX()); + position.y += (y - e.getY()); + viewport.setViewPosition(position); + viewer.revalidate(); + } } - } - /** - * Mouse Moved event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) {} + /** + * Mouse Moved event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) {} - /** - * Mouse Wheel Moved event zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - // System.out.println(e.getWheelRotation()); - if (e.isControlDown()) { - if (e.getWheelRotation() != 0) { - viewer.zoom(e.getWheelRotation() * 2, e.getPoint()); - } - } else { - if (e.getWheelRotation() != 0) { - viewer.zoom(e.getWheelRotation(), e.getPoint()); - } + /** + * Mouse Wheel Moved event zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + // System.out.println(e.getWheelRotation()); + if (e.isControlDown()) { + if (e.getWheelRotation() != 0) { + viewer.zoom(e.getWheelRotation() * 2, e.getPoint()); + } + } else { + if (e.getWheelRotation() != 0) { + viewer.zoom(e.getWheelRotation(), e.getPoint()); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/controller/CursorController.java b/src/main/java/edu/rpi/legup/controller/CursorController.java index a97f147b8..2706bd522 100644 --- a/src/main/java/edu/rpi/legup/controller/CursorController.java +++ b/src/main/java/edu/rpi/legup/controller/CursorController.java @@ -7,48 +7,48 @@ import java.util.TimerTask; public class CursorController { - public static final Cursor BUSY_CURSOR = new Cursor(Cursor.WAIT_CURSOR); - public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); - public static final int DELAY = 200; // in milliseconds + public static final Cursor BUSY_CURSOR = new Cursor(Cursor.WAIT_CURSOR); + public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); + public static final int DELAY = 200; // in milliseconds - private CursorController() { - // Intentionally left empty - } + private CursorController() { + // Intentionally left empty + } - /** - * Creates an ActionListener that will still do the same action processing as the given - * ActionListener while also displaying a loading cursor if the time it takes to execute the given - * process exceeds the time (in milliseconds) specified in this.DELAY - * - *

Sources consulted: http://www.catalysoft.com/articles/busycursor.html - * - * @param component The component you want to set the cursor for - * @param mainActionListener The ActionListener that does the intended action processing - * @return An ActionListener object that does the same action processing as mainActionListener - * while also modifying the cursor if needed - */ - public static ActionListener createListener( - final Component component, final ActionListener mainActionListener) { - ActionListener actionListener = - e -> { - TimerTask timerTask = - new TimerTask() { - @Override - public void run() { - component.setCursor(BUSY_CURSOR); - } - }; + /** + * Creates an ActionListener that will still do the same action processing as the given + * ActionListener while also displaying a loading cursor if the time it takes to execute the + * given process exceeds the time (in milliseconds) specified in this.DELAY + * + *

Sources consulted: http://www.catalysoft.com/articles/busycursor.html + * + * @param component The component you want to set the cursor for + * @param mainActionListener The ActionListener that does the intended action processing + * @return An ActionListener object that does the same action processing as mainActionListener + * while also modifying the cursor if needed + */ + public static ActionListener createListener( + final Component component, final ActionListener mainActionListener) { + ActionListener actionListener = + e -> { + TimerTask timerTask = + new TimerTask() { + @Override + public void run() { + component.setCursor(BUSY_CURSOR); + } + }; - Timer timer = new Timer(); - try { - timer.schedule(timerTask, DELAY); - mainActionListener.actionPerformed(e); - } finally { - timer.cancel(); - component.setCursor(DEFAULT_CURSOR); - } - }; + Timer timer = new Timer(); + try { + timer.schedule(timerTask, DELAY); + mainActionListener.actionPerformed(e); + } finally { + timer.cancel(); + component.setCursor(DEFAULT_CURSOR); + } + }; - return actionListener; - } + return actionListener; + } } diff --git a/src/main/java/edu/rpi/legup/controller/EditorElementController.java b/src/main/java/edu/rpi/legup/controller/EditorElementController.java index 7aa1fe06c..5a23885af 100644 --- a/src/main/java/edu/rpi/legup/controller/EditorElementController.java +++ b/src/main/java/edu/rpi/legup/controller/EditorElementController.java @@ -10,43 +10,43 @@ import javax.swing.*; public class EditorElementController implements ActionListener { - protected Object lastSource; - protected ElementController elementController; - protected ElementButton prevButton; - - public EditorElementController() { - super(); - elementController = null; - prevButton = null; - } - - public void setElementController(ElementController elementController) { - this.elementController = elementController; - } - - public void buttonPressed(Element element) { - // TODO: implement what happens when element is pressed - - System.out.printf("%s button pressed!\n", element.getElementName()); - if (elementController != null) { - elementController.setSelectedElement(element); + protected Object lastSource; + protected ElementController elementController; + protected ElementButton prevButton; + + public EditorElementController() { + super(); + elementController = null; + prevButton = null; } - } - @Override - public void actionPerformed(ActionEvent e) { - lastSource = e.getSource(); - ElementButton button = (ElementButton) lastSource; - buttonPressed(button.getElement()); + public void setElementController(ElementController elementController) { + this.elementController = elementController; + } + + public void buttonPressed(Element element) { + // TODO: implement what happens when element is pressed - // reset border in previous selected button - if (this.prevButton != null) { - this.prevButton.resetBorder(); + System.out.printf("%s button pressed!\n", element.getElementName()); + if (elementController != null) { + elementController.setSelectedElement(element); + } } - // change border color when select a button - button.setBorderToSelected(); + @Override + public void actionPerformed(ActionEvent e) { + lastSource = e.getSource(); + ElementButton button = (ElementButton) lastSource; + buttonPressed(button.getElement()); + + // reset border in previous selected button + if (this.prevButton != null) { + this.prevButton.resetBorder(); + } - this.prevButton = button; - } + // change border color when select a button + button.setBorderToSelected(); + + this.prevButton = button; + } } diff --git a/src/main/java/edu/rpi/legup/controller/ElementController.java b/src/main/java/edu/rpi/legup/controller/ElementController.java index 6b6707c32..5840650e1 100644 --- a/src/main/java/edu/rpi/legup/controller/ElementController.java +++ b/src/main/java/edu/rpi/legup/controller/ElementController.java @@ -27,324 +27,325 @@ import java.awt.event.*; public class ElementController - implements MouseListener, MouseMotionListener, ActionListener, KeyListener { - protected BoardView boardView; - private Element selectedElement; + implements MouseListener, MouseMotionListener, ActionListener, KeyListener { + protected BoardView boardView; + private Element selectedElement; - /** - * ElementController Constructor controller to handles ui events associated interacting with a - * {@link BoardView} - */ - public ElementController() { - this.boardView = null; - this.selectedElement = null; - } + /** + * ElementController Constructor controller to handles ui events associated interacting with a + * {@link BoardView} + */ + public ElementController() { + this.boardView = null; + this.selectedElement = null; + } - public void setSelectedElement(Element selectedElement) { - this.selectedElement = selectedElement; - } + public void setSelectedElement(Element selectedElement) { + this.selectedElement = selectedElement; + } - /** - * Sets the {@link BoardView} - * - * @param boardView board view - */ - public void setBoardView(BoardView boardView) { - this.boardView = boardView; - } + /** + * Sets the {@link BoardView} + * + * @param boardView board view + */ + public void setBoardView(BoardView boardView) { + this.boardView = boardView; + } - /** - * Invoked when the mouse button has been clicked (pressed and released) on a component. - * - * @param e the event to be processed - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Invoked when the mouse button has been clicked (pressed and released) on a component. + * + * @param e the event to be processed + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e the event to be processed - */ - @Override - public void mousePressed(MouseEvent e) {} + /** + * Invoked when a mouse button has been pressed on a component. + * + * @param e the event to be processed + */ + @Override + public void mousePressed(MouseEvent e) {} - /** - * Invoked when a mouse button has been released on a component. - * - * @param e the event to be processed - */ - @Override - public void mouseReleased(MouseEvent e) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = null; - if (treePanel != null) { - treeView = treePanel.getTreeView(); - } + /** + * Invoked when a mouse button has been released on a component. + * + * @param e the event to be processed + */ + @Override + public void mouseReleased(MouseEvent e) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = null; + if (treePanel != null) { + treeView = treePanel.getTreeView(); + } - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - ElementView elementView = boardView.getElement(e.getPoint()); - TreeViewSelection selection = null; - if (treeView != null) { - selection = treeView.getSelection(); - } - // funny - if (elementView != null) { - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - AutoCaseRuleCommand autoCaseRuleCommand = - new AutoCaseRuleCommand(elementView, selection, caseBoard.getCaseRule(), caseBoard, e); - if (autoCaseRuleCommand.canExecute()) { - autoCaseRuleCommand.execute(); - getInstance().getHistory().pushChange(autoCaseRuleCommand); - if (treePanel != null) { - treePanel.updateError(""); - } - } else { - if (treePanel != null) { - treePanel.updateError(autoCaseRuleCommand.getError()); - } + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - } else { - if (selection != null) { - ICommand edit = new EditDataCommand(elementView, selection, e); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - if (treePanel != null) { - treePanel.updateError(""); - } - } else { - if (treePanel != null) { - treePanel.updateError(edit.getError()); + Board board = boardView.getBoard(); + ElementView elementView = boardView.getElement(e.getPoint()); + TreeViewSelection selection = null; + if (treeView != null) { + selection = treeView.getSelection(); + } + // funny + if (elementView != null) { + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + AutoCaseRuleCommand autoCaseRuleCommand = + new AutoCaseRuleCommand( + elementView, selection, caseBoard.getCaseRule(), caseBoard, e); + if (autoCaseRuleCommand.canExecute()) { + autoCaseRuleCommand.execute(); + getInstance().getHistory().pushChange(autoCaseRuleCommand); + if (treePanel != null) { + treePanel.updateError(""); + } + } else { + if (treePanel != null) { + treePanel.updateError(autoCaseRuleCommand.getError()); + } + } + } else { + if (selection != null) { + ICommand edit = new EditDataCommand(elementView, selection, e); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + if (treePanel != null) { + treePanel.updateError(""); + } + } else { + if (treePanel != null) { + treePanel.updateError(edit.getError()); + } + } + } } - } } - } - } - // if (selectedElement != null) { - GridBoard b = (GridBoard) this.boardView.getBoard(); - Point point = e.getPoint(); - Point scaledPoint = - new Point( - (int) Math.floor(point.x / (30 * this.boardView.getScale())), - (int) Math.floor(point.y / (30 * this.boardView.getScale()))); - if (this.boardView.getBoard() instanceof TreeTentBoard) { - scaledPoint.setLocation(scaledPoint.getX() - 1, scaledPoint.getY() - 1); + // if (selectedElement != null) { + GridBoard b = (GridBoard) this.boardView.getBoard(); + Point point = e.getPoint(); + Point scaledPoint = + new Point( + (int) Math.floor(point.x / (30 * this.boardView.getScale())), + (int) Math.floor(point.y / (30 * this.boardView.getScale()))); + if (this.boardView.getBoard() instanceof TreeTentBoard) { + scaledPoint.setLocation(scaledPoint.getX() - 1, scaledPoint.getY() - 1); + } + System.out.printf( + "selected Element is NOT null, attempting to change board at (%d, %d)\n", + scaledPoint.x, scaledPoint.y); + // System.out.println("Before: " + b.getCell(scaledPoint.x, + // scaledPoint.y).getData()); + b.setCell(scaledPoint.x, scaledPoint.y, this.selectedElement, e); + // System.out.println("After: " + b.getCell(scaledPoint.x, + // scaledPoint.y).getData()); + // } else { + // System.out.println("selected Element is null!"); + // } + boardView.repaint(); } - System.out.printf( - "selected Element is NOT null, attempting to change board at (%d, %d)\n", - scaledPoint.x, scaledPoint.y); - // System.out.println("Before: " + b.getCell(scaledPoint.x, - // scaledPoint.y).getData()); - b.setCell(scaledPoint.x, scaledPoint.y, this.selectedElement, e); - // System.out.println("After: " + b.getCell(scaledPoint.x, - // scaledPoint.y).getData()); - // } else { - // System.out.println("selected Element is null!"); - // } - boardView.repaint(); - } - /** - * Invoked when the mouse enters a component. - * - * @param e the event to be processed - */ - @Override - public void mouseEntered(MouseEvent e) { - boardView.setFocusable(true); - boardView.requestFocusInWindow(); - TreeElement treeElement = boardView.getTreeElement(); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); - } - Board board = boardView.getBoard(); - ElementView elementView = boardView.getElement(e.getPoint()); - ElementSelection selection = boardView.getSelection(); - String error = null; - if (elementView != null) { - selection.newHover(elementView); - if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { - PuzzleElement element = elementView.getPuzzleElement(); - if (treeElement != null - && treeElement.getType() == TreeElementType.TRANSITION - && board.getModifiedData().contains(element)) { - TreeTransition transition = (TreeTransition) treeElement; - if (transition.isJustified() && !transition.isCorrect()) { - error = transition.getRule().checkRuleAt(transition, element); - } + /** + * Invoked when the mouse enters a component. + * + * @param e the event to be processed + */ + @Override + public void mouseEntered(MouseEvent e) { + boardView.setFocusable(true); + boardView.requestFocusInWindow(); + TreeElement treeElement = boardView.getTreeElement(); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - if (error != null) { - dynamicView.updateError(error); - } else { - dynamicView.resetStatus(); + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + Board board = boardView.getBoard(); + ElementView elementView = boardView.getElement(e.getPoint()); + ElementSelection selection = boardView.getSelection(); + String error = null; + if (elementView != null) { + selection.newHover(elementView); + if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { + PuzzleElement element = elementView.getPuzzleElement(); + if (treeElement != null + && treeElement.getType() == TreeElementType.TRANSITION + && board.getModifiedData().contains(element)) { + TreeTransition transition = (TreeTransition) treeElement; + if (transition.isJustified() && !transition.isCorrect()) { + error = transition.getRule().checkRuleAt(transition, element); + } + } + if (error != null) { + dynamicView.updateError(error); + } else { + dynamicView.resetStatus(); + } + } + boardView.repaint(); } - } - boardView.repaint(); } - } - /** - * Invoked when the mouse exits a component. - * - * @param e the event to be processed - */ - @Override - public void mouseExited(MouseEvent e) { - boardView.setFocusable(false); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); - } - ElementView element = boardView.getElement(e.getPoint()); - if (element != null) { - boardView.getSelection().clearHover(); - dynamicView.resetStatus(); - boardView.repaint(); + /** + * Invoked when the mouse exits a component. + * + * @param e the event to be processed + */ + @Override + public void mouseExited(MouseEvent e) { + boardView.setFocusable(false); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + ElementView element = boardView.getElement(e.getPoint()); + if (element != null) { + boardView.getSelection().clearHover(); + dynamicView.resetStatus(); + boardView.repaint(); + } } - } - /** - * Invoked when the mouse dragged - * - * @param e the event to be processed - */ - @Override - public void mouseDragged(MouseEvent e) {} + /** + * Invoked when the mouse dragged + * + * @param e the event to be processed + */ + @Override + public void mouseDragged(MouseEvent e) {} - /** - * Invoked when the mouse moved - * - * @param e the event to be processed - */ - @Override - public void mouseMoved(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - TreeElement treeElement = boardView.getTreeElement(); - DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); - if (dynamicView == null) { - dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); - } - ElementView elementView = boardView.getElement(e.getPoint()); - ElementSelection selection = boardView.getSelection(); - String error = null; - if (elementView != null && elementView != selection.getHover()) { - selection.newHover(elementView); - if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { - PuzzleElement element = elementView.getPuzzleElement(); - if (treeElement != null - && treeElement.getType() == TreeElementType.TRANSITION - && board.getModifiedData().contains(element)) { - TreeTransition transition = (TreeTransition) treeElement; - if (transition.isJustified() && !transition.isCorrect()) { - error = transition.getRule().checkRuleAt(transition, element); - } + /** + * Invoked when the mouse moved + * + * @param e the event to be processed + */ + @Override + public void mouseMoved(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); } - if (error != null) { - dynamicView.updateError(error); - } else { - dynamicView.resetStatus(); + Board board = boardView.getBoard(); + TreeElement treeElement = boardView.getTreeElement(); + DynamicView dynamicView = getInstance().getLegupUI().getDynamicBoardView(); + if (dynamicView == null) { + dynamicView = getInstance().getLegupUI().getEditorDynamicBoardView(); + } + ElementView elementView = boardView.getElement(e.getPoint()); + ElementSelection selection = boardView.getSelection(); + String error = null; + if (elementView != null && elementView != selection.getHover()) { + selection.newHover(elementView); + if (LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.SHOW_MISTAKES)) { + PuzzleElement element = elementView.getPuzzleElement(); + if (treeElement != null + && treeElement.getType() == TreeElementType.TRANSITION + && board.getModifiedData().contains(element)) { + TreeTransition transition = (TreeTransition) treeElement; + if (transition.isJustified() && !transition.isCorrect()) { + error = transition.getRule().checkRuleAt(transition, element); + } + } + if (error != null) { + dynamicView.updateError(error); + } else { + dynamicView.resetStatus(); + } + } + boardView.repaint(); } - } - boardView.repaint(); } - } - public void changeCell(MouseEvent e, PuzzleElement data) {} + public void changeCell(MouseEvent e, PuzzleElement data) {} - /** - * Invoked when an action occurs. - * - * @param e the event to be processed - */ - @SuppressWarnings("Unchecked") - @Override - public void actionPerformed(ActionEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - ElementView selectedElement = boardView.getSelection().getFirstSelection(); - PuzzleElement puzzleElement = selectedElement.getPuzzleElement(); + /** + * Invoked when an action occurs. + * + * @param e the event to be processed + */ + @SuppressWarnings("Unchecked") + @Override + public void actionPerformed(ActionEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + ElementView selectedElement = boardView.getSelection().getFirstSelection(); + PuzzleElement puzzleElement = selectedElement.getPuzzleElement(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeTransitionView transitionView = (TreeTransitionView) selectedView; + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeTransitionView transitionView = (TreeTransitionView) selectedView; - Board prevBord = transitionView.getTreeElement().getParents().get(0).getBoard(); + Board prevBord = transitionView.getTreeElement().getParents().get(0).getBoard(); - int value = (Integer) ((SelectionItemView) e.getSource()).getData().getData(); + int value = (Integer) ((SelectionItemView) e.getSource()).getData().getData(); - puzzleElement.setData(value); + puzzleElement.setData(value); - if (puzzleElement.equalsData(prevBord.getPuzzleElement(puzzleElement))) { - puzzleElement.setModified(false); - } else { - puzzleElement.setModified(true); - } + if (puzzleElement.equalsData(prevBord.getPuzzleElement(puzzleElement))) { + puzzleElement.setModified(false); + } else { + puzzleElement.setModified(true); + } - transitionView.getTreeElement().propagateChange(puzzleElement); + transitionView.getTreeElement().propagateChange(puzzleElement); - boardView.repaint(); - boardView.getSelection().clearSelection(); - } + boardView.repaint(); + boardView.getSelection().clearSelection(); + } - /** - * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a - * definition of a key typed event. - * - * @param e the event to be processed - */ - @Override - public void keyTyped(KeyEvent e) {} + /** + * Invoked when a key has been typed. See the class description for {@link KeyEvent} for a + * definition of a key typed event. + * + * @param e the event to be processed + */ + @Override + public void keyTyped(KeyEvent e) {} - /** - * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a - * definition of a key pressed event. - * - * @param e the event to be processed - */ - @Override - public void keyPressed(KeyEvent e) {} + /** + * Invoked when a key has been pressed. See the class description for {@link KeyEvent} for a + * definition of a key pressed event. + * + * @param e the event to be processed + */ + @Override + public void keyPressed(KeyEvent e) {} - /** - * Invoked when a key has been released. See the class description for {@link KeyEvent} for a - * definition of a key released event. - * - * @param e the event to be processed - */ - @Override - public void keyReleased(KeyEvent e) { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - if (boardView == null) { - boardView = getInstance().getLegupUI().getEditorBoardView(); - } - Board board = boardView.getBoard(); - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { - puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); - } + /** + * Invoked when a key has been released. See the class description for {@link KeyEvent} for a + * definition of a key released event. + * + * @param e the event to be processed + */ + @Override + public void keyReleased(KeyEvent e) { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + if (boardView == null) { + boardView = getInstance().getLegupUI().getEditorBoardView(); + } + Board board = boardView.getBoard(); + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/controller/RuleController.java b/src/main/java/edu/rpi/legup/controller/RuleController.java index f72dddbde..6e88dc4be 100644 --- a/src/main/java/edu/rpi/legup/controller/RuleController.java +++ b/src/main/java/edu/rpi/legup/controller/RuleController.java @@ -17,102 +17,105 @@ import java.util.List; public class RuleController implements ActionListener { - protected Object lastSource; + protected Object lastSource; - /** - * RuleController Constructor creates a controller object to listen to ui events from a {@link - * RulePanel} - */ - public RuleController() { - super(); - } + /** + * RuleController Constructor creates a controller object to listen to ui events from a {@link + * RulePanel} + */ + public RuleController() { + super(); + } - /** - * Button Pressed event occurs a when a rule button has been pressed - * - * @param rule rule of the button that was pressed - */ - public void buttonPressed(Rule rule) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = treePanel.getTreeView(); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - List selectedViews = selection.getSelectedViews(); + /** + * Button Pressed event occurs a when a rule button has been pressed + * + * @param rule rule of the button that was pressed + */ + public void buttonPressed(Rule rule) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = treePanel.getTreeView(); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + List selectedViews = selection.getSelectedViews(); - String updateErrorString = ""; - if (rule.getRuleType() == RuleType.CASE) { - CaseRule caseRule = (CaseRule) rule; - if (selectedViews.size() == 1) { - TreeElementView elementView = selection.getFirstSelection(); - TreeElement element = elementView.getTreeElement(); - if (element.getType() == TreeElementType.TRANSITION) { - ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); - if (caseRuleCommand.canExecute()) { - caseRuleCommand.execute(); - getInstance().getHistory().pushChange(caseRuleCommand); - } else { - updateErrorString = caseRuleCommand.getError(); - } - } else { - if (LegupPreferences.getInstance() - .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) - .equalsIgnoreCase(Boolean.toString(true))) { - CaseBoard caseBoard = caseRule.getCaseBoard(element.getBoard()); - if (caseBoard != null && caseBoard.getCount() > 0) { - puzzle.notifyBoardListeners(listener -> listener.onCaseBoardAdded(caseBoard)); + String updateErrorString = ""; + if (rule.getRuleType() == RuleType.CASE) { + CaseRule caseRule = (CaseRule) rule; + if (selectedViews.size() == 1) { + TreeElementView elementView = selection.getFirstSelection(); + TreeElement element = elementView.getTreeElement(); + if (element.getType() == TreeElementType.TRANSITION) { + ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); + if (caseRuleCommand.canExecute()) { + caseRuleCommand.execute(); + getInstance().getHistory().pushChange(caseRuleCommand); + } else { + updateErrorString = caseRuleCommand.getError(); + } + } else { + if (LegupPreferences.getInstance() + .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) + .equalsIgnoreCase(Boolean.toString(true))) { + CaseBoard caseBoard = caseRule.getCaseBoard(element.getBoard()); + if (caseBoard != null && caseBoard.getCount() > 0) { + puzzle.notifyBoardListeners( + listener -> listener.onCaseBoardAdded(caseBoard)); + } else { + updateErrorString = "This board cannot be applied with this case rule."; + } + } else { + updateErrorString = + "Auto generated case rules are turned off in preferences."; + } + } } else { - updateErrorString = "This board cannot be applied with this case rule."; + ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); + if (caseRuleCommand.canExecute()) { + caseRuleCommand.execute(); + getInstance().getHistory().pushChange(caseRuleCommand); + } else { + updateErrorString = caseRuleCommand.getError(); + } } - } else { - updateErrorString = "Auto generated case rules are turned off in preferences."; - } - } - } else { - ICommand caseRuleCommand = new ValidateCaseRuleCommand(selection, caseRule); - if (caseRuleCommand.canExecute()) { - caseRuleCommand.execute(); - getInstance().getHistory().pushChange(caseRuleCommand); - } else { - updateErrorString = caseRuleCommand.getError(); - } - } - } else { - if (rule.getRuleType() == RuleType.CONTRADICTION) { - ICommand validate = - new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); } else { - updateErrorString = validate.getError(); - } - } else { - boolean def = - LegupPreferences.getInstance().getUserPrefAsBool(LegupPreferences.ALLOW_DEFAULT_RULES); - ICommand validate = - def - ? new ApplyDefaultDirectRuleCommand(selection, (DirectRule) rule) - : new ValidateDirectRuleCommand(selection, (DirectRule) rule); - if (validate.canExecute()) { - getInstance().getHistory().pushChange(validate); - validate.execute(); - } else { - updateErrorString = validate.getError(); + if (rule.getRuleType() == RuleType.CONTRADICTION) { + ICommand validate = + new ValidateContradictionRuleCommand(selection, (ContradictionRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + updateErrorString = validate.getError(); + } + } else { + boolean def = + LegupPreferences.getInstance() + .getUserPrefAsBool(LegupPreferences.ALLOW_DEFAULT_RULES); + ICommand validate = + def + ? new ApplyDefaultDirectRuleCommand(selection, (DirectRule) rule) + : new ValidateDirectRuleCommand(selection, (DirectRule) rule); + if (validate.canExecute()) { + getInstance().getHistory().pushChange(validate); + validate.execute(); + } else { + updateErrorString = validate.getError(); + } + } } - } + GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(updateErrorString); } - GameBoardFacade.getInstance().getLegupUI().getTreePanel().updateError(updateErrorString); - } - /** - * ICommand Performed event occurs when a rule button has been pressed - * - * @param e action event object - */ - @Override - public void actionPerformed(ActionEvent e) { - lastSource = e.getSource(); - RuleButton button = (RuleButton) lastSource; - buttonPressed(button.getRule()); - } + /** + * ICommand Performed event occurs when a rule button has been pressed + * + * @param e action event object + */ + @Override + public void actionPerformed(ActionEvent e) { + lastSource = e.getSource(); + RuleButton button = (RuleButton) lastSource; + buttonPressed(button.getRule()); + } } diff --git a/src/main/java/edu/rpi/legup/controller/ToolbarController.java b/src/main/java/edu/rpi/legup/controller/ToolbarController.java index 489e6b69f..6cbb5ee60 100644 --- a/src/main/java/edu/rpi/legup/controller/ToolbarController.java +++ b/src/main/java/edu/rpi/legup/controller/ToolbarController.java @@ -5,23 +5,23 @@ import java.awt.event.ActionListener; public class ToolbarController implements ActionListener { - private LegupUI legupUI; + private LegupUI legupUI; - /** - * ToolbarController Constructor - creates a new {@link ToolbarController} to listen for button - * pressed from the tool mBar - * - * @param legupUI legupUI - */ - public ToolbarController(LegupUI legupUI) { - this.legupUI = legupUI; - } + /** + * ToolbarController Constructor - creates a new {@link ToolbarController} to listen for button + * pressed from the tool mBar + * + * @param legupUI legupUI + */ + public ToolbarController(LegupUI legupUI) { + this.legupUI = legupUI; + } - /** - * ICommand Performed event - - * - * @param e action event - */ - @Override - public void actionPerformed(ActionEvent e) {} + /** + * ICommand Performed event - + * + * @param e action event + */ + @Override + public void actionPerformed(ActionEvent e) {} } diff --git a/src/main/java/edu/rpi/legup/controller/TreeController.java b/src/main/java/edu/rpi/legup/controller/TreeController.java index f19b40cb1..80fdee1af 100644 --- a/src/main/java/edu/rpi/legup/controller/TreeController.java +++ b/src/main/java/edu/rpi/legup/controller/TreeController.java @@ -12,152 +12,155 @@ import javax.swing.*; public class TreeController extends Controller { - /** - * TreeController Constructor creates a controller object to listen to ui events from a {@link - * TreePanel} - */ - public TreeController() {} + /** + * TreeController Constructor creates a controller object to listen to ui events from a {@link + * TreePanel} + */ + public TreeController() {} - /** - * Mouse Clicked event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseClicked(MouseEvent e) {} + /** + * Mouse Clicked event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseClicked(MouseEvent e) {} - /** - * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning - * - * @param e MouseEvent object - */ - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); - } + /** + * Mouse Pressed event sets the cursor to the move cursor and stores info for possible panning + * + * @param e MouseEvent object + */ + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); + } - /** - * Mouse Released event sets the cursor back to the default cursor and reset info for panning Set - * board modifiability - * - * @param e MouseEvent object - */ - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); + /** + * Mouse Released event sets the cursor back to the default cursor and reset info for panning + * Set board modifiability + * + * @param e MouseEvent object + */ + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); - if (treeElementView != null) { - if (e.isShiftDown()) { - selection.addToSelection(treeElementView); - } else { - if (e.isControlDown()) { - if (!(selection.getSelectedViews().size() == 1 - && treeElementView == selection.getFirstSelection())) { - selection.toggleSelection(treeElementView); - } - } else { - selection.newSelection(treeElementView); + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); + if (treeElementView != null) { + if (e.isShiftDown()) { + selection.addToSelection(treeElementView); + } else { + if (e.isControlDown()) { + if (!(selection.getSelectedViews().size() == 1 + && treeElementView == selection.getFirstSelection())) { + selection.toggleSelection(treeElementView); + } + } else { + selection.newSelection(treeElementView); + } + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); } - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); } - } - /** - * Mouse Entered event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseEntered(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - Tree tree = getInstance().getTree(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - if (treeElementView != null) { - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); + /** + * Mouse Entered event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseEntered(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + Tree tree = getInstance().getTree(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + if (treeElementView != null) { + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); + } } - } - /** - * Mouse Exited event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseExited(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView elementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - TreeViewSelection selection = treeView.getSelection(); + /** + * Mouse Exited event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseExited(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView elementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + TreeViewSelection selection = treeView.getSelection(); - selection.setMousePoint(null); - if (elementView != null) { - TreeElementView selectedView = selection.getFirstSelection(); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(selectedView.getTreeElement())); + selection.setMousePoint(null); + if (elementView != null) { + TreeElementView selectedView = selection.getFirstSelection(); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(selectedView.getTreeElement())); + } } - } - /** - * Mouse Dragged event adjusts the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseDragged(MouseEvent e) { - super.mouseDragged(e); - } + /** + * Mouse Dragged event adjusts the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseDragged(MouseEvent e) { + super.mouseDragged(e); + } - /** - * Mouse Moved event no default action - * - * @param e MouseEvent object - */ - @Override - public void mouseMoved(MouseEvent e) { - TreeView treeView = (TreeView) viewer; - Point point = treeView.getActualPoint(e.getPoint()); - TreeElementView treeElementView = treeView.getTreeElementView(point); - Puzzle puzzle = getInstance().getPuzzleModule(); - if (puzzle != null) { - TreeViewSelection selection = treeView.getSelection(); - selection.setMousePoint(treeView.getActualPoint(e.getPoint())); - if (treeElementView != null && treeElementView != selection.getHover()) { - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(treeElementView.getTreeElement())); - selection.newHover(treeElementView); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } else { - if (treeElementView == null && selection.getHover() != null) { - puzzle.notifyBoardListeners( - listener -> - listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); - selection.clearHover(); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + /** + * Mouse Moved event no default action + * + * @param e MouseEvent object + */ + @Override + public void mouseMoved(MouseEvent e) { + TreeView treeView = (TreeView) viewer; + Point point = treeView.getActualPoint(e.getPoint()); + TreeElementView treeElementView = treeView.getTreeElementView(point); + Puzzle puzzle = getInstance().getPuzzleModule(); + if (puzzle != null) { + TreeViewSelection selection = treeView.getSelection(); + selection.setMousePoint(treeView.getActualPoint(e.getPoint())); + if (treeElementView != null && treeElementView != selection.getHover()) { + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged(treeElementView.getTreeElement())); + selection.newHover(treeElementView); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } else { + if (treeElementView == null && selection.getHover() != null) { + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged( + selection.getFirstSelection().getTreeElement())); + selection.clearHover(); + puzzle.notifyTreeListeners( + listener -> listener.onTreeSelectionChanged(selection)); + } + } } - } } - } - /** - * Mouse Wheel Moved event zooms in on the viewport - * - * @param e MouseEvent object - */ - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - super.viewer.scroll(e.getWheelRotation()); - } + /** + * Mouse Wheel Moved event zooms in on the viewport + * + * @param e MouseEvent object + */ + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + super.viewer.scroll(e.getWheelRotation()); + } } diff --git a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java index 2f9c3e553..b413bebb7 100644 --- a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java @@ -12,102 +12,103 @@ public class AddTreeElementCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - private Map addChild; + private Map addChild; - /** - * AddTreeElementCommand Constructor creates a command for adding a tree element to the proof tree - * - * @param selection selection of tree elements views - */ - public AddTreeElementCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - this.addChild = new HashMap<>(); - } + /** + * AddTreeElementCommand Constructor creates a command for adding a tree element to the proof + * tree + * + * @param selection selection of tree elements views + */ + public AddTreeElementCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + this.addChild = new HashMap<>(); + } - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement treeElement = view.getTreeElement(); - TreeElement child = addChild.get(treeElement); - if (child == null) { - child = tree.addTreeElement(treeElement); - } else { - if (treeElement.getType() == TreeElementType.NODE) { - child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); - } else { - child = tree.addTreeElement((TreeTransition) treeElement, (TreeNode) child); - } - } - addChild.put(treeElement, child); + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement treeElement = view.getTreeElement(); + TreeElement child = addChild.get(treeElement); + if (child == null) { + child = tree.addTreeElement(treeElement); + } else { + if (treeElement.getType() == TreeElementType.NODE) { + child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); + } else { + child = tree.addTreeElement((TreeTransition) treeElement, (TreeNode) child); + } + } + addChild.put(treeElement, child); - final TreeElement finalChild = child; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalChild)); + final TreeElement finalChild = child; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalChild)); - newSelection.addToSelection(treeView.getElementView(child)); - } + newSelection.addToSelection(treeView.getElementView(child)); + } - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) element; - if (transition.getChildNode() != null) { - return CommandError.ADD_WITH_CHILD.toString(); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } else { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - TreeTransition transition = node.getChildren().get(0); - if (transition.getParents().size() > 1) { - return CommandError.ADD_TO_MERGE.toString(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) element; + if (transition.getChildNode() != null) { + return CommandError.ADD_WITH_CHILD.toString(); + } + } else { + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + TreeTransition transition = node.getChildren().get(0); + if (transition.getParents().size() > 1) { + return CommandError.ADD_TO_MERGE.toString(); + } + } + } } - } } - } + return null; } - return null; - } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - for (TreeElementView view : selection.getSelectedViews()) { - TreeElement element = view.getTreeElement(); - TreeElement child = addChild.get(element); - tree.removeTreeElement(child); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(child)); - newSelection.addToSelection(treeView.getElementView(element)); + for (TreeElementView view : selection.getSelectedViews()) { + TreeElement element = view.getTreeElement(); + TreeElement child = addChild.get(element); + tree.removeTreeElement(child); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(child)); + newSelection.addToSelection(treeView.getElementView(element)); + } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } } diff --git a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java index a2c68112c..02dffae44 100644 --- a/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ApplyDefaultDirectRuleCommand.java @@ -12,114 +12,118 @@ public class ApplyDefaultDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - private DirectRule rule; - private Map addMap; - - /** - * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a basic - * rule - * - * @param selection selection of tree element views - * @param rule basic rule for the command - */ - public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.rule = rule; - this.addMap = new HashMap<>(); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_SELECTED_VIEWS.toString(); - } else { - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - if (!node.getChildren().isEmpty()) { - - return CommandError.DEFAULT_APPLICATION + " - " + CommandError.NO_CHILDREN.toString(); - } else { - if (rule.getDefaultBoard(node) == null) { - return CommandError.DEFAULT_APPLICATION - + " - This selection contains a tree element that this rule" - + " cannot be applied to."; - } - } + private TreeViewSelection selection; + private DirectRule rule; + private Map addMap; + + /** + * ApplyDefaultDirectRuleCommand Constructor creates a command for applying the default of a + * basic rule + * + * @param selection selection of tree element views + * @param rule basic rule for the command + */ + public ApplyDefaultDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.rule = rule; + this.addMap = new HashMap<>(); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.DEFAULT_APPLICATION + + " - " + + CommandError.NO_SELECTED_VIEWS.toString(); } else { - return CommandError.DEFAULT_APPLICATION - + " - " - + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + if (!node.getChildren().isEmpty()) { + + return CommandError.DEFAULT_APPLICATION + + " - " + + CommandError.NO_CHILDREN.toString(); + } else { + if (rule.getDefaultBoard(node) == null) { + return CommandError.DEFAULT_APPLICATION + + " - This selection contains a tree element that this rule" + + " cannot be applied to."; + } + } + } else { + return CommandError.DEFAULT_APPLICATION + + " - " + + CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + } } - } - } - return null; - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - TreeTransition transition = addMap.get(node); - TreeNode childNode; - if (transition == null) { - transition = (TreeTransition) tree.addTreeElement(node); - childNode = (TreeNode) tree.addTreeElement(transition); - addMap.put(node, transition); - } else { - tree.addTreeElement(node, transition); - childNode = transition.getChildNode(); - } - - transition.setRule(rule); - Board defaultBoard = rule.getDefaultBoard(node); - transition.setBoard(defaultBoard); - Board copyBoard = defaultBoard.copy(); - copyBoard.setModifiable(false); - childNode.setBoard(copyBoard); - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(childNode)); + return null; } - final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + TreeTransition transition = addMap.get(node); + TreeNode childNode; + if (transition == null) { + transition = (TreeTransition) tree.addTreeElement(node); + childNode = (TreeNode) tree.addTreeElement(transition); + addMap.put(node, transition); + } else { + tree.addTreeElement(node, transition); + childNode = transition.getChildNode(); + } - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + transition.setRule(rule); + Board defaultBoard = rule.getDefaultBoard(node); + transition.setBoard(defaultBoard); + Board copyBoard = defaultBoard.copy(); + copyBoard.setModifiable(false); + childNode.setBoard(copyBoard); - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode node = nodeView.getTreeElement(); - final TreeTransition transition = addMap.get(node); + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + + final TreeElement finalTreeElement = newSelection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode node = nodeView.getTreeElement(); + final TreeTransition transition = addMap.get(node); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java b/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java index 501f1d0a5..54e33756a 100644 --- a/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/AutoCaseRuleCommand.java @@ -15,131 +15,132 @@ public class AutoCaseRuleCommand extends PuzzleCommand { - private ElementView elementView; - private TreeViewSelection selection; - private CaseRule caseRule; - private CaseBoard caseBoard; - private MouseEvent mouseEvent; - - private List caseTrans; - - private static final int MAX_CASES = 10; - - /** - * AutoCaseRuleCommand Constructor creates a command for validating a case rule - * - * @param elementView currently selected puzzle puzzleElement view that is being edited - * @param selection currently selected tree puzzleElement views that is being edited - * @param caseRule currently selected caseRule puzzleElement view that is being edited - * @param caseBoard currently selected caseBoard puzzleElement view that is being edited - * @param mouseEvent currently selected mouseEvent puzzleElement view that is being edited - */ - public AutoCaseRuleCommand( - ElementView elementView, - TreeViewSelection selection, - CaseRule caseRule, - CaseBoard caseBoard, - MouseEvent mouseEvent) { - this.elementView = elementView; - this.selection = selection.copy(); - this.caseRule = caseRule; - this.caseBoard = caseBoard; - this.mouseEvent = mouseEvent; - this.caseTrans = new ArrayList<>(); - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); - if (caseTrans.isEmpty()) { - List cases = - caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()); - for (Board board : cases) { - final TreeTransition transition = (TreeTransition) tree.addTreeElement(node); - board.setModifiable(false); - transition.setBoard(board); - transition.setRule(caseRule); - transition.setSelection(elementView.getPuzzleElement().copy()); - caseTrans.add(transition); - - TreeNode childNode = (TreeNode) tree.addTreeElement(transition); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - newSelection.addToSelection(treeView.getElementView(childNode)); - } - } else { - for (final TreeTransition transition : caseTrans) { - tree.addTreeElement(node, transition); - TreeNode childNode = transition.getChildNode(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - newSelection.addToSelection(treeView.getElementView(childNode)); - } + private ElementView elementView; + private TreeViewSelection selection; + private CaseRule caseRule; + private CaseBoard caseBoard; + private MouseEvent mouseEvent; + + private List caseTrans; + + private static final int MAX_CASES = 10; + + /** + * AutoCaseRuleCommand Constructor creates a command for validating a case rule + * + * @param elementView currently selected puzzle puzzleElement view that is being edited + * @param selection currently selected tree puzzleElement views that is being edited + * @param caseRule currently selected caseRule puzzleElement view that is being edited + * @param caseBoard currently selected caseBoard puzzleElement view that is being edited + * @param mouseEvent currently selected mouseEvent puzzleElement view that is being edited + */ + public AutoCaseRuleCommand( + ElementView elementView, + TreeViewSelection selection, + CaseRule caseRule, + CaseBoard caseBoard, + MouseEvent mouseEvent) { + this.elementView = elementView; + this.selection = selection.copy(); + this.caseRule = caseRule; + this.caseBoard = caseBoard; + this.mouseEvent = mouseEvent; + this.caseTrans = new ArrayList<>(); } - final TreeElement finalTreeElement = node.getChildren().get(0).getChildNode(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - if (selection.getSelectedViews().size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); + if (caseTrans.isEmpty()) { + List cases = + caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()); + for (Board board : cases) { + final TreeTransition transition = (TreeTransition) tree.addTreeElement(node); + board.setModifiable(false); + transition.setBoard(board); + transition.setRule(caseRule); + transition.setSelection(elementView.getPuzzleElement().copy()); + caseTrans.add(transition); + + TreeNode childNode = (TreeNode) tree.addTreeElement(transition); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + } else { + for (final TreeTransition transition : caseTrans) { + tree.addTreeElement(node, transition); + TreeNode childNode = transition.getChildNode(); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + newSelection.addToSelection(treeView.getElementView(childNode)); + } + } + + final TreeElement finalTreeElement = node.getChildren().get(0).getChildNode(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - TreeElementView treeElementView = selection.getFirstSelection(); - if (treeElementView.getType() != TreeElementType.NODE) { - return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + if (selection.getSelectedViews().size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); + } + + TreeElementView treeElementView = selection.getFirstSelection(); + if (treeElementView.getType() != TreeElementType.NODE) { + return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + + TreeNodeView nodeView = (TreeNodeView) treeElementView; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.NO_CHILDREN.toString(); + } + + if (!caseBoard.isPickable(elementView.getPuzzleElement(), mouseEvent)) { + return "The selected data element is not pickable with this case rule."; + } + + if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() + == 0) { + return "The selection must produce at least one case"; + } + + if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() + > MAX_CASES) { + return "The selection can produce a max of " + MAX_CASES + " cases"; + } + + return null; } - TreeNodeView nodeView = (TreeNodeView) treeElementView; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.NO_CHILDREN.toString(); - } + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (!caseBoard.isPickable(elementView.getPuzzleElement(), mouseEvent)) { - return "The selected data element is not pickable with this case rule."; - } + TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); - if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() == 0) { - return "The selection must produce at least one case"; - } + for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { + final TreeTransition finalTran = it.next(); + it.remove(); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); + } - if (caseRule.getCases(caseBoard.getBaseBoard(), elementView.getPuzzleElement()).size() - > MAX_CASES) { - return "The selection can produce a max of " + MAX_CASES + " cases"; + final TreeElement finalTreeElement = node; + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } - - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeNode node = (TreeNode) selection.getFirstSelection().getTreeElement(); - - for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { - final TreeTransition finalTran = it.next(); - it.remove(); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); - } - - final TreeElement finalTreeElement = node; - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } } diff --git a/src/main/java/edu/rpi/legup/history/CommandError.java b/src/main/java/edu/rpi/legup/history/CommandError.java index 7b2bc41ed..35b7bb15b 100644 --- a/src/main/java/edu/rpi/legup/history/CommandError.java +++ b/src/main/java/edu/rpi/legup/history/CommandError.java @@ -1,29 +1,29 @@ package edu.rpi.legup.history; public enum CommandError { - NO_SELECTED_VIEWS("The selection does not have any tree elements."), - ONE_SELECTED_VIEW("The selection must have exactly one tree element."), - UNMODIFIABLE_BOARD("The selection contains a board which is not modifiable."), - UNMODIFIABLE_DATA("The selection contains a board where the data element is not modifiable."), - CONTAINS_ROOT("The selection contains the root tree node."), - ONE_CHILD("The selection contains a tree node that does not have exactly one child."), - ADD_WITH_CHILD("The selection contains a tree transition that already has a child tree node."), - TWO_TO_MERGE("The selection must have at least two tree nodes to merge."), - CONTAINS_MERGE("The selection contains a merging transition."), - ADD_TO_MERGE("The selection contains a tree node that merges."), - NO_CHILDREN("The selection contains a tree node that has children."), - SELECTION_CONTAINS_NODE("The selection contains a tree node."), - SELECTION_CONTAINS_TRANSITION("The selection contains a tree transition."), - DEFAULT_APPLICATION("[Apply Default Rule Application]"); + NO_SELECTED_VIEWS("The selection does not have any tree elements."), + ONE_SELECTED_VIEW("The selection must have exactly one tree element."), + UNMODIFIABLE_BOARD("The selection contains a board which is not modifiable."), + UNMODIFIABLE_DATA("The selection contains a board where the data element is not modifiable."), + CONTAINS_ROOT("The selection contains the root tree node."), + ONE_CHILD("The selection contains a tree node that does not have exactly one child."), + ADD_WITH_CHILD("The selection contains a tree transition that already has a child tree node."), + TWO_TO_MERGE("The selection must have at least two tree nodes to merge."), + CONTAINS_MERGE("The selection contains a merging transition."), + ADD_TO_MERGE("The selection contains a tree node that merges."), + NO_CHILDREN("The selection contains a tree node that has children."), + SELECTION_CONTAINS_NODE("The selection contains a tree node."), + SELECTION_CONTAINS_TRANSITION("The selection contains a tree transition."), + DEFAULT_APPLICATION("[Apply Default Rule Application]"); - private String value; + private String value; - CommandError(String value) { - this.value = value; - } + CommandError(String value) { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/main/java/edu/rpi/legup/history/CommandState.java b/src/main/java/edu/rpi/legup/history/CommandState.java index 36e4def4f..f47c0405d 100644 --- a/src/main/java/edu/rpi/legup/history/CommandState.java +++ b/src/main/java/edu/rpi/legup/history/CommandState.java @@ -1,19 +1,19 @@ package edu.rpi.legup.history; public enum CommandState { - CREATED("Created"), - EXECUTED("Executed"), - UNDOED("Undoed"), - REDOED("Redoed"); + CREATED("Created"), + EXECUTED("Executed"), + UNDOED("Undoed"), + REDOED("Redoed"); - private String value; + private String value; - CommandState(String value) { - this.value = value; - } + CommandState(String value) { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java index e301175fe..0469685c1 100644 --- a/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/DeleteTreeElementCommand.java @@ -8,94 +8,97 @@ import java.util.List; public class DeleteTreeElementCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - /** - * DeleteTreeElementCommand Constructor creates a PuzzleCommand for deleting a tree puzzleElement - * - * @param selection the currently selected tree elements before the command is executed - */ - public DeleteTreeElementCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - } + /** + * DeleteTreeElementCommand Constructor creates a PuzzleCommand for deleting a tree + * puzzleElement + * + * @param selection the currently selected tree elements before the command is executed + */ + public DeleteTreeElementCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + } - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - List selectedViews = selection.getSelectedViews(); + List selectedViews = selection.getSelectedViews(); - TreeElementView firstSelectedView = selectedViews.get(0); - TreeElementView newSelectedView; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - newSelectedView = nodeView.getParentView(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - newSelectedView = transitionView.getParentViews().get(0); - } + TreeElementView firstSelectedView = selectedViews.get(0); + TreeElementView newSelectedView; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + newSelectedView = nodeView.getParentView(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + newSelectedView = transitionView.getParentViews().get(0); + } + + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + tree.removeTreeElement(element); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(element)); + } - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - tree.removeTreeElement(element); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(element)); + final TreeViewSelection newSelection = new TreeViewSelection(newSelectedView); + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(newSelectedView.getTreeElement())); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeSelectionChanged(newSelection)); } - final TreeViewSelection newSelection = new TreeViewSelection(newSelectedView); - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(newSelectedView.getTreeElement())); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeSelectionChanged(newSelection)); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + if (element.getType() == TreeElementType.NODE && ((TreeNode) element).isRoot()) { + return CommandError.CONTAINS_ROOT.toString(); + } + } + return null; } - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - if (element.getType() == TreeElementType.NODE && ((TreeNode) element).isRoot()) { - return CommandError.CONTAINS_ROOT.toString(); - } - } - return null; - } + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + List selectedViews = selection.getSelectedViews(); - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - List selectedViews = selection.getSelectedViews(); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getParent().setChildNode(node); - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getParent().setChildNode(node); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(node)); + } else { + TreeTransition transition = (TreeTransition) element; + transition.getParents().forEach(node -> node.addChild(transition)); + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(node)); - } else { - TreeTransition transition = (TreeTransition) element; - transition.getParents().forEach(node -> node.addChild(transition)); - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + } + } - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - } + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged( + selection.getFirstSelection().getTreeElement())); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } - - puzzle.notifyBoardListeners( - listener -> listener.onTreeElementChanged(selection.getFirstSelection().getTreeElement())); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } } diff --git a/src/main/java/edu/rpi/legup/history/EditDataCommand.java b/src/main/java/edu/rpi/legup/history/EditDataCommand.java index 6b5f4062f..d65f03d66 100644 --- a/src/main/java/edu/rpi/legup/history/EditDataCommand.java +++ b/src/main/java/edu/rpi/legup/history/EditDataCommand.java @@ -14,155 +14,155 @@ import java.util.List; public class EditDataCommand extends PuzzleCommand { - private TreeTransition transition; - private PuzzleElement savePuzzleElement; - private PuzzleElement puzzleElement; - - private ElementView elementView; - private TreeViewSelection selection; - private MouseEvent event; - - /** - * EditDataCommand Constructor create a puzzle command for editing a board - * - * @param elementView currently selected puzzle puzzleElement view that is being edited - * @param selection currently selected tree puzzleElement views that is being edited - * @param event mouse event - */ - public EditDataCommand(ElementView elementView, TreeViewSelection selection, MouseEvent event) { - this.elementView = elementView; - this.selection = selection.copy(); - this.event = event; - this.puzzleElement = null; - this.savePuzzleElement = null; - this.transition = null; - } - - /** Executes a command */ - @SuppressWarnings("unchecked") - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - Board board = treeElement.getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - if (treeNode.getChildren().isEmpty()) { - if (transition == null) { - transition = tree.addNewTransition(treeNode); + private TreeTransition transition; + private PuzzleElement savePuzzleElement; + private PuzzleElement puzzleElement; + + private ElementView elementView; + private TreeViewSelection selection; + private MouseEvent event; + + /** + * EditDataCommand Constructor create a puzzle command for editing a board + * + * @param elementView currently selected puzzle puzzleElement view that is being edited + * @param selection currently selected tree puzzleElement views that is being edited + * @param event mouse event + */ + public EditDataCommand(ElementView elementView, TreeViewSelection selection, MouseEvent event) { + this.elementView = elementView; + this.selection = selection.copy(); + this.event = event; + this.puzzleElement = null; + this.savePuzzleElement = null; + this.transition = null; + } + + /** Executes a command */ + @SuppressWarnings("unchecked") + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + Board board = treeElement.getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + if (treeNode.getChildren().isEmpty()) { + if (transition == null) { + transition = tree.addNewTransition(treeNode); + } + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); + } + + board = transition.getBoard(); + + puzzleElement = board.getPuzzleElement(selectedPuzzleElement); + savePuzzleElement = puzzleElement.copy(); + } else { + transition = (TreeTransition) treeElement; + puzzleElement = board.getPuzzleElement(selectedPuzzleElement); + savePuzzleElement = puzzleElement.copy(); } - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - } - board = transition.getBoard(); + Board prevBoard = transition.getParents().get(0).getBoard(); - puzzleElement = board.getPuzzleElement(selectedPuzzleElement); - savePuzzleElement = puzzleElement.copy(); - } else { - transition = (TreeTransition) treeElement; - puzzleElement = board.getPuzzleElement(selectedPuzzleElement); - savePuzzleElement = puzzleElement.copy(); - } + boardView.getElementController().changeCell(event, puzzleElement); - Board prevBoard = transition.getParents().get(0).getBoard(); + if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { + board.removeModifiedData(puzzleElement); + } else { + board.addModifiedData(puzzleElement); + } + transition.propagateChange(puzzleElement); - boardView.getElementController().changeCell(event, puzzleElement); + final TreeElement finalTreeElement = transition; + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); - if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { - board.removeModifiedData(puzzleElement); - } else { - board.addModifiedData(puzzleElement); - } - transition.propagateChange(puzzleElement); - - final TreeElement finalTreeElement = transition; - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); - - final TreeViewSelection newSelection = - new TreeViewSelection(treeView.getElementView(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); + final TreeViewSelection newSelection = + new TreeViewSelection(treeView.getElementView(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - TreeElementView selectedView = selection.getFirstSelection(); - Board board = selectedView.getTreeElement().getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - if (selectedView.getType() == TreeElementType.NODE) { - - TreeNodeView nodeView = (TreeNodeView) selectedView; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } else { - if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); } - } - } else { - TreeTransitionView transitionView = (TreeTransitionView) selectedView; - if (!transitionView.getTreeElement().getBoard().isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } else { - if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); + TreeElementView selectedView = selection.getFirstSelection(); + Board board = selectedView.getTreeElement().getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + if (selectedView.getType() == TreeElementType.NODE) { + + TreeNodeView nodeView = (TreeNodeView) selectedView; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } else { + if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); + } + } + } else { + TreeTransitionView transitionView = (TreeTransitionView) selectedView; + if (!transitionView.getTreeElement().getBoard().isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } else { + if (!board.getPuzzleElement(selectedPuzzleElement).isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); + } + } } - } - } - return null; - } - - /** Undoes an command */ - @SuppressWarnings("unchecked") - @Override - public void undoCommand() { - TreeElementView selectedView = selection.getFirstSelection(); - Tree tree = getInstance().getTree(); - Puzzle puzzle = getInstance().getPuzzleModule(); - - Board board = transition.getBoard(); - PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); - - if (selectedView.getType() == TreeElementType.NODE) { - tree.removeTreeElement(transition); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeElementRemoved(transition)); + return null; } - Board prevBoard = transition.getParents().get(0).getBoard(); + /** Undoes an command */ + @SuppressWarnings("unchecked") + @Override + public void undoCommand() { + TreeElementView selectedView = selection.getFirstSelection(); + Tree tree = getInstance().getTree(); + Puzzle puzzle = getInstance().getPuzzleModule(); + + Board board = transition.getBoard(); + PuzzleElement selectedPuzzleElement = elementView.getPuzzleElement(); + + if (selectedView.getType() == TreeElementType.NODE) { + tree.removeTreeElement(transition); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeElementRemoved(transition)); + } - puzzleElement.setData(savePuzzleElement.getData()); - board.notifyChange(puzzleElement); + Board prevBoard = transition.getParents().get(0).getBoard(); - if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { - board.removeModifiedData(puzzleElement); - } else { - board.addModifiedData(puzzleElement); - } - transition.propagateChange(puzzleElement); + puzzleElement.setData(savePuzzleElement.getData()); + board.notifyChange(puzzleElement); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); + if (prevBoard.getPuzzleElement(selectedPuzzleElement).equalsData(puzzleElement)) { + board.removeModifiedData(puzzleElement); + } else { + board.addModifiedData(puzzleElement); + } + transition.propagateChange(puzzleElement); + + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(puzzleElement)); - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/History.java b/src/main/java/edu/rpi/legup/history/History.java index 8221449e6..371284f8c 100644 --- a/src/main/java/edu/rpi/legup/history/History.java +++ b/src/main/java/edu/rpi/legup/history/History.java @@ -7,92 +7,94 @@ import org.apache.logging.log4j.Logger; public class History { - private static final Logger LOGGER = LogManager.getLogger(History.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(History.class.getName()); - private final Object lock = new Object(); - private List history; - private int curIndex; + private final Object lock = new Object(); + private List history; + private int curIndex; - /** - * History Constructor this holds information about changes to the board and Tree structure for - * undoing and redoing operations. Though history is an List, it is implemented like a stack. The - * curIndex points to the top of the stack (where the last change was made). - */ - public History() { - history = new ArrayList<>(); - curIndex = -1; - } + /** + * History Constructor this holds information about changes to the board and Tree structure for + * undoing and redoing operations. Though history is an List, it is implemented like a stack. + * The curIndex points to the top of the stack (where the last change was made). + */ + public History() { + history = new ArrayList<>(); + curIndex = -1; + } - /** - * Pushes a change to the history list and increments the current index. If the current index does - * not point to the top of the stack, then at least 1 undo operation was called and that - * information will be lost by the next change - * - * @param command command to be pushed onto the stack - */ - public void pushChange(ICommand command) { - synchronized (lock) { - if (curIndex < history.size() - 1) { - for (int i = history.size() - 1; i > curIndex; i--) { - history.remove(i); + /** + * Pushes a change to the history list and increments the current index. If the current index + * does not point to the top of the stack, then at least 1 undo operation was called and that + * information will be lost by the next change + * + * @param command command to be pushed onto the stack + */ + public void pushChange(ICommand command) { + synchronized (lock) { + if (curIndex < history.size() - 1) { + for (int i = history.size() - 1; i > curIndex; i--) { + history.remove(i); + } + } + history.add(command); + curIndex++; + LOGGER.info("Pushed " + command.getClass().getSimpleName() + " to stack."); + GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onPushChange(command)); } - } - history.add(command); - curIndex++; - LOGGER.info("Pushed " + command.getClass().getSimpleName() + " to stack."); - GameBoardFacade.getInstance().notifyHistoryListeners(l -> l.onPushChange(command)); } - } - /** Undoes an action */ - public void undo() { - synchronized (lock) { - if (curIndex > -1) { - ICommand command = history.get(curIndex--); - command.undo(); - LOGGER.info("Undoed " + command.getClass().getSimpleName()); - GameBoardFacade.getInstance() - .notifyHistoryListeners(l -> l.onUndo(curIndex < 0, curIndex == history.size() - 1)); - } + /** Undoes an action */ + public void undo() { + synchronized (lock) { + if (curIndex > -1) { + ICommand command = history.get(curIndex--); + command.undo(); + LOGGER.info("Undoed " + command.getClass().getSimpleName()); + GameBoardFacade.getInstance() + .notifyHistoryListeners( + l -> l.onUndo(curIndex < 0, curIndex == history.size() - 1)); + } + } } - } - /** Redoes an action */ - public void redo() { - synchronized (lock) { - if (curIndex < history.size() - 1) { - ICommand command = history.get(++curIndex); - command.redo(); - LOGGER.info("Redoed " + command.getClass().getSimpleName()); - GameBoardFacade.getInstance() - .notifyHistoryListeners(l -> l.onRedo(curIndex < 0, curIndex == history.size() - 1)); - } + /** Redoes an action */ + public void redo() { + synchronized (lock) { + if (curIndex < history.size() - 1) { + ICommand command = history.get(++curIndex); + command.redo(); + LOGGER.info("Redoed " + command.getClass().getSimpleName()); + GameBoardFacade.getInstance() + .notifyHistoryListeners( + l -> l.onRedo(curIndex < 0, curIndex == history.size() - 1)); + } + } } - } - /** Clears all actions from the history stack */ - public void clear() { - history.clear(); - curIndex = -1; - LOGGER.debug("History Cleared"); - GameBoardFacade.getInstance().notifyHistoryListeners(IHistoryListener::onClearHistory); - } + /** Clears all actions from the history stack */ + public void clear() { + history.clear(); + curIndex = -1; + LOGGER.debug("History Cleared"); + GameBoardFacade.getInstance().notifyHistoryListeners(IHistoryListener::onClearHistory); + } - /** - * Gets the current index that points to the action at the top of stack - * - * @return index of the action on top of the stack - */ - public int getIndex() { - return curIndex; - } + /** + * Gets the current index that points to the action at the top of stack + * + * @return index of the action on top of the stack + */ + public int getIndex() { + return curIndex; + } - /** - * Gets the amount of actions that have been pushed onto the stack - * - * @return size of the history stack - */ - public int size() { - return history.size(); - } + /** + * Gets the amount of actions that have been pushed onto the stack + * + * @return size of the history stack + */ + public int size() { + return history.size(); + } } diff --git a/src/main/java/edu/rpi/legup/history/ICommand.java b/src/main/java/edu/rpi/legup/history/ICommand.java index b10cdc861..913d9daaf 100644 --- a/src/main/java/edu/rpi/legup/history/ICommand.java +++ b/src/main/java/edu/rpi/legup/history/ICommand.java @@ -1,27 +1,27 @@ package edu.rpi.legup.history; public interface ICommand { - /** Executes a command */ - void execute(); + /** Executes a command */ + void execute(); - /** - * Determines whether this command can be executed - * - * @return true if can execute, false otherwise - */ - boolean canExecute(); + /** + * Determines whether this command can be executed + * + * @return true if can execute, false otherwise + */ + boolean canExecute(); - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - String getError(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + String getError(); - /** Undoes a command */ - void undo(); + /** Undoes a command */ + void undo(); - /** Redoes a command */ - void redo(); + /** Redoes a command */ + void redo(); } diff --git a/src/main/java/edu/rpi/legup/history/IHistoryListener.java b/src/main/java/edu/rpi/legup/history/IHistoryListener.java index 1b3253b9f..f464941d6 100644 --- a/src/main/java/edu/rpi/legup/history/IHistoryListener.java +++ b/src/main/java/edu/rpi/legup/history/IHistoryListener.java @@ -1,29 +1,29 @@ package edu.rpi.legup.history; public interface IHistoryListener { - /** - * Called when a action is pushed onto the edu.rpi.legup.history stack - * - * @param command action to push onto the stack - */ - void onPushChange(ICommand command); + /** + * Called when a action is pushed onto the edu.rpi.legup.history stack + * + * @param command action to push onto the stack + */ + void onPushChange(ICommand command); - /** - * Called when an action is undone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - void onUndo(boolean isBottom, boolean isTop); + /** + * Called when an action is undone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + void onUndo(boolean isBottom, boolean isTop); - /** - * Called when an action is redone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - void onRedo(boolean isBottom, boolean isTop); + /** + * Called when an action is redone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + void onRedo(boolean isBottom, boolean isTop); - /** Called when the edu.rpi.legup.history is cleared */ - void onClearHistory(); + /** Called when the edu.rpi.legup.history is cleared */ + void onClearHistory(); } diff --git a/src/main/java/edu/rpi/legup/history/IHistorySubject.java b/src/main/java/edu/rpi/legup/history/IHistorySubject.java index 63acfa4c6..78fefff00 100644 --- a/src/main/java/edu/rpi/legup/history/IHistorySubject.java +++ b/src/main/java/edu/rpi/legup/history/IHistorySubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface IHistorySubject { - /** - * Adds a history listener - * - * @param listener listener to add - */ - void addHistoryListener(IHistoryListener listener); + /** + * Adds a history listener + * + * @param listener listener to add + */ + void addHistoryListener(IHistoryListener listener); - /** - * Removes a history listener - * - * @param listener listener to remove - */ - void removeHistoryListener(IHistoryListener listener); + /** + * Removes a history listener + * + * @param listener listener to remove + */ + void removeHistoryListener(IHistoryListener listener); - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - void notifyHistoryListeners(Consumer algorithm); + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + void notifyHistoryListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java b/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java index 42a547e84..71d072328 100644 --- a/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java +++ b/src/main/java/edu/rpi/legup/history/InvalidCommandStateTransition.java @@ -2,14 +2,14 @@ public class InvalidCommandStateTransition extends RuntimeException { - public InvalidCommandStateTransition( - PuzzleCommand puzzleCommand, CommandState from, CommandState to) { - super( - "PuzzleCommand - " - + puzzleCommand.getClass().getSimpleName() - + " - Attempted invalid command state transition from " - + from - + " to " - + to); - } + public InvalidCommandStateTransition( + PuzzleCommand puzzleCommand, CommandState from, CommandState to) { + super( + "PuzzleCommand - " + + puzzleCommand.getClass().getSimpleName() + + " - Attempted invalid command state transition from " + + from + + " to " + + to); + } } diff --git a/src/main/java/edu/rpi/legup/history/MergeCommand.java b/src/main/java/edu/rpi/legup/history/MergeCommand.java index e170e9856..f234a0884 100644 --- a/src/main/java/edu/rpi/legup/history/MergeCommand.java +++ b/src/main/java/edu/rpi/legup/history/MergeCommand.java @@ -11,128 +11,128 @@ import java.util.Set; public class MergeCommand extends PuzzleCommand { - private TreeViewSelection selection; - private TreeTransition transition; - - /** - * Merge Command Constructor create a command for merging tree nodes. - * - * @param selection selection of tree elements - */ - public MergeCommand(TreeViewSelection selection) { - this.selection = selection.copy(); - this.transition = null; - } - - /** Executes an command */ - @Override - public void executeCommand() { - List selectedViews = selection.getSelectedViews(); - - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeNode mergedNode; - if (transition == null) { - List mergingNodes = new ArrayList<>(); - List mergingBoards = new ArrayList<>(); - for (TreeElementView view : selectedViews) { - TreeNode node = ((TreeNodeView) view).getTreeElement(); - mergingNodes.add(node); - mergingBoards.add(node.getBoard()); - } - - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - Board lcaBoard = lca.getBoard(); - - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); - - mergedNode = new TreeNode(mergedBoard.copy()); - transition = new TreeTransition(mergedBoard); - transition.setRule(new MergeRule()); - transition.setChildNode(mergedNode); - mergedNode.setParent(transition); - } else { - mergedNode = transition.getChildNode(); + private TreeViewSelection selection; + private TreeTransition transition; + + /** + * Merge Command Constructor create a command for merging tree nodes. + * + * @param selection selection of tree elements + */ + public MergeCommand(TreeViewSelection selection) { + this.selection = selection.copy(); + this.transition = null; } - transition.getParents().clear(); - for (TreeElementView elementView : selectedViews) { - TreeNode node = (TreeNode) elementView.getTreeElement(); + /** Executes an command */ + @Override + public void executeCommand() { + List selectedViews = selection.getSelectedViews(); + + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeNode mergedNode; + if (transition == null) { + List mergingNodes = new ArrayList<>(); + List mergingBoards = new ArrayList<>(); + for (TreeElementView view : selectedViews) { + TreeNode node = ((TreeNodeView) view).getTreeElement(); + mergingNodes.add(node); + mergingBoards.add(node.getBoard()); + } + + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + Board lcaBoard = lca.getBoard(); + + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + mergedNode = new TreeNode(mergedBoard.copy()); + transition = new TreeTransition(mergedBoard); + transition.setRule(new MergeRule()); + transition.setChildNode(mergedNode); + mergedNode.setParent(transition); + } else { + mergedNode = transition.getChildNode(); + } + + transition.getParents().clear(); + for (TreeElementView elementView : selectedViews) { + TreeNode node = (TreeNode) elementView.getTreeElement(); + + node.addChild(transition); + transition.addParent(node); + } + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - node.addChild(transition); - transition.addParent(node); + final TreeViewSelection newSelection = new TreeViewSelection(); + newSelection.addToSelection(treeView.getElementView(mergedNode)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - - final TreeViewSelection newSelection = new TreeViewSelection(); - newSelection.addToSelection(treeView.getElementView(mergedNode)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - TreeTransition transition = - ((TreeNode) selection.getFirstSelection().getTreeElement()).getChildren().get(0); - tree.removeTreeElement(transition); - - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - Tree tree = GameBoardFacade.getInstance().getTree(); - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() < 2) { - return CommandError.TWO_TO_MERGE.toString(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + TreeTransition transition = + ((TreeNode) selection.getFirstSelection().getTreeElement()).getChildren().get(0); + tree.removeTreeElement(transition); + + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } - List nodeList = new ArrayList<>(); - for (TreeElementView view : selection.getSelectedViews()) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (!nodeView.getChildrenViews().isEmpty()) { - return CommandError.NO_CHILDREN.toString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + Tree tree = GameBoardFacade.getInstance().getTree(); + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() < 2) { + return CommandError.TWO_TO_MERGE.toString(); } - nodeList.add(nodeView.getTreeElement()); - } else { - return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); - } - } - List mergingNodes = new ArrayList<>(); - for (TreeElementView view : selectedViews) { - TreeNode node = ((TreeNodeView) view).getTreeElement(); - mergingNodes.add(node); - } + List nodeList = new ArrayList<>(); + for (TreeElementView view : selection.getSelectedViews()) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (!nodeView.getChildrenViews().isEmpty()) { + return CommandError.NO_CHILDREN.toString(); + } + nodeList.add(nodeView.getTreeElement()); + } else { + return CommandError.SELECTION_CONTAINS_TRANSITION.toString(); + } + } - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - return "Unable to merge tree elements."; - } - Set leafNodes = tree.getLeafTreeElements(lca); - if (leafNodes.size() != mergingNodes.size()) { - // return "Unable to merge tree elements."; - } + List mergingNodes = new ArrayList<>(); + for (TreeElementView view : selectedViews) { + TreeNode node = ((TreeNodeView) view).getTreeElement(); + mergingNodes.add(node); + } - for (TreeNode node : mergingNodes) { - if (!leafNodes.contains(node)) { - // return "Unable to merge tree elements."; - } - } + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + return "Unable to merge tree elements."; + } + Set leafNodes = tree.getLeafTreeElements(lca); + if (leafNodes.size() != mergingNodes.size()) { + // return "Unable to merge tree elements."; + } + + for (TreeNode node : mergingNodes) { + if (!leafNodes.contains(node)) { + // return "Unable to merge tree elements."; + } + } - return null; - } + return null; + } } diff --git a/src/main/java/edu/rpi/legup/history/PuzzleCommand.java b/src/main/java/edu/rpi/legup/history/PuzzleCommand.java index 482c11cc7..3768e3cbd 100644 --- a/src/main/java/edu/rpi/legup/history/PuzzleCommand.java +++ b/src/main/java/edu/rpi/legup/history/PuzzleCommand.java @@ -1,91 +1,91 @@ package edu.rpi.legup.history; public abstract class PuzzleCommand implements ICommand { - private CommandState state; - private boolean isCached; - private String cachedError; + private CommandState state; + private boolean isCached; + private String cachedError; - /** Puzzle Command Constructor for creating an undoable and redoable change to the model. */ - protected PuzzleCommand() { - this.state = CommandState.CREATED; - this.isCached = false; - this.cachedError = null; - } + /** Puzzle Command Constructor for creating an undoable and redoable change to the model. */ + protected PuzzleCommand() { + this.state = CommandState.CREATED; + this.isCached = false; + this.cachedError = null; + } - /** Executes an command */ - @Override - public final void execute() { - if (canExecute()) { - executeCommand(); - state = CommandState.EXECUTED; + /** Executes an command */ + @Override + public final void execute() { + if (canExecute()) { + executeCommand(); + state = CommandState.EXECUTED; + } } - } - /** Determines whether this command can be executed */ - @Override - public final boolean canExecute() { - cachedError = getError(); - isCached = true; - return cachedError == null; - } + /** Determines whether this command can be executed */ + @Override + public final boolean canExecute() { + cachedError = getError(); + isCached = true; + return cachedError == null; + } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public final String getError() { - if (isCached) { - return cachedError; - } else { - return getErrorString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public final String getError() { + if (isCached) { + return cachedError; + } else { + return getErrorString(); + } } - } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - public abstract String getErrorString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + public abstract String getErrorString(); - /** Executes an command */ - public abstract void executeCommand(); + /** Executes an command */ + public abstract void executeCommand(); - /** Undoes an command */ - public abstract void undoCommand(); + /** Undoes an command */ + public abstract void undoCommand(); - /** Redoes an command */ - public void redoCommand() { - if (state == CommandState.UNDOED) { - executeCommand(); - state = CommandState.REDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); + /** Redoes an command */ + public void redoCommand() { + if (state == CommandState.UNDOED) { + executeCommand(); + state = CommandState.REDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); + } } - } - /** Undoes an command */ - @Override - public final void undo() { - if (state == CommandState.EXECUTED || state == CommandState.REDOED) { - undoCommand(); - state = CommandState.UNDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.UNDOED); + /** Undoes an command */ + @Override + public final void undo() { + if (state == CommandState.EXECUTED || state == CommandState.REDOED) { + undoCommand(); + state = CommandState.UNDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.UNDOED); + } } - } - /** Redoes an command */ - public final void redo() { - if (state == CommandState.UNDOED) { - redoCommand(); - state = CommandState.REDOED; - } else { - throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); + /** Redoes an command */ + public final void redo() { + if (state == CommandState.UNDOED) { + redoCommand(); + state = CommandState.REDOED; + } else { + throw new InvalidCommandStateTransition(this, state, CommandState.REDOED); + } } - } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java index 4718a56c8..7737ecfd3 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateCaseRuleCommand.java @@ -14,118 +14,118 @@ public class ValidateCaseRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - private CaseRule caseRule; - - private Map oldRule; - private Map addNode; - - /** - * AutoCaseRuleCommand Constructor creates a command for verifying a case rule - * - * @param selection currently selected tree puzzleElement views that is being edited - * @param caseRule currently selected caseRule puzzleElement view that is being edited - */ - public ValidateCaseRuleCommand(TreeViewSelection selection, CaseRule caseRule) { - this.selection = selection.copy(); - this.caseRule = caseRule; - this.oldRule = new HashMap<>(); - this.addNode = new HashMap<>(); - } - - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeTransition transition = (TreeTransition) element; - oldRule.put(transition, transition.getRule()); - - transition.setRule(caseRule); - - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); - } else { - childNode = (TreeNode) tree.addTreeElement(transition, childNode); + private TreeViewSelection selection; + private CaseRule caseRule; + + private Map oldRule; + private Map addNode; + + /** + * AutoCaseRuleCommand Constructor creates a command for verifying a case rule + * + * @param selection currently selected tree puzzleElement views that is being edited + * @param caseRule currently selected caseRule puzzleElement view that is being edited + */ + public ValidateCaseRuleCommand(TreeViewSelection selection, CaseRule caseRule) { + this.selection = selection.copy(); + this.caseRule = caseRule; + this.oldRule = new HashMap<>(); + this.addNode = new HashMap<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeTransition transition = (TreeTransition) element; + oldRule.put(transition, transition.getRule()); + + transition.setRule(caseRule); + + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); + } else { + childNode = (TreeNode) tree.addTreeElement(transition, childNode); + } + + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + newSelection.addToSelection(treeView.getElementView(childNode)); } - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); - newSelection.addToSelection(treeView.getElementView(childNode)); + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); + } + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); - } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - return CommandError.SELECTION_CONTAINS_NODE.toString(); - } else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + return CommandError.SELECTION_CONTAINS_NODE.toString(); + } else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); + } + } } - } - } - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeTransition transition = (TreeTransition) element; - - transition.setRule(oldRule.get(transition)); - - final TreeNode childNode = transition.getChildNode(); - if (addNode.get(transition) != null) { - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + return null; } - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeTransition transition = (TreeTransition) element; + + transition.setRule(oldRule.get(transition)); + + final TreeNode childNode = transition.getChildNode(); + if (addNode.get(transition) != null) { + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java index cc60029bf..8737b4008 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateContradictionRuleCommand.java @@ -11,147 +11,156 @@ import java.util.Map; public class ValidateContradictionRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; - - private Map> saveElements; - private ContradictionRule newRule; - private Map addTran; - - /** - * ValidateContradictionRuleCommand Constructor creates a puzzle command for verifying a - * contradiction rule - * - * @param selection currently selected tree puzzleElement views - * @param rule contradiction rule to be set to all the tree elements - */ - public ValidateContradictionRuleCommand(TreeViewSelection selection, ContradictionRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.saveElements = new HashMap<>(); - this.addTran = new HashMap<>(); - } - - /** Executes a command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement treeElement = view.getTreeElement(); - TreeNode treeNode; - if (treeElement.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) treeElement; - treeNode = transition.getParents().get(0); - } else { - treeNode = (TreeNode) treeElement; - } - - if (!treeNode.getChildren().isEmpty()) { - ArrayList save = new ArrayList<>(treeNode.getChildren()); - saveElements.put(treeNode, save); - } - - treeNode - .getChildren() - .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); - - treeNode.getChildren().clear(); - - TreeTransition transition = addTran.get(treeElement); - if (transition == null) { - transition = tree.addNewTransition(treeNode); - transition.setRule(newRule); - transition.getBoard().setModifiable(false); - tree.addTreeElement(transition); - } else { - transition.getBoard().setModifiable(false); - tree.addTreeElement(treeNode, transition); - } - - final TreeTransition finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(transition)); + private TreeViewSelection selection; + + private Map> saveElements; + private ContradictionRule newRule; + private Map addTran; + + /** + * ValidateContradictionRuleCommand Constructor creates a puzzle command for verifying a + * contradiction rule + * + * @param selection currently selected tree puzzleElement views + * @param rule contradiction rule to be set to all the tree elements + */ + public ValidateContradictionRuleCommand(TreeViewSelection selection, ContradictionRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.saveElements = new HashMap<>(); + this.addTran = new HashMap<>(); } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - if (transitionView.getChildView() != null) { - finalTreeElement = transitionView.getChildView().getTreeElement(); - } else { - finalTreeElement = null; - } - } + /** Executes a command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement treeElement = view.getTreeElement(); + TreeNode treeNode; + if (treeElement.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) treeElement; + treeNode = transition.getParents().get(0); + } else { + treeNode = (TreeNode) treeElement; + } + + if (!treeNode.getChildren().isEmpty()) { + ArrayList save = new ArrayList<>(treeNode.getChildren()); + saveElements.put(treeNode, save); + } + + treeNode.getChildren() + .forEach( + n -> + puzzle.notifyTreeListeners( + listener -> listener.onTreeElementRemoved(n))); + + treeNode.getChildren().clear(); + + TreeTransition transition = addTran.get(treeElement); + if (transition == null) { + transition = tree.addNewTransition(treeNode); + transition.setRule(newRule); + transition.getBoard().setModifiable(false); + tree.addTreeElement(transition); + } else { + transition.getBoard().setModifiable(false); + tree.addTreeElement(treeNode, transition); + } + + final TreeTransition finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(transition)); + } - if (finalTreeElement != null) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); + } else { + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + if (transitionView.getChildView() != null) { + finalTreeElement = transitionView.getChildView().getTreeElement(); + } else { + finalTreeElement = null; + } + } - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.TRANSITION) { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); + if (finalTreeElement != null) { + puzzle.notifyBoardListeners( + listener -> listener.onTreeElementChanged(finalTreeElement)); } - } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - return null; - } - - /** Undoes a command */ - @Override - public void undoCommand() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - - List selectedViews = selection.getSelectedViews(); - for (TreeElementView view : selectedViews) { - TreeElement element = view.getTreeElement(); - TreeNode node; - if (element.getType() == TreeElementType.TRANSITION) { - TreeTransition transition = (TreeTransition) element; - node = transition.getParents().get(0); - } else { - node = (TreeNode) element; - } - node.getChildren() - .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(n))); - node.getChildren().clear(); - - ArrayList save = saveElements.get(node); - - if (save != null) { - node.getChildren().addAll(save); - node.getChildren() - .forEach(n -> puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(n))); - } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); + } + + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.TRANSITION) { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); + } + } + } + return null; } - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + /** Undoes a command */ + @Override + public void undoCommand() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + + List selectedViews = selection.getSelectedViews(); + for (TreeElementView view : selectedViews) { + TreeElement element = view.getTreeElement(); + TreeNode node; + if (element.getType() == TreeElementType.TRANSITION) { + TreeTransition transition = (TreeTransition) element; + node = transition.getParents().get(0); + } else { + node = (TreeNode) element; + } + node.getChildren() + .forEach( + n -> + puzzle.notifyTreeListeners( + listener -> listener.onTreeElementRemoved(n))); + node.getChildren().clear(); + + ArrayList save = saveElements.get(node); + + if (save != null) { + node.getChildren().addAll(save); + node.getChildren() + .forEach( + n -> + puzzle.notifyTreeListeners( + listener -> listener.onTreeElementAdded(n))); + } + } + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java index 0fe35218f..d9c063464 100644 --- a/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java +++ b/src/main/java/edu/rpi/legup/history/ValidateDirectRuleCommand.java @@ -11,132 +11,132 @@ import java.util.Map; public class ValidateDirectRuleCommand extends PuzzleCommand { - private TreeViewSelection selection; + private TreeViewSelection selection; - private Map oldRules; - private Map addNode; - private DirectRule newRule; + private Map oldRules; + private Map addNode; + private DirectRule newRule; - /** - * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule - * - * @param selection selection of tree elements - * @param rule basic rule - */ - public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { - this.selection = selection.copy(); - this.newRule = rule; - this.oldRules = new HashMap<>(); - this.addNode = new HashMap<>(); - } + /** + * ValidateDesireRuleCommand Constructor creates a command for verifying a basic rule + * + * @param selection selection of tree elements + * @param rule basic rule + */ + public ValidateDirectRuleCommand(TreeViewSelection selection, DirectRule rule) { + this.selection = selection.copy(); + this.newRule = rule; + this.oldRules = new HashMap<>(); + this.addNode = new HashMap<>(); + } + + /** Executes an command */ + @Override + public void executeCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + final TreeViewSelection newSelection = new TreeViewSelection(); - /** Executes an command */ - @Override - public void executeCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - final TreeViewSelection newSelection = new TreeViewSelection(); + List selectedViews = selection.getSelectedViews(); + for (TreeElementView selectedView : selectedViews) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); - List selectedViews = selection.getSelectedViews(); - for (TreeElementView selectedView : selectedViews) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); + oldRules.put(transition, transition.getRule()); + transition.setRule(newRule); - oldRules.put(transition, transition.getRule()); - transition.setRule(newRule); + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + childNode = addNode.get(transition); + if (childNode == null) { + childNode = (TreeNode) tree.addTreeElement(transition); + addNode.put(transition, childNode); + } else { + tree.addTreeElement(transition, childNode); + } - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - childNode = addNode.get(transition); - if (childNode == null) { - childNode = (TreeNode) tree.addTreeElement(transition); - addNode.put(transition, childNode); + final TreeNode finalNode = childNode; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); + } + newSelection.addToSelection(treeView.getElementView(childNode)); + } + TreeElementView firstSelectedView = selection.getFirstSelection(); + final TreeElement finalTreeElement; + if (firstSelectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) firstSelectedView; + finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); } else { - tree.addTreeElement(transition, childNode); + TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; + finalTreeElement = transitionView.getChildView().getTreeElement(); } - - final TreeNode finalNode = childNode; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalNode)); - } - newSelection.addToSelection(treeView.getElementView(childNode)); - } - TreeElementView firstSelectedView = selection.getFirstSelection(); - final TreeElement finalTreeElement; - if (firstSelectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) firstSelectedView; - finalTreeElement = nodeView.getChildrenViews().get(0).getTreeElement(); - } else { - TreeTransitionView transitionView = (TreeTransitionView) firstSelectedView; - finalTreeElement = transitionView.getChildView().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); - } - - for (TreeElementView view : selectedViews) { - if (view.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - if (nodeView.getChildrenViews().size() != 1) { - return CommandError.ONE_CHILD.toString(); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - } else { - TreeTransitionView transView = (TreeTransitionView) view; - if (transView.getParentViews().size() > 1) { - return CommandError.CONTAINS_MERGE.toString(); + + for (TreeElementView view : selectedViews) { + if (view.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + if (nodeView.getChildrenViews().size() != 1) { + return CommandError.ONE_CHILD.toString(); + } + } else { + TreeTransitionView transView = (TreeTransitionView) view; + if (transView.getParentViews().size() > 1) { + return CommandError.CONTAINS_MERGE.toString(); + } + } } - } + return null; } - return null; - } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = GameBoardFacade.getInstance().getTree(); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = GameBoardFacade.getInstance().getTree(); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - for (TreeElementView selectedView : selection.getSelectedViews()) { - TreeElement element = selectedView.getTreeElement(); - TreeTransitionView transitionView; - if (element.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - transitionView = nodeView.getChildrenViews().get(0); - } else { - transitionView = (TreeTransitionView) selectedView; - } - TreeTransition transition = transitionView.getTreeElement(); - transition.setRule(oldRules.get(transition)); + for (TreeElementView selectedView : selection.getSelectedViews()) { + TreeElement element = selectedView.getTreeElement(); + TreeTransitionView transitionView; + if (element.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + transitionView = nodeView.getChildrenViews().get(0); + } else { + transitionView = (TreeTransitionView) selectedView; + } + TreeTransition transition = transitionView.getTreeElement(); + transition.setRule(oldRules.get(transition)); - if (addNode.get(transition) != null) { - final TreeNode childNode = transition.getChildNode(); - tree.removeTreeElement(childNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); - } - } + if (addNode.get(transition) != null) { + final TreeNode childNode = transition.getChildNode(); + tree.removeTreeElement(childNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(childNode)); + } + } - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); + } } diff --git a/src/main/java/edu/rpi/legup/model/Puzzle.java b/src/main/java/edu/rpi/legup/model/Puzzle.java index 6e5e681b2..7971c95af 100644 --- a/src/main/java/edu/rpi/legup/model/Puzzle.java +++ b/src/main/java/edu/rpi/legup/model/Puzzle.java @@ -36,614 +36,615 @@ import org.xml.sax.SAXException; public abstract class Puzzle implements IBoardSubject, ITreeSubject { - private static final Logger LOGGER = LogManager.getLogger(Puzzle.class.getName()); - - protected String name; - protected Board currentBoard; - protected Tree tree; - protected BoardView boardView; - protected PuzzleImporter importer; - protected PuzzleExporter exporter; - protected ElementFactory factory; - - private List boardListeners; - private List treeListeners; - - protected List directRules; - protected List contradictionRules; - protected List caseRules; - protected List placeableElements; - protected List nonPlaceableElements; - - /** Puzzle Constructor - creates a new Puzzle */ - public Puzzle() { - this.boardListeners = new ArrayList<>(); - this.treeListeners = new ArrayList<>(); - - this.directRules = new ArrayList<>(); - this.contradictionRules = new ArrayList<>(); - this.caseRules = new ArrayList<>(); - - this.placeableElements = new ArrayList<>(); - this.nonPlaceableElements = new ArrayList<>(); - - registerRules(); - registerPuzzleElements(); - } - - private void registerPuzzleElements() { - String packageName = this.getClass().getPackage().toString().replace("package ", ""); - - try { - Class[] possElements = LegupUtils.getClasses(packageName); - - for (Class c : possElements) { - - System.out.println("possible element: " + c.getName()); - - // check that the element is not abstract - if (Modifier.isAbstract(c.getModifiers())) continue; - - for (Annotation a : c.getAnnotations()) { - if (a.annotationType() == RegisterElement.class) { - RegisterElement registerElement = (RegisterElement) a; - Constructor cons = c.getConstructor(); - try { - Element element = (Element) cons.newInstance(); - - switch (element.getElementType()) { - case PLACEABLE: - this.addPlaceableElement((PlaceableElement) element); - break; - case NONPLACEABLE: - this.addNonPlaceableElement((NonPlaceableElement) element); - break; - default: - break; - } - } catch (InvocationTargetException e) { - System.out.println(" Failed "); - e.getTargetException().printStackTrace(); + private static final Logger LOGGER = LogManager.getLogger(Puzzle.class.getName()); + + protected String name; + protected Board currentBoard; + protected Tree tree; + protected BoardView boardView; + protected PuzzleImporter importer; + protected PuzzleExporter exporter; + protected ElementFactory factory; + + private List boardListeners; + private List treeListeners; + + protected List directRules; + protected List contradictionRules; + protected List caseRules; + protected List placeableElements; + protected List nonPlaceableElements; + + /** Puzzle Constructor - creates a new Puzzle */ + public Puzzle() { + this.boardListeners = new ArrayList<>(); + this.treeListeners = new ArrayList<>(); + + this.directRules = new ArrayList<>(); + this.contradictionRules = new ArrayList<>(); + this.caseRules = new ArrayList<>(); + + this.placeableElements = new ArrayList<>(); + this.nonPlaceableElements = new ArrayList<>(); + + registerRules(); + registerPuzzleElements(); + } + + private void registerPuzzleElements() { + String packageName = this.getClass().getPackage().toString().replace("package ", ""); + + try { + Class[] possElements = LegupUtils.getClasses(packageName); + + for (Class c : possElements) { + + System.out.println("possible element: " + c.getName()); + + // check that the element is not abstract + if (Modifier.isAbstract(c.getModifiers())) continue; + + for (Annotation a : c.getAnnotations()) { + if (a.annotationType() == RegisterElement.class) { + RegisterElement registerElement = (RegisterElement) a; + Constructor cons = c.getConstructor(); + try { + Element element = (Element) cons.newInstance(); + + switch (element.getElementType()) { + case PLACEABLE: + this.addPlaceableElement((PlaceableElement) element); + break; + case NONPLACEABLE: + this.addNonPlaceableElement((NonPlaceableElement) element); + break; + default: + break; + } + } catch (InvocationTargetException e) { + System.out.println(" Failed "); + e.getTargetException().printStackTrace(); + } + } + } + } + + // } catch (IOException | ClassNotFoundException | NoSuchMethodException | + // InstantiationException | IllegalAccessException | + // InvocationTargetException + // e) { + // LOGGER.error("Unable to find rules for " + + // this.getClass().getSimpleName(), e); + // } + } catch (Exception e) { + LOGGER.error("Unable to find elements for " + this.getClass().getSimpleName(), e); + } + } + + private void registerRules() { + String packageName = this.getClass().getPackage().toString().replace("package ", ""); + + try { + Class[] possRules = LegupUtils.getClasses(packageName); + + for (Class c : possRules) { + + System.out.println("possible rule: " + c.getName()); + + // check that the rule is not abstract + if (Modifier.isAbstract(c.getModifiers())) continue; + + for (Annotation a : c.getAnnotations()) { + if (a.annotationType() == RegisterRule.class) { + RegisterRule registerRule = (RegisterRule) a; + Constructor cons = c.getConstructor(); + try { + Rule rule = (Rule) cons.newInstance(); + + switch (rule.getRuleType()) { + case BASIC: + this.addDirectRule((DirectRule) rule); + break; + case CASE: + this.addCaseRule((CaseRule) rule); + break; + case CONTRADICTION: + this.addContradictionRule((ContradictionRule) rule); + break; + case MERGE: + break; + default: + break; + } + } catch (InvocationTargetException e) { + System.out.println(" Failed "); + e.getTargetException().printStackTrace(); + } + } + } } - } + + // } catch (IOException | ClassNotFoundException | NoSuchMethodException | + // InstantiationException | IllegalAccessException | + // InvocationTargetException + // e) { + // LOGGER.error("Unable to find rules for " + + // this.getClass().getSimpleName(), e); + // } + } catch (Exception e) { + LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); + } + } + + /** Initializes the view. Called by the invoker of the class */ + public abstract void initializeView(); + + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + public abstract Board generatePuzzle(int difficulty); + + /** + * Checks if the given height and width are valid board dimensions for the given puzzle + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @return true if the given dimensions are valid for the given puzzle, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows > 0 && columns > 0; + } + + /** + * Checks if the given array of statements is valid text input for the given puzzle + * + * @param statements + * @return + */ + public boolean isValidTextInput(String[] statements) { + return statements.length > 0; + } + + /** + * Determines if the edu.rpi.legup.puzzle was solves correctly + * + * @return true if the board was solved correctly, false otherwise + */ + public boolean isPuzzleComplete() { + if (tree == null) { + return false; } - } - - // } catch (IOException | ClassNotFoundException | NoSuchMethodException | - // InstantiationException | IllegalAccessException | - // InvocationTargetException - // e) { - // LOGGER.error("Unable to find rules for " + - // this.getClass().getSimpleName(), e); - // } - } catch (Exception e) { - LOGGER.error("Unable to find elements for " + this.getClass().getSimpleName(), e); - } - } - - private void registerRules() { - String packageName = this.getClass().getPackage().toString().replace("package ", ""); - - try { - Class[] possRules = LegupUtils.getClasses(packageName); - - for (Class c : possRules) { - - System.out.println("possible rule: " + c.getName()); - - // check that the rule is not abstract - if (Modifier.isAbstract(c.getModifiers())) continue; - - for (Annotation a : c.getAnnotations()) { - if (a.annotationType() == RegisterRule.class) { - RegisterRule registerRule = (RegisterRule) a; - Constructor cons = c.getConstructor(); - try { - Rule rule = (Rule) cons.newInstance(); - - switch (rule.getRuleType()) { - case BASIC: - this.addDirectRule((DirectRule) rule); - break; - case CASE: - this.addCaseRule((CaseRule) rule); - break; - case CONTRADICTION: - this.addContradictionRule((ContradictionRule) rule); - break; - case MERGE: - break; - default: - break; - } - } catch (InvocationTargetException e) { - System.out.println(" Failed "); - e.getTargetException().printStackTrace(); + + boolean isComplete = tree.isValid(); + if (isComplete) { + for (TreeElement leaf : tree.getLeafTreeElements()) { + if (leaf.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) leaf; + if (!node.isRoot()) { + isComplete &= + node.getParent().isContradictoryBranch() + || isBoardComplete(node.getBoard()); + } else { + isComplete &= isBoardComplete(node.getBoard()); + } + } else { + isComplete = false; + } } - } } - } - - // } catch (IOException | ClassNotFoundException | NoSuchMethodException | - // InstantiationException | IllegalAccessException | - // InvocationTargetException - // e) { - // LOGGER.error("Unable to find rules for " + - // this.getClass().getSimpleName(), e); - // } - } catch (Exception e) { - LOGGER.error("Unable to find rules for " + this.getClass().getSimpleName(), e); - } - } - - /** Initializes the view. Called by the invoker of the class */ - public abstract void initializeView(); - - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - public abstract Board generatePuzzle(int difficulty); - - /** - * Checks if the given height and width are valid board dimensions for the given puzzle - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @return true if the given dimensions are valid for the given puzzle, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows > 0 && columns > 0; - } - - /** - * Checks if the given array of statements is valid text input for the given puzzle - * - * @param statements - * @return - */ - public boolean isValidTextInput(String[] statements) { - return statements.length > 0; - } - - /** - * Determines if the edu.rpi.legup.puzzle was solves correctly - * - * @return true if the board was solved correctly, false otherwise - */ - public boolean isPuzzleComplete() { - if (tree == null) { - return false; - } - - boolean isComplete = tree.isValid(); - if (isComplete) { - for (TreeElement leaf : tree.getLeafTreeElements()) { - if (leaf.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) leaf; - if (!node.isRoot()) { - isComplete &= - node.getParent().isContradictoryBranch() || isBoardComplete(node.getBoard()); - } else { - isComplete &= isBoardComplete(node.getBoard()); - } + return isComplete; + } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + public abstract boolean isBoardComplete(Board board); + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + public abstract void onBoardChange(Board board); + + /** + * Imports the board using the file stream + * + * @param fileName the file that is imported + * @throws InvalidFileFormatException if file is invalid + */ + public void importPuzzle(String fileName) throws InvalidFileFormatException { + try { + importPuzzle(new FileInputStream(fileName)); + } catch (IOException e) { + LOGGER.error("Importing puzzle error", e); + throw new InvalidFileFormatException("Could not find file"); + } + } + + /** + * Imports the board using the file stream + * + * @param inputStream the file stream that is imported + * @throws InvalidFileFormatException if file stream is invalid + */ + public void importPuzzle(InputStream inputStream) throws InvalidFileFormatException { + Document document; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document = builder.parse(inputStream); + } catch (IOException | SAXException | ParserConfigurationException e) { + LOGGER.error("Importing puzzle error", e); + throw new InvalidFileFormatException("Could not find file"); + } + + org.w3c.dom.Element rootNode = document.getDocumentElement(); + if (rootNode.getTagName().equals("Legup")) { + Node node = rootNode.getElementsByTagName("puzzle").item(0); + if (importer == null) { + throw new InvalidFileFormatException("Puzzle importer null"); + } + importer.initializePuzzle(node); } else { - isComplete = false; + LOGGER.error("Invalid file"); + throw new InvalidFileFormatException("Invalid file: must be a Legup file"); } - } - } - return isComplete; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - public abstract boolean isBoardComplete(Board board); - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - public abstract void onBoardChange(Board board); - - /** - * Imports the board using the file stream - * - * @param fileName the file that is imported - * @throws InvalidFileFormatException if file is invalid - */ - public void importPuzzle(String fileName) throws InvalidFileFormatException { - try { - importPuzzle(new FileInputStream(fileName)); - } catch (IOException e) { - LOGGER.error("Importing puzzle error", e); - throw new InvalidFileFormatException("Could not find file"); - } - } - - /** - * Imports the board using the file stream - * - * @param inputStream the file stream that is imported - * @throws InvalidFileFormatException if file stream is invalid - */ - public void importPuzzle(InputStream inputStream) throws InvalidFileFormatException { - Document document; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - document = builder.parse(inputStream); - } catch (IOException | SAXException | ParserConfigurationException e) { - LOGGER.error("Importing puzzle error", e); - throw new InvalidFileFormatException("Could not find file"); - } - - org.w3c.dom.Element rootNode = document.getDocumentElement(); - if (rootNode.getTagName().equals("Legup")) { - Node node = rootNode.getElementsByTagName("puzzle").item(0); - if (importer == null) { - throw new InvalidFileFormatException("Puzzle importer null"); - } - importer.initializePuzzle(node); - } else { - LOGGER.error("Invalid file"); - throw new InvalidFileFormatException("Invalid file: must be a Legup file"); - } - } - - /** - * Gets the edu.rpi.legup.puzzle importer for importing edu.rpi.legup.puzzle files - * - * @return edu.rpi.legup.puzzle importer - */ - public PuzzleImporter getImporter() { - return importer; - } - - /** - * Gets the edu.rpi.legup.puzzle exporter for exporting edu.rpi.legup.puzzle files - * - * @return edu.rpi.legup.puzzle exporter - */ - public PuzzleExporter getExporter() { - return exporter; - } - - /** - * Gets the name of the edu.rpi.legup.puzzle - * - * @return name of the edu.rpi.legup.puzzle - */ - public String getName() { - return name; - } - - /** - * Gets the list of direct rules - * - * @return list of basic rules - */ - public List getDirectRules() { - return directRules; - } - - public List getPlaceableElements() { - return placeableElements; - } - - public List getNonPlaceableElements() { - return nonPlaceableElements; - } - - /** - * Sets the list of direct rules - * - * @param directRules list of basic rules - */ - public void setDirectRules(List directRules) { - this.directRules = directRules; - } - - /** - * Adds a basic rule to this Puzzle - * - * @param rule basic rule to add - */ - public void addDirectRule(DirectRule rule) { - directRules.add(rule); - } - - public void addPlaceableElement(PlaceableElement element) { - placeableElements.add(element); - } - - public void addNonPlaceableElement(NonPlaceableElement element) { - nonPlaceableElements.add(element); - } - - /** - * Remove a basic rule from this Puzzle - * - * @param rule basic rule to remove - */ - public void removeDirectRule(DirectRule rule) { - directRules.remove(rule); - } - - /** - * Gets the list of contradiction rules - * - * @return list of contradiction rules - */ - public List getContradictionRules() { - return contradictionRules; - } - - /** - * Sets the list of contradiction rules - * - * @param contradictionRules list of contradiction rules - */ - public void setContradictionRules(List contradictionRules) { - this.contradictionRules = contradictionRules; - } - - /** - * Adds a contradiction rule to this Puzzle - * - * @param rule contradiction rule to add - */ - public void addContradictionRule(ContradictionRule rule) { - contradictionRules.add(rule); - } - - /** - * Remove a contradiction rule from this Puzzle - * - * @param rule contradiction rule to remove - */ - public void removeContradictionRule(ContradictionRule rule) { - contradictionRules.remove(rule); - } - - /** - * Gets the list of case rules - * - * @return list of case rules - */ - public List getCaseRules() { - return caseRules; - } - - /** - * Sets the list of case rules - * - * @param caseRules list of case rules - */ - public void setCaseRules(List caseRules) { - this.caseRules = caseRules; - } - - /** - * Adds a case rule to this Puzzle - * - * @param rule case rule to add - */ - public void addCaseRule(CaseRule rule) { - caseRules.add(rule); - } - - /** - * Removes a case rule from this Puzzle - * - * @param rule case rule to remove - */ - public void removeCaseRule(CaseRule rule) { - caseRules.remove(rule); - } - - /** - * Gets the rule using the specified name - * - * @param name name of the rule - * @return Rule - */ - public Rule getRuleByName(String name) { - for (Rule rule : directRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - for (Rule rule : contradictionRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - for (Rule rule : caseRules) { - if (rule.getRuleName().equals(name)) { - return rule; - } - } - Rule mergeRule = new MergeRule(); - if (mergeRule.getRuleName().equals(name)) { - return mergeRule; - } - return null; - } - - /** - * Gets the rule using the specified name - * - * @param id name of the rule - * @return Rule - */ - public Rule getRuleByID(String id) { - for (Rule rule : directRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - for (Rule rule : contradictionRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - for (Rule rule : caseRules) { - if (rule.getRuleID().equals(id)) { - return rule; - } - } - Rule mergeRule = new MergeRule(); - if (mergeRule.getRuleID().equals(id)) { - return mergeRule; - } - return null; - } - - /** - * Gets the current board - * - * @return current board - */ - public Board getCurrentBoard() { - return currentBoard; - } - - /** - * Sets the current board - * - * @param currentBoard the current board - */ - public void setCurrentBoard(Board currentBoard) { - this.currentBoard = currentBoard; - } - - /** - * Gets the Tree for keeping the board states - * - * @return Tree - */ - public Tree getTree() { - return tree; - } - - /** - * Sets the Tree for keeping the board states - * - * @param tree tree of board states - */ - public void setTree(Tree tree) { - this.tree = tree; - } - - /** - * Gets the board view that displays the board - * - * @return board view - */ - public BoardView getBoardView() { - return boardView; - } - - /** - * Sets the board view that displays the board - * - * @param boardView board view - */ - public void setBoardView(BoardView boardView) { - this.boardView = boardView; - } - - /** - * Gets the ElementFactory associated with this edu.rpi.legup.puzzle - * - * @return ElementFactory associated with this edu.rpi.legup.puzzle - */ - public ElementFactory getFactory() { - return factory; - } - - /** - * Sets the ElementFactory associated with this edu.rpi.legup.puzzle - * - * @param factory ElementFactory associated with this edu.rpi.legup.puzzle - */ - public void setFactory(ElementFactory factory) { - this.factory = factory; - } - - /** - * Adds a board listener - * - * @param listener listener to add - */ - @Override - public void addBoardListener(IBoardListener listener) { - boardListeners.add(listener); - } - - /** - * Removes a board listener - * - * @param listener listener to remove - */ - @Override - public void removeBoardListener(IBoardListener listener) { - boardListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyBoardListeners(Consumer algorithm) { - boardListeners.forEach(algorithm); - } - - /** - * Adds a board listener - * - * @param listener listener to add - */ - @Override - public void addTreeListener(ITreeListener listener) { - treeListeners.add(listener); - } - - /** - * Removes a tree listener - * - * @param listener listener to remove - */ - @Override - public void removeTreeListener(ITreeListener listener) { - treeListeners.remove(listener); - } - - /** - * Notifies listeners - * - * @param algorithm algorithm to notify the listeners with - */ - @Override - public void notifyTreeListeners(Consumer algorithm) { - treeListeners.forEach(algorithm); - } - - /** - * Check if the puzzle is valid - * - * @return if the puzzle is valid - */ - public boolean checkValidity() { - return true; - } + } + + /** + * Gets the edu.rpi.legup.puzzle importer for importing edu.rpi.legup.puzzle files + * + * @return edu.rpi.legup.puzzle importer + */ + public PuzzleImporter getImporter() { + return importer; + } + + /** + * Gets the edu.rpi.legup.puzzle exporter for exporting edu.rpi.legup.puzzle files + * + * @return edu.rpi.legup.puzzle exporter + */ + public PuzzleExporter getExporter() { + return exporter; + } + + /** + * Gets the name of the edu.rpi.legup.puzzle + * + * @return name of the edu.rpi.legup.puzzle + */ + public String getName() { + return name; + } + + /** + * Gets the list of direct rules + * + * @return list of basic rules + */ + public List getDirectRules() { + return directRules; + } + + public List getPlaceableElements() { + return placeableElements; + } + + public List getNonPlaceableElements() { + return nonPlaceableElements; + } + + /** + * Sets the list of direct rules + * + * @param directRules list of basic rules + */ + public void setDirectRules(List directRules) { + this.directRules = directRules; + } + + /** + * Adds a basic rule to this Puzzle + * + * @param rule basic rule to add + */ + public void addDirectRule(DirectRule rule) { + directRules.add(rule); + } + + public void addPlaceableElement(PlaceableElement element) { + placeableElements.add(element); + } + + public void addNonPlaceableElement(NonPlaceableElement element) { + nonPlaceableElements.add(element); + } + + /** + * Remove a basic rule from this Puzzle + * + * @param rule basic rule to remove + */ + public void removeDirectRule(DirectRule rule) { + directRules.remove(rule); + } + + /** + * Gets the list of contradiction rules + * + * @return list of contradiction rules + */ + public List getContradictionRules() { + return contradictionRules; + } + + /** + * Sets the list of contradiction rules + * + * @param contradictionRules list of contradiction rules + */ + public void setContradictionRules(List contradictionRules) { + this.contradictionRules = contradictionRules; + } + + /** + * Adds a contradiction rule to this Puzzle + * + * @param rule contradiction rule to add + */ + public void addContradictionRule(ContradictionRule rule) { + contradictionRules.add(rule); + } + + /** + * Remove a contradiction rule from this Puzzle + * + * @param rule contradiction rule to remove + */ + public void removeContradictionRule(ContradictionRule rule) { + contradictionRules.remove(rule); + } + + /** + * Gets the list of case rules + * + * @return list of case rules + */ + public List getCaseRules() { + return caseRules; + } + + /** + * Sets the list of case rules + * + * @param caseRules list of case rules + */ + public void setCaseRules(List caseRules) { + this.caseRules = caseRules; + } + + /** + * Adds a case rule to this Puzzle + * + * @param rule case rule to add + */ + public void addCaseRule(CaseRule rule) { + caseRules.add(rule); + } + + /** + * Removes a case rule from this Puzzle + * + * @param rule case rule to remove + */ + public void removeCaseRule(CaseRule rule) { + caseRules.remove(rule); + } + + /** + * Gets the rule using the specified name + * + * @param name name of the rule + * @return Rule + */ + public Rule getRuleByName(String name) { + for (Rule rule : directRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + for (Rule rule : contradictionRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + for (Rule rule : caseRules) { + if (rule.getRuleName().equals(name)) { + return rule; + } + } + Rule mergeRule = new MergeRule(); + if (mergeRule.getRuleName().equals(name)) { + return mergeRule; + } + return null; + } + + /** + * Gets the rule using the specified name + * + * @param id name of the rule + * @return Rule + */ + public Rule getRuleByID(String id) { + for (Rule rule : directRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + for (Rule rule : contradictionRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + for (Rule rule : caseRules) { + if (rule.getRuleID().equals(id)) { + return rule; + } + } + Rule mergeRule = new MergeRule(); + if (mergeRule.getRuleID().equals(id)) { + return mergeRule; + } + return null; + } + + /** + * Gets the current board + * + * @return current board + */ + public Board getCurrentBoard() { + return currentBoard; + } + + /** + * Sets the current board + * + * @param currentBoard the current board + */ + public void setCurrentBoard(Board currentBoard) { + this.currentBoard = currentBoard; + } + + /** + * Gets the Tree for keeping the board states + * + * @return Tree + */ + public Tree getTree() { + return tree; + } + + /** + * Sets the Tree for keeping the board states + * + * @param tree tree of board states + */ + public void setTree(Tree tree) { + this.tree = tree; + } + + /** + * Gets the board view that displays the board + * + * @return board view + */ + public BoardView getBoardView() { + return boardView; + } + + /** + * Sets the board view that displays the board + * + * @param boardView board view + */ + public void setBoardView(BoardView boardView) { + this.boardView = boardView; + } + + /** + * Gets the ElementFactory associated with this edu.rpi.legup.puzzle + * + * @return ElementFactory associated with this edu.rpi.legup.puzzle + */ + public ElementFactory getFactory() { + return factory; + } + + /** + * Sets the ElementFactory associated with this edu.rpi.legup.puzzle + * + * @param factory ElementFactory associated with this edu.rpi.legup.puzzle + */ + public void setFactory(ElementFactory factory) { + this.factory = factory; + } + + /** + * Adds a board listener + * + * @param listener listener to add + */ + @Override + public void addBoardListener(IBoardListener listener) { + boardListeners.add(listener); + } + + /** + * Removes a board listener + * + * @param listener listener to remove + */ + @Override + public void removeBoardListener(IBoardListener listener) { + boardListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyBoardListeners(Consumer algorithm) { + boardListeners.forEach(algorithm); + } + + /** + * Adds a board listener + * + * @param listener listener to add + */ + @Override + public void addTreeListener(ITreeListener listener) { + treeListeners.add(listener); + } + + /** + * Removes a tree listener + * + * @param listener listener to remove + */ + @Override + public void removeTreeListener(ITreeListener listener) { + treeListeners.remove(listener); + } + + /** + * Notifies listeners + * + * @param algorithm algorithm to notify the listeners with + */ + @Override + public void notifyTreeListeners(Consumer algorithm) { + treeListeners.forEach(algorithm); + } + + /** + * Check if the puzzle is valid + * + * @return if the puzzle is valid + */ + public boolean checkValidity() { + return true; + } } diff --git a/src/main/java/edu/rpi/legup/model/PuzzleExporter.java b/src/main/java/edu/rpi/legup/model/PuzzleExporter.java index cccf0155c..a052a736a 100644 --- a/src/main/java/edu/rpi/legup/model/PuzzleExporter.java +++ b/src/main/java/edu/rpi/legup/model/PuzzleExporter.java @@ -21,125 +21,126 @@ import org.w3c.dom.Element; public abstract class PuzzleExporter { - private static final Logger LOGGER = LogManager.getLogger(PuzzleExporter.class.getName()); - - protected Puzzle puzzle; - - /** - * PuzzleExporter Constructor exports the puzzle object to a file - * - * @param puzzle puzzle that is to be exported - */ - public PuzzleExporter(Puzzle puzzle) { - this.puzzle = puzzle; - } - - /** - * Exports the puzzle to an xml formatted file - * - * @param fileName name of file to be exported - * @throws ExportFileException if puzzle can not be exported - */ - public void exportPuzzle(String fileName) throws ExportFileException { - try { - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document newDocument = docBuilder.newDocument(); - - org.w3c.dom.Element legupElement = newDocument.createElement("Legup"); - legupElement.setAttribute("version", "3.0.0"); - newDocument.appendChild(legupElement); - - org.w3c.dom.Element timeSavedElement = newDocument.createElement("saved"); - legupElement.appendChild(timeSavedElement); - - org.w3c.dom.Element puzzleElement = newDocument.createElement("puzzle"); - puzzleElement.setAttribute("name", puzzle.getName()); - legupElement.appendChild(puzzleElement); - - puzzleElement.appendChild(createBoardElement(newDocument)); - if (puzzle.getTree() != null && !puzzle.getTree().getRootNode().getChildren().isEmpty()) { - puzzleElement.appendChild(createProofElement(newDocument)); - } - - org.w3c.dom.Element statusElement = newDocument.createElement("solved"); - String isSolved = "false"; - if (puzzle.isPuzzleComplete()) { - isSolved = "true"; - } - statusElement.setAttribute("isSolved", isSolved); - LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/New_York")); - String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - statusElement.setAttribute("lastSaved", time); - legupElement.appendChild(statusElement); - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - DOMSource source = new DOMSource(newDocument); - StreamResult result = new StreamResult(new File(fileName)); - - transformer.transform(source, result); - } catch (ParserConfigurationException | TransformerException e) { - throw new ExportFileException("Puzzle Exporter: parser configuration exception"); - } catch (Exception e) { - throw e; - // throw new ExportFileException(e.getMessage()); + private static final Logger LOGGER = LogManager.getLogger(PuzzleExporter.class.getName()); + + protected Puzzle puzzle; + + /** + * PuzzleExporter Constructor exports the puzzle object to a file + * + * @param puzzle puzzle that is to be exported + */ + public PuzzleExporter(Puzzle puzzle) { + this.puzzle = puzzle; } - } - - protected abstract Element createBoardElement(Document newDocument); - - protected Element createProofElement(Document newDocument) { - org.w3c.dom.Element proofElement = newDocument.createElement("proof"); - org.w3c.dom.Element treeElement = createTreeElement(newDocument); - proofElement.appendChild(treeElement); - return proofElement; - } - - protected Element createTreeElement(Document newDocument) { - org.w3c.dom.Element treeElement = newDocument.createElement("tree"); - - Set visited = new HashSet<>(); - List nodes = new ArrayList<>(); - nodes.add(puzzle.getTree().getRootNode()); - while (!nodes.isEmpty()) { - TreeNode treeNode = nodes.get(nodes.size() - 1); - nodes.remove(treeNode); - if (!visited.contains(treeNode)) { - visited.add(treeNode); - - org.w3c.dom.Element nodeElement = newDocument.createElement("node"); - nodeElement.setAttribute("id", String.valueOf(treeNode.hashCode())); - if (treeNode.isRoot()) { - nodeElement.setAttribute("root", "true"); + + /** + * Exports the puzzle to an xml formatted file + * + * @param fileName name of file to be exported + * @throws ExportFileException if puzzle can not be exported + */ + public void exportPuzzle(String fileName) throws ExportFileException { + try { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + Document newDocument = docBuilder.newDocument(); + + org.w3c.dom.Element legupElement = newDocument.createElement("Legup"); + legupElement.setAttribute("version", "3.0.0"); + newDocument.appendChild(legupElement); + + org.w3c.dom.Element timeSavedElement = newDocument.createElement("saved"); + legupElement.appendChild(timeSavedElement); + + org.w3c.dom.Element puzzleElement = newDocument.createElement("puzzle"); + puzzleElement.setAttribute("name", puzzle.getName()); + legupElement.appendChild(puzzleElement); + + puzzleElement.appendChild(createBoardElement(newDocument)); + if (puzzle.getTree() != null + && !puzzle.getTree().getRootNode().getChildren().isEmpty()) { + puzzleElement.appendChild(createProofElement(newDocument)); + } + + org.w3c.dom.Element statusElement = newDocument.createElement("solved"); + String isSolved = "false"; + if (puzzle.isPuzzleComplete()) { + isSolved = "true"; + } + statusElement.setAttribute("isSolved", isSolved); + LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/New_York")); + String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + statusElement.setAttribute("lastSaved", time); + legupElement.appendChild(statusElement); + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + + DOMSource source = new DOMSource(newDocument); + StreamResult result = new StreamResult(new File(fileName)); + + transformer.transform(source, result); + } catch (ParserConfigurationException | TransformerException e) { + throw new ExportFileException("Puzzle Exporter: parser configuration exception"); + } catch (Exception e) { + throw e; + // throw new ExportFileException(e.getMessage()); } + } + + protected abstract Element createBoardElement(Document newDocument); + + protected Element createProofElement(Document newDocument) { + org.w3c.dom.Element proofElement = newDocument.createElement("proof"); + org.w3c.dom.Element treeElement = createTreeElement(newDocument); + proofElement.appendChild(treeElement); + return proofElement; + } - for (TreeTransition transition : treeNode.getChildren()) { - org.w3c.dom.Element transElement = newDocument.createElement("transition"); - transElement.setAttribute("id", String.valueOf(transition.hashCode())); - - TreeNode child = transition.getChildNode(); - if (child != null) { - transElement.setAttribute("child", String.valueOf(child.hashCode())); - nodes.add(child); - } - - if (transition.isJustified()) { - transElement.setAttribute("rule", transition.getRule().getRuleName()); - transElement.setAttribute("rule_id", transition.getRule().getRuleID()); - } - - for (PuzzleElement data : transition.getBoard().getModifiedData()) { - transElement.appendChild(puzzle.getFactory().exportCell(newDocument, data)); - } - nodeElement.appendChild(transElement); + protected Element createTreeElement(Document newDocument) { + org.w3c.dom.Element treeElement = newDocument.createElement("tree"); + + Set visited = new HashSet<>(); + List nodes = new ArrayList<>(); + nodes.add(puzzle.getTree().getRootNode()); + while (!nodes.isEmpty()) { + TreeNode treeNode = nodes.get(nodes.size() - 1); + nodes.remove(treeNode); + if (!visited.contains(treeNode)) { + visited.add(treeNode); + + org.w3c.dom.Element nodeElement = newDocument.createElement("node"); + nodeElement.setAttribute("id", String.valueOf(treeNode.hashCode())); + if (treeNode.isRoot()) { + nodeElement.setAttribute("root", "true"); + } + + for (TreeTransition transition : treeNode.getChildren()) { + org.w3c.dom.Element transElement = newDocument.createElement("transition"); + transElement.setAttribute("id", String.valueOf(transition.hashCode())); + + TreeNode child = transition.getChildNode(); + if (child != null) { + transElement.setAttribute("child", String.valueOf(child.hashCode())); + nodes.add(child); + } + + if (transition.isJustified()) { + transElement.setAttribute("rule", transition.getRule().getRuleName()); + transElement.setAttribute("rule_id", transition.getRule().getRuleID()); + } + + for (PuzzleElement data : transition.getBoard().getModifiedData()) { + transElement.appendChild(puzzle.getFactory().exportCell(newDocument, data)); + } + nodeElement.appendChild(transElement); + } + treeElement.appendChild(nodeElement); + } } - treeElement.appendChild(nodeElement); - } + return treeElement; } - return treeElement; - } } diff --git a/src/main/java/edu/rpi/legup/model/PuzzleImporter.java b/src/main/java/edu/rpi/legup/model/PuzzleImporter.java index 77332278b..0cc163200 100644 --- a/src/main/java/edu/rpi/legup/model/PuzzleImporter.java +++ b/src/main/java/edu/rpi/legup/model/PuzzleImporter.java @@ -14,399 +14,402 @@ import org.w3c.dom.NodeList; public abstract class PuzzleImporter { - private static final Logger LOGGER = LogManager.getLogger(PuzzleImporter.class.getName()); - - protected Puzzle puzzle; - - /** - * PuzzleImporter Constructor creates the puzzle object - * - * @param puzzle puzzle that is imported - */ - public PuzzleImporter(Puzzle puzzle) { - this.puzzle = puzzle; - } - - public abstract boolean acceptsRowsAndColumnsInput(); - - public abstract boolean acceptsTextInput(); - - /** - * Initializes an empty puzzle - * - * @param rows number of rows on the puzzle - * @param columns number of columns on the puzzle - * @throws RuntimeException if puzzle can not be made - */ - public void initializePuzzle(int rows, int columns) throws RuntimeException { - if (this.puzzle.isValidDimensions(rows, columns)) { - initializeBoard(rows, columns); - } else { - throw new IllegalArgumentException("Invalid dimensions provided"); + private static final Logger LOGGER = LogManager.getLogger(PuzzleImporter.class.getName()); + + protected Puzzle puzzle; + + /** + * PuzzleImporter Constructor creates the puzzle object + * + * @param puzzle puzzle that is imported + */ + public PuzzleImporter(Puzzle puzzle) { + this.puzzle = puzzle; } - } - - public void initializePuzzle(String[] statements) - throws InputMismatchException, IllegalArgumentException { - // Note: Error checking for the statements will be left up to the puzzles that support - // text input. For example, some puzzles may be okay with "blank" statements (Strings with - // length = 0) while others may not. - initializeBoard(statements); - } - - /** - * Initializes the puzzle attributes - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public void initializePuzzle(Node node) throws InvalidFileFormatException { - if (node.getNodeName().equalsIgnoreCase("puzzle")) { - org.w3c.dom.Element puzzleElement = (org.w3c.dom.Element) node; - - boolean initBoard = false; - boolean initProof = false; - NodeList childNodes = puzzleElement.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - Node n = childNodes.item(i); - if (n.getNodeName().equalsIgnoreCase("board")) { - if (initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: duplicate board puzzleElement found"); - } - initializeBoard(n); - initBoard = true; + + public abstract boolean acceptsRowsAndColumnsInput(); + + public abstract boolean acceptsTextInput(); + + /** + * Initializes an empty puzzle + * + * @param rows number of rows on the puzzle + * @param columns number of columns on the puzzle + * @throws RuntimeException if puzzle can not be made + */ + public void initializePuzzle(int rows, int columns) throws RuntimeException { + if (this.puzzle.isValidDimensions(rows, columns)) { + initializeBoard(rows, columns); } else { - if (n.getNodeName().equalsIgnoreCase("proof")) { - if (initProof) { - throw new InvalidFileFormatException( - "Puzzle creation error: duplicate proof puzzleElement found"); + throw new IllegalArgumentException("Invalid dimensions provided"); + } + } + + public void initializePuzzle(String[] statements) + throws InputMismatchException, IllegalArgumentException { + // Note: Error checking for the statements will be left up to the puzzles that support + // text input. For example, some puzzles may be okay with "blank" statements (Strings with + // length = 0) while others may not. + initializeBoard(statements); + } + + /** + * Initializes the puzzle attributes + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public void initializePuzzle(Node node) throws InvalidFileFormatException { + if (node.getNodeName().equalsIgnoreCase("puzzle")) { + org.w3c.dom.Element puzzleElement = (org.w3c.dom.Element) node; + + boolean initBoard = false; + boolean initProof = false; + NodeList childNodes = puzzleElement.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node n = childNodes.item(i); + if (n.getNodeName().equalsIgnoreCase("board")) { + if (initBoard) { + throw new InvalidFileFormatException( + "Puzzle creation error: duplicate board puzzleElement found"); + } + initializeBoard(n); + initBoard = true; + } else { + if (n.getNodeName().equalsIgnoreCase("proof")) { + if (initProof) { + throw new InvalidFileFormatException( + "Puzzle creation error: duplicate proof puzzleElement found"); + } + if (!initBoard) { + throw new InvalidFileFormatException( + "Puzzle creation error: could not find board puzzleElement"); + } + initializeProof(n); + initProof = true; + } else { + if (!n.getNodeName().equalsIgnoreCase("#text")) { + throw new InvalidFileFormatException( + "Puzzle creation error: unknown node found in file"); + } + } + } } + if (!initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: could not find board puzzleElement"); + throw new InvalidFileFormatException( + "Puzzle creation error: could not find board puzzleElement"); } - initializeProof(n); - initProof = true; - } else { - if (!n.getNodeName().equalsIgnoreCase("#text")) { - throw new InvalidFileFormatException( - "Puzzle creation error: unknown node found in file"); + if (!initProof) { + createDefaultTree(); } - } + } else { + throw new InvalidFileFormatException( + "Invalid file format; does not contain \"puzzle\" node"); } - } - - if (!initBoard) { - throw new InvalidFileFormatException( - "Puzzle creation error: could not find board puzzleElement"); - } - if (!initProof) { - createDefaultTree(); - } - } else { - throw new InvalidFileFormatException("Invalid file format; does not contain \"puzzle\" node"); } - } - - /** - * Creates the board for building - * - * @param rows number of rows on the puzzle - * @param columns number of columns on the puzzle - * @throws RuntimeException if board can not be created - */ - public abstract void initializeBoard(int rows, int columns); - - /** - * Creates an empty board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public abstract void initializeBoard(Node node) throws InvalidFileFormatException; - - public abstract void initializeBoard(String[] statements) - throws UnsupportedOperationException, IllegalArgumentException; - - /** - * Creates the proof for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - public void initializeProof(Node node) throws InvalidFileFormatException { - if (node.getNodeName().equalsIgnoreCase("proof")) { - org.w3c.dom.Element proofElement = (org.w3c.dom.Element) node; - NodeList treeList = proofElement.getElementsByTagName("tree"); - - boolean initTree = false; - for (int i = 0; i < treeList.getLength(); i++) { - Node n = treeList.item(i); - if (n.getNodeName().equalsIgnoreCase("tree")) { - if (initTree) { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate tree puzzleElement"); - } - createTree(n); - initTree = true; + + /** + * Creates the board for building + * + * @param rows number of rows on the puzzle + * @param columns number of columns on the puzzle + * @throws RuntimeException if board can not be created + */ + public abstract void initializeBoard(int rows, int columns); + + /** + * Creates an empty board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public abstract void initializeBoard(Node node) throws InvalidFileFormatException; + + public abstract void initializeBoard(String[] statements) + throws UnsupportedOperationException, IllegalArgumentException; + + /** + * Creates the proof for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + public void initializeProof(Node node) throws InvalidFileFormatException { + if (node.getNodeName().equalsIgnoreCase("proof")) { + org.w3c.dom.Element proofElement = (org.w3c.dom.Element) node; + NodeList treeList = proofElement.getElementsByTagName("tree"); + + boolean initTree = false; + for (int i = 0; i < treeList.getLength(); i++) { + Node n = treeList.item(i); + if (n.getNodeName().equalsIgnoreCase("tree")) { + if (initTree) { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate tree puzzleElement"); + } + createTree(n); + initTree = true; + } else { + throw new InvalidFileFormatException( + "Proof Tree construction error: unknown puzzleElement found"); + } + } + if (!initTree) { + createDefaultTree(); + } } else { - throw new InvalidFileFormatException( - "Proof Tree construction error: unknown puzzleElement found"); + throw new InvalidFileFormatException( + "Invalid file format; does not contain \"proof\" node"); } - } - if (!initTree) { - createDefaultTree(); - } - } else { - throw new InvalidFileFormatException("Invalid file format; does not contain \"proof\" node"); - } - } - - /** - * Sets the puzzleElement from the xml document node - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - protected void setCells(Node node) throws InvalidFileFormatException { - NodeList dataList = ((org.w3c.dom.Element) node).getElementsByTagName("cell"); - Board board = puzzle.getCurrentBoard(); - for (int i = 0; i < dataList.getLength(); i++) { - PuzzleElement data = - puzzle.getFactory().importCell(dataList.item(i), puzzle.getCurrentBoard()); - board.setPuzzleElement(data.getIndex(), data); } - } - - /** - * Creates the tree for the edu.rpi.legup.puzzle - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - protected void createTree(Node node) throws InvalidFileFormatException { - Element treeElement = (org.w3c.dom.Element) node; - - Tree tree = new Tree(); - puzzle.setTree(tree); - - NodeList nodeList = ((org.w3c.dom.Element) node).getElementsByTagName("node"); - - HashMap treeNodes = new HashMap<>(); - HashMap treeTransitions = new HashMap<>(); - HashMap nodeChanges = new HashMap<>(); - - for (int i = 0; i < nodeList.getLength(); i++) { - org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); - String nodeId = treeNodeElement.getAttribute("id"); - String isRoot = treeNodeElement.getAttribute("root"); - if (nodeId.isEmpty()) { - throw new InvalidFileFormatException("Proof Tree construction error: cannot find node ID"); - } - if (treeNodes.containsKey(nodeId)) { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate tree node ID found"); - } - TreeNode treeNode = new TreeNode(puzzle.getCurrentBoard().copy()); - if (isRoot.equalsIgnoreCase("true")) { - if (tree.getRootNode() != null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: multiple root nodes declared"); + + /** + * Sets the puzzleElement from the xml document node + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + protected void setCells(Node node) throws InvalidFileFormatException { + NodeList dataList = ((org.w3c.dom.Element) node).getElementsByTagName("cell"); + Board board = puzzle.getCurrentBoard(); + for (int i = 0; i < dataList.getLength(); i++) { + PuzzleElement data = + puzzle.getFactory().importCell(dataList.item(i), puzzle.getCurrentBoard()); + board.setPuzzleElement(data.getIndex(), data); } - treeNode.setRoot(true); - tree.setRootNode(treeNode); - } - treeNodes.put(nodeId, treeNode); } - for (int i = 0; i < nodeList.getLength(); i++) { - org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); - String nodeId = treeNodeElement.getAttribute("id"); - TreeNode treeNode = treeNodes.get(nodeId); - - NodeList transList = treeNodeElement.getElementsByTagName("transition"); - for (int k = 0; k < transList.getLength(); k++) { - org.w3c.dom.Element trans = (org.w3c.dom.Element) transList.item(k); - String transId = trans.getAttribute("id"); - TreeTransition transition = treeTransitions.get(transId); - if (transition != null) { - if (transition.getRule() instanceof MergeRule) { - transition.addParent(treeNode); - treeNode.addChild(transition); - continue; - } else { - throw new InvalidFileFormatException( - "Proof Tree construction error: duplicate transition ID found"); - } + /** + * Creates the tree for the edu.rpi.legup.puzzle + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + protected void createTree(Node node) throws InvalidFileFormatException { + Element treeElement = (org.w3c.dom.Element) node; + + Tree tree = new Tree(); + puzzle.setTree(tree); + + NodeList nodeList = ((org.w3c.dom.Element) node).getElementsByTagName("node"); + + HashMap treeNodes = new HashMap<>(); + HashMap treeTransitions = new HashMap<>(); + HashMap nodeChanges = new HashMap<>(); + + for (int i = 0; i < nodeList.getLength(); i++) { + org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); + String nodeId = treeNodeElement.getAttribute("id"); + String isRoot = treeNodeElement.getAttribute("root"); + if (nodeId.isEmpty()) { + throw new InvalidFileFormatException( + "Proof Tree construction error: cannot find node ID"); + } + if (treeNodes.containsKey(nodeId)) { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate tree node ID found"); + } + TreeNode treeNode = new TreeNode(puzzle.getCurrentBoard().copy()); + if (isRoot.equalsIgnoreCase("true")) { + if (tree.getRootNode() != null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: multiple root nodes declared"); + } + treeNode.setRoot(true); + tree.setRootNode(treeNode); + } + treeNodes.put(nodeId, treeNode); } - String childId = trans.getAttribute("child"); - String ruleName = trans.getAttribute("rule"); - String ruleId = trans.getAttribute("rule_id"); - - TreeNode child = treeNodes.get(childId); - - transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - - Rule rule; - if (!ruleName.isEmpty()) { - rule = puzzle.getRuleByID(ruleId); - if (rule == null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: could not find rule by ID"); - } - transition.setRule(rule); + for (int i = 0; i < nodeList.getLength(); i++) { + org.w3c.dom.Element treeNodeElement = (org.w3c.dom.Element) nodeList.item(i); + String nodeId = treeNodeElement.getAttribute("id"); + TreeNode treeNode = treeNodes.get(nodeId); + + NodeList transList = treeNodeElement.getElementsByTagName("transition"); + for (int k = 0; k < transList.getLength(); k++) { + org.w3c.dom.Element trans = (org.w3c.dom.Element) transList.item(k); + String transId = trans.getAttribute("id"); + TreeTransition transition = treeTransitions.get(transId); + if (transition != null) { + if (transition.getRule() instanceof MergeRule) { + transition.addParent(treeNode); + treeNode.addChild(transition); + continue; + } else { + throw new InvalidFileFormatException( + "Proof Tree construction error: duplicate transition ID found"); + } + } + + String childId = trans.getAttribute("child"); + String ruleName = trans.getAttribute("rule"); + String ruleId = trans.getAttribute("rule_id"); + + TreeNode child = treeNodes.get(childId); + + transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + + Rule rule; + if (!ruleName.isEmpty()) { + rule = puzzle.getRuleByID(ruleId); + if (rule == null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: could not find rule by ID"); + } + transition.setRule(rule); + } + + treeNode.addChild(transition); + if (child != null) { + child.setParent(transition); + transition.setChildNode(child); + } + + nodeChanges.put(transition, trans); + treeTransitions.put(transId, transition); + } } - treeNode.addChild(transition); - if (child != null) { - child.setParent(transition); - transition.setChildNode(child); + // validateTreeStructure(treeNodes, treeTransitions); + System.err.println("Tree Size: " + treeTransitions.size()); + for (Map.Entry entry : nodeChanges.entrySet()) { + makeTransitionChanges(entry.getKey(), entry.getValue()); } - - nodeChanges.put(transition, trans); - treeTransitions.put(transId, transition); - } } - // validateTreeStructure(treeNodes, treeTransitions); - System.err.println("Tree Size: " + treeTransitions.size()); - for (Map.Entry entry : nodeChanges.entrySet()) { - makeTransitionChanges(entry.getKey(), entry.getValue()); - } - } - - protected void validateTreeStructure( - HashMap nodes, HashMap transitions) - throws InvalidFileFormatException { - Tree tree = puzzle.getTree(); + protected void validateTreeStructure( + HashMap nodes, HashMap transitions) + throws InvalidFileFormatException { + Tree tree = puzzle.getTree(); - if (tree == null) { - throw new InvalidFileFormatException("Proof Tree construction error: invalid tree"); - } - - HashMap connectedNodes = new HashMap<>(); - HashMap connectedTransitions = new HashMap<>(); + if (tree == null) { + throw new InvalidFileFormatException("Proof Tree construction error: invalid tree"); + } - for (TreeNode node : nodes.values()) { - connectedNodes.put(node, false); - } + HashMap connectedNodes = new HashMap<>(); + HashMap connectedTransitions = new HashMap<>(); - for (TreeTransition trans : transitions.values()) { - connectedTransitions.put(trans, false); - } + for (TreeNode node : nodes.values()) { + connectedNodes.put(node, false); + } - ArrayList treeElements = new ArrayList<>(); - treeElements.add(tree.getRootNode()); - while (!treeElements.isEmpty()) { - TreeElement element = treeElements.get(treeElements.size() - 1); - treeElements.remove(element); - if (element.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) element; - - if (connectedNodes.get(treeNode)) { - // for(TreeTransition trans : treeNode.getParents()) - // { - // if(!(trans.getRule() instanceof MergeRule)) - // { - // throw new InvalidFileFormatException("Proof Tree - // structure - // validation error: cyclic tree detected"); - // } - // } + for (TreeTransition trans : transitions.values()) { + connectedTransitions.put(trans, false); } - connectedNodes.replace(treeNode, true); - for (TreeTransition trans : treeNode.getChildren()) { - treeElements.add(trans); + ArrayList treeElements = new ArrayList<>(); + treeElements.add(tree.getRootNode()); + while (!treeElements.isEmpty()) { + TreeElement element = treeElements.get(treeElements.size() - 1); + treeElements.remove(element); + if (element.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) element; + + if (connectedNodes.get(treeNode)) { + // for(TreeTransition trans : treeNode.getParents()) + // { + // if(!(trans.getRule() instanceof MergeRule)) + // { + // throw new InvalidFileFormatException("Proof Tree + // structure + // validation error: cyclic tree detected"); + // } + // } + } + connectedNodes.replace(treeNode, true); + + for (TreeTransition trans : treeNode.getChildren()) { + treeElements.add(trans); + } + } else { + TreeTransition treeTransition = (TreeTransition) element; + + if (connectedTransitions.get(treeTransition)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: cyclic tree detected"); + } + connectedTransitions.replace(treeTransition, true); + + if (treeTransition.getChildNode() != null) { + treeElements.add(treeTransition.getChildNode()); + } + } } - } else { - TreeTransition treeTransition = (TreeTransition) element; - if (connectedTransitions.get(treeTransition)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: cyclic tree detected"); + for (TreeNode node : nodes.values()) { + if (!connectedNodes.get(node)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: disjoint node detected"); + } } - connectedTransitions.replace(treeTransition, true); - if (treeTransition.getChildNode() != null) { - treeElements.add(treeTransition.getChildNode()); + for (TreeTransition trans : transitions.values()) { + if (!connectedTransitions.get(trans)) { + throw new InvalidFileFormatException( + "Proof Tree structure validation error: disjoint transition detected"); + } } - } } - for (TreeNode node : nodes.values()) { - if (!connectedNodes.get(node)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: disjoint node detected"); - } - } + protected void makeTransitionChanges(TreeTransition transition, Node transElement) + throws InvalidFileFormatException { + if (transition.getRule() instanceof MergeRule) { + List mergingNodes = transition.getParents(); + List mergingBoards = new ArrayList<>(); + mergingNodes.forEach(n -> mergingBoards.add(n.getBoard())); + + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + throw new InvalidFileFormatException( + "Proof Tree construction error: unable to find merge node"); + } + Board lcaBoard = lca.getBoard(); - for (TreeTransition trans : transitions.values()) { - if (!connectedTransitions.get(trans)) { - throw new InvalidFileFormatException( - "Proof Tree structure validation error: disjoint transition detected"); - } - } - } - - protected void makeTransitionChanges(TreeTransition transition, Node transElement) - throws InvalidFileFormatException { - if (transition.getRule() instanceof MergeRule) { - List mergingNodes = transition.getParents(); - List mergingBoards = new ArrayList<>(); - mergingNodes.forEach(n -> mergingBoards.add(n.getBoard())); - - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - throw new InvalidFileFormatException( - "Proof Tree construction error: unable to find merge node"); - } - Board lcaBoard = lca.getBoard(); - - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); - - transition.setBoard(mergedBoard); - TreeNode childNode = transition.getChildNode(); - if (childNode != null) { - childNode.setBoard(mergedBoard.copy()); - } - } else { - NodeList cellList = transElement.getChildNodes(); - for (int i = 0; i < cellList.getLength(); i++) { - Node node = cellList.item(i); - if (node.getNodeName().equalsIgnoreCase("cell")) { - Board board = transition.getBoard(); - PuzzleElement cell = puzzle.getFactory().importCell(node, board); - - board.setPuzzleElement(cell.getIndex(), cell); - board.addModifiedData(cell); - transition.propagateChange(cell); + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + transition.setBoard(mergedBoard); + TreeNode childNode = transition.getChildNode(); + if (childNode != null) { + childNode.setBoard(mergedBoard.copy()); + } } else { - if (!node.getNodeName().equalsIgnoreCase("#text")) { - throw new InvalidFileFormatException( - "Proof Tree construction error: unknown node in transition"); - } + NodeList cellList = transElement.getChildNodes(); + for (int i = 0; i < cellList.getLength(); i++) { + Node node = cellList.item(i); + if (node.getNodeName().equalsIgnoreCase("cell")) { + Board board = transition.getBoard(); + PuzzleElement cell = puzzle.getFactory().importCell(node, board); + + board.setPuzzleElement(cell.getIndex(), cell); + board.addModifiedData(cell); + transition.propagateChange(cell); + } else { + if (!node.getNodeName().equalsIgnoreCase("#text")) { + throw new InvalidFileFormatException( + "Proof Tree construction error: unknown node in transition"); + } + } + } } - } } - } - - protected void createDefaultTree() { - TreeNode root = new TreeNode(puzzle.getCurrentBoard()); - root.setRoot(true); - Tree tree = new Tree(); - tree.setRootNode(root); - puzzle.setTree(tree); - } - - /** - * Gets the result of building the Puzzle - * - * @return puzzle - */ - public Puzzle getPuzzle() { - return puzzle; - } + + protected void createDefaultTree() { + TreeNode root = new TreeNode(puzzle.getCurrentBoard()); + root.setRoot(true); + Tree tree = new Tree(); + tree.setRootNode(root); + puzzle.setTree(tree); + } + + /** + * Gets the result of building the Puzzle + * + * @return puzzle + */ + public Puzzle getPuzzle() { + return puzzle; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/Element.java b/src/main/java/edu/rpi/legup/model/elements/Element.java index 5ad31782a..8b75d075d 100644 --- a/src/main/java/edu/rpi/legup/model/elements/Element.java +++ b/src/main/java/edu/rpi/legup/model/elements/Element.java @@ -6,71 +6,72 @@ @RegisterElement public abstract class Element { - protected String elementID; - protected String elementName; - protected String description; + protected String elementID; + protected String elementName; + protected String description; - protected String imageName; - protected ImageIcon image; + protected String imageName; + protected ImageIcon image; - protected ElementType elementType; + protected ElementType elementType; - private final String INVALID_USE_MESSAGE; + private final String INVALID_USE_MESSAGE; - public Element(String elementID, String elementName, String description, String imageName) { - this.elementID = elementID; - this.elementName = elementName; - this.description = description; - this.imageName = imageName; - this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.elementName; - loadImage(); - } + public Element(String elementID, String elementName, String description, String imageName) { + this.elementID = elementID; + this.elementName = elementName; + this.description = description; + this.imageName = imageName; + this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.elementName; + loadImage(); + } - private void loadImage() { - if (imageName != null) { - this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(imageName)); - // Resize images to be 100px wide - Image image = this.image.getImage(); - if (this.image.getIconWidth() < 120) return; - int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); - if (height == 0) { - System.out.println("height is 0 error"); - System.out.println("height: " + this.image.getIconHeight()); - System.out.println("width: " + this.image.getIconWidth()); - return; - } - BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = bimage.createGraphics(); - g.drawImage(image, 0, 0, 100, height, null); - this.image = new ImageIcon(bimage); + private void loadImage() { + if (imageName != null) { + this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(imageName)); + // Resize images to be 100px wide + Image image = this.image.getImage(); + if (this.image.getIconWidth() < 120) return; + int height = + (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); + if (height == 0) { + System.out.println("height is 0 error"); + System.out.println("height: " + this.image.getIconHeight()); + System.out.println("width: " + this.image.getIconWidth()); + return; + } + BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = bimage.createGraphics(); + g.drawImage(image, 0, 0, 100, height, null); + this.image = new ImageIcon(bimage); + } } - } - public String getElementName() { - return elementName; - } + public String getElementName() { + return elementName; + } - public void setElementName(String elementName) { - this.elementName = elementName; - } + public void setElementName(String elementName) { + this.elementName = elementName; + } - public String getElementID() { - return elementID; - } + public String getElementID() { + return elementID; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public ImageIcon getImageIcon() { - return image; - } + public ImageIcon getImageIcon() { + return image; + } - public ElementType getElementType() { - return elementType; - } + public ElementType getElementType() { + return elementType; + } - public String getInvalidUseOfRuleMessage() { - return this.INVALID_USE_MESSAGE; - } + public String getInvalidUseOfRuleMessage() { + return this.INVALID_USE_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/ElementType.java b/src/main/java/edu/rpi/legup/model/elements/ElementType.java index 1e32e6adf..dff4fe04f 100644 --- a/src/main/java/edu/rpi/legup/model/elements/ElementType.java +++ b/src/main/java/edu/rpi/legup/model/elements/ElementType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.model.elements; public enum ElementType { - PLACEABLE, - NONPLACEABLE + PLACEABLE, + NONPLACEABLE } diff --git a/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java b/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java index 94d14c4b5..4ab0ab509 100644 --- a/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/NonPlaceableElement.java @@ -1,9 +1,9 @@ package edu.rpi.legup.model.elements; public abstract class NonPlaceableElement extends Element { - public NonPlaceableElement( - String elementID, String elementName, String description, String imageName) { - super(elementID, elementName, description, imageName); - this.elementType = ElementType.NONPLACEABLE; - } + public NonPlaceableElement( + String elementID, String elementName, String description, String imageName) { + super(elementID, elementName, description, imageName); + this.elementType = ElementType.NONPLACEABLE; + } } diff --git a/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java b/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java index b79fbf407..133658700 100644 --- a/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java +++ b/src/main/java/edu/rpi/legup/model/elements/PlaceableElement.java @@ -1,9 +1,9 @@ package edu.rpi.legup.model.elements; public abstract class PlaceableElement extends Element { - public PlaceableElement( - String elementID, String elementName, String description, String imageName) { - super(elementID, elementName, description, imageName); - this.elementType = ElementType.PLACEABLE; - } + public PlaceableElement( + String elementID, String elementName, String description, String imageName) { + super(elementID, elementName, description, imageName); + this.elementType = ElementType.PLACEABLE; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/Board.java b/src/main/java/edu/rpi/legup/model/gameboard/Board.java index 453f698b4..d8bdf5199 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/Board.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/Board.java @@ -7,209 +7,209 @@ public abstract class Board { - protected List puzzleElements; - protected Set modifiedData; - protected boolean isModifiable; - - /** Board Constructor creates an empty board. */ - public Board() { - this.puzzleElements = new ArrayList<>(); - this.modifiedData = new HashSet<>(); - this.isModifiable = true; - } - - /** - * Board Constructor creates a board with null elements. - * - * @param size number of elements for the board - */ - public Board(int size) { - this(); - for (int i = 0; i < size; i++) { - puzzleElements.add(null); - } - } - - /** - * Gets a specific {@link PuzzleElement} on this board. - * - * @param puzzleElement equivalent puzzleElement - * @return equivalent puzzleElement on this board - */ - public PuzzleElement getPuzzleElement(PuzzleElement puzzleElement) { - int index = puzzleElement.getIndex(); - return index < puzzleElements.size() ? puzzleElements.get(index) : null; - } - - /** - * Sets a specific {@link PuzzleElement} on the board. - * - * @param index index of the puzzleElement - * @param puzzleElement new puzzleElement at the index - */ - public void setPuzzleElement(int index, PuzzleElement puzzleElement) { - if (index < puzzleElements.size()) { - puzzleElements.set(index, puzzleElement); - } - } - - /** - * Gets the number of elements on the board. - * - * @return number of elements on the board - */ - public int getElementCount() { - return puzzleElements.size(); - } - - /** - * Gets the {@link PuzzleElement} on the board. - * - * @return puzzle elements on the board - */ - public List getPuzzleElements() { - return puzzleElements; - } - - /** - * Sets the {@link PuzzleElement} on the board. - * - * @param puzzleElements elements on the board - */ - public void setPuzzleElements(List puzzleElements) { - this.puzzleElements = puzzleElements; - } - - /** - * Gets the modifiable attribute for the board. - * - * @return true if the board is modifiable, false otherwise - */ - public boolean isModifiable() { - return isModifiable; - } - - /** - * Sets the modifiable attribute for the board. - * - * @param isModifiable true if the board is modifiable, false otherwise - */ - public void setModifiable(boolean isModifiable) { - this.isModifiable = isModifiable; - } - - /** - * Gets whether any of {@link PuzzleElement} of this board has been modified by the user. - * - * @return true if the board has been modified, false otherwise - */ - public boolean isModified() { - return !modifiedData.isEmpty(); - } - - /** - * Gets the set of modified {@link PuzzleElement} of the board. - * - * @return set of modified puzzle element of the board - */ - public Set getModifiedData() { - return modifiedData; - } - - /** - * Adds a {@link PuzzleElement} that has been modified to the list. - * - * @param puzzleElement puzzleElement that has been modified - */ - public void addModifiedData(PuzzleElement puzzleElement) { - modifiedData.add(puzzleElement); - puzzleElement.setModified(true); - } - - /** - * Removes a {@link PuzzleElement} that is no longer modified. - * - * @param data puzzleElement that is no longer modified - */ - public void removeModifiedData(PuzzleElement data) { - modifiedData.remove(data); - data.setModified(false); - } - - /** - * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent - * puzzle element with the new data. - * - * @param puzzleElement equivalent puzzle element with the new data. - */ - @SuppressWarnings("unchecked") - public void notifyChange(PuzzleElement puzzleElement) { - puzzleElements.set(puzzleElement.getIndex(), puzzleElement); - } - - /** - * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element - * with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - public void notifyAddition(PuzzleElement puzzleElement) {} - - /** - * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle - * element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - public void notifyDeletion(PuzzleElement puzzleElement) {} - - @SuppressWarnings("unchecked") - public Board mergedBoard(Board lca, List boards) { - if (lca == null || boards.isEmpty()) { - return null; - } - - Board mergedBoard = lca.copy(); - - Board firstBoard = boards.get(0); - for (PuzzleElement lcaData : lca.getPuzzleElements()) { - PuzzleElement mData = firstBoard.getPuzzleElement(lcaData); - - boolean isSame = true; - for (Board board : boards) { - isSame &= mData.equalsData(board.getPuzzleElement(lcaData)); - } - - if (isSame && !lcaData.equalsData(mData)) { - PuzzleElement mergedData = mergedBoard.getPuzzleElement(lcaData); - mergedData.setData(mData.getData()); - mergedBoard.addModifiedData(mergedData); - } - } - - return mergedBoard; - } - - /** - * Determines if this board contains the equivalent puzzle elements as the one specified - * - * @param board board to check equivalence - * @return true if the boards are equivalent, false otherwise - */ - @SuppressWarnings("unchecked") - public boolean equalsBoard(Board board) { - for (PuzzleElement element : puzzleElements) { - if (!element.equalsData(board.getPuzzleElement(element))) { - return false; - } - } - return true; - } - - /** - * Performs a deep copy of this board. - * - * @return a new copy of the board that is independent of this one - */ - public abstract Board copy(); + protected List puzzleElements; + protected Set modifiedData; + protected boolean isModifiable; + + /** Board Constructor creates an empty board. */ + public Board() { + this.puzzleElements = new ArrayList<>(); + this.modifiedData = new HashSet<>(); + this.isModifiable = true; + } + + /** + * Board Constructor creates a board with null elements. + * + * @param size number of elements for the board + */ + public Board(int size) { + this(); + for (int i = 0; i < size; i++) { + puzzleElements.add(null); + } + } + + /** + * Gets a specific {@link PuzzleElement} on this board. + * + * @param puzzleElement equivalent puzzleElement + * @return equivalent puzzleElement on this board + */ + public PuzzleElement getPuzzleElement(PuzzleElement puzzleElement) { + int index = puzzleElement.getIndex(); + return index < puzzleElements.size() ? puzzleElements.get(index) : null; + } + + /** + * Sets a specific {@link PuzzleElement} on the board. + * + * @param index index of the puzzleElement + * @param puzzleElement new puzzleElement at the index + */ + public void setPuzzleElement(int index, PuzzleElement puzzleElement) { + if (index < puzzleElements.size()) { + puzzleElements.set(index, puzzleElement); + } + } + + /** + * Gets the number of elements on the board. + * + * @return number of elements on the board + */ + public int getElementCount() { + return puzzleElements.size(); + } + + /** + * Gets the {@link PuzzleElement} on the board. + * + * @return puzzle elements on the board + */ + public List getPuzzleElements() { + return puzzleElements; + } + + /** + * Sets the {@link PuzzleElement} on the board. + * + * @param puzzleElements elements on the board + */ + public void setPuzzleElements(List puzzleElements) { + this.puzzleElements = puzzleElements; + } + + /** + * Gets the modifiable attribute for the board. + * + * @return true if the board is modifiable, false otherwise + */ + public boolean isModifiable() { + return isModifiable; + } + + /** + * Sets the modifiable attribute for the board. + * + * @param isModifiable true if the board is modifiable, false otherwise + */ + public void setModifiable(boolean isModifiable) { + this.isModifiable = isModifiable; + } + + /** + * Gets whether any of {@link PuzzleElement} of this board has been modified by the user. + * + * @return true if the board has been modified, false otherwise + */ + public boolean isModified() { + return !modifiedData.isEmpty(); + } + + /** + * Gets the set of modified {@link PuzzleElement} of the board. + * + * @return set of modified puzzle element of the board + */ + public Set getModifiedData() { + return modifiedData; + } + + /** + * Adds a {@link PuzzleElement} that has been modified to the list. + * + * @param puzzleElement puzzleElement that has been modified + */ + public void addModifiedData(PuzzleElement puzzleElement) { + modifiedData.add(puzzleElement); + puzzleElement.setModified(true); + } + + /** + * Removes a {@link PuzzleElement} that is no longer modified. + * + * @param data puzzleElement that is no longer modified + */ + public void removeModifiedData(PuzzleElement data) { + modifiedData.remove(data); + data.setModified(false); + } + + /** + * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent + * puzzle element with the new data. + * + * @param puzzleElement equivalent puzzle element with the new data. + */ + @SuppressWarnings("unchecked") + public void notifyChange(PuzzleElement puzzleElement) { + puzzleElements.set(puzzleElement.getIndex(), puzzleElement); + } + + /** + * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + public void notifyAddition(PuzzleElement puzzleElement) {} + + /** + * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + public void notifyDeletion(PuzzleElement puzzleElement) {} + + @SuppressWarnings("unchecked") + public Board mergedBoard(Board lca, List boards) { + if (lca == null || boards.isEmpty()) { + return null; + } + + Board mergedBoard = lca.copy(); + + Board firstBoard = boards.get(0); + for (PuzzleElement lcaData : lca.getPuzzleElements()) { + PuzzleElement mData = firstBoard.getPuzzleElement(lcaData); + + boolean isSame = true; + for (Board board : boards) { + isSame &= mData.equalsData(board.getPuzzleElement(lcaData)); + } + + if (isSame && !lcaData.equalsData(mData)) { + PuzzleElement mergedData = mergedBoard.getPuzzleElement(lcaData); + mergedData.setData(mData.getData()); + mergedBoard.addModifiedData(mergedData); + } + } + + return mergedBoard; + } + + /** + * Determines if this board contains the equivalent puzzle elements as the one specified + * + * @param board board to check equivalence + * @return true if the boards are equivalent, false otherwise + */ + @SuppressWarnings("unchecked") + public boolean equalsBoard(Board board) { + for (PuzzleElement element : puzzleElements) { + if (!element.equalsData(board.getPuzzleElement(element))) { + return false; + } + } + return true; + } + + /** + * Performs a deep copy of this board. + * + * @return a new copy of the board that is independent of this one + */ + public abstract Board copy(); } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java b/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java index 93176b941..fa3625a43 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/CaseBoard.java @@ -6,49 +6,49 @@ import java.util.Set; public class CaseBoard extends Board { - protected Board baseBoard; - protected CaseRule caseRule; - protected Set pickablePuzzleElements; - - public CaseBoard(Board baseBoard, CaseRule caseRule) { - this.baseBoard = baseBoard; - this.caseRule = caseRule; - this.pickablePuzzleElements = new HashSet<>(); - } - - public void addPickableElement(PuzzleElement puzzleElement) { - pickablePuzzleElements.add(puzzleElement); - } - - public void removePickableElement(PuzzleElement puzzleElement) { - pickablePuzzleElements.remove(puzzleElement); - } - - public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { - return pickablePuzzleElements.contains(baseBoard.getPuzzleElement(puzzleElement)); - } - - public Board getBaseBoard() { - return baseBoard; - } - - public void setBaseBoard(Board baseBoard) { - this.baseBoard = baseBoard; - } - - public CaseRule getCaseRule() { - return caseRule; - } - - public void setCaseRule(CaseRule caseRule) { - this.caseRule = caseRule; - } - - public int getCount() { - return pickablePuzzleElements.size(); - } - - public CaseBoard copy() { - return null; - } + protected Board baseBoard; + protected CaseRule caseRule; + protected Set pickablePuzzleElements; + + public CaseBoard(Board baseBoard, CaseRule caseRule) { + this.baseBoard = baseBoard; + this.caseRule = caseRule; + this.pickablePuzzleElements = new HashSet<>(); + } + + public void addPickableElement(PuzzleElement puzzleElement) { + pickablePuzzleElements.add(puzzleElement); + } + + public void removePickableElement(PuzzleElement puzzleElement) { + pickablePuzzleElements.remove(puzzleElement); + } + + public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { + return pickablePuzzleElements.contains(baseBoard.getPuzzleElement(puzzleElement)); + } + + public Board getBaseBoard() { + return baseBoard; + } + + public void setBaseBoard(Board baseBoard) { + this.baseBoard = baseBoard; + } + + public CaseRule getCaseRule() { + return caseRule; + } + + public void setCaseRule(CaseRule caseRule) { + this.caseRule = caseRule; + } + + public int getCount() { + return pickablePuzzleElements.size(); + } + + public CaseBoard copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java b/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java index f0ea22dbe..bfc785bdd 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/ElementFactory.java @@ -7,24 +7,24 @@ public abstract class ElementFactory { - /** - * Creates a {@link PuzzleElement} based on the xml document Node and adds it to the board. - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException thrown if the xml node is invalid for the specific puzzle - * element - */ - public abstract PuzzleElement importCell(Node node, Board board) - throws InvalidFileFormatException; + /** + * Creates a {@link PuzzleElement} based on the xml document Node and adds it to the board. + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException thrown if the xml node is invalid for the specific puzzle + * element + */ + public abstract PuzzleElement importCell(Node node, Board board) + throws InvalidFileFormatException; - /** - * Creates a xml document {@link PuzzleElement} from a cell for exporting. - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public abstract Element exportCell(Document document, PuzzleElement puzzleElement); + /** + * Creates a xml document {@link PuzzleElement} from a cell for exporting. + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public abstract Element exportCell(Document document, PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java b/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java index 1cb7e564a..9593690ce 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/GridBoard.java @@ -8,161 +8,162 @@ public class GridBoard extends Board { - protected Dimension dimension; + protected Dimension dimension; - /** - * GridBoard Constructor creates a board for grid using puzzles from a width and height. - * - * @param width width of the board - * @param height height of the board - */ - public GridBoard(int width, int height) { - this.dimension = new Dimension(width, height); + /** + * GridBoard Constructor creates a board for grid using puzzles from a width and height. + * + * @param width width of the board + * @param height height of the board + */ + public GridBoard(int width, int height) { + this.dimension = new Dimension(width, height); - for (int i = 0; i < width * height; i++) { - puzzleElements.add(null); + for (int i = 0; i < width * height; i++) { + puzzleElements.add(null); + } } - } - - /** - * GridBoard Constructor creates a board for grid using puzzles from a size. - * - * @param size width and height of the GridBoard - */ - public GridBoard(int size) { - this(size, size); - } - /** - * Gets a {@link GridCell} from the board. - * - * @param x x location of the cell - * @param y y location of the cell - * @return grid cell at location (x, y) - */ - public GridCell getCell(int x, int y) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - System.err.printf("not in bounds, bounds are %dx%d\n", dimension.width, dimension.height); - return null; + /** + * GridBoard Constructor creates a board for grid using puzzles from a size. + * + * @param size width and height of the GridBoard + */ + public GridBoard(int size) { + this(size, size); } - return (GridCell) puzzleElements.get(y * dimension.width + x); - } - /** - * Sets the {@link GridCell} at the location (x,y). This method does not set the cell if the - * location specified is out of bounds. - * - * @param x x location of the cell - * @param y y location of the cell - * @param cell grid cell to set at location (x,y) - */ - public void setCell(int x, int y, GridCell cell) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return; + /** + * Gets a {@link GridCell} from the board. + * + * @param x x location of the cell + * @param y y location of the cell + * @return grid cell at location (x, y) + */ + public GridCell getCell(int x, int y) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + System.err.printf( + "not in bounds, bounds are %dx%d\n", dimension.width, dimension.height); + return null; + } + return (GridCell) puzzleElements.get(y * dimension.width + x); } - puzzleElements.set(y * dimension.width + x, cell); - } - public void setCell(int x, int y, Element e, MouseEvent m) { - if (this instanceof TreeTentBoard - && ((y == dimension.height && 0 <= x && x < dimension.width) - || (x == dimension.width && 0 <= y && y < dimension.height))) { - TreeTentBoard treeTentBoard = ((TreeTentBoard) this); - TreeTentClue clue = treeTentBoard.getClue(x, y); - if (y == dimension.height) { - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.height) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } - } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } else { - clue.setData(dimension.height); - } + /** + * Sets the {@link GridCell} at the location (x,y). This method does not set the cell if the + * location specified is out of bounds. + * + * @param x x location of the cell + * @param y y location of the cell + * @param cell grid cell to set at location (x,y) + */ + public void setCell(int x, int y, GridCell cell) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return; } - } else { // x == dimension.width - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.width) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } + puzzleElements.set(y * dimension.width + x, cell); + } + + public void setCell(int x, int y, Element e, MouseEvent m) { + if (this instanceof TreeTentBoard + && ((y == dimension.height && 0 <= x && x < dimension.width) + || (x == dimension.width && 0 <= y && y < dimension.height))) { + TreeTentBoard treeTentBoard = ((TreeTentBoard) this); + TreeTentClue clue = treeTentBoard.getClue(x, y); + if (y == dimension.height) { + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.height) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.height); + } + } + } else { // x == dimension.width + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.width) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.width); + } + } + } } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); - } else { - clue.setData(dimension.width); - } + if (e != null && y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return; + } else { + if (e != null) { + puzzleElements.get(y * dimension.width + x).setType(e, m); + } + } } - } - } else { - if (e != null && y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return; - } else { - if (e != null) { - puzzleElements.get(y * dimension.width + x).setType(e, m); - } - } + // puzzleElements.set(y * dimension.width + x, puzzleElements.get(y * dimension.width + // + + // x)); } - // puzzleElements.set(y * dimension.width + x, puzzleElements.get(y * dimension.width - // + - // x)); - } - /** - * Gets the width of the board. - * - * @return width of the board - */ - public int getWidth() { - return dimension.width; - } + /** + * Gets the width of the board. + * + * @return width of the board + */ + public int getWidth() { + return dimension.width; + } - /** - * Gets the height of the board. - * - * @return height of the board - */ - public int getHeight() { - return dimension.height; - } + /** + * Gets the height of the board. + * + * @return height of the board + */ + public int getHeight() { + return dimension.height; + } - /** - * Gets the dimension of the grid board - * - * @return the dimension of the grid board - */ - public Dimension getDimension() { - return dimension; - } + /** + * Gets the dimension of the grid board + * + * @return the dimension of the grid board + */ + public Dimension getDimension() { + return dimension; + } - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - public GridBoard copy() { - GridBoard newGridBoard = new GridBoard(this.dimension.width, this.dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - newGridBoard.setCell(x, y, getCell(x, y).copy()); - } + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + public GridBoard copy() { + GridBoard newGridBoard = new GridBoard(this.dimension.width, this.dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + newGridBoard.setCell(x, y, getCell(x, y).copy()); + } + } + return newGridBoard; } - return newGridBoard; - } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java b/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java index 9cc3d0768..a33c3ec80 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/GridCell.java @@ -3,59 +3,59 @@ import java.awt.*; public class GridCell extends PuzzleElement { - protected Point location; + protected Point location; - /** - * GridCell Constructor creates a grid cell at the specified location given as a {@link Point} - * - * @param value data value that represents the grid cell - * @param location location on the board - */ - public GridCell(T value, Point location) { - super(value); - this.location = location; - } + /** + * GridCell Constructor creates a grid cell at the specified location given as a {@link Point} + * + * @param value data value that represents the grid cell + * @param location location on the board + */ + public GridCell(T value, Point location) { + super(value); + this.location = location; + } - /** - * GridCell Constructor creates a grid cell at the specified location given as x,y pair - * - * @param value data value that represents the grid cell - * @param x x location - * @param y y location - */ - public GridCell(T value, int x, int y) { - this(value, new Point(x, y)); - } + /** + * GridCell Constructor creates a grid cell at the specified location given as x,y pair + * + * @param value data value that represents the grid cell + * @param x x location + * @param y y location + */ + public GridCell(T value, int x, int y) { + this(value, new Point(x, y)); + } - /** - * Gets the location of the grid cell on the board - * - * @return location of the grid cell - */ - public Point getLocation() { - return location; - } + /** + * Gets the location of the grid cell on the board + * + * @return location of the grid cell + */ + public Point getLocation() { + return location; + } - /** - * Sets the location of the grid cell on the board - * - * @param location location of the grid cell - */ - public void setLocation(Point location) { - this.location = location; - } + /** + * Sets the location of the grid cell on the board + * + * @param location location of the grid cell + */ + public void setLocation(Point location) { + this.location = location; + } - /** - * Performs a deep copy on the grid cell - * - * @return a new copy of the grid cell that is independent of this one - */ - public GridCell copy() { - GridCell copy = new GridCell<>(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setModified(isModified); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the grid cell + * + * @return a new copy of the grid cell that is independent of this one + */ + public GridCell copy() { + GridCell copy = new GridCell<>(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setModified(isModified); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java b/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java index 215419d54..4ce030a04 100644 --- a/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java +++ b/src/main/java/edu/rpi/legup/model/gameboard/PuzzleElement.java @@ -4,181 +4,181 @@ import java.awt.event.MouseEvent; public abstract class PuzzleElement { - protected int index; - protected T data; - protected boolean isModifiable; - protected boolean isModified; - protected boolean isGiven; - protected boolean isValid; - protected int casesDepended; - - /** PuzzleElement Constructor creates a new puzzle element. */ - public PuzzleElement() { - this.index = -1; - this.data = null; - this.isModifiable = true; - this.isModified = false; - this.isGiven = false; - this.isValid = true; - this.casesDepended = 0; - } - - /** - * PuzzleElement Constructor creates a new puzzle element from the specified data. - * - * @param data data used to create the puzzle element - */ - public PuzzleElement(T data) { - this(); - this.data = data; - } - - /** - * Gets the data that represents this puzzle element. - * - * @return data value - */ - public T getData() { - return data; - } - - /** - * Sets the data value that represents this puzzle element. - * - * @param data data value that represents this puzzle element - */ - public void setData(T data) { - this.data = data; - } - - public void setType(Element e, MouseEvent m) { - return; - } - - /** - * Gets whether this puzzle element is modifiable. - * - * @return true if this puzzle element is modifiable, false otherwise - */ - public boolean isModifiable() { - return isModifiable; - } - - /** - * Sets whether this puzzle element is modifiable. - * - * @param isModifiable true if this puzzle element is modifiable, false otherwise - */ - public void setModifiable(boolean isModifiable) { - this.isModifiable = isModifiable; - } - - /** - * Gets whether the puzzle element has been modified. - * - * @return true if the puzzle element has been modified, false otherwise - */ - public boolean isModified() { - return isModified; - } - - /** - * Sets whether the puzzle element has been modified. - * - * @param isModified true if the puzzle element has been modified, false otherwise - */ - public void setModified(boolean isModified) { - this.isModified = isModified; - } - - /** - * Gets the index of this puzzle element - * - * @return index of this puzzle element - */ - public int getIndex() { - return index; - } - - /** - * Sets the index of this puzzle element - * - * @param index index of this puzzle element - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Gets whether this puzzle element is given - * - * @return true if the puzzle element is given, false otherwise - */ - public boolean isGiven() { - return isGiven; - } - - /** - * Sets whether this puzzle element is given - * - * @param given true if the puzzle element is given, false otherwise - */ - public void setGiven(boolean given) { - isGiven = given; - } - - /** - * Get whether this puzzle element data is a valid change according to the rule applied to the - * transition that this puzzle element is contained in. - * - * @return true if the puzzle element logically follows from the rule, otherwise false. - */ - public boolean isValid() { - return this.isValid; - } - - /** - * Sets whether this puzzle element data is a valid change according to the rule applied to the - * transition that this puzzle element is contained in. - * - * @param isValid true if the puzzle element logically follows from the rule, otherwise false. - */ - public void setValid(boolean isValid) { - this.isValid = isValid; - } - - /** - * Get the number of case rules that depend upon the state of this element - * - * @return number of cases - */ - public int getCasesDepended() { - return this.casesDepended; - } - - /** - * Sets the number of case rules that depend upon the state of this element - * - * @param cases number of cases - */ - public void setCasesDepended(int cases) { - this.casesDepended = cases; - } - - /** - * Tests whether two puzzle elements objects have the same puzzle element - * - * @param puzzleElement puzzle element to check for equality - * @return true if the puzzle element are equal, false otherwise - */ - public boolean equalsData(PuzzleElement puzzleElement) { - return data.equals(puzzleElement.data); - } - - /** - * Copies this puzzle element to a new puzzle element object - * - * @return copied puzzle element object - */ - public abstract PuzzleElement copy(); + protected int index; + protected T data; + protected boolean isModifiable; + protected boolean isModified; + protected boolean isGiven; + protected boolean isValid; + protected int casesDepended; + + /** PuzzleElement Constructor creates a new puzzle element. */ + public PuzzleElement() { + this.index = -1; + this.data = null; + this.isModifiable = true; + this.isModified = false; + this.isGiven = false; + this.isValid = true; + this.casesDepended = 0; + } + + /** + * PuzzleElement Constructor creates a new puzzle element from the specified data. + * + * @param data data used to create the puzzle element + */ + public PuzzleElement(T data) { + this(); + this.data = data; + } + + /** + * Gets the data that represents this puzzle element. + * + * @return data value + */ + public T getData() { + return data; + } + + /** + * Sets the data value that represents this puzzle element. + * + * @param data data value that represents this puzzle element + */ + public void setData(T data) { + this.data = data; + } + + public void setType(Element e, MouseEvent m) { + return; + } + + /** + * Gets whether this puzzle element is modifiable. + * + * @return true if this puzzle element is modifiable, false otherwise + */ + public boolean isModifiable() { + return isModifiable; + } + + /** + * Sets whether this puzzle element is modifiable. + * + * @param isModifiable true if this puzzle element is modifiable, false otherwise + */ + public void setModifiable(boolean isModifiable) { + this.isModifiable = isModifiable; + } + + /** + * Gets whether the puzzle element has been modified. + * + * @return true if the puzzle element has been modified, false otherwise + */ + public boolean isModified() { + return isModified; + } + + /** + * Sets whether the puzzle element has been modified. + * + * @param isModified true if the puzzle element has been modified, false otherwise + */ + public void setModified(boolean isModified) { + this.isModified = isModified; + } + + /** + * Gets the index of this puzzle element + * + * @return index of this puzzle element + */ + public int getIndex() { + return index; + } + + /** + * Sets the index of this puzzle element + * + * @param index index of this puzzle element + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Gets whether this puzzle element is given + * + * @return true if the puzzle element is given, false otherwise + */ + public boolean isGiven() { + return isGiven; + } + + /** + * Sets whether this puzzle element is given + * + * @param given true if the puzzle element is given, false otherwise + */ + public void setGiven(boolean given) { + isGiven = given; + } + + /** + * Get whether this puzzle element data is a valid change according to the rule applied to the + * transition that this puzzle element is contained in. + * + * @return true if the puzzle element logically follows from the rule, otherwise false. + */ + public boolean isValid() { + return this.isValid; + } + + /** + * Sets whether this puzzle element data is a valid change according to the rule applied to the + * transition that this puzzle element is contained in. + * + * @param isValid true if the puzzle element logically follows from the rule, otherwise false. + */ + public void setValid(boolean isValid) { + this.isValid = isValid; + } + + /** + * Get the number of case rules that depend upon the state of this element + * + * @return number of cases + */ + public int getCasesDepended() { + return this.casesDepended; + } + + /** + * Sets the number of case rules that depend upon the state of this element + * + * @param cases number of cases + */ + public void setCasesDepended(int cases) { + this.casesDepended = cases; + } + + /** + * Tests whether two puzzle elements objects have the same puzzle element + * + * @param puzzleElement puzzle element to check for equality + * @return true if the puzzle element are equal, false otherwise + */ + public boolean equalsData(PuzzleElement puzzleElement) { + return data.equals(puzzleElement.data); + } + + /** + * Copies this puzzle element to a new puzzle element object + * + * @return copied puzzle element object + */ + public abstract PuzzleElement copy(); } diff --git a/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java b/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java index b5c712ead..461128562 100644 --- a/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java +++ b/src/main/java/edu/rpi/legup/model/observer/IBoardListener.java @@ -5,24 +5,24 @@ import edu.rpi.legup.model.tree.TreeElement; public interface IBoardListener { - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - void onTreeElementChanged(TreeElement treeElement); + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + void onTreeElementChanged(TreeElement treeElement); - /** - * Called when the a case board has been added to the view. - * - * @param caseBoard case board to be added - */ - void onCaseBoardAdded(CaseBoard caseBoard); + /** + * Called when the a case board has been added to the view. + * + * @param caseBoard case board to be added + */ + void onCaseBoardAdded(CaseBoard caseBoard); - /** - * Called when a {@link PuzzleElement}'s data on the board has changed. - * - * @param puzzleElement puzzleElement that has changed - */ - void onBoardDataChanged(PuzzleElement puzzleElement); + /** + * Called when a {@link PuzzleElement}'s data on the board has changed. + * + * @param puzzleElement puzzleElement that has changed + */ + void onBoardDataChanged(PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java b/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java index 73bd2b6f8..c7bf13141 100644 --- a/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java +++ b/src/main/java/edu/rpi/legup/model/observer/IBoardSubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface IBoardSubject { - /** - * Adds a board listener. - * - * @param listener listener to add - */ - void addBoardListener(IBoardListener listener); + /** + * Adds a board listener. + * + * @param listener listener to add + */ + void addBoardListener(IBoardListener listener); - /** - * Removes a board listener. - * - * @param listener listener to remove - */ - void removeBoardListener(IBoardListener listener); + /** + * Removes a board listener. + * + * @param listener listener to remove + */ + void removeBoardListener(IBoardListener listener); - /** - * Notifies all of the listeners using the specified algorithm. - * - * @param algorithm algorithm used to notify the listeners - */ - void notifyBoardListeners(Consumer algorithm); + /** + * Notifies all of the listeners using the specified algorithm. + * + * @param algorithm algorithm used to notify the listeners + */ + void notifyBoardListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java b/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java index 915b0adc9..d5e7fdb2d 100644 --- a/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java +++ b/src/main/java/edu/rpi/legup/model/observer/ITreeListener.java @@ -4,27 +4,27 @@ import edu.rpi.legup.ui.proofeditorui.treeview.TreeViewSelection; public interface ITreeListener { - /** - * Called when a {@link TreeElement} is added to the tree. - * - * @param treeElement tree element that was added to the tree - */ - void onTreeElementAdded(TreeElement treeElement); + /** + * Called when a {@link TreeElement} is added to the tree. + * + * @param treeElement tree element that was added to the tree + */ + void onTreeElementAdded(TreeElement treeElement); - /** - * Called when a {@link TreeElement} is removed from the tree. - * - * @param element TreeElement that was removed to the tree - */ - void onTreeElementRemoved(TreeElement element); + /** + * Called when a {@link TreeElement} is removed from the tree. + * + * @param element TreeElement that was removed to the tree + */ + void onTreeElementRemoved(TreeElement element); - /** - * Called when the {@link TreeViewSelection} was changed. - * - * @param selection tree view selection that was changed - */ - void onTreeSelectionChanged(TreeViewSelection selection); + /** + * Called when the {@link TreeViewSelection} was changed. + * + * @param selection tree view selection that was changed + */ + void onTreeSelectionChanged(TreeViewSelection selection); - /** Called when the model has finished updating the tree. */ - void onUpdateTree(); + /** Called when the model has finished updating the tree. */ + void onUpdateTree(); } diff --git a/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java b/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java index 7cf1bb1ef..66d5d9a5e 100644 --- a/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java +++ b/src/main/java/edu/rpi/legup/model/observer/ITreeSubject.java @@ -3,24 +3,24 @@ import java.util.function.Consumer; public interface ITreeSubject { - /** - * Adds a board listener. - * - * @param listener listener to add - */ - void addTreeListener(ITreeListener listener); + /** + * Adds a board listener. + * + * @param listener listener to add + */ + void addTreeListener(ITreeListener listener); - /** - * Removes a tree listener. - * - * @param listener listener to remove - */ - void removeTreeListener(ITreeListener listener); + /** + * Removes a tree listener. + * + * @param listener listener to remove + */ + void removeTreeListener(ITreeListener listener); - /** - * Notifies all of the listeners using the specified algorithm. - * - * @param algorithm algorithm used to notify the listeners - */ - void notifyTreeListeners(Consumer algorithm); + /** + * Notifies all of the listeners using the specified algorithm. + * + * @param algorithm algorithm used to notify the listeners + */ + void notifyTreeListeners(Consumer algorithm); } diff --git a/src/main/java/edu/rpi/legup/model/rules/CaseRule.java b/src/main/java/edu/rpi/legup/model/rules/CaseRule.java index 4fcd69065..e87896fcc 100644 --- a/src/main/java/edu/rpi/legup/model/rules/CaseRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/CaseRule.java @@ -13,135 +13,135 @@ public abstract class CaseRule extends Rule { - private final String INVALID_USE_MESSAGE; - - /** - * CaseRule Constructor creates a new case rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public CaseRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = CASE; - this.INVALID_USE_MESSAGE = "Invalid use of the case rule " + this.ruleName; - } - - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - public abstract CaseBoard getCaseBoard(Board board); - - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - public abstract List getCases(Board board, PuzzleElement puzzleElement); - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - List parentNodes = transition.getParents(); - if (parentNodes.size() != 1) { - return "Must not have multiple parent nodes"; + private final String INVALID_USE_MESSAGE; + + /** + * CaseRule Constructor creates a new case rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public CaseRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = CASE; + this.INVALID_USE_MESSAGE = "Invalid use of the case rule " + this.ruleName; } - for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { - if (childTrans.getRule() == null - || !childTrans.getRule().getClass().equals(this.getClass())) { - return "All children nodes must be justified with the same case rule."; - } - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + public abstract CaseBoard getCaseBoard(Board board); + + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + public abstract List getCases(Board board, PuzzleElement puzzleElement); + + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + List parentNodes = transition.getParents(); + if (parentNodes.size() != 1) { + return "Must not have multiple parent nodes"; + } - String check = checkRuleRaw(transition); + for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { + if (childTrans.getRule() == null + || !childTrans.getRule().getClass().equals(this.getClass())) { + return "All children nodes must be justified with the same case rule."; + } + } - // Mark transition and new data as valid or not - boolean isCorrect = (check == null); - for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { - childTrans.setCorrect(isCorrect); - for (PuzzleElement element : childTrans.getBoard().getModifiedData()) { - element.setValid(isCorrect); - } - } + String check = checkRuleRaw(transition); - return check; - } - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public abstract String checkRuleRaw(TreeTransition transition); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return this.INVALID_USE_MESSAGE; - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - List cases = getCases(board, puzzleElement); - for (Board caseBoard : cases) { - Set data = caseBoard.getModifiedData(); - for (PuzzleElement element : data) { - if (!elements.contains(board.getPuzzleElement(element))) { - elements.add(board.getPuzzleElement(element)); + // Mark transition and new data as valid or not + boolean isCorrect = (check == null); + for (TreeTransition childTrans : parentNodes.get(0).getChildren()) { + childTrans.setCorrect(isCorrect); + for (PuzzleElement element : childTrans.getBoard().getModifiedData()) { + element.setValid(isCorrect); + } } - } + + return check; } - return elements; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public abstract String checkRuleRaw(TreeTransition transition); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return this.INVALID_USE_MESSAGE; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + List cases = getCases(board, puzzleElement); + for (Board caseBoard : cases) { + Set data = caseBoard.getModifiedData(); + for (PuzzleElement element : data) { + if (!elements.contains(board.getPuzzleElement(element))) { + elements.add(board.getPuzzleElement(element)); + } + } + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java b/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java index 8ae3f02c6..b38a95fd2 100644 --- a/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/ContradictionRule.java @@ -8,102 +8,102 @@ public abstract class ContradictionRule extends Rule { - private final String NO_CONTRADICTION_MESSAGE = - "No instance of the contradiction " + this.ruleName + " here"; + private final String NO_CONTRADICTION_MESSAGE = + "No instance of the contradiction " + this.ruleName + " here"; - /** - * ContradictionRule Constructor creates a new contradiction rule - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public ContradictionRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - ruleType = CONTRADICTION; - } + /** + * ContradictionRule Constructor creates a new contradiction rule + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public ContradictionRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + ruleType = CONTRADICTION; + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - return checkContradiction(transition.getBoard()); - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + return checkContradiction(transition.getBoard()); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkContradictionAt(transition.getBoard(), puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkContradictionAt(transition.getBoard(), puzzleElement); + } - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return checkContradiction(transition.getBoard()); - } + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return checkContradiction(transition.getBoard()); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkContradictionAt(transition.getBoard(), puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkContradictionAt(transition.getBoard(), puzzleElement); + } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - public String checkContradiction(Board board) { - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - String checkStr = checkContradictionAt(board, puzzleElement); - if (checkStr == null) { - return checkStr; - } + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + public String checkContradiction(Board board) { + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + String checkStr = checkContradictionAt(board, puzzleElement); + if (checkStr == null) { + return checkStr; + } + } + return this.NO_CONTRADICTION_MESSAGE; } - return this.NO_CONTRADICTION_MESSAGE; - } - public String getNoContradictionMessage() { - return this.NO_CONTRADICTION_MESSAGE; - } + public String getNoContradictionMessage() { + return this.NO_CONTRADICTION_MESSAGE; + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - public abstract String checkContradictionAt(Board board, PuzzleElement puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + public abstract String checkContradictionAt(Board board, PuzzleElement puzzleElement); } diff --git a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java index 1ce44318a..d550bc02c 100644 --- a/src/main/java/edu/rpi/legup/model/rules/DirectRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/DirectRule.java @@ -8,96 +8,97 @@ import edu.rpi.legup.model.tree.TreeTransition; public abstract class DirectRule extends Rule { - /** - * DirectRule Constructor creates a new basic rule. - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public DirectRule(String ruleID, String ruleName, String description, String imageName) { - super(ruleID, ruleName, description, imageName); - this.ruleType = BASIC; - } + /** + * DirectRule Constructor creates a new basic rule. + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public DirectRule(String ruleID, String ruleName, String description, String imageName) { + super(ruleID, ruleName, description, imageName); + this.ruleType = BASIC; + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRule(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - // System.out.println(finalBoard.getModifiedData().size()); - if (transition.getParents().size() != 1 - || transition.getParents().get(0).getChildren().size() != 1) { - return "State must have only 1 parent and 1 child"; - } else if (finalBoard.getModifiedData().isEmpty()) { - // null transition - return null; - } else { - return checkRuleRaw(transition); + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRule(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + // System.out.println(finalBoard.getModifiedData().size()); + if (transition.getParents().size() != 1 + || transition.getParents().get(0).getChildren().size() != 1) { + return "State must have only 1 parent and 1 child"; + } else if (finalBoard.getModifiedData().isEmpty()) { + // null transition + return null; + } else { + return checkRuleRaw(transition); + } } - } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public String checkRuleRaw(TreeTransition transition) { - Board finalBoard = transition.getBoard(); - String checkStr = null; + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public String checkRuleRaw(TreeTransition transition) { + Board finalBoard = transition.getBoard(); + String checkStr = null; - // Go directly to specific direct rule's judgement if no cell's are edited - if (finalBoard.getModifiedData().size() == 0) { - checkStr = checkRuleRawAt(transition, null); - } - for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { - String tempStr = checkRuleAt(transition, puzzleElement); - if (tempStr != null) { - checkStr = tempStr; - } + // Go directly to specific direct rule's judgement if no cell's are edited + if (finalBoard.getModifiedData().size() == 0) { + checkStr = checkRuleRawAt(transition, null); + } + for (PuzzleElement puzzleElement : finalBoard.getModifiedData()) { + String tempStr = checkRuleAt(transition, puzzleElement); + if (tempStr != null) { + checkStr = tempStr; + } + } + return checkStr; } - return checkStr; - } - /** - * Checks whether the child node logically follows from the parent node at the specific {@link - * PuzzleElement} using this rule. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - Board finalBoard = transition.getBoard(); - puzzleElement = finalBoard.getPuzzleElement(puzzleElement); - String checkStr; - if (!puzzleElement.isModified()) { - checkStr = "PuzzleElement must be modified"; - } else { - if (transition.getParents().size() != 1 - || transition.getParents().get(0).getChildren().size() != 1) { - checkStr = "State must have only 1 parent and 1 child"; - } else { - checkStr = checkRuleRawAt(transition, puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific {@link + * PuzzleElement} using this rule. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + Board finalBoard = transition.getBoard(); + puzzleElement = finalBoard.getPuzzleElement(puzzleElement); + String checkStr; + if (!puzzleElement.isModified()) { + checkStr = "PuzzleElement must be modified"; + } else { + if (transition.getParents().size() != 1 + || transition.getParents().get(0).getChildren().size() != 1) { + checkStr = "State must have only 1 parent and 1 child"; + } else { + checkStr = checkRuleRawAt(transition, puzzleElement); + } + } + puzzleElement.setValid(checkStr == null); + return checkStr; } - puzzleElement.setValid(checkStr == null); - return checkStr; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - public abstract Board getDefaultBoard(TreeNode node); + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + public abstract Board getDefaultBoard(TreeNode node); } diff --git a/src/main/java/edu/rpi/legup/model/rules/MergeRule.java b/src/main/java/edu/rpi/legup/model/rules/MergeRule.java index 25c543abb..f7badcd8b 100644 --- a/src/main/java/edu/rpi/legup/model/rules/MergeRule.java +++ b/src/main/java/edu/rpi/legup/model/rules/MergeRule.java @@ -11,88 +11,88 @@ import java.util.List; public class MergeRule extends Rule { - /** MergeRule Constructor merges to board states together */ - public MergeRule() { - super( - "MERGE", - "Merge Rule", - "Merge any number of nodes into one", - "edu/rpi/legup/images/Legup/MergeRule.png"); - this.ruleType = MERGE; - } - - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @SuppressWarnings("unchecked") - @Override - public String checkRuleRaw(TreeTransition transition) { - Board board = transition.getBoard(); - List mergingNodes = new ArrayList<>(); - List mergingBoards = new ArrayList<>(); - for (TreeNode treeNode : transition.getParents()) { - mergingNodes.add(treeNode); - mergingBoards.add(treeNode.getBoard()); + /** MergeRule Constructor merges to board states together */ + public MergeRule() { + super( + "MERGE", + "Merge Rule", + "Merge any number of nodes into one", + "edu/rpi/legup/images/Legup/MergeRule.png"); + this.ruleType = MERGE; } - TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); - if (lca == null) { - return "Merge was not correctly created."; - } - Board lcaBoard = lca.getBoard(); + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @SuppressWarnings("unchecked") + @Override + public String checkRuleRaw(TreeTransition transition) { + Board board = transition.getBoard(); + List mergingNodes = new ArrayList<>(); + List mergingBoards = new ArrayList<>(); + for (TreeNode treeNode : transition.getParents()) { + mergingNodes.add(treeNode); + mergingBoards.add(treeNode.getBoard()); + } - Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + TreeNode lca = Tree.getLowestCommonAncestor(mergingNodes); + if (lca == null) { + return "Merge was not correctly created."; + } + Board lcaBoard = lca.getBoard(); - for (PuzzleElement m : mergedBoard.getPuzzleElements()) { - if (!m.equalsData(board.getPuzzleElement(m))) { - return "Merge was not correctly created."; - } - } + Board mergedBoard = lcaBoard.mergedBoard(lcaBoard, mergingBoards); + + for (PuzzleElement m : mergedBoard.getPuzzleElements()) { + if (!m.equalsData(board.getPuzzleElement(m))) { + return "Merge was not correctly created."; + } + } - return null; - } + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRule(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRule(transition); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRule(TreeTransition transition) { - return checkRuleRaw(transition); - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRule(TreeTransition transition) { + return checkRuleRaw(transition); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRawAt(transition, puzzleElement); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRawAt(transition, puzzleElement); + } } diff --git a/src/main/java/edu/rpi/legup/model/rules/Rule.java b/src/main/java/edu/rpi/legup/model/rules/Rule.java index d15b79e5e..f70bb2889 100644 --- a/src/main/java/edu/rpi/legup/model/rules/Rule.java +++ b/src/main/java/edu/rpi/legup/model/rules/Rule.java @@ -10,154 +10,156 @@ @RegisterRule public abstract class Rule { - protected String ruleID; - protected String ruleName; - protected String description; - protected String imageName; - protected ImageIcon image; - protected RuleType ruleType; - - private final String INVALID_USE_MESSAGE; - - /** - * Rule Constructor creates a new rule - * - * @param ruleID ID of the rule - * @param ruleName name of the rule - * @param description description of the rule - * @param imageName file name of the image - */ - public Rule(String ruleID, String ruleName, String description, String imageName) { - this.ruleID = ruleID; - this.ruleName = ruleName; - this.description = description; - this.imageName = imageName; - this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.ruleName; - loadImage(); - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - public abstract String checkRule(TreeTransition transition); - - /** - * Checks whether the transition logically follows from the parent node using this rule. This - * method is the one that should overridden in child classes - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - protected abstract String checkRuleRaw(TreeTransition transition); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public abstract String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - protected abstract String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement); - - /** Loads the image file */ - public void loadImage() { - if (imageName != null) { - String name = imageName; - LegupPreferences prefs = LegupPreferences.getInstance(); - if (name.contains("shorttruthtable") - && prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - name = name.replace("ruleimages", "ruleimages_cb"); - } - this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(name)); - // Resize images to be 100px wide - Image image = this.image.getImage(); - if (this.image.getIconWidth() < 120) return; - int height = (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); - if (height == 0) { - System.out.println("height is 0 error"); - System.out.println("height: " + this.image.getIconHeight()); - System.out.println("width: " + this.image.getIconWidth()); - return; - } - BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); - Graphics2D g = bimage.createGraphics(); - g.drawImage(image, 0, 0, 100, height, null); - this.image = new ImageIcon(bimage); + protected String ruleID; + protected String ruleName; + protected String description; + protected String imageName; + protected ImageIcon image; + protected RuleType ruleType; + + private final String INVALID_USE_MESSAGE; + + /** + * Rule Constructor creates a new rule + * + * @param ruleID ID of the rule + * @param ruleName name of the rule + * @param description description of the rule + * @param imageName file name of the image + */ + public Rule(String ruleID, String ruleName, String description, String imageName) { + this.ruleID = ruleID; + this.ruleName = ruleName; + this.description = description; + this.imageName = imageName; + this.INVALID_USE_MESSAGE = "Invalid use of the rule " + this.ruleName; + loadImage(); + } + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + public abstract String checkRule(TreeTransition transition); + + /** + * Checks whether the transition logically follows from the parent node using this rule. This + * method is the one that should overridden in child classes + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + protected abstract String checkRuleRaw(TreeTransition transition); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public abstract String checkRuleAt(TreeTransition transition, PuzzleElement puzzleElement); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + protected abstract String checkRuleRawAt( + TreeTransition transition, PuzzleElement puzzleElement); + + /** Loads the image file */ + public void loadImage() { + if (imageName != null) { + String name = imageName; + LegupPreferences prefs = LegupPreferences.getInstance(); + if (name.contains("shorttruthtable") + && prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + name = name.replace("ruleimages", "ruleimages_cb"); + } + this.image = new ImageIcon(ClassLoader.getSystemClassLoader().getResource(name)); + // Resize images to be 100px wide + Image image = this.image.getImage(); + if (this.image.getIconWidth() < 120) return; + int height = + (int) (100 * ((double) this.image.getIconHeight() / this.image.getIconWidth())); + if (height == 0) { + System.out.println("height is 0 error"); + System.out.println("height: " + this.image.getIconHeight()); + System.out.println("width: " + this.image.getIconWidth()); + return; + } + BufferedImage bimage = new BufferedImage(100, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = bimage.createGraphics(); + g.drawImage(image, 0, 0, 100, height, null); + this.image = new ImageIcon(bimage); + } + } + + /** + * Gets the name of the rule + * + * @return name of the rule + */ + public String getRuleName() { + return ruleName; + } + + /** + * Gets the name of the rule + * + * @return name of the rule + */ + public String getRuleID() { + return ruleID; + } + + /** + * Sets the rule name + * + * @param ruleName new name of the rule + */ + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + + /** + * Gets the description of the rule + * + * @return the description of the rule + */ + public String getDescription() { + return description; + } + + /** + * Gets the image icon of the rule + * + * @return image icon of the rule + */ + public ImageIcon getImageIcon() { + return image; + } + + /** + * Gets the rule type + * + * @return rule type + */ + public RuleType getRuleType() { + return ruleType; + } + + public String getInvalidUseOfRuleMessage() { + return this.INVALID_USE_MESSAGE; } - } - - /** - * Gets the name of the rule - * - * @return name of the rule - */ - public String getRuleName() { - return ruleName; - } - - /** - * Gets the name of the rule - * - * @return name of the rule - */ - public String getRuleID() { - return ruleID; - } - - /** - * Sets the rule name - * - * @param ruleName new name of the rule - */ - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - - /** - * Gets the description of the rule - * - * @return the description of the rule - */ - public String getDescription() { - return description; - } - - /** - * Gets the image icon of the rule - * - * @return image icon of the rule - */ - public ImageIcon getImageIcon() { - return image; - } - - /** - * Gets the rule type - * - * @return rule type - */ - public RuleType getRuleType() { - return ruleType; - } - - public String getInvalidUseOfRuleMessage() { - return this.INVALID_USE_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/model/rules/RuleType.java b/src/main/java/edu/rpi/legup/model/rules/RuleType.java index 48589e836..06aa1844b 100644 --- a/src/main/java/edu/rpi/legup/model/rules/RuleType.java +++ b/src/main/java/edu/rpi/legup/model/rules/RuleType.java @@ -1,8 +1,8 @@ package edu.rpi.legup.model.rules; public enum RuleType { - BASIC, - CASE, - CONTRADICTION, - MERGE + BASIC, + CASE, + CONTRADICTION, + MERGE } diff --git a/src/main/java/edu/rpi/legup/model/tree/Tree.java b/src/main/java/edu/rpi/legup/model/tree/Tree.java index 2e5604a2c..a0746db87 100644 --- a/src/main/java/edu/rpi/legup/model/tree/Tree.java +++ b/src/main/java/edu/rpi/legup/model/tree/Tree.java @@ -7,185 +7,186 @@ import java.util.Set; public class Tree { - private TreeNode rootNode; - - /** - * Tree Constructor creates the tree structure from the initial {@link Board} - * - * @param initBoard initial board - */ - public Tree(Board initBoard) { - this.rootNode = new TreeNode(initBoard); - this.rootNode.setRoot(true); - } - - /** Tree Constructor creates the tree structure with null root node */ - public Tree() { - this.rootNode = null; - } - - public TreeTransition addNewTransition(TreeNode treeNode) { - TreeTransition transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - treeNode.addChild(transition); - treeNode.getChildren().forEach(TreeTransition::reverify); - return transition; - } - - public TreeNode addNode(TreeTransition transition) { - TreeNode treeNode = new TreeNode(transition.getBoard().copy()); - transition.setChildNode(treeNode); - treeNode.setParent(transition); - return treeNode; - } - - public TreeElement addTreeElement(TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) element; - return addTreeElement(treeNode, new TreeTransition(treeNode, treeNode.getBoard().copy())); - } else { - TreeTransition transition = (TreeTransition) element; - Board copyBoard = transition.board.copy(); - copyBoard.setModifiable(false); - return addTreeElement(transition, new TreeNode(copyBoard)); + private TreeNode rootNode; + + /** + * Tree Constructor creates the tree structure from the initial {@link Board} + * + * @param initBoard initial board + */ + public Tree(Board initBoard) { + this.rootNode = new TreeNode(initBoard); + this.rootNode.setRoot(true); } - } - - public TreeElement addTreeElement(TreeNode treeNode, TreeTransition transition) { - treeNode.addChild(transition); - treeNode.getChildren().forEach(TreeTransition::reverify); - return transition; - } - - public TreeElement addTreeElement(TreeTransition transition, TreeNode treeNode) { - transition.setChildNode(treeNode); - treeNode.setParent(transition); - return treeNode; - } - - public void removeTreeElement(TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getParent().setChildNode(null); - } else { - TreeTransition transition = (TreeTransition) element; - transition.getParents().forEach(n -> n.removeChild(transition)); - transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); + + /** Tree Constructor creates the tree structure with null root node */ + public Tree() { + this.rootNode = null; + } + + public TreeTransition addNewTransition(TreeNode treeNode) { + TreeTransition transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + treeNode.addChild(transition); + treeNode.getChildren().forEach(TreeTransition::reverify); + return transition; + } + + public TreeNode addNode(TreeTransition transition) { + TreeNode treeNode = new TreeNode(transition.getBoard().copy()); + transition.setChildNode(treeNode); + treeNode.setParent(transition); + return treeNode; + } + + public TreeElement addTreeElement(TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) element; + return addTreeElement( + treeNode, new TreeTransition(treeNode, treeNode.getBoard().copy())); + } else { + TreeTransition transition = (TreeTransition) element; + Board copyBoard = transition.board.copy(); + copyBoard.setModifiable(false); + return addTreeElement(transition, new TreeNode(copyBoard)); + } + } + + public TreeElement addTreeElement(TreeNode treeNode, TreeTransition transition) { + treeNode.addChild(transition); + treeNode.getChildren().forEach(TreeTransition::reverify); + return transition; } - } - - /** - * Determines if the tree is valid by checking whether this tree puzzleElement and all descendants - * of this tree puzzleElement is justified and justified correctly - * - * @return true if tree is valid, false otherwise - */ - public boolean isValid() { - return rootNode.isValidBranch(); - } - - /** - * Gets a Set of TreeNodes that are leaf nodes - * - * @return Set of TreeNodes that are leaf nodes - */ - public Set getLeafTreeElements() { - Set leafs = new HashSet<>(); - getLeafTreeElements(leafs, rootNode); - return leafs; - } - - /** - * Gets a Set of TreeNodes that are leaf nodes from the sub tree rooted at the specified node - * - * @param node node that is input - * @return Set of TreeNodes that are leaf nodes from the sub tree - */ - public Set getLeafTreeElements(TreeNode node) { - Set leafs = new HashSet<>(); - getLeafTreeElements(leafs, node); - return leafs; - } - - /** - * Recursively gets a Set of TreeNodes that are leaf nodes - * - * @param leafs Set of TreeNodes that are leaf nodes - * @param element current TreeNode being evaluated - */ - private void getLeafTreeElements(Set leafs, TreeElement element) { - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - List childTrans = node.getChildren(); - if (childTrans.isEmpty()) { - leafs.add(node); - } else { - childTrans.forEach(t -> getLeafTreeElements(leafs, t)); - } - } else { - TreeTransition transition = (TreeTransition) element; - TreeNode childNode = transition.getChildNode(); - if (childNode == null) { - leafs.add(transition); - } else { - getLeafTreeElements(leafs, childNode); - } + + public TreeElement addTreeElement(TreeTransition transition, TreeNode treeNode) { + transition.setChildNode(treeNode); + treeNode.setParent(transition); + return treeNode; } - } - - /** - * Gets the lowest common ancestor (LCA) among the list of {@link TreeNode} passed into the - * function. This lowest common ancestor is the most immediate ancestor node such that the list of - * tree nodes specified are descendants of the node. This will return null if no such ancestor - * exists - * - * @param nodes list of tree nodes to find the LCA - * @return the first ancestor node that all tree nodes have in common, otherwise null if none - * exists - */ - public static TreeNode getLowestCommonAncestor(List nodes) { - if (nodes.isEmpty()) { - return null; - } else { - if (nodes.size() == 1) { - return nodes.get(0); - } else { - List> ancestors = new ArrayList<>(); - for (TreeNode node : nodes) { - ancestors.add(node.getAncestors()); + + public void removeTreeElement(TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getParent().setChildNode(null); + } else { + TreeTransition transition = (TreeTransition) element; + transition.getParents().forEach(n -> n.removeChild(transition)); + transition.getParents().get(0).getChildren().forEach(TreeTransition::reverify); } + } + + /** + * Determines if the tree is valid by checking whether this tree puzzleElement and all + * descendants of this tree puzzleElement is justified and justified correctly + * + * @return true if tree is valid, false otherwise + */ + public boolean isValid() { + return rootNode.isValidBranch(); + } - List first = ancestors.get(0); + /** + * Gets a Set of TreeNodes that are leaf nodes + * + * @return Set of TreeNodes that are leaf nodes + */ + public Set getLeafTreeElements() { + Set leafs = new HashSet<>(); + getLeafTreeElements(leafs, rootNode); + return leafs; + } + + /** + * Gets a Set of TreeNodes that are leaf nodes from the sub tree rooted at the specified node + * + * @param node node that is input + * @return Set of TreeNodes that are leaf nodes from the sub tree + */ + public Set getLeafTreeElements(TreeNode node) { + Set leafs = new HashSet<>(); + getLeafTreeElements(leafs, node); + return leafs; + } - for (TreeNode node : first) { - boolean isCommon = true; - for (List nList : ancestors) { - isCommon &= nList.contains(node); - } + /** + * Recursively gets a Set of TreeNodes that are leaf nodes + * + * @param leafs Set of TreeNodes that are leaf nodes + * @param element current TreeNode being evaluated + */ + private void getLeafTreeElements(Set leafs, TreeElement element) { + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + List childTrans = node.getChildren(); + if (childTrans.isEmpty()) { + leafs.add(node); + } else { + childTrans.forEach(t -> getLeafTreeElements(leafs, t)); + } + } else { + TreeTransition transition = (TreeTransition) element; + TreeNode childNode = transition.getChildNode(); + if (childNode == null) { + leafs.add(transition); + } else { + getLeafTreeElements(leafs, childNode); + } + } + } - if (isCommon) { - return node; - } + /** + * Gets the lowest common ancestor (LCA) among the list of {@link TreeNode} passed into the + * function. This lowest common ancestor is the most immediate ancestor node such that the list + * of tree nodes specified are descendants of the node. This will return null if no such + * ancestor exists + * + * @param nodes list of tree nodes to find the LCA + * @return the first ancestor node that all tree nodes have in common, otherwise null if none + * exists + */ + public static TreeNode getLowestCommonAncestor(List nodes) { + if (nodes.isEmpty()) { + return null; + } else { + if (nodes.size() == 1) { + return nodes.get(0); + } else { + List> ancestors = new ArrayList<>(); + for (TreeNode node : nodes) { + ancestors.add(node.getAncestors()); + } + + List first = ancestors.get(0); + + for (TreeNode node : first) { + boolean isCommon = true; + for (List nList : ancestors) { + isCommon &= nList.contains(node); + } + + if (isCommon) { + return node; + } + } + } } - } + return null; + } + + /** + * Gets the root node of this tree + * + * @return the root node of the tree + */ + public TreeNode getRootNode() { + return rootNode; + } + + /** + * Sets the root node of this tree + * + * @param rootNode the root node of the tree + */ + public void setRootNode(TreeNode rootNode) { + this.rootNode = rootNode; } - return null; - } - - /** - * Gets the root node of this tree - * - * @return the root node of the tree - */ - public TreeNode getRootNode() { - return rootNode; - } - - /** - * Sets the root node of this tree - * - * @param rootNode the root node of the tree - */ - public void setRootNode(TreeNode rootNode) { - this.rootNode = rootNode; - } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeElement.java b/src/main/java/edu/rpi/legup/model/tree/TreeElement.java index d7f21c3b7..59f75acf3 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeElement.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeElement.java @@ -3,61 +3,61 @@ import edu.rpi.legup.model.gameboard.Board; public abstract class TreeElement { - protected TreeElementType type; - protected Board board; - - /** - * TreeElement Constructor creates a tree puzzleElement that is part of a tree - * - * @param type type of tree puzzleElement (NODE or TRANSITION) - */ - public TreeElement(TreeElementType type) { - this.type = type; - } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must lead - * to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - public abstract boolean isContradictoryBranch(); - - /** - * Recursively determines if the sub-tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and - * justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - public abstract boolean isValidBranch(); - - /** - * Gets the type of tree puzzleElement - * - * @return NODE if this tree puzzleElement is a tree node, TRANSITION, if this tree puzzleElement - * is a transition - */ - public TreeElementType getType() { - return type; - } - - /** - * Gets the board at this TreeElement - * - * @return the board at this TreeElement - */ - public Board getBoard() { - return board; - } - - /** - * Sets the board at this TreeElement - * - * @param board the board at this TreeElement - */ - public void setBoard(Board board) { - this.board = board; - } + protected TreeElementType type; + protected Board board; + + /** + * TreeElement Constructor creates a tree puzzleElement that is part of a tree + * + * @param type type of tree puzzleElement (NODE or TRANSITION) + */ + public TreeElement(TreeElementType type) { + this.type = type; + } + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must + * lead to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + public abstract boolean isContradictoryBranch(); + + /** + * Recursively determines if the sub-tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified + * and justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + public abstract boolean isValidBranch(); + + /** + * Gets the type of tree puzzleElement + * + * @return NODE if this tree puzzleElement is a tree node, TRANSITION, if this tree + * puzzleElement is a transition + */ + public TreeElementType getType() { + return type; + } + + /** + * Gets the board at this TreeElement + * + * @return the board at this TreeElement + */ + public Board getBoard() { + return board; + } + + /** + * Sets the board at this TreeElement + * + * @param board the board at this TreeElement + */ + public void setBoard(Board board) { + this.board = board; + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java b/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java index 42eeb6c34..67437a535 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeElementType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.model.tree; public enum TreeElementType { - NODE, - TRANSITION + NODE, + TRANSITION } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeNode.java b/src/main/java/edu/rpi/legup/model/tree/TreeNode.java index 4d1652a3c..a2ac7cb21 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeNode.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeNode.java @@ -5,328 +5,328 @@ import java.util.*; public class TreeNode extends TreeElement { - private TreeTransition parent; - private List children; - private boolean isRoot; - - /** - * TreeNode Constructor creates a tree node whenever a rule has been made - * - * @param board board associated with this tree node - */ - public TreeNode(Board board) { - super(TreeElementType.NODE); - this.board = board; - this.parent = null; - this.children = new ArrayList<>(); - this.isRoot = false; - } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must lead - * to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - @Override - public boolean isContradictoryBranch() { - boolean leadsToContra = true; - for (TreeTransition child : children) { - leadsToContra &= child.isContradictoryBranch(); + private TreeTransition parent; + private List children; + private boolean isRoot; + + /** + * TreeNode Constructor creates a tree node whenever a rule has been made + * + * @param board board associated with this tree node + */ + public TreeNode(Board board) { + super(TreeElementType.NODE); + this.board = board; + this.parent = null; + this.children = new ArrayList<>(); + this.isRoot = false; } - return leadsToContra && !children.isEmpty(); - } - - /** - * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and - * justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - @Override - public boolean isValidBranch() { - for (TreeTransition transition : children) { - if (!transition.isValidBranch()) { - return false; - } - } - return true; - } - - /** - * Gets all of the ancestors of this node - * - * @return list of all of the ancestors for this node - */ - public List getAncestors() { - List ancestors = new ArrayList<>(); - Queue it = new LinkedList<>(); - it.add(this); - - while (!it.isEmpty()) { - TreeNode next = it.poll(); - if (next.getParent() != null) { - for (TreeNode treeNode : next.getParent().getParents()) { - if (!it.contains(treeNode)) { - it.add(treeNode); - } - } - } - if (!ancestors.contains(next)) { - ancestors.add(next); - } + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must + * lead to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + @Override + public boolean isContradictoryBranch() { + boolean leadsToContra = true; + for (TreeTransition child : children) { + leadsToContra &= child.isContradictoryBranch(); + } + return leadsToContra && !children.isEmpty(); } - return ancestors; - } - - /** - * Gets a list of the descendants of this node - * - * @return list of all the descendants for this node - */ - public List getDescendants() { - List descendants = new ArrayList<>(); - Queue it = new LinkedList<>(); - it.add(this); - - while (!it.isEmpty()) { - TreeElement next = it.poll(); - - if (next.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) next; - for (TreeTransition transition : node.getChildren()) { - if (!descendants.contains(transition)) { - descendants.add(transition); - it.add(transition); - } + + /** + * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified + * and justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + @Override + public boolean isValidBranch() { + for (TreeTransition transition : children) { + if (!transition.isValidBranch()) { + return false; + } } - } else { - TreeTransition trans = (TreeTransition) next; - TreeNode childNode = trans.getChildNode(); - if (childNode != null && !descendants.contains(childNode)) { - descendants.add(childNode); - it.add(childNode); + return true; + } + + /** + * Gets all of the ancestors of this node + * + * @return list of all of the ancestors for this node + */ + public List getAncestors() { + List ancestors = new ArrayList<>(); + Queue it = new LinkedList<>(); + it.add(this); + + while (!it.isEmpty()) { + TreeNode next = it.poll(); + if (next.getParent() != null) { + for (TreeNode treeNode : next.getParent().getParents()) { + if (!it.contains(treeNode)) { + it.add(treeNode); + } + } + } + + if (!ancestors.contains(next)) { + ancestors.add(next); + } } - } + return ancestors; } - return descendants; - } - - /** - * Gets a DisjointSets containing the children of this node such that the sets contained within - * the DisjointSets are such that elements in the same set are branches of this tree node that - * will eventually merge. This could mean that multiple merges take place before this happens. - * - * @return DisjointSets of tree transitions containing unique non-merging branches - */ - public DisjointSets findMergingBranches() { - DisjointSets branches = new DisjointSets<>(); - children.forEach(branches::createSet); - - for (TreeTransition tran : children) { - branches.createSet(tran); - - TreeNode child = tran.getChildNode(); - if (child != null) { - List nodes = new ArrayList<>(); - nodes.add(child); - while (!nodes.isEmpty()) { - TreeElement element = nodes.get(0); - branches.createSet(element); - branches.union(tran, element); - - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - nodes.addAll(node.getChildren()); - } else { - TreeTransition childTran = (TreeTransition) element; - if (childTran.getChildNode() != null) { - nodes.add(childTran.getChildNode()); + + /** + * Gets a list of the descendants of this node + * + * @return list of all the descendants for this node + */ + public List getDescendants() { + List descendants = new ArrayList<>(); + Queue it = new LinkedList<>(); + it.add(this); + + while (!it.isEmpty()) { + TreeElement next = it.poll(); + + if (next.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) next; + for (TreeTransition transition : node.getChildren()) { + if (!descendants.contains(transition)) { + descendants.add(transition); + it.add(transition); + } + } + } else { + TreeTransition trans = (TreeTransition) next; + TreeNode childNode = trans.getChildNode(); + if (childNode != null && !descendants.contains(childNode)) { + descendants.add(childNode); + it.add(childNode); + } } - } - nodes.remove(element); } - } + return descendants; } - DisjointSets mergingBranches = new DisjointSets<>(); - children.forEach(mergingBranches::createSet); + /** + * Gets a DisjointSets containing the children of this node such that the sets contained within + * the DisjointSets are such that elements in the same set are branches of this tree node that + * will eventually merge. This could mean that multiple merges take place before this happens. + * + * @return DisjointSets of tree transitions containing unique non-merging branches + */ + public DisjointSets findMergingBranches() { + DisjointSets branches = new DisjointSets<>(); + children.forEach(branches::createSet); + + for (TreeTransition tran : children) { + branches.createSet(tran); + + TreeNode child = tran.getChildNode(); + if (child != null) { + List nodes = new ArrayList<>(); + nodes.add(child); + while (!nodes.isEmpty()) { + TreeElement element = nodes.get(0); + branches.createSet(element); + branches.union(tran, element); + + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + nodes.addAll(node.getChildren()); + } else { + TreeTransition childTran = (TreeTransition) element; + if (childTran.getChildNode() != null) { + nodes.add(childTran.getChildNode()); + } + } + nodes.remove(element); + } + } + } + + DisjointSets mergingBranches = new DisjointSets<>(); + children.forEach(mergingBranches::createSet); - for (TreeTransition tran : children) { - for (TreeTransition tran1 : children) { - if (branches.find(tran) == branches.find(tran1)) { - mergingBranches.union(tran, tran1); + for (TreeTransition tran : children) { + for (TreeTransition tran1 : children) { + if (branches.find(tran) == branches.find(tran1)) { + mergingBranches.union(tran, tran1); + } + } } - } + return mergingBranches; } - return mergingBranches; - } - - /** - * Finds the point at which the set of tree elements passed in will merge. This must be a set - * gotten from findMergingBranches method DisjointSets - * - * @param branches tree elements to find the merging point - * @return tree transition of the merging point or null if no such point exists - */ - @SuppressWarnings("unchecked") - public static TreeTransition findMergingPoint(Set branches) { - DisjointSets mergeSet = new DisjointSets<>(); - Set branchesCopy = new HashSet<>(branches); - TreeElement headBranch = branchesCopy.iterator().next(); - branchesCopy.remove(headBranch); - - for (TreeElement element : branchesCopy) { - mergeSet.createSet(element); - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - node.getDescendants() - .forEach( - (TreeElement e) -> { - if (!mergeSet.contains(e)) { - mergeSet.createSet(e); - } - mergeSet.union(element, e); - }); - } else { - TreeTransition transition = (TreeTransition) element; - TreeNode childNode = transition.getChildNode(); - if (childNode != null) { - List des = childNode.getDescendants(); - for (TreeElement e : des) { - if (!mergeSet.contains(e)) { - mergeSet.createSet(e); + + /** + * Finds the point at which the set of tree elements passed in will merge. This must be a set + * gotten from findMergingBranches method DisjointSets + * + * @param branches tree elements to find the merging point + * @return tree transition of the merging point or null if no such point exists + */ + @SuppressWarnings("unchecked") + public static TreeTransition findMergingPoint(Set branches) { + DisjointSets mergeSet = new DisjointSets<>(); + Set branchesCopy = new HashSet<>(branches); + TreeElement headBranch = branchesCopy.iterator().next(); + branchesCopy.remove(headBranch); + + for (TreeElement element : branchesCopy) { + mergeSet.createSet(element); + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + node.getDescendants() + .forEach( + (TreeElement e) -> { + if (!mergeSet.contains(e)) { + mergeSet.createSet(e); + } + mergeSet.union(element, e); + }); + } else { + TreeTransition transition = (TreeTransition) element; + TreeNode childNode = transition.getChildNode(); + if (childNode != null) { + List des = childNode.getDescendants(); + for (TreeElement e : des) { + if (!mergeSet.contains(e)) { + mergeSet.createSet(e); + } + mergeSet.union(element, e); + } + } } - mergeSet.union(element, e); - } } - } - } - Queue next = new LinkedList<>(); - next.add(headBranch); + Queue next = new LinkedList<>(); + next.add(headBranch); - while (!next.isEmpty()) { - TreeElement element = next.poll(); - if (!mergeSet.contains(element)) { - mergeSet.createSet(element); - } - mergeSet.union(headBranch, element); + while (!next.isEmpty()) { + TreeElement element = next.poll(); + if (!mergeSet.contains(element)) { + mergeSet.createSet(element); + } + mergeSet.union(headBranch, element); + + if (mergeSet.setCount() == 1) { + if (element.getType() == TreeElementType.TRANSITION) { + return (TreeTransition) element; + } + return null; + } - if (mergeSet.setCount() == 1) { - if (element.getType() == TreeElementType.TRANSITION) { - return (TreeTransition) element; + if (element.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) element; + next.addAll(node.getChildren()); + } else { + TreeTransition tran = (TreeTransition) element; + next.add(tran.getChildNode()); + } } return null; - } - - if (element.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) element; - next.addAll(node.getChildren()); - } else { - TreeTransition tran = (TreeTransition) element; - next.add(tran.getChildNode()); - } } - return null; - } - - /** - * Determines if the specified tree transition is a parent of this node - * - * @param parent tree transition that could be a parent - * @return true if the specified tree transition is a parent of this node, false otherwise - */ - public boolean isParent(TreeTransition parent) { - return this.parent == parent; - } - - /** - * Adds a child to this tree node - * - * @param child child to add - */ - public void addChild(TreeTransition child) { - children.add(child); - } - - /** - * Removes a child to this tree node - * - * @param child child to remove - */ - public void removeChild(TreeTransition child) { - children.remove(child); - } - - /** - * Determines if the specified tree node is a child of this node - * - * @param child tree node that could be a child - * @return true if the specified tree node is a child of this node, false otherwise - */ - public boolean isChild(TreeNode child) { - return children.contains(child); - } - - /** - * Gets the TreeNode's parent - * - * @return the TreeNode's parent - */ - public TreeTransition getParent() { - return parent; - } - - /** - * Sets the TreeNode's parent - * - * @param parent the TreeNode's parent - */ - public void setParent(TreeTransition parent) { - this.parent = parent; - } - - /** - * Gets the TreeNode's children - * - * @return the TreeNode's children - */ - public List getChildren() { - return children; - } - - /** - * Sets the TreeNode's children - * - * @param children the TreeNode's children - */ - public void setChildren(List children) { - this.children = children; - } - - /** - * Is this node the root of the tree - * - * @return true if this node is the root of the tree, false otherwise - */ - public boolean isRoot() { - return isRoot; - } - - /** - * Sets the root of the tree - * - * @param isRoot true if this node is the root of the tree, false otherwise - */ - public void setRoot(boolean isRoot) { - this.isRoot = isRoot; - } - - public void clearChildren() { - this.children.clear(); - } + + /** + * Determines if the specified tree transition is a parent of this node + * + * @param parent tree transition that could be a parent + * @return true if the specified tree transition is a parent of this node, false otherwise + */ + public boolean isParent(TreeTransition parent) { + return this.parent == parent; + } + + /** + * Adds a child to this tree node + * + * @param child child to add + */ + public void addChild(TreeTransition child) { + children.add(child); + } + + /** + * Removes a child to this tree node + * + * @param child child to remove + */ + public void removeChild(TreeTransition child) { + children.remove(child); + } + + /** + * Determines if the specified tree node is a child of this node + * + * @param child tree node that could be a child + * @return true if the specified tree node is a child of this node, false otherwise + */ + public boolean isChild(TreeNode child) { + return children.contains(child); + } + + /** + * Gets the TreeNode's parent + * + * @return the TreeNode's parent + */ + public TreeTransition getParent() { + return parent; + } + + /** + * Sets the TreeNode's parent + * + * @param parent the TreeNode's parent + */ + public void setParent(TreeTransition parent) { + this.parent = parent; + } + + /** + * Gets the TreeNode's children + * + * @return the TreeNode's children + */ + public List getChildren() { + return children; + } + + /** + * Sets the TreeNode's children + * + * @param children the TreeNode's children + */ + public void setChildren(List children) { + this.children = children; + } + + /** + * Is this node the root of the tree + * + * @return true if this node is the root of the tree, false otherwise + */ + public boolean isRoot() { + return isRoot; + } + + /** + * Sets the root of the tree + * + * @param isRoot true if this node is the root of the tree, false otherwise + */ + public void setRoot(boolean isRoot) { + this.isRoot = isRoot; + } + + public void clearChildren() { + this.children.clear(); + } } diff --git a/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java b/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java index e20ba8b6a..e79cd4b96 100644 --- a/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java +++ b/src/main/java/edu/rpi/legup/model/tree/TreeTransition.java @@ -9,413 +9,412 @@ import java.util.List; public class TreeTransition extends TreeElement { - private ArrayList parents; - private TreeNode childNode; - private Rule rule; - - private PuzzleElement selection; - private boolean isCorrect; - private boolean isVerified; - - /** - * TreeTransition Constructor create a transition from one node to another - * - * @param board board state of the transition - */ - public TreeTransition(Board board) { - super(TreeElementType.TRANSITION); - this.parents = new ArrayList<>(); - this.childNode = null; - this.board = board; - this.rule = null; - this.selection = null; - this.isCorrect = false; - this.isVerified = false; - } - - /** - * TreeTransition Constructor - create a transition from one node to another - * - * @param parent parent tree node associated with the transition - * @param board board state of the transition - */ - public TreeTransition(TreeNode parent, Board board) { - this(board); - this.parents.add(parent); - } - - /** - * Recursively propagates the change of puzzleElement down the tree - * - * @param element puzzleElement of the change made - */ - @SuppressWarnings("unchecked") - public void propagateChange(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyChange(element); - changed = true; - } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyChange(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyChange(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - PuzzleElement copy = element.copy(); - copy.setModifiable(false); - child.propagateChange(copy); - } - } - } - } else { - // Overwrite previous modifications to this element - board.removeModifiedData(board.getPuzzleElement(element)); - - // apply changes to tranistion - board.notifyChange(element); - - // mark first transition as modified - if (!board - .getPuzzleElement(element) - .equalsData(parents.get(0).getBoard().getPuzzleElement(element))) { - board.addModifiedData(element); - } - - // propagate to children - if (childNode != null) { - - // find starting board - TreeNode head = childNode; - while (head.getParent() != null) { - head = head.getParent().getParents().get(0); - } - Board headBoard = head.getBoard(); + private ArrayList parents; + private TreeNode childNode; + private Rule rule; + + private PuzzleElement selection; + private boolean isCorrect; + private boolean isVerified; + + /** + * TreeTransition Constructor create a transition from one node to another + * + * @param board board state of the transition + */ + public TreeTransition(Board board) { + super(TreeElementType.TRANSITION); + this.parents = new ArrayList<>(); + this.childNode = null; + this.board = board; + this.rule = null; + this.selection = null; + this.isCorrect = false; + this.isVerified = false; + } - PuzzleElement copy = element.copy(); - // Set as modifiable if reverted to starting value (and started modifiable) - if (headBoard.getPuzzleElement(element).equalsData(element)) { - copy.setModifiable(headBoard.getPuzzleElement(element).isModifiable()); + /** + * TreeTransition Constructor - create a transition from one node to another + * + * @param parent parent tree node associated with the transition + * @param board board state of the transition + */ + public TreeTransition(TreeNode parent, Board board) { + this(board); + this.parents.add(parent); + } + + /** + * Recursively propagates the change of puzzleElement down the tree + * + * @param element puzzleElement of the change made + */ + @SuppressWarnings("unchecked") + public void propagateChange(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyChange(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyChange(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyChange(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + PuzzleElement copy = element.copy(); + copy.setModifiable(false); + child.propagateChange(copy); + } + } + } } else { - copy.setModifiable(false); - } + // Overwrite previous modifications to this element + board.removeModifiedData(board.getPuzzleElement(element)); - // apply changes to result node - childNode.getBoard().notifyChange(copy); + // apply changes to tranistion + board.notifyChange(element); - // apply to all child transitions - for (TreeTransition child : childNode.getChildren()) { - child.propagateChange(copy.copy()); + // mark first transition as modified + if (!board.getPuzzleElement(element) + .equalsData(parents.get(0).getBoard().getPuzzleElement(element))) { + board.addModifiedData(element); + } + + // propagate to children + if (childNode != null) { + + // find starting board + TreeNode head = childNode; + while (head.getParent() != null) { + head = head.getParent().getParents().get(0); + } + Board headBoard = head.getBoard(); + + PuzzleElement copy = element.copy(); + // Set as modifiable if reverted to starting value (and started modifiable) + if (headBoard.getPuzzleElement(element).equalsData(element)) { + copy.setModifiable(headBoard.getPuzzleElement(element).isModifiable()); + } else { + copy.setModifiable(false); + } + + // apply changes to result node + childNode.getBoard().notifyChange(copy); + + // apply to all child transitions + for (TreeTransition child : childNode.getChildren()) { + child.propagateChange(copy.copy()); + } + } } - } + reverify(); } - reverify(); - } - - /** - * Recursively propagates the addition of puzzleElement down the tree - * - * @param element puzzleElement of the addition made - */ - @SuppressWarnings("unchecked") - public void propagateAddition(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyDeletion(element); - changed = true; + + /** + * Recursively propagates the addition of puzzleElement down the tree + * + * @param element puzzleElement of the addition made + */ + @SuppressWarnings("unchecked") + public void propagateAddition(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyDeletion(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyAddition(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyAddition(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateAddition(element.copy()); + } + } + } } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyAddition(element); - changed = true; - } - } - if (changed && childNode != null) { - childNode.getBoard().notifyAddition(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateAddition(element.copy()); - } + if (childNode != null) { + board.notifyAddition(element); + childNode.getBoard().notifyAddition(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateAddition(element.copy()); + } + } } - } - } else { - if (childNode != null) { - board.notifyAddition(element); - childNode.getBoard().notifyAddition(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateAddition(element.copy()); + reverify(); + } + + /** + * Recursively propagates the change of puzzleElement down the tree + * + * @param element puzzleElement of the change made + */ + @SuppressWarnings("unchecked") + public void propagateDeletion(PuzzleElement element) { + if (isJustified() && rule.getRuleType() == RuleType.MERGE) { + TreeNode lca = Tree.getLowestCommonAncestor(parents); + Board lcaBoard = lca.getBoard(); + List boards = new ArrayList<>(); + parents.forEach(p -> boards.add(p.getBoard())); + PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); + boolean isSame = true; + for (Board board : boards) { + isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); + } + + if (isSame) { + boolean changed = false; + PuzzleElement mergedData = board.getPuzzleElement(element); + if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { + mergedData.setData(element.getData()); + board.removeModifiedData(element); + board.notifyDeletion(element); + changed = true; + } else { + if (!lcaElement.equalsData(element)) { + mergedData.setData(element.getData()); + board.addModifiedData(mergedData); + board.notifyAddition(element); + changed = true; + } + } + if (changed && childNode != null) { + childNode.getBoard().notifyDeletion(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateDeletion(element.copy()); + } + } + } + } else { + if (childNode != null) { + board.notifyDeletion(element); + childNode.getBoard().notifyDeletion(element.copy()); + for (TreeTransition child : childNode.getChildren()) { + child.propagateDeletion(element.copy()); + } + } } - } + reverify(); } - reverify(); - } - - /** - * Recursively propagates the change of puzzleElement down the tree - * - * @param element puzzleElement of the change made - */ - @SuppressWarnings("unchecked") - public void propagateDeletion(PuzzleElement element) { - if (isJustified() && rule.getRuleType() == RuleType.MERGE) { - TreeNode lca = Tree.getLowestCommonAncestor(parents); - Board lcaBoard = lca.getBoard(); - List boards = new ArrayList<>(); - parents.forEach(p -> boards.add(p.getBoard())); - PuzzleElement lcaElement = lcaBoard.getPuzzleElement(element); - boolean isSame = true; - for (Board board : boards) { - isSame &= element.equalsData(board.getPuzzleElement(lcaElement)); - } - - if (isSame) { - boolean changed = false; - PuzzleElement mergedData = board.getPuzzleElement(element); - if (lcaElement.equalsData(element) && !mergedData.equalsData(element)) { - mergedData.setData(element.getData()); - board.removeModifiedData(element); - board.notifyDeletion(element); - changed = true; + + /** + * Determines if this tree node leads to a contradiction. Every path from this tree node must + * lead to a contradiction including all of its children + * + * @return true if this tree node leads to a contradiction, false otherwise + */ + @Override + public boolean isContradictoryBranch() { + if (isJustified() && isCorrect() && rule.getRuleType() == RuleType.CONTRADICTION) { + return true; } else { - if (!lcaElement.equalsData(element)) { - mergedData.setData(element.getData()); - board.addModifiedData(mergedData); - board.notifyAddition(element); - changed = true; - } + if (childNode == null) { + return false; + } else { + return childNode.isContradictoryBranch() && isJustified() && isCorrect(); + } } - if (changed && childNode != null) { - childNode.getBoard().notifyDeletion(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateDeletion(element.copy()); - } + } + + /** + * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking + * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified + * and justified correctly + * + * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is + * valid, false otherwise + */ + @Override + public boolean isValidBranch() { + return isJustified() && isCorrect() && childNode != null && childNode.isValidBranch(); + } + + /** + * Gets the parent tree nodes of this transition + * + * @return parent tree nodes of this tree transition + */ + public ArrayList getParents() { + return parents; + } + + /** + * Sets the parent tree nodes of this transition + * + * @param parents parents tree nodes of this tree transition + */ + public void setParents(ArrayList parents) { + this.parents = parents; + } + + /** + * Adds a parent tree node to this tree transition + * + * @param parent parent tree node to add + */ + public void addParent(TreeNode parent) { + parents.add(parent); + } + + /** + * Removes a parent tree node to this tree transition + * + * @param parent parent tree node to remove + */ + public void removeParent(TreeNode parent) { + parents.remove(parent); + } + + /** + * Determines if the specified tree node is a parent of this transition + * + * @param parent tree node that could be a parent + * @return true if the specified tree node is a parent of this transition, false otherwise + */ + public boolean isParent(TreeNode parent) { + return parents.contains(parent); + } + + /** + * Gets the childNode tree node of this transition + * + * @return childNode tree node + */ + public TreeNode getChildNode() { + return childNode; + } + + /** + * Sets the childNode tree node of this transition + * + * @param childNode childNode tree node + */ + public void setChildNode(TreeNode childNode) { + this.childNode = childNode; + } + + /** + * Gets the rule associated with this transition + * + * @return rule of this transition + */ + public Rule getRule() { + return rule; + } + + /** + * Sets the rule associated with this transition + * + * @param rule rule of this transition + */ + public void setRule(Rule rule) { + this.rule = rule; + isVerified = false; + } + + /** + * Gets he selected element associated with this transition + * + * @return If this is a case rule, the selected element for that rule, null otherwise + */ + public PuzzleElement getSelection() { + if (this.rule instanceof CaseRule) { + return selection; } - } - } else { - if (childNode != null) { - board.notifyDeletion(element); - childNode.getBoard().notifyDeletion(element.copy()); - for (TreeTransition child : childNode.getChildren()) { - child.propagateDeletion(element.copy()); + return null; + } + + /** + * Sets the selected element associated with this transition + * + * @param selection selected element for this transition + */ + public void setSelection(PuzzleElement selection) { + this.selection = selection; + } + + /** + * Gets whether this transition is correctly justified + * + * @return true if this transition is correctly justified, false otherwise + */ + public boolean isCorrect() { + if (isJustified() && !isVerified) { + isCorrect = rule.checkRule(this) == null; + isVerified = true; } - } + return isJustified() && isCorrect; } - reverify(); - } - - /** - * Determines if this tree node leads to a contradiction. Every path from this tree node must lead - * to a contradiction including all of its children - * - * @return true if this tree node leads to a contradiction, false otherwise - */ - @Override - public boolean isContradictoryBranch() { - if (isJustified() && isCorrect() && rule.getRuleType() == RuleType.CONTRADICTION) { - return true; - } else { - if (childNode == null) { - return false; - } else { - return childNode.isContradictoryBranch() && isJustified() && isCorrect(); - } + + /** + * Sets whether this transition is correctly justified + * + * @param isCorrect true if this transition is correctly justified, false otherwise + */ + public void setCorrect(boolean isCorrect) { + this.isCorrect = isCorrect; + this.isVerified = true; } - } - - /** - * Recursively determines if the sub tree rooted at this tree puzzleElement is valid by checking - * whether this tree puzzleElement and all descendants of this tree puzzleElement is justified and - * justified correctly - * - * @return true if this tree puzzleElement and all descendants of this tree puzzleElement is - * valid, false otherwise - */ - @Override - public boolean isValidBranch() { - return isJustified() && isCorrect() && childNode != null && childNode.isValidBranch(); - } - - /** - * Gets the parent tree nodes of this transition - * - * @return parent tree nodes of this tree transition - */ - public ArrayList getParents() { - return parents; - } - - /** - * Sets the parent tree nodes of this transition - * - * @param parents parents tree nodes of this tree transition - */ - public void setParents(ArrayList parents) { - this.parents = parents; - } - - /** - * Adds a parent tree node to this tree transition - * - * @param parent parent tree node to add - */ - public void addParent(TreeNode parent) { - parents.add(parent); - } - - /** - * Removes a parent tree node to this tree transition - * - * @param parent parent tree node to remove - */ - public void removeParent(TreeNode parent) { - parents.remove(parent); - } - - /** - * Determines if the specified tree node is a parent of this transition - * - * @param parent tree node that could be a parent - * @return true if the specified tree node is a parent of this transition, false otherwise - */ - public boolean isParent(TreeNode parent) { - return parents.contains(parent); - } - - /** - * Gets the childNode tree node of this transition - * - * @return childNode tree node - */ - public TreeNode getChildNode() { - return childNode; - } - - /** - * Sets the childNode tree node of this transition - * - * @param childNode childNode tree node - */ - public void setChildNode(TreeNode childNode) { - this.childNode = childNode; - } - - /** - * Gets the rule associated with this transition - * - * @return rule of this transition - */ - public Rule getRule() { - return rule; - } - - /** - * Sets the rule associated with this transition - * - * @param rule rule of this transition - */ - public void setRule(Rule rule) { - this.rule = rule; - isVerified = false; - } - - /** - * Gets he selected element associated with this transition - * - * @return If this is a case rule, the selected element for that rule, null otherwise - */ - public PuzzleElement getSelection() { - if (this.rule instanceof CaseRule) { - return selection; + + /** + * Forces check of rule on this transition regardless if it has been cached already + * + * @return true if this transition is correctly justified, false otherwise + */ + public boolean reverify() { + isVerified = false; + return isCorrect(); } - return null; - } - - /** - * Sets the selected element associated with this transition - * - * @param selection selected element for this transition - */ - public void setSelection(PuzzleElement selection) { - this.selection = selection; - } - - /** - * Gets whether this transition is correctly justified - * - * @return true if this transition is correctly justified, false otherwise - */ - public boolean isCorrect() { - if (isJustified() && !isVerified) { - isCorrect = rule.checkRule(this) == null; - isVerified = true; + + /** + * Gets whether this transition is justified + * + * @return true if this transition is justified, false otherwise + */ + public boolean isJustified() { + return rule != null; } - return isJustified() && isCorrect; - } - - /** - * Sets whether this transition is correctly justified - * - * @param isCorrect true if this transition is correctly justified, false otherwise - */ - public void setCorrect(boolean isCorrect) { - this.isCorrect = isCorrect; - this.isVerified = true; - } - - /** - * Forces check of rule on this transition regardless if it has been cached already - * - * @return true if this transition is correctly justified, false otherwise - */ - public boolean reverify() { - isVerified = false; - return isCorrect(); - } - - /** - * Gets whether this transition is justified - * - * @return true if this transition is justified, false otherwise - */ - public boolean isJustified() { - return rule != null; - } - - /*public int modifiedData_size(){ - return board.getModifiedData().size(); - }*/ + + /*public int modifiedData_size(){ + return board.getModifiedData().size(); + }*/ } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java b/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java index fcfa70cd4..41af3f626 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/Battleship.java @@ -6,164 +6,164 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Battleship extends Puzzle { - public Battleship() { - super(); + public Battleship() { + super(); - this.name = "Battleship"; + this.name = "Battleship"; - this.importer = new BattleshipImporter(this); - this.exporter = new BattleshipExporter(this); + this.importer = new BattleshipImporter(this); + this.exporter = new BattleshipExporter(this); - this.factory = new BattleshipCellFactory(); - } + this.factory = new BattleshipCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new BattleshipView((BattleshipBoard) currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new BattleshipView((BattleshipBoard) currentBoard); + addBoardListener(boardView); + } - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Battleship - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Battleship, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for Battleship + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Battleship, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - BattleshipBoard battleShipBoard = (BattleshipBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + BattleshipBoard battleShipBoard = (BattleshipBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(battleShipBoard) == null) { - return false; - } + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(battleShipBoard) == null) { + return false; + } + } + for (PuzzleElement data : battleShipBoard.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) data; + if (cell.getType() == BattleshipType.UNKNOWN) { + return false; + } + } + return true; } - for (PuzzleElement data : battleShipBoard.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) data; - if (cell.getType() == BattleshipType.UNKNOWN) { - return false; - } - } - return true; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} - // - // @Override - // public void onTreeSelectionChange(ArrayList newSelection) - // { - // - // } + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} - @Override - public void importPuzzle(String fileName) { - // if(fileName != null) - // { - // InputStream inputStream = new FileInputStream(fileName); - // DocumentBuilder builder = null;//factory.newDocumentBuilder(); - // Document document = builder.parse(inputStream); - // - // BattleShipBoard battleShipBoard; - // - // PuzzleElement rootNode = document.getDocumentElement(); - // PuzzleElement puzzleElement = (PuzzleElement) - // rootNode.getElementsByTagName("edu.rpi.legup.puzzle").item(0); - // PuzzleElement boardElement = (PuzzleElement) - // puzzleElement.getElementsByTagName("board").item(0); - // PuzzleElement axesElement = (PuzzleElement) - // boardElement.getElementsByTagName("axes").item(0); - // PuzzleElement shipElement = (PuzzleElement) - // boardElement.getElementsByTagName("ships").item(0); - // PuzzleElement cellElement = (PuzzleElement) - // boardElement.getElementsByTagName("cells").item(0); - // PuzzleElement rightElement = (PuzzleElement) - // axesElement.getElementsByTagName("right").item(0); - // PuzzleElement bottomElement = (PuzzleElement) - // axesElement.getElementsByTagName("bottom").item(0); - // NodeList rightClueList = rightElement.getElementsByTagName("clue"); - // NodeList bottomClueList = bottomElement.getElementsByTagName("clue"); - // NodeList shipList = shipElement.getElementsByTagName("ship"); - // NodeList cells = cellElement.getElementsByTagName("cell"); // - // int size = Integer.valueOf(boardElement.getAttribute("size")); - // battleShipBoard = new BattleShipBoard(size); + // @Override + // public void onTreeSelectionChange(ArrayList newSelection) + // { // - // ArrayList battleShipData = new ArrayList<>(); - // for(int i = 0; i < size * size; i++) - // { - // battleShipData.add(null); - // } - // - // for (int i = 0; i < rightClueList.getLength(); i++) { - // battleShipBoard.getRight()[i] = - // Integer.valueOf(rightClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); - // } - // - // for (int i = 0; i < bottomClueList.getLength(); i++) { - // battleShipBoard.getBottom()[i] = - // Integer.valueOf(bottomClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); - // } - // - // for (int i = 0; i < shipList.getLength(); i++) { - // int length = - // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("length").getNodeValue()); - // int count = - // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("count").getNodeValue()); - // battleShipBoard.getShips().add(new Ship(length, count)); - // } - // - // for (int i = 0; i < cells.getLength(); i++) { - // int x = - // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("x").getNodeValue()); - // int y = - // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("y").getNodeValue()); - // String value = - // cells.item(i).getAttributes().getNamedItem("value").getNodeValue().toUpperCase(); - // - // BattleShipCell cell = new - // BattleShipCell(BattleShipType.valueOf(value).ordinal(), new Point(x, y)); - // battleShipBoard.setCell(x, y, cell); - // cell.setModifiable(false); - // cell.setGiven(true); - // } - // - // for (int x = 0; x < size; x++) { - // for (int y = 0; y < size; y++) { - // if (battleShipBoard.getCell(x, y) == null) { - // BattleShipCell cell = new BattleShipCell(9, new Point(x, y)); - // cell.setModifiable(true); - // battleShipBoard.setCell(x, y, cell); - // } - // } - // } - // this.currentBoard = battleShipBoard; - // this.tree = new Tree(currentBoard); - // } - } + // } + + @Override + public void importPuzzle(String fileName) { + // if(fileName != null) + // { + // InputStream inputStream = new FileInputStream(fileName); + // DocumentBuilder builder = null;//factory.newDocumentBuilder(); + // Document document = builder.parse(inputStream); + // + // BattleShipBoard battleShipBoard; + // + // PuzzleElement rootNode = document.getDocumentElement(); + // PuzzleElement puzzleElement = (PuzzleElement) + // rootNode.getElementsByTagName("edu.rpi.legup.puzzle").item(0); + // PuzzleElement boardElement = (PuzzleElement) + // puzzleElement.getElementsByTagName("board").item(0); + // PuzzleElement axesElement = (PuzzleElement) + // boardElement.getElementsByTagName("axes").item(0); + // PuzzleElement shipElement = (PuzzleElement) + // boardElement.getElementsByTagName("ships").item(0); + // PuzzleElement cellElement = (PuzzleElement) + // boardElement.getElementsByTagName("cells").item(0); + // PuzzleElement rightElement = (PuzzleElement) + // axesElement.getElementsByTagName("right").item(0); + // PuzzleElement bottomElement = (PuzzleElement) + // axesElement.getElementsByTagName("bottom").item(0); + // NodeList rightClueList = rightElement.getElementsByTagName("clue"); + // NodeList bottomClueList = bottomElement.getElementsByTagName("clue"); + // NodeList shipList = shipElement.getElementsByTagName("ship"); + // NodeList cells = cellElement.getElementsByTagName("cell"); + // + // int size = Integer.valueOf(boardElement.getAttribute("size")); + // battleShipBoard = new BattleShipBoard(size); + // + // ArrayList battleShipData = new ArrayList<>(); + // for(int i = 0; i < size * size; i++) + // { + // battleShipData.add(null); + // } + // + // for (int i = 0; i < rightClueList.getLength(); i++) { + // battleShipBoard.getRight()[i] = + // Integer.valueOf(rightClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); + // } + // + // for (int i = 0; i < bottomClueList.getLength(); i++) { + // battleShipBoard.getBottom()[i] = + // Integer.valueOf(bottomClueList.item(i).getAttributes().getNamedItem("value").getNodeValue()); + // } + // + // for (int i = 0; i < shipList.getLength(); i++) { + // int length = + // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("length").getNodeValue()); + // int count = + // Integer.valueOf(shipList.item(i).getAttributes().getNamedItem("count").getNodeValue()); + // battleShipBoard.getShips().add(new Ship(length, count)); + // } + // + // for (int i = 0; i < cells.getLength(); i++) { + // int x = + // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("x").getNodeValue()); + // int y = + // Integer.valueOf(cells.item(i).getAttributes().getNamedItem("y").getNodeValue()); + // String value = + // cells.item(i).getAttributes().getNamedItem("value").getNodeValue().toUpperCase(); + // + // BattleShipCell cell = new + // BattleShipCell(BattleShipType.valueOf(value).ordinal(), new Point(x, y)); + // battleShipBoard.setCell(x, y, cell); + // cell.setModifiable(false); + // cell.setGiven(true); + // } + // + // for (int x = 0; x < size; x++) { + // for (int y = 0; y < size; y++) { + // if (battleShipBoard.getCell(x, y) == null) { + // BattleShipCell cell = new BattleShipCell(9, new Point(x, y)); + // cell.setModifiable(true); + // battleShipBoard.setCell(x, y, cell); + // } + // } + // } + // this.currentBoard = battleShipBoard; + // this.tree = new Tree(currentBoard); + // } + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java index cbf7ffbcd..555c8471f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipBoard.java @@ -8,148 +8,148 @@ public class BattleshipBoard extends GridBoard { - private List east; - private List south; + private List east; + private List south; - /** - * Constructor for creating a rectangular battleship board. - * - * @param width width of the board - * @param height height of the board - */ - public BattleshipBoard(int width, int height) { - super(width, height); + /** + * Constructor for creating a rectangular battleship board. + * + * @param width width of the board + * @param height height of the board + */ + public BattleshipBoard(int width, int height) { + super(width, height); - this.east = new ArrayList<>(); - this.south = new ArrayList<>(); + this.east = new ArrayList<>(); + this.south = new ArrayList<>(); - for (int i = 0; i < height; i++) { - east.add(null); + for (int i = 0; i < height; i++) { + east.add(null); + } + for (int i = 0; i < width; i++) { + south.add(null); + } } - for (int i = 0; i < width; i++) { - south.add(null); - } - } - - /** - * Constructor for creating a square-sized battleship board. - * - * @param size size of the board - */ - public BattleshipBoard(int size) { - this(size, size); - } - /** - * Gets the east {@link BattleshipClue} - * - * @return List of BattleShipClue objects on the east side of the board - */ - public List getEast() { - return east; - } + /** + * Constructor for creating a square-sized battleship board. + * + * @param size size of the board + */ + public BattleshipBoard(int size) { + this(size, size); + } - /** - * Gets the east {@link BattleshipClue} - * - * @return east battle ship clues - */ - public List getSouth() { - return south; - } + /** + * Gets the east {@link BattleshipClue} + * + * @return List of BattleShipClue objects on the east side of the board + */ + public List getEast() { + return east; + } - @Override - public BattleshipCell getCell(int x, int y) { - return (BattleshipCell) super.getCell(x, y); - } + /** + * Gets the east {@link BattleshipClue} + * + * @return east battle ship clues + */ + public List getSouth() { + return south; + } - @Override - /** - * Creates a copy of the current board - * - * @return the copy of the board - */ - public BattleshipBoard copy() { - BattleshipBoard copy = new BattleshipBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + @Override + public BattleshipCell getCell(int x, int y) { + return (BattleshipCell) super.getCell(x, y); } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + @Override + /** + * Creates a copy of the current board + * + * @return the copy of the board + */ + public BattleshipBoard copy() { + BattleshipBoard copy = new BattleshipBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.east = this.east; + copy.south = this.south; + return copy; } - copy.east = this.east; - copy.south = this.south; - return copy; - } - /** - * Get a list of all orthogonally adjacent cells. - * - * @param cell The cell to get adjacent cells from. - * @return List of adjacent cells in clockwise order: { up, right, down, left } - */ - public List getAdjOrthogonals(BattleshipCell cell) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - BattleshipCell up = getCell(loc.x, loc.y - 1); - BattleshipCell right = getCell(loc.x + 1, loc.y); - BattleshipCell down = getCell(loc.x, loc.y + 1); - BattleshipCell left = getCell(loc.x - 1, loc.y); - adj.add(up); - adj.add(right); - adj.add(down); - adj.add(left); - return adj; - } + /** + * Get a list of all orthogonally adjacent cells. + * + * @param cell The cell to get adjacent cells from. + * @return List of adjacent cells in clockwise order: { up, right, down, left } + */ + public List getAdjOrthogonals(BattleshipCell cell) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + BattleshipCell up = getCell(loc.x, loc.y - 1); + BattleshipCell right = getCell(loc.x + 1, loc.y); + BattleshipCell down = getCell(loc.x, loc.y + 1); + BattleshipCell left = getCell(loc.x - 1, loc.y); + adj.add(up); + adj.add(right); + adj.add(down); + adj.add(left); + return adj; + } - /** - * Get a list of all diagonally adjacent cells. - * - * @param cell The cell to get diagonally adjacent cells from. - * @return List of diagonally adjacent cells in clockwise order: - * { upRight, downRight, downLeft, upLeft } - */ - public List getAdjDiagonals(BattleshipCell cell) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - BattleshipCell upRight = getCell(loc.x + 1, loc.y - 1); - BattleshipCell downRight = getCell(loc.x + 1, loc.y + 1); - BattleshipCell downLeft = getCell(loc.x - 1, loc.y + 1); - BattleshipCell upLeft = getCell(loc.x - 1, loc.y - 1); - dia.add(upRight); - dia.add(downRight); - dia.add(downLeft); - dia.add(upLeft); - return dia; - } + /** + * Get a list of all diagonally adjacent cells. + * + * @param cell The cell to get diagonally adjacent cells from. + * @return List of diagonally adjacent cells in clockwise order: + * { upRight, downRight, downLeft, upLeft } + */ + public List getAdjDiagonals(BattleshipCell cell) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + BattleshipCell upRight = getCell(loc.x + 1, loc.y - 1); + BattleshipCell downRight = getCell(loc.x + 1, loc.y + 1); + BattleshipCell downLeft = getCell(loc.x - 1, loc.y + 1); + BattleshipCell upLeft = getCell(loc.x - 1, loc.y - 1); + dia.add(upRight); + dia.add(downRight); + dia.add(downLeft); + dia.add(upLeft); + return dia; + } - /** - * Get a list of cells in a row. - * - * @param y The y-coordinate of the row. - * @return List of cells in the row in increasing x-coordinate order. - */ - public List getRow(int y) { - List row = new ArrayList<>(); - for (int x = 0; x < dimension.width; x++) { - row.add(getCell(x, y)); + /** + * Get a list of cells in a row. + * + * @param y The y-coordinate of the row. + * @return List of cells in the row in increasing x-coordinate order. + */ + public List getRow(int y) { + List row = new ArrayList<>(); + for (int x = 0; x < dimension.width; x++) { + row.add(getCell(x, y)); + } + return row; } - return row; - } - /** - * Get a list of cells in a column. - * - * @param x The x-coordinate of the column. - * @return List of cells in the column in increasing y-coordinate order. - */ - public List getColumn(int x) { - List column = new ArrayList<>(); - for (int y = 0; y < dimension.height; y++) { - column.add(getCell(x, y)); + /** + * Get a list of cells in a column. + * + * @param x The x-coordinate of the column. + * @return List of cells in the column in increasing y-coordinate order. + */ + public List getColumn(int x) { + List column = new ArrayList<>(); + for (int y = 0; y < dimension.height; y++) { + column.add(getCell(x, y)); + } + return column; } - return column; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java index 1e902633e..5a5b86094 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCell.java @@ -5,35 +5,35 @@ public class BattleshipCell extends GridCell { - /** - * BattleShipCell Constructor - creates a BattleShipCell from the specified value and location - * - * @param value value of the BattleShipCell - * @param location position of the BattleShipCell - */ - public BattleshipCell(BattleshipType value, Point location) { - super(value, location); - } + /** + * BattleShipCell Constructor - creates a BattleShipCell from the specified value and location + * + * @param value value of the BattleShipCell + * @param location position of the BattleShipCell + */ + public BattleshipCell(BattleshipType value, Point location) { + super(value, location); + } - /** - * Gets the type of this BattleShipCell - * - * @return type of BattleShipCell - */ - public BattleshipType getType() { - return data; - } + /** + * Gets the type of this BattleShipCell + * + * @return type of BattleShipCell + */ + public BattleshipType getType() { + return data; + } - /** - * Performs a deep copy on the BattleShipCell - * - * @return a new copy of the BattleShipCell that is independent of this one - */ - public BattleshipCell copy() { - BattleshipCell copy = new BattleshipCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the BattleShipCell + * + * @return a new copy of the BattleShipCell that is independent of this one + */ + public BattleshipCell copy() { + BattleshipCell copy = new BattleshipCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java index d97a44034..9db0cca84 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellController.java @@ -5,39 +5,39 @@ import java.awt.event.MouseEvent; public class BattleshipCellController extends ElementController { - /** - * Controller class for the Battleship puzzle - receives user mouse input and changes what's shown - * on the GUI - * - * @param data the PuzzleElement to be changed - * @param e the user mouse input - */ - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - BattleshipCell cell = (BattleshipCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == BattleshipType.SHIP_MIDDLE) { - cell.setData(BattleshipType.UNKNOWN); + /** + * Controller class for the Battleship puzzle - receives user mouse input and changes what's + * shown on the GUI + * + * @param data the PuzzleElement to be changed + * @param e the user mouse input + */ + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + BattleshipCell cell = (BattleshipCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == BattleshipType.SHIP_MIDDLE) { + cell.setData(BattleshipType.UNKNOWN); + } else { + cell.setData(BattleshipType.getType(cell.getData().value + 1)); + } + } } else { - cell.setData(BattleshipType.getType(cell.getData().value + 1)); + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == BattleshipType.UNKNOWN) { + cell.setData(BattleshipType.SHIP_MIDDLE); + } else { + cell.setData(BattleshipType.getType(cell.getData().value - 1)); + } + } } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == BattleshipType.UNKNOWN) { - cell.setData(BattleshipType.SHIP_MIDDLE); - } else { - cell.setData(BattleshipType.getType(cell.getData().value - 1)); - } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java index f967a677e..1b3b6c427 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipCellFactory.java @@ -10,66 +10,68 @@ import org.w3c.dom.Node; public class BattleshipCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) - throws InvalidFileFormatException { - try { - BattleshipBoard battleShipBoard = (BattleshipBoard) board; - int width = battleShipBoard.getWidth(); - int height = battleShipBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - if (node.getNodeName().equalsIgnoreCase("cell")) { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) + throws InvalidFileFormatException { + try { + BattleshipBoard battleShipBoard = (BattleshipBoard) board; + int width = battleShipBoard.getWidth(); + int height = battleShipBoard.getHeight(); + NamedNodeMap attributeList = node.getAttributes(); + if (node.getNodeName().equalsIgnoreCase("cell")) { - int value = Integer.parseInt(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.parseInt(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.parseInt(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("BattleShip Factory: cell location out of bounds"); - } - if (value < 0 || value > 3) { - throw new InvalidFileFormatException("BattleShip Factory: cell unknown value"); - } + int value = Integer.parseInt(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.parseInt(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.parseInt(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "BattleShip Factory: cell location out of bounds"); + } + if (value < 0 || value > 3) { + throw new InvalidFileFormatException("BattleShip Factory: cell unknown value"); + } - BattleshipCell cell = new BattleshipCell(BattleshipType.getType(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } else { - throw new InvalidFileFormatException( - "BattleShip Factory: unknown puzzleElement puzzleElement"); - } - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "BattleShip Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("BattleShip Factory: could not find attribute(s)"); + BattleshipCell cell = + new BattleshipCell(BattleshipType.getType(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } else { + throw new InvalidFileFormatException( + "BattleShip Factory: unknown puzzleElement puzzleElement"); + } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "BattleShip Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("BattleShip Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - BattleshipCell cell = (BattleshipCell) puzzleElement; - Point loc = cell.getLocation(); + BattleshipCell cell = (BattleshipCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java index 1ed0face1..6b5856639 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClue.java @@ -4,75 +4,75 @@ public class BattleshipClue extends PuzzleElement { - private BattleshipType type; + private BattleshipType type; - public BattleshipClue(int value, int index, BattleshipType type) { - super(value); - this.index = index; - this.type = type; - } + public BattleshipClue(int value, int index, BattleshipType type) { + super(value); + this.index = index; + this.type = type; + } - /** - * Returns the column number as a string - * - * @param col the column number that is to be converted and returned - * @return int value - */ - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; + /** + * Returns the column number as a string + * + * @param col the column number that is to be converted and returned + * @return int value + */ + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; + } + return sb.reverse().toString(); } - return sb.reverse().toString(); - } - /** - * Returns the column string as an integer - * - * @param col the column number as a string that is to be converted and returned - * @return string value - */ - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; + /** + * Returns the column string as an integer + * + * @param col the column number as a string that is to be converted and returned + * @return string value + */ + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; + } + return result; } - return result; - } - /** - * Gets the int value that represents this puzzleElement - * - * @return int value - */ - @Override - public Integer getData() { - return (Integer) super.getData(); - } + /** + * Gets the int value that represents this puzzleElement + * + * @return int value + */ + @Override + public Integer getData() { + return (Integer) super.getData(); + } - /** - * Returns the type of the battleship object (ship or clue) - * - * @return BattleshipType type - */ - public BattleshipType getType() { - return type; - } + /** + * Returns the type of the battleship object (ship or clue) + * + * @return BattleshipType type + */ + public BattleshipType getType() { + return type; + } - /** - * Sets the type of the battleship object (ship or clue) to the given type - * - * @param type given Battleship type - */ - public void setType(BattleshipType type) { - this.type = type; - } + /** + * Sets the type of the battleship object (ship or clue) to the given type + * + * @param type given Battleship type + */ + public void setType(BattleshipType type) { + this.type = type; + } - public BattleshipClue copy() { - return null; - } + public BattleshipClue copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java index e2ad8b863..788c860f3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipClueView.java @@ -5,55 +5,55 @@ public class BattleshipClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public BattleshipClueView(BattleshipClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public BattleshipClue getPuzzleElement() { - return (BattleshipClue) super.getPuzzleElement(); - } - - @Override - /** - * Draws the clue from the PuzzleElement associated with this view on the given frame - * - * @param graphics2D the frame the clue is to be drawn on - */ - public void draw(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - BattleshipClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - value = String.valueOf(clue.getData() + 1); - break; - case CLUE_EAST: - value = String.valueOf(clue.getData()); - break; - case CLUE_SOUTH: - value = String.valueOf(clue.getData()); - break; - case CLUE_WEST: - value = BattleshipClue.colNumToString(clue.getData() + 1); - break; - default: - value = ""; + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public BattleshipClueView(BattleshipClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public BattleshipClue getPuzzleElement() { + return (BattleshipClue) super.getPuzzleElement(); } - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + @Override + /** + * Draws the clue from the PuzzleElement associated with this view on the given frame + * + * @param graphics2D the frame the clue is to be drawn on + */ + public void draw(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + BattleshipClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + value = String.valueOf(clue.getData() + 1); + break; + case CLUE_EAST: + value = String.valueOf(clue.getData()); + break; + case CLUE_SOUTH: + value = String.valueOf(clue.getData()); + break; + case CLUE_WEST: + value = BattleshipClue.colNumToString(clue.getData() + 1); + break; + default: + value = ""; + } + + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java index fed0afaf3..1898468ce 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipElementView.java @@ -4,94 +4,107 @@ import java.awt.*; public class BattleshipElementView extends GridElementView { - private static final Stroke OUTLINE_STROKE = new BasicStroke(1); - private static final Color OUTLINE_COLOR = new Color(0x212121); + private static final Stroke OUTLINE_STROKE = new BasicStroke(1); + private static final Color OUTLINE_COLOR = new Color(0x212121); - private static final Color UNKNOWN_COLOR = new Color(0xE0E0E0); - private static final Color WATER_COLOR = new Color(0x1565C0); - private static final Color SHIP_COLOR = new Color(0x757575); + private static final Color UNKNOWN_COLOR = new Color(0xE0E0E0); + private static final Color WATER_COLOR = new Color(0x1565C0); + private static final Color SHIP_COLOR = new Color(0x757575); - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 10); - private static final Color FONT_COLOR = new Color(0xFFEB3B); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 10); + private static final Color FONT_COLOR = new Color(0xFFEB3B); - public BattleshipElementView(BattleshipCell cell) { - super(cell); - } + public BattleshipElementView(BattleshipCell cell) { + super(cell); + } - @Override - /** - * Draws on the given frame based on the type of the cell of the current puzzleElement - * - * @param graphics2D the frame to be drawn on - */ - public void drawElement(Graphics2D graphics2D) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - BattleshipType type = cell.getType(); + @Override + /** + * Draws on the given frame based on the type of the cell of the current puzzleElement + * + * @param graphics2D the frame to be drawn on + */ + public void drawElement(Graphics2D graphics2D) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + BattleshipType type = cell.getType(); - switch (type) { - case UNKNOWN: - graphics2D.setColor(UNKNOWN_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - case WATER: - graphics2D.setColor(WATER_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - case SHIP_UNKNOWN: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillRect( - location.x + 3 * size.width / 8, - location.y + 3 * size.height / 8, - size.width / 4, - size.height / 4); + switch (type) { + case UNKNOWN: + graphics2D.setColor(UNKNOWN_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + case WATER: + graphics2D.setColor(WATER_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + case SHIP_UNKNOWN: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillRect( + location.x + 3 * size.width / 8, + location.y + 3 * size.height / 8, + size.width / 4, + size.height / 4); - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = "?"; - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - break; - case SUBMARINE: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillOval( - location.x + size.width / 4, - location.y + size.width / 4, - size.width / 2, - size.height / 2); - break; - case SHIP_TOP: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x, location.y - size.height / 2, size.width, size.height, 180, 180); - break; - case SHIP_RIGHT: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x + size.height / 2, location.y, size.width, size.height, 90, 180); - break; - case SHIP_BOTTOM: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x, location.y + size.height / 2, size.width, size.height, 0, 180); - break; - case SHIP_LEFT: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillArc( - location.x - size.height / 2, location.y, size.width, size.height, 270, 180); - break; - case SHIP_MIDDLE: - graphics2D.setColor(SHIP_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - break; - default: - graphics2D.setColor(new Color(0xE040FB)); - break; - } + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = "?"; + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + + ((size.height - metrics.getHeight()) / 2) + + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + break; + case SUBMARINE: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillOval( + location.x + size.width / 4, + location.y + size.width / 4, + size.width / 2, + size.height / 2); + break; + case SHIP_TOP: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x, + location.y - size.height / 2, + size.width, + size.height, + 180, + 180); + break; + case SHIP_RIGHT: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x + size.height / 2, location.y, size.width, size.height, 90, 180); + break; + case SHIP_BOTTOM: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x, location.y + size.height / 2, size.width, size.height, 0, 180); + break; + case SHIP_LEFT: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillArc( + location.x - size.height / 2, + location.y, + size.width, + size.height, + 270, + 180); + break; + case SHIP_MIDDLE: + graphics2D.setColor(SHIP_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + break; + default: + graphics2D.setColor(new Color(0xE040FB)); + break; + } - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.setStroke(OUTLINE_STROKE); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.setStroke(OUTLINE_STROKE); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java index d9ec97a58..cbc364842 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipExporter.java @@ -6,60 +6,60 @@ public class BattleshipExporter extends PuzzleExporter { - public BattleshipExporter(Battleship battleShip) { - super(battleShip); - } - - /** - * Creates and returns a new board element in the XML document specified - * - * @param newDocument the XML document to append to - * @return the new board element - */ - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - BattleshipBoard board; - if (puzzle.getTree() != null) { - board = (BattleshipBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (BattleshipBoard) puzzle.getBoardView().getBoard(); + public BattleshipExporter(Battleship battleShip) { + super(battleShip); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + /** + * Creates and returns a new board element in the XML document specified + * + * @param newDocument the XML document to append to + * @return the new board element + */ + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + BattleshipBoard board; + if (puzzle.getTree() != null) { + board = (BattleshipBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (BattleshipBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - if (cell.getData() != BattleshipType.getType(0)) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (BattleshipClue clue : board.getEast()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", BattleshipClue.colNumToString(clue.getIndex())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + if (cell.getData() != BattleshipType.getType(0)) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (BattleshipClue clue : board.getEast()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", String.valueOf(clue.getIndex())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (BattleshipClue clue : board.getEast()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", BattleshipClue.colNumToString(clue.getIndex())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); + + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (BattleshipClue clue : board.getEast()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", String.valueOf(clue.getIndex())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); - return boardElement; - } + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java index 012bf9b5c..cbc1dd02b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipImporter.java @@ -8,176 +8,183 @@ import org.w3c.dom.NodeList; public class BattleshipImporter extends PuzzleImporter { - public BattleshipImporter(Battleship battleShip) { - super(battleShip); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } - - @Override - public boolean acceptsTextInput() { - return false; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - BattleshipBoard battleShipBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - battleShipBoard = new BattleshipBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - battleShipBoard = new BattleshipBoard(width, height); - } - } - - if (battleShipBoard == null) { - throw new InvalidFileFormatException("BattleShip Importer: " + "invalid board dimensions"); - } - - int width = battleShipBoard.getWidth(); - int height = battleShipBoard.getHeight(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - BattleshipCell cell = - (BattleshipCell) - puzzle.getFactory().importCell(elementDataList.item(i), battleShipBoard); - Point loc = cell.getLocation(); - if (cell.getData() != BattleshipType.getType(0)) { - cell.setModifiable(false); - cell.setGiven(true); - } - battleShipBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (battleShipBoard.getCell(x, y) == null) { - BattleshipCell cell = new BattleshipCell(BattleshipType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - battleShipBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("BattleShip Importer: " + "cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis2.hasAttribute("side")) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != battleShipBoard.getHeight() - || southClues.getLength() != battleShipBoard.getWidth()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " - + "there must be same number of clues as the dimension " - + "of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = BattleshipClue.colStringToColNum(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > battleShipBoard.getHeight()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "clue index out of bounds"); - } + public BattleshipImporter(Battleship battleShip) { + super(battleShip); + } - if (battleShipBoard.getEast().get(index - 1) != null) { - throw new InvalidFileFormatException("BattleShip Importer: " + "duplicate clue index"); - } - battleShipBoard - .getEast() - .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > battleShipBoard.getWidth()) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "clue index out of bounds"); - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - if (battleShipBoard.getSouth().get(index - 1) != null) { - throw new InvalidFileFormatException("BattleShip Importer: " + "duplicate clue index"); + @Override + public boolean acceptsTextInput() { + return false; + } + + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + BattleshipBoard battleShipBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + battleShipBoard = new BattleshipBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + battleShipBoard = new BattleshipBoard(width, height); + } + } + + if (battleShipBoard == null) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "invalid board dimensions"); + } + + int width = battleShipBoard.getWidth(); + int height = battleShipBoard.getHeight(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + BattleshipCell cell = + (BattleshipCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), battleShipBoard); + Point loc = cell.getLocation(); + if (cell.getData() != BattleshipType.getType(0)) { + cell.setModifiable(false); + cell.setGiven(true); + } + battleShipBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (battleShipBoard.getCell(x, y) == null) { + BattleshipCell cell = + new BattleshipCell(BattleshipType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + battleShipBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("BattleShip Importer: " + "cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis2.hasAttribute("side")) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != battleShipBoard.getHeight() + || southClues.getLength() != battleShipBoard.getWidth()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + + "there must be same number of clues as the dimension " + + "of the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = BattleshipClue.colStringToColNum(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > battleShipBoard.getHeight()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "clue index out of bounds"); + } + + if (battleShipBoard.getEast().get(index - 1) != null) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "duplicate clue index"); + } + battleShipBoard + .getEast() + .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > battleShipBoard.getWidth()) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "clue index out of bounds"); + } + + if (battleShipBoard.getSouth().get(index - 1) != null) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "duplicate clue index"); + } + battleShipBoard + .getSouth() + .set( + index - 1, + new BattleshipClue(value, index, BattleshipType.CLUE_SOUTH)); + } + + puzzle.setCurrentBoard(battleShipBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "BattleShip Importer: " + "unknown value where integer expected"); } - battleShipBoard - .getSouth() - .set(index - 1, new BattleshipClue(value, index, BattleshipType.CLUE_SOUTH)); - } - - puzzle.setCurrentBoard(battleShipBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "BattleShip Importer: " + "unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Battleship cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Battleship cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java index 2cee10469..0d505f43c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipType.java @@ -1,52 +1,52 @@ package edu.rpi.legup.puzzle.battleship; public enum BattleshipType { - UNKNOWN, - WATER, - SUBMARINE, - SHIP_UNKNOWN, - SHIP_TOP, - SHIP_RIGHT, - SHIP_BOTTOM, - SHIP_LEFT, - SHIP_MIDDLE, - CLUE_NORTH, - CLUE_EAST, - CLUE_SOUTH, - CLUE_WEST; + UNKNOWN, + WATER, + SUBMARINE, + SHIP_UNKNOWN, + SHIP_TOP, + SHIP_RIGHT, + SHIP_BOTTOM, + SHIP_LEFT, + SHIP_MIDDLE, + CLUE_NORTH, + CLUE_EAST, + CLUE_SOUTH, + CLUE_WEST; - public int value; + public int value; - BattleshipType() { - this.value = this.ordinal(); - } + BattleshipType() { + this.value = this.ordinal(); + } - /** - * Gets the enum of this BattleShipType - * - * @param value the integer value input - * @return enum equivalent BattleShipType of integer value - */ - public static BattleshipType getType(int value) { - BattleshipType[] vals = values(); - if (value >= 0 && value < vals.length) { - return vals[value]; + /** + * Gets the enum of this BattleShipType + * + * @param value the integer value input + * @return enum equivalent BattleShipType of integer value + */ + public static BattleshipType getType(int value) { + BattleshipType[] vals = values(); + if (value >= 0 && value < vals.length) { + return vals[value]; + } + return null; } - return null; - } - /** - * Checks if the type is a ship. - * - * @param type the {@link BattleshipType} to check - * @return true if the type is a ship, false otherwise - */ - public static boolean isShip(BattleshipType type) { - return type == SHIP_UNKNOWN - || type == SHIP_TOP - || type == SHIP_RIGHT - || type == SHIP_BOTTOM - || type == SHIP_LEFT - || type == SHIP_MIDDLE; - } + /** + * Checks if the type is a ship. + * + * @param type the {@link BattleshipType} to check + * @return true if the type is a ship, false otherwise + */ + public static boolean isShip(BattleshipType type) { + return type == SHIP_UNKNOWN + || type == SHIP_TOP + || type == SHIP_RIGHT + || type == SHIP_BOTTOM + || type == SHIP_LEFT + || type == SHIP_MIDDLE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java index b82828fb8..4095db54a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/BattleshipView.java @@ -7,22 +7,23 @@ public class BattleshipView extends GridBoardView { - public BattleshipView(BattleshipBoard board) { - super(new BoardController(), new BattleshipCellController(), board.getDimension()); + public BattleshipView(BattleshipBoard board) { + super(new BoardController(), new BattleshipCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) puzzleElement; - Point loc = cell.getLocation(); - BattleshipElementView elementView = new BattleshipElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) puzzleElement; + Point loc = cell.getLocation(); + BattleshipElementView elementView = new BattleshipElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); - } + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java index 41abeabe1..f1ecd6685 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/AdjacentShipsContradictionRule.java @@ -10,79 +10,79 @@ public class AdjacentShipsContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "No instance of the contradiction " + this.ruleName + " here"; + private final String NO_CONTRADICTION_MESSAGE = + "No instance of the contradiction " + this.ruleName + " here"; - public AdjacentShipsContradictionRule() { - super( - "BTSP-CONT-0001", - "Adjacent Ships", - "Cells next to the battleship must be water.", - "edu/rpi/legup/images/battleship/contradictions" + "/AdjacentShips.png"); - } + public AdjacentShipsContradictionRule() { + super( + "BTSP-CONT-0001", + "Adjacent Ships", + "Cells next to the battleship must be water.", + "edu/rpi/legup/images/battleship/contradictions" + "/AdjacentShips.png"); + } - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule. - * - * @param board board to check contradiction - * @param puzzleElement equivalent {@link PuzzleElement} - * @return null if the transition contains a contradiction at the specified {@link - * PuzzleElement}, otherwise return a no contradiction message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - BattleshipBoard bsBoard = (BattleshipBoard) board; - BattleshipCell cell = (BattleshipCell) bsBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule. + * + * @param board board to check contradiction + * @param puzzleElement equivalent {@link PuzzleElement} + * @return null if the transition contains a contradiction at the specified {@link + * PuzzleElement}, otherwise return a no contradiction message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + BattleshipBoard bsBoard = (BattleshipBoard) board; + BattleshipCell cell = (BattleshipCell) bsBoard.getPuzzleElement(puzzleElement); - // rule only applies to battleship cells - if (!BattleshipType.isShip(cell.getType())) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } + // rule only applies to battleship cells + if (!BattleshipType.isShip(cell.getType())) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } - // check orthogonally adjacent cells - List orthoAdjCells = bsBoard.getAdjOrthogonals(cell); + // check orthogonally adjacent cells + List orthoAdjCells = bsBoard.getAdjOrthogonals(cell); - BattleshipCell up = orthoAdjCells.get(0); - BattleshipCell right = orthoAdjCells.get(1); - BattleshipCell down = orthoAdjCells.get(2); - BattleshipCell left = orthoAdjCells.get(3); + BattleshipCell up = orthoAdjCells.get(0); + BattleshipCell right = orthoAdjCells.get(1); + BattleshipCell down = orthoAdjCells.get(2); + BattleshipCell left = orthoAdjCells.get(3); - boolean isVertical = - (up != null && BattleshipType.isShip(up.getData())) - || (down != null && BattleshipType.isShip(down.getData())); + boolean isVertical = + (up != null && BattleshipType.isShip(up.getData())) + || (down != null && BattleshipType.isShip(down.getData())); - boolean isHorizontal = - (left != null && BattleshipType.isShip(left.getData())) - || (right != null && BattleshipType.isShip(right.getData())); + boolean isHorizontal = + (left != null && BattleshipType.isShip(left.getData())) + || (right != null && BattleshipType.isShip(right.getData())); - // ships cannot be both vertical and horizontal - if (isVertical && isHorizontal) { - return null; - } + // ships cannot be both vertical and horizontal + if (isVertical && isHorizontal) { + return null; + } - // check diagonally adjacent cells - List diagAdjCells = bsBoard.getAdjDiagonals(cell); + // check diagonally adjacent cells + List diagAdjCells = bsBoard.getAdjDiagonals(cell); - BattleshipCell upRight = diagAdjCells.get(0); - BattleshipCell downRight = diagAdjCells.get(1); - BattleshipCell downLeft = diagAdjCells.get(2); - BattleshipCell upLeft = diagAdjCells.get(3); + BattleshipCell upRight = diagAdjCells.get(0); + BattleshipCell downRight = diagAdjCells.get(1); + BattleshipCell downLeft = diagAdjCells.get(2); + BattleshipCell upLeft = diagAdjCells.get(3); - // diagonally adjacent cells must be water - if (upRight != null && BattleshipType.isShip(upRight.getData())) { - return null; - } - if (downRight != null && BattleshipType.isShip(downRight.getData())) { - return null; - } - if (downLeft != null && BattleshipType.isShip(downLeft.getData())) { - return null; - } - if (upLeft != null && BattleshipType.isShip(upLeft.getData())) { - return null; - } + // diagonally adjacent cells must be water + if (upRight != null && BattleshipType.isShip(upRight.getData())) { + return null; + } + if (downRight != null && BattleshipType.isShip(downRight.getData())) { + return null; + } + if (downLeft != null && BattleshipType.isShip(downLeft.getData())) { + return null; + } + if (upLeft != null && BattleshipType.isShip(upLeft.getData())) { + return null; + } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java index ab9a88525..670a136a4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ContinueShipDirectRule.java @@ -8,37 +8,38 @@ public class ContinueShipDirectRule extends DirectRule { - public ContinueShipDirectRule() { - super( - "BTSP-BASC-0001", - "Continue Ship", - "", - "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); - } + public ContinueShipDirectRule() { + super( + "BTSP-BASC-0001", + "Continue Ship", + "", + "edu/rpi/legup/images/battleship/rules/ContinueShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should be overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should be overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java index c4f4432d7..9bc4065aa 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithShipsDirectRule.java @@ -14,94 +14,95 @@ public class FinishWithShipsDirectRule extends DirectRule { - public FinishWithShipsDirectRule() { - super( - "BTSP-BASC-0002", - "Finish with Ships", - "The number of undetermined squares is equal to the number " - + "of segments remaining for each clue.", - "edu/rpi/legup/images/battleship/rules/finishShip.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should be overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message. - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - BattleshipBoard initBoard = (BattleshipBoard) transition.getParents().get(0).getBoard(); - BattleshipCell initCell = (BattleshipCell) initBoard.getPuzzleElement(puzzleElement); - BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); - BattleshipCell finalCell = (BattleshipCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == BattleshipType.UNKNOWN - && BattleshipType.isShip(finalCell.getType()))) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; - } - - if (isForced(initBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() - + ": This cell is not forced to" - + "be a ship segment."; + public FinishWithShipsDirectRule() { + super( + "BTSP-BASC-0002", + "Finish with Ships", + "The number of undetermined squares is equal to the number " + + "of segments remaining for each clue.", + "edu/rpi/legup/images/battleship/rules/finishShip.png"); } - } - private boolean isForced(BattleshipBoard board, BattleshipCell cell) { - Point loc = cell.getLocation(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should be overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message. + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + BattleshipBoard initBoard = (BattleshipBoard) transition.getParents().get(0).getBoard(); + BattleshipCell initCell = (BattleshipCell) initBoard.getPuzzleElement(puzzleElement); + BattleshipBoard finalBoard = (BattleshipBoard) transition.getBoard(); + BattleshipCell finalCell = (BattleshipCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == BattleshipType.UNKNOWN + && BattleshipType.isShip(finalCell.getType()))) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a ship."; + } - // count the number of ship segments and unknowns in the row - List row = board.getRow(loc.y); - int rowCount = 0; - for (BattleshipCell c : row) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { - rowCount++; - } + if (isForced(initBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This cell is not forced to" + + "be a ship segment."; + } } - // count the number of ship segments and unknowns in the column - List col = board.getColumn(loc.x); - int colCount = 0; - for (BattleshipCell c : col) { - if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { - colCount++; - } - } + private boolean isForced(BattleshipBoard board, BattleshipCell cell) { + Point loc = cell.getLocation(); + + // count the number of ship segments and unknowns in the row + List row = board.getRow(loc.y); + int rowCount = 0; + for (BattleshipCell c : row) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { + rowCount++; + } + } - // compare the counts with the clues - BattleshipClue east = board.getEast().get(loc.y); - BattleshipClue south = board.getSouth().get(loc.x); + // count the number of ship segments and unknowns in the column + List col = board.getColumn(loc.x); + int colCount = 0; + for (BattleshipCell c : col) { + if (c.getType() == BattleshipType.SHIP_UNKNOWN || BattleshipType.isShip(c.getType())) { + colCount++; + } + } - return rowCount <= east.getData() && colCount <= south.getData(); - } + // compare the counts with the clues + BattleshipClue east = board.getEast().get(loc.y); + BattleshipClue south = board.getSouth().get(loc.x); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board. - * @return default board or null if this rule cannot be applied to this tree node. - */ - @Override - public Board getDefaultBoard(TreeNode node) { - BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); - for (PuzzleElement element : board.getPuzzleElements()) { - BattleshipCell cell = (BattleshipCell) element; - if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { - cell.setData(BattleshipType.SHIP_UNKNOWN); - board.addModifiedData(cell); - } + return rowCount <= east.getData() && colCount <= south.getData(); } - if (board.getModifiedData().isEmpty()) { - return null; - } else { - return board; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board. + * @return default board or null if this rule cannot be applied to this tree node. + */ + @Override + public Board getDefaultBoard(TreeNode node) { + BattleshipBoard board = (BattleshipBoard) node.getBoard().copy(); + for (PuzzleElement element : board.getPuzzleElements()) { + BattleshipCell cell = (BattleshipCell) element; + if (cell.getType() == BattleshipType.UNKNOWN && isForced(board, cell)) { + cell.setData(BattleshipType.SHIP_UNKNOWN); + board.addModifiedData(cell); + } + } + + if (board.getModifiedData().isEmpty()) { + return null; + } else { + return board; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java index 6f32b35a6..99e5925e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/FinishWithWaterDirectRule.java @@ -8,37 +8,38 @@ public class FinishWithWaterDirectRule extends DirectRule { - public FinishWithWaterDirectRule() { - super( - "BTSP-BASC-0003", - "Finish with Water", - "", - "edu/rpi/legup/images/battleship/rules/finishWater.png"); - } + public FinishWithWaterDirectRule() { + super( + "BTSP-BASC-0003", + "Finish with Water", + "", + "edu/rpi/legup/images/battleship/rules/finishWater.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java index 05ed95fbd..e8cfebb90 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/IncompleteShipContradictionRule.java @@ -6,25 +6,25 @@ public class IncompleteShipContradictionRule extends ContradictionRule { - public IncompleteShipContradictionRule() { - super( - "BTSP-CONT-0002", - "Incomplete Ship", - "", - "edu/rpi/legup/images/battleship/contradictions/IncompleteShip.png"); - } + public IncompleteShipContradictionRule() { + super( + "BTSP-CONT-0002", + "Incomplete Ship", + "", + "edu/rpi/legup/images/battleship/contradictions/IncompleteShip.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java index afc4f8fc0..93079fb71 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeCaseRule.java @@ -8,63 +8,63 @@ import java.util.List; public class SegmentTypeCaseRule extends CaseRule { - public SegmentTypeCaseRule() { - super( - "BTSP-CASE-0001", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/cases/SegmentType.png"); - } + public SegmentTypeCaseRule() { + super( + "BTSP-CASE-0001", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/cases/SegmentType.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java index f95625e5e..8576ef722 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SegmentTypeDirectRule.java @@ -8,37 +8,38 @@ public class SegmentTypeDirectRule extends DirectRule { - public SegmentTypeDirectRule() { - super( - "BTSP-BASC-0004", - "Segment Type", - "", - "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); - } + public SegmentTypeDirectRule() { + super( + "BTSP-BASC-0004", + "Segment Type", + "", + "edu/rpi/legup/images/battleship/rules/SegmentChoice.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java index 3033bafbd..da8f33cc2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipLocationCaseRule.java @@ -9,63 +9,63 @@ public class ShipLocationCaseRule extends CaseRule { - public ShipLocationCaseRule() { - super( - "BTSP-CASE-0002", - "Ship Location", - "", - "edu/rpi/legup/images/battleship/cases/ShipLocations.png"); - } + public ShipLocationCaseRule() { + super( + "BTSP-CASE-0002", + "Ship Location", + "", + "edu/rpi/legup/images/battleship/cases/ShipLocations.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java index 3696049eb..3c123d7c1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/ShipOrWaterCaseRule.java @@ -9,63 +9,63 @@ public class ShipOrWaterCaseRule extends CaseRule { - public ShipOrWaterCaseRule() { - super( - "BTSP-CASE-0003", - "Ship or Water", - "", - "edu/rpi/legup/images/battleship/cases/ShipOrWater.png"); - } + public ShipOrWaterCaseRule() { + super( + "BTSP-CASE-0003", + "Ship or Water", + "", + "edu/rpi/legup/images/battleship/cases/ShipOrWater.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java index 5a1821be0..d26c3ed29 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/SurroundShipDirectRule.java @@ -8,37 +8,38 @@ public class SurroundShipDirectRule extends DirectRule { - public SurroundShipDirectRule() { - super( - "BTSP-BASC-0005", - "Surround Ship", - "", - "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); - } + public SurroundShipDirectRule() { + super( + "BTSP-BASC-0005", + "Surround Ship", + "", + "edu/rpi/legup/images/battleship/rules/SurroundShip.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java index a3dbba9c4..d10e086d2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewInFleetContradictionRule.java @@ -6,25 +6,25 @@ public class TooFewInFleetContradictionRule extends ContradictionRule { - public TooFewInFleetContradictionRule() { - super( - "BTSP-CONT-0003", - "Too Few in Fleet", - "", - "edu/rpi/legup/images/battleship/contradictions/too_few_in_fleet.png"); - } + public TooFewInFleetContradictionRule() { + super( + "BTSP-CONT-0003", + "Too Few in Fleet", + "", + "edu/rpi/legup/images/battleship/contradictions/too_few_in_fleet.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java index b4814796d..382ba6e39 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooFewRowColContradictionRule.java @@ -6,25 +6,25 @@ public class TooFewRowColContradictionRule extends ContradictionRule { - public TooFewRowColContradictionRule() { - super( - "BTSP-CONT-0004", - "Too few in row/col", - "", - "edu/rpi/legup/images/battleship/contradictions/too_few_segments.png"); - } + public TooFewRowColContradictionRule() { + super( + "BTSP-CONT-0004", + "Too few in row/col", + "", + "edu/rpi/legup/images/battleship/contradictions/too_few_segments.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java index a375b63e2..d58701c0b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyInFleetContradictionRule.java @@ -6,25 +6,25 @@ public class TooManyInFleetContradictionRule extends ContradictionRule { - public TooManyInFleetContradictionRule() { - super( - "BTSP-CONT-0005", - "Too Many in Fleet", - "", - "edu/rpi/legup/images/battleship/contradictions/too_many_in_fleet.png"); - } + public TooManyInFleetContradictionRule() { + super( + "BTSP-CONT-0005", + "Too Many in Fleet", + "", + "edu/rpi/legup/images/battleship/contradictions/too_many_in_fleet.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java index abb72b5ca..27caa0524 100644 --- a/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java +++ b/src/main/java/edu/rpi/legup/puzzle/battleship/rules/TooManyRowColContradiction.java @@ -6,25 +6,25 @@ public class TooManyRowColContradiction extends ContradictionRule { - public TooManyRowColContradiction() { - super( - "BTSP-CONT-0006", - "Too Many row/col", - "", - "edu/rpi/legup/images/battleship/contradictions/too_many_segments.png"); - } + public TooManyRowColContradiction() { + super( + "BTSP-CONT-0006", + "Too Many row/col", + "", + "edu/rpi/legup/images/battleship/contradictions/too_many_segments.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java index 28d2a2790..79574caa6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/Fillapix.java @@ -6,60 +6,60 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Fillapix extends Puzzle { - /** Fillapix Constructor */ - public Fillapix() { - super(); + /** Fillapix Constructor */ + public Fillapix() { + super(); - this.name = "Fillapix"; + this.name = "Fillapix"; - this.importer = new FillapixImporter(this); - this.exporter = new FillapixExporter(this); + this.importer = new FillapixImporter(this); + this.exporter = new FillapixExporter(this); - this.factory = new FillapixCellFactory(); - } - - /** Initializes the game board */ - @Override - public void initializeView() { - boardView = new FillapixView((FillapixBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + this.factory = new FillapixCellFactory(); + } - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** Initializes the game board */ + @Override + public void initializeView() { + boardView = new FillapixView((FillapixBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - @Override - /** - * Determines if the given dimensions are valid for Fillapix - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Fillapix, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return super.isValidDimensions(rows, columns); - } + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - public boolean isBoardComplete(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(fillapixBoard) == null) { - return false; - } + @Override + /** + * Determines if the given dimensions are valid for Fillapix + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Fillapix, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return super.isValidDimensions(rows, columns); } - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN) { - return false; - } + + @Override + public boolean isBoardComplete(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(fillapixBoard) == null) { + return false; + } + } + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN) { + return false; + } + } + return true; } - return true; - } - @Override - public void onBoardChange(Board board) {} + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java index eaf408fcd..a6672bd4f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixBoard.java @@ -6,62 +6,62 @@ import java.util.logging.Logger; public class FillapixBoard extends GridBoard { - private static final Logger LOGGER = Logger.getLogger(FillapixBoard.class.getName()); + private static final Logger LOGGER = Logger.getLogger(FillapixBoard.class.getName()); - public FillapixBoard(int width, int height) { - super(width, height); - } - - public FillapixBoard(int size) { - this(size, size); - } - - public FillapixCell getCell(int x, int y) { - return (FillapixCell) super.getCell(x, y); - } - - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - @Override - public FillapixBoard copy() { - FillapixBoard copy = new FillapixBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + public FillapixBoard(int width, int height) { + super(width, height); } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + public FillapixBoard(int size) { + this(size, size); } - return copy; - } - /** - * Finds the number of cells that match the specified type around and on a particular cell - * - * @param cell the cell we're looking around - * @param type the CellState whether it's black, white, or unknown - * @return integer number of cells that match specified type - */ - public int getNumCells(FillapixCell cell, FillapixCellType type) { - Point loc = cell.getLocation(); + public FillapixCell getCell(int x, int y) { + return (FillapixCell) super.getCell(x, y); + } - int numCells = 0; - for (int i = -1; i < 2; i++) { - for (int j = -1; j < 2; j++) { - if (loc.x + i > dimension.width || loc.y + j > dimension.height) { - continue; + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + @Override + public FillapixBoard copy() { + FillapixBoard copy = new FillapixBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } } - FillapixCell c = getCell(loc.x + i, loc.y + j); - if (c != null && c.getType() == type) { - numCells++; + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); } - } + return copy; } - return numCells; - } + /** + * Finds the number of cells that match the specified type around and on a particular cell + * + * @param cell the cell we're looking around + * @param type the CellState whether it's black, white, or unknown + * @return integer number of cells that match specified type + */ + public int getNumCells(FillapixCell cell, FillapixCellType type) { + Point loc = cell.getLocation(); + + int numCells = 0; + for (int i = -1; i < 2; i++) { + for (int j = -1; j < 2; j++) { + if (loc.x + i > dimension.width || loc.y + j > dimension.height) { + continue; + } + FillapixCell c = getCell(loc.x + i, loc.y + j); + if (c != null && c.getType() == type) { + numCells++; + } + } + } + + return numCells; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java index 772006cc8..a9e5aa2df 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCell.java @@ -8,98 +8,98 @@ public class FillapixCell extends GridCell implements Comparable { - public static final int DEFAULT_VALUE = 10; + public static final int DEFAULT_VALUE = 10; - public FillapixCell(int value, Point location) { - super(value, location); - } + public FillapixCell(int value, Point location) { + super(value, location); + } - public int getNumber() { - int temp = (data % 100); - return temp == 10 ? -1 : temp; - } + public int getNumber() { + int temp = (data % 100); + return temp == 10 ? -1 : temp; + } - public void setNumber(int number) { - int temp = number == -1 ? 10 : number; - data = (data / 100) * 100 + temp; - } + public void setNumber(int number) { + int temp = number == -1 ? 10 : number; + data = (data / 100) * 100 + temp; + } - public FillapixCellType getType() { - switch (data / 100) { - case 0: - return FillapixCellType.UNKNOWN; - case 1: - return FillapixCellType.BLACK; - default: - return FillapixCellType.WHITE; + public FillapixCellType getType() { + switch (data / 100) { + case 0: + return FillapixCellType.UNKNOWN; + case 1: + return FillapixCellType.BLACK; + default: + return FillapixCellType.WHITE; + } } - } - public void setCellType(FillapixCellType type) { - data = type.value * 100 + (data % 100); - } + public void setCellType(FillapixCellType type) { + data = type.value * 100 + (data % 100); + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "FPIX-PLAC-0001": - this.setCellType(FillapixCellType.BLACK); - break; - case "FPIX-PLAC-0002": - this.setCellType(FillapixCellType.WHITE); - break; - case "FPIX-UNPL-0001": - int n = this.getNumber(); - switch (m.getButton()) { - case MouseEvent.BUTTON1: - n++; - break; - case MouseEvent.BUTTON3: - n--; - break; - } - if (n > 9) { - n = 0; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "FPIX-PLAC-0001": + this.setCellType(FillapixCellType.BLACK); + break; + case "FPIX-PLAC-0002": + this.setCellType(FillapixCellType.WHITE); + break; + case "FPIX-UNPL-0001": + int n = this.getNumber(); + switch (m.getButton()) { + case MouseEvent.BUTTON1: + n++; + break; + case MouseEvent.BUTTON3: + n--; + break; + } + if (n > 9) { + n = 0; + } + if (n < 0) { + n = 9; + } + this.setNumber(n); + break; + default: + this.setCellType(FillapixCellType.UNKNOWN); + this.data = -1; + break; } - if (n < 0) { - n = 9; - } - this.setNumber(n); - break; - default: - this.setCellType(FillapixCellType.UNKNOWN); - this.data = -1; - break; } - } - /** - * Performs a deep copy on the FillapixCell - * - * @return a new copy of the FillapixCell that is independent of this one - */ - @Override - public FillapixCell copy() { - FillapixCell cell = new FillapixCell(data, (Point) location.clone()); - cell.setIndex(index); - cell.setModifiable(isModifiable); - return cell; - } + /** + * Performs a deep copy on the FillapixCell + * + * @return a new copy of the FillapixCell that is independent of this one + */ + @Override + public FillapixCell copy() { + FillapixCell cell = new FillapixCell(data, (Point) location.clone()); + cell.setIndex(index); + cell.setModifiable(isModifiable); + return cell; + } - public boolean equals(FillapixCell otherCell) { - // return this.location.equals(otherCell.location) && this.index == otherCell.index - // && - // this.data == otherCell.data; - // return this.index == otherCell.index && this.data == otherCell.data; - // return this.index == otherCell.index; - return this.location.x == otherCell.location.x && this.location.y == otherCell.location.y; - } + public boolean equals(FillapixCell otherCell) { + // return this.location.equals(otherCell.location) && this.index == otherCell.index + // && + // this.data == otherCell.data; + // return this.index == otherCell.index && this.data == otherCell.data; + // return this.index == otherCell.index; + return this.location.x == otherCell.location.x && this.location.y == otherCell.location.y; + } - public int compareTo(FillapixCell otherCell) { - return this.index - otherCell.index; - } + public int compareTo(FillapixCell otherCell) { + return this.index - otherCell.index; + } - public int hashCode() { - return Objects.hash(this.index); - } + public int hashCode() { + return Objects.hash(this.index); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java index 45182c88f..f59c0df47 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellController.java @@ -5,44 +5,44 @@ import java.awt.event.MouseEvent; public class FillapixCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement puzzleElement) { - FillapixCell cell = (FillapixCell) puzzleElement; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getType() == FillapixCellType.UNKNOWN) { - cell.setCellType(FillapixCellType.BLACK); - } else { - if (cell.getType() == FillapixCellType.BLACK) { - cell.setCellType(FillapixCellType.WHITE); - } else { - if (cell.getType() == FillapixCellType.WHITE) { - cell.setCellType(FillapixCellType.UNKNOWN); + @Override + public void changeCell(MouseEvent e, PuzzleElement puzzleElement) { + FillapixCell cell = (FillapixCell) puzzleElement; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getType() == FillapixCellType.UNKNOWN) { + cell.setCellType(FillapixCellType.BLACK); + } else { + if (cell.getType() == FillapixCellType.BLACK) { + cell.setCellType(FillapixCellType.WHITE); + } else { + if (cell.getType() == FillapixCellType.WHITE) { + cell.setCellType(FillapixCellType.UNKNOWN); + } + } + } } - } - } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getType() == FillapixCellType.UNKNOWN) { - cell.setCellType(FillapixCellType.WHITE); } else { - if (cell.getType() == FillapixCellType.BLACK) { - cell.setCellType(FillapixCellType.UNKNOWN); - } else { - if (cell.getType() == FillapixCellType.WHITE) { - cell.setCellType(FillapixCellType.BLACK); + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getType() == FillapixCellType.UNKNOWN) { + cell.setCellType(FillapixCellType.WHITE); + } else { + if (cell.getType() == FillapixCellType.BLACK) { + cell.setCellType(FillapixCellType.UNKNOWN); + } else { + if (cell.getType() == FillapixCellType.WHITE) { + cell.setCellType(FillapixCellType.BLACK); + } + } + } } - } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java index 37b4130b2..9f689bc96 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellFactory.java @@ -10,65 +10,66 @@ import org.w3c.dom.Node; public class FillapixCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public FillapixCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Fillapix Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public FillapixCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Fillapix Factory: unknown puzzleElement puzzleElement"); + } - FillapixBoard fillapixBoard = (FillapixBoard) board; - int width = fillapixBoard.getWidth(); - int height = fillapixBoard.getHeight(); + FillapixBoard fillapixBoard = (FillapixBoard) board; + int width = fillapixBoard.getWidth(); + int height = fillapixBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Fillapix Factory: cell location out of bounds"); - } - if (value / 100 > 2 || value % 100 > 10) { - throw new InvalidFileFormatException("Fillapix Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "Fillapix Factory: cell location out of bounds"); + } + if (value / 100 > 2 || value % 100 > 10) { + throw new InvalidFileFormatException("Fillapix Factory: cell unknown value"); + } - FillapixCell cell = new FillapixCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Fillapix Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Fillapix Factory: could not find attribute(s)"); + FillapixCell cell = new FillapixCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Fillapix Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Fillapix Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - FillapixCell cell = (FillapixCell) puzzleElement; - Point loc = cell.getLocation(); + FillapixCell cell = (FillapixCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java index 659cebb1b..28a263467 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixCellType.java @@ -1,17 +1,17 @@ package edu.rpi.legup.puzzle.fillapix; public enum FillapixCellType { - UNKNOWN(0), - BLACK(1), - WHITE(2); + UNKNOWN(0), + BLACK(1), + WHITE(2); - public int value; + public int value; - FillapixCellType(int value) { - this.value = value; - } + FillapixCellType(int value) { + this.value = value; + } - public String toString() { - return super.toString().toLowerCase(); - } + public String toString() { + return super.toString().toLowerCase(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java index 97b864bc9..47465a522 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixElementView.java @@ -4,58 +4,59 @@ import java.awt.*; public class FillapixElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); - public FillapixElementView(FillapixCell cell) { - super(cell); - } + public FillapixElementView(FillapixCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public FillapixCell getPuzzleElement() { - return (FillapixCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public FillapixCell getPuzzleElement() { + return (FillapixCell) super.getPuzzleElement(); + } - /** - * Draws the fillapix puzzleElement to the screen - * - * @param graphics2D graphics object - */ - @Override - public void drawElement(Graphics2D graphics2D) { - FillapixCell cell = (FillapixCell) puzzleElement; - FillapixCellType type = cell.getType(); - graphics2D.setStroke(new BasicStroke(1)); - switch (type) { - case UNKNOWN: - graphics2D.setColor(GRAY_COLOR); - break; - case BLACK: + /** + * Draws the fillapix puzzleElement to the screen + * + * @param graphics2D graphics object + */ + @Override + public void drawElement(Graphics2D graphics2D) { + FillapixCell cell = (FillapixCell) puzzleElement; + FillapixCellType type = cell.getType(); + graphics2D.setStroke(new BasicStroke(1)); + switch (type) { + case UNKNOWN: + graphics2D.setColor(GRAY_COLOR); + break; + case BLACK: + graphics2D.setColor(BLACK_COLOR); + break; + default: + graphics2D.setColor(WHITE_COLOR); + break; + } + graphics2D.fillRect(location.x, location.y, size.width, size.height); + if (cell.getNumber() >= 0 && cell.getNumber() < 10) { + graphics2D.setColor(type == FillapixCellType.WHITE ? BLACK_COLOR : WHITE_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getNumber()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } graphics2D.setColor(BLACK_COLOR); - break; - default: - graphics2D.setColor(WHITE_COLOR); - break; - } - graphics2D.fillRect(location.x, location.y, size.width, size.height); - if (cell.getNumber() >= 0 && cell.getNumber() < 10) { - graphics2D.setColor(type == FillapixCellType.WHITE ? BLACK_COLOR : WHITE_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getNumber()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); + graphics2D.drawRect(location.x, location.y, size.width, size.height); } - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java index 1df8157cf..ffabd8762 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixExporter.java @@ -6,34 +6,34 @@ public class FillapixExporter extends PuzzleExporter { - public FillapixExporter(Fillapix fillapix) { - super(fillapix); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - FillapixBoard board; - if (puzzle.getTree() != null) { - board = (FillapixBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (FillapixBoard) puzzle.getBoardView().getBoard(); + public FillapixExporter(Fillapix fillapix) { + super(fillapix); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + FillapixBoard board; + if (puzzle.getTree() != null) { + board = (FillapixBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (FillapixBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) puzzleElement; - if (cell.getNumber() != -1 || cell.getType() != FillapixCellType.UNKNOWN) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) puzzleElement; + if (cell.getNumber() != -1 || cell.getType() != FillapixCellType.UNKNOWN) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java index 5877fd25b..d16bc8219 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixImporter.java @@ -8,110 +8,116 @@ import org.w3c.dom.NodeList; public class FillapixImporter extends PuzzleImporter { - public FillapixImporter(Fillapix fillapix) { - super(fillapix); - } + public FillapixImporter(Fillapix fillapix) { + super(fillapix); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be made - */ - @Override - public void initializeBoard(int rows, int columns) { - FillapixBoard fillapixBoard = new FillapixBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be made + */ + @Override + public void initializeBoard(int rows, int columns) { + FillapixBoard fillapixBoard = new FillapixBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - FillapixCell cell = new FillapixCell(FillapixCellType.UNKNOWN.value, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setNumber(FillapixCell.DEFAULT_VALUE); - cell.setModifiable(true); - fillapixBoard.setCell(x, y, cell); - } + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + FillapixCell cell = + new FillapixCell(FillapixCellType.UNKNOWN.value, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setNumber(FillapixCell.DEFAULT_VALUE); + cell.setModifiable(true); + fillapixBoard.setCell(x, y, cell); + } + } + puzzle.setCurrentBoard(fillapixBoard); } - puzzle.setCurrentBoard(fillapixBoard); - } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Fillapix Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Fillapix Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Fillapix Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Fillapix Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - FillapixBoard fillapixBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - fillapixBoard = new FillapixBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - fillapixBoard = new FillapixBoard(width, height); - } - } + FillapixBoard fillapixBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + fillapixBoard = new FillapixBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + fillapixBoard = new FillapixBoard(width, height); + } + } - if (fillapixBoard == null) { - throw new InvalidFileFormatException("Fillapix Importer: invalid board dimensions"); - } + if (fillapixBoard == null) { + throw new InvalidFileFormatException("Fillapix Importer: invalid board dimensions"); + } - int width = fillapixBoard.getWidth(); - int height = fillapixBoard.getHeight(); + int width = fillapixBoard.getWidth(); + int height = fillapixBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - FillapixCell cell = - (FillapixCell) puzzle.getFactory().importCell(elementDataList.item(i), fillapixBoard); - Point loc = cell.getLocation(); - cell.setModifiable(true); - cell.setGiven(true); - fillapixBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + FillapixCell cell = + (FillapixCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), fillapixBoard); + Point loc = cell.getLocation(); + cell.setModifiable(true); + cell.setGiven(true); + fillapixBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (fillapixBoard.getCell(x, y) == null) { - FillapixCell cell = new FillapixCell(FillapixCell.DEFAULT_VALUE, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - fillapixBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (fillapixBoard.getCell(x, y) == null) { + FillapixCell cell = + new FillapixCell(FillapixCell.DEFAULT_VALUE, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + fillapixBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(fillapixBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Fillapix Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(fillapixBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Fillapix Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Fillapix cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Fillapix cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java index 6eeb4bd25..571a0c7f7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixUtilities.java @@ -8,231 +8,234 @@ public class FillapixUtilities { - public static boolean isForcedBlack(FillapixBoard board, FillapixCell cell) { - TooFewBlackCellsContradictionRule tooManyBlackCells = new TooFewBlackCellsContradictionRule(); - FillapixBoard whiteCaseBoard = board.copy(); - FillapixCell whiteCell = (FillapixCell) whiteCaseBoard.getPuzzleElement(cell); - whiteCell.setCellType(FillapixCellType.WHITE); - ArrayList adjCells = getAdjacentCells(whiteCaseBoard, whiteCell); - for (FillapixCell adjCell : adjCells) { - if (tooManyBlackCells.checkContradictionAt(whiteCaseBoard, adjCell) == null) { - return true; - } - } - return false; - } - - public static boolean isForcedWhite(FillapixBoard board, FillapixCell cell) { - TooManyBlackCellsContradictionRule tooManyBlackCells = new TooManyBlackCellsContradictionRule(); - FillapixBoard blackCaseBoard = board.copy(); - FillapixCell blackCell = (FillapixCell) blackCaseBoard.getPuzzleElement(cell); - blackCell.setCellType(FillapixCellType.BLACK); - ArrayList adjCells = getAdjacentCells(blackCaseBoard, blackCell); - for (FillapixCell adjCell : adjCells) { - if (tooManyBlackCells.checkContradictionAt(blackCaseBoard, adjCell) == null) { - return true; - } + public static boolean isForcedBlack(FillapixBoard board, FillapixCell cell) { + TooFewBlackCellsContradictionRule tooManyBlackCells = + new TooFewBlackCellsContradictionRule(); + FillapixBoard whiteCaseBoard = board.copy(); + FillapixCell whiteCell = (FillapixCell) whiteCaseBoard.getPuzzleElement(cell); + whiteCell.setCellType(FillapixCellType.WHITE); + ArrayList adjCells = getAdjacentCells(whiteCaseBoard, whiteCell); + for (FillapixCell adjCell : adjCells) { + if (tooManyBlackCells.checkContradictionAt(whiteCaseBoard, adjCell) == null) { + return true; + } + } + return false; } - return false; - } - public static boolean isComplete(FillapixBoard board, FillapixCell cell) { - int cellNum = cell.getNumber(); - int cellTouchBlack = 0; - ArrayList adjCells = getAdjacentCells(board, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - cellTouchBlack++; - } + public static boolean isForcedWhite(FillapixBoard board, FillapixCell cell) { + TooManyBlackCellsContradictionRule tooManyBlackCells = + new TooManyBlackCellsContradictionRule(); + FillapixBoard blackCaseBoard = board.copy(); + FillapixCell blackCell = (FillapixCell) blackCaseBoard.getPuzzleElement(cell); + blackCell.setCellType(FillapixCellType.BLACK); + ArrayList adjCells = getAdjacentCells(blackCaseBoard, blackCell); + for (FillapixCell adjCell : adjCells) { + if (tooManyBlackCells.checkContradictionAt(blackCaseBoard, adjCell) == null) { + return true; + } + } + return false; } - return cellNum == cellTouchBlack; - } - public static boolean hasEmptyAdjacent(FillapixBoard board, FillapixCell cell) { - ArrayList adjCells = getAdjacentCells(board, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - return true; - } + public static boolean isComplete(FillapixBoard board, FillapixCell cell) { + int cellNum = cell.getNumber(); + int cellTouchBlack = 0; + ArrayList adjCells = getAdjacentCells(board, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + cellTouchBlack++; + } + } + return cellNum == cellTouchBlack; } - return false; - } - /** Gets all cells adjacent to a specific cell. The cell itself will be included. */ - public static ArrayList getAdjacentCells(FillapixBoard board, FillapixCell cell) { - ArrayList adjCells = new ArrayList(); - Point cellLoc = cell.getLocation(); - for (int i = -1; i <= 1; i++) { - for (int j = -1; j <= 1; j++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; + public static boolean hasEmptyAdjacent(FillapixBoard board, FillapixCell cell) { + ArrayList adjCells = getAdjacentCells(board, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + return true; + } } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } + return false; } - return adjCells; - } - /** - * Gets all cells that are contained in the square defined as having 'distance' cells between the - * center and the outer wall. For example, distance = 1: - * - *

|X|X|X|X|X| - * - *

|X| | | |X| - * - *

|X| |O| |X| - * - *

|X| | | |X| - * - *

|X|X|X|X|X| - * - *

O is 'cell', and all 'X' will be returned in the ArrayList - */ - public static ArrayList getCellsAtDistance( - FillapixBoard board, FillapixCell cell, int distance) { - ArrayList adjCells = new ArrayList(); - Point cellLoc = cell.getLocation(); - int i = 0, j = 0; - // top line - for (i = cellLoc.x - (distance), j = cellLoc.y - (distance + 1); - i <= cellLoc.x + (distance + 1); - i++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // right line - for (i = cellLoc.x + (distance + 1), j = cellLoc.y - (distance); - j <= cellLoc.y + (distance + 1); - j++) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // bottom line - for (i = cellLoc.x + (distance), j = cellLoc.y + (distance + 1); - i <= cellLoc.x - (distance + 1); - i--) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); - } - // left line - for (i = cellLoc.x - (distance + 1), j = cellLoc.y + (distance); - j <= cellLoc.y - (distance + 1); - j--) { - if (cellLoc.getX() + i < 0 - || cellLoc.y + j < 0 - || cellLoc.x + i >= board.getWidth() - || cellLoc.y + j >= board.getHeight()) { - continue; - } - FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); - if (adjCell == null) { - continue; - } - adjCells.add(adjCell); + /** Gets all cells adjacent to a specific cell. The cell itself will be included. */ + public static ArrayList getAdjacentCells(FillapixBoard board, FillapixCell cell) { + ArrayList adjCells = new ArrayList(); + Point cellLoc = cell.getLocation(); + for (int i = -1; i <= 1; i++) { + for (int j = -1; j <= 1; j++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + } + return adjCells; } - return adjCells; - } + /** + * Gets all cells that are contained in the square defined as having 'distance' cells between + * the center and the outer wall. For example, distance = 1: + * + *

|X|X|X|X|X| + * + *

|X| | | |X| + * + *

|X| |O| |X| + * + *

|X| | | |X| + * + *

|X|X|X|X|X| + * + *

O is 'cell', and all 'X' will be returned in the ArrayList + */ + public static ArrayList getCellsAtDistance( + FillapixBoard board, FillapixCell cell, int distance) { + ArrayList adjCells = new ArrayList(); + Point cellLoc = cell.getLocation(); + int i = 0, j = 0; + // top line + for (i = cellLoc.x - (distance), j = cellLoc.y - (distance + 1); + i <= cellLoc.x + (distance + 1); + i++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // right line + for (i = cellLoc.x + (distance + 1), j = cellLoc.y - (distance); + j <= cellLoc.y + (distance + 1); + j++) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // bottom line + for (i = cellLoc.x + (distance), j = cellLoc.y + (distance + 1); + i <= cellLoc.x - (distance + 1); + i--) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } + // left line + for (i = cellLoc.x - (distance + 1), j = cellLoc.y + (distance); + j <= cellLoc.y - (distance + 1); + j--) { + if (cellLoc.getX() + i < 0 + || cellLoc.y + j < 0 + || cellLoc.x + i >= board.getWidth() + || cellLoc.y + j >= board.getHeight()) { + continue; + } + FillapixCell adjCell = board.getCell(cellLoc.x + i, cellLoc.y + j); + if (adjCell == null) { + continue; + } + adjCells.add(adjCell); + } - /** - * Finds all possible combinations of chosenNumObj items can be chosen from - * totalNumObj total items. For example, if 1 item is chosen from 2 possible items, the - * combinations are: - * - *

[ [true,false], [false,true] ]
- * - * @param totalNumItems the total number of items that can possibly be chosen - * @param chosenNumItems the number of items to be chosen - * @return an ArrayList of Boolean arrays. Each index in the ArrayList represents a distinct - * combination. Each Boolean array will be totalNumItems long and each index will - * be true if the corresponding item is included in that combination, and - * false otherwise. - */ - public static ArrayList getCombinations(int chosenNumItems, int totalNumItems) { - ArrayList combinations = new ArrayList(); + return adjCells; + } - // calculate all combinations - boolean[] array = new boolean[totalNumItems]; - recurseCombinations(combinations, 0, chosenNumItems, 0, totalNumItems, array); + /** + * Finds all possible combinations of chosenNumObj items can be chosen from + * totalNumObj total items. For example, if 1 item is chosen from 2 possible items, the + * combinations are: + * + *
[ [true,false], [false,true] ]
+ * + * @param totalNumItems the total number of items that can possibly be chosen + * @param chosenNumItems the number of items to be chosen + * @return an ArrayList of Boolean arrays. Each index in the ArrayList represents a distinct + * combination. Each Boolean array will be totalNumItems long and each index + * will be true if the corresponding item is included in that combination, and + * + * false otherwise. + */ + public static ArrayList getCombinations(int chosenNumItems, int totalNumItems) { + ArrayList combinations = new ArrayList(); - return combinations; - } + // calculate all combinations + boolean[] array = new boolean[totalNumItems]; + recurseCombinations(combinations, 0, chosenNumItems, 0, totalNumItems, array); - private static void recurseCombinations( - ArrayList result, - int curIndex, - int maxBlack, - int numBlack, - int len, - boolean[] workingArray) { - if (curIndex == len) { - // complete, but not valid solution - if (numBlack != maxBlack) { - return; - } - // complete and valid solution - result.add(workingArray.clone()); - return; - } - // there is no chance of completing the required number of solutions, so quit - if (len - curIndex < maxBlack - numBlack) { - return; + return combinations; } - if (numBlack < maxBlack) { - workingArray[curIndex] = true; - recurseCombinations(result, curIndex + 1, maxBlack, numBlack + 1, len, workingArray); + private static void recurseCombinations( + ArrayList result, + int curIndex, + int maxBlack, + int numBlack, + int len, + boolean[] workingArray) { + if (curIndex == len) { + // complete, but not valid solution + if (numBlack != maxBlack) { + return; + } + // complete and valid solution + result.add(workingArray.clone()); + return; + } + // there is no chance of completing the required number of solutions, so quit + if (len - curIndex < maxBlack - numBlack) { + return; + } + + if (numBlack < maxBlack) { + workingArray[curIndex] = true; + recurseCombinations(result, curIndex + 1, maxBlack, numBlack + 1, len, workingArray); + } + workingArray[curIndex] = false; + recurseCombinations(result, curIndex + 1, maxBlack, numBlack, len, workingArray); } - workingArray[curIndex] = false; - recurseCombinations(result, curIndex + 1, maxBlack, numBlack, len, workingArray); - } - public static boolean checkBoardForContradiction(FillapixBoard board) { - ContradictionRule tooManyBlack = new TooManyBlackCellsContradictionRule(); - ContradictionRule tooManyWhite = new TooFewBlackCellsContradictionRule(); - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - if (tooManyBlack.checkContradictionAt(board, board.getCell(i, j)) == null - || tooManyWhite.checkContradictionAt(board, board.getCell(i, j)) == null) { - return true; + public static boolean checkBoardForContradiction(FillapixBoard board) { + ContradictionRule tooManyBlack = new TooManyBlackCellsContradictionRule(); + ContradictionRule tooManyWhite = new TooFewBlackCellsContradictionRule(); + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + if (tooManyBlack.checkContradictionAt(board, board.getCell(i, j)) == null + || tooManyWhite.checkContradictionAt(board, board.getCell(i, j)) == null) { + return true; + } + } } - } + return false; } - return false; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java index eea7c7a4d..55332e47d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/FillapixView.java @@ -6,17 +6,18 @@ import java.awt.*; public class FillapixView extends GridBoardView { - public FillapixView(FillapixBoard board) { - super(new BoardController(), new FillapixCellController(), board.getDimension()); + public FillapixView(FillapixBoard board) { + super(new BoardController(), new FillapixCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) puzzleElement; - Point loc = cell.getLocation(); - FillapixElementView elementView = new FillapixElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) puzzleElement; + Point loc = cell.getLocation(); + FillapixElementView elementView = new FillapixElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java index ce4ba520c..1d7c038a3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/BlackTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BlackTile extends PlaceableElement { - public BlackTile() { - super( - "FPIX-PLAC-0001", - "Black Tile", - "The black tile", - "edu/rpi/legup/images/fillapix/tiles/BlackTile.png"); - } + public BlackTile() { + super( + "FPIX-PLAC-0001", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/fillapix/tiles/BlackTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java index 0b76b1b57..e869aeaf9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/NumberTile.java @@ -3,28 +3,28 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super( - "FPIX-UNPL-0001", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/fillapix/tiles/NumberTile.png"); - object_num = 0; - } + public NumberTile() { + super( + "FPIX-UNPL-0001", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/fillapix/tiles/NumberTile.png"); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java index 25104eb60..6778c1758 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "FPIX-UNPL-0002", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/fillapix/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "FPIX-UNPL-0002", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/fillapix/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java index 935c9bc1b..67065a7e9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/elements/WhiteTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class WhiteTile extends PlaceableElement { - public WhiteTile() { - super( - "FPIX-PLAC-0002", - "White Tile", - "The white tile", - "edu/rpi/legup/images/fillapix/tiles/WhiteTile.png"); - } + public WhiteTile() { + super( + "FPIX-PLAC-0002", + "White Tile", + "The white tile", + "edu/rpi/legup/images/fillapix/tiles/WhiteTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java index 02699327e..860a6c011 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/BlackOrWhiteCaseRule.java @@ -12,81 +12,81 @@ import java.util.List; public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "FPIX-CASE-0001", - "Black or White", - "Each cell is either black or white.", - "edu/rpi/legup/images/fillapix/cases/BlackOrWhite.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); - fillapixBoard.setModifiable(false); - for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) data; - if (cell.getType() == FillapixCellType.UNKNOWN) { - caseBoard.addPickableElement(data); - } + public BlackOrWhiteCaseRule() { + super( + "FPIX-CASE-0001", + "Black or White", + "Each cell is either black or white.", + "edu/rpi/legup/images/fillapix/cases/BlackOrWhite.png"); } - return caseBoard; - } - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); + @Override + public CaseBoard getCaseBoard(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); + fillapixBoard.setModifiable(false); + for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) data; + if (cell.getType() == FillapixCellType.UNKNOWN) { + caseBoard.addPickableElement(data); + } + } + return caseBoard; + } - Board case1 = board.copy(); - FillapixCell cell1 = (FillapixCell) case1.getPuzzleElement(puzzleElement); - cell1.setCellType(FillapixCellType.BLACK); - case1.addModifiedData(cell1); - cases.add(case1); + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); - Board case2 = board.copy(); - FillapixCell cell2 = (FillapixCell) case2.getPuzzleElement(puzzleElement); - cell2.setCellType(FillapixCellType.WHITE); - case2.addModifiedData(cell2); - cases.add(case2); + Board case1 = board.copy(); + FillapixCell cell1 = (FillapixCell) case1.getPuzzleElement(puzzleElement); + cell1.setCellType(FillapixCellType.BLACK); + case1.addModifiedData(cell1); + cases.add(case1); - return cases; - } + Board case2 = board.copy(); + FillapixCell cell2 = (FillapixCell) case2.getPuzzleElement(puzzleElement); + cell2.setCellType(FillapixCellType.WHITE); + case2.addModifiedData(cell2); + cases.add(case2); - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + return cases; } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - FillapixCell mod1 = (FillapixCell) case1.getBoard().getModifiedData().iterator().next(); - FillapixCell mod2 = (FillapixCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - if (!((mod1.getType() == FillapixCellType.BLACK && mod2.getType() == FillapixCellType.WHITE) - || (mod2.getType() == FillapixCellType.BLACK - && mod1.getType() == FillapixCellType.WHITE))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty cell and a lit cell."; - } + FillapixCell mod1 = (FillapixCell) case1.getBoard().getModifiedData().iterator().next(); + FillapixCell mod2 = (FillapixCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } + + if (!((mod1.getType() == FillapixCellType.BLACK && mod2.getType() == FillapixCellType.WHITE) + || (mod2.getType() == FillapixCellType.BLACK + && mod1.getType() == FillapixCellType.WHITE))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty cell and a lit cell."; + } - return null; - } + return null; + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java index da0ccb057..ccc002f46 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithBlackDirectRule.java @@ -11,55 +11,56 @@ import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; public class FinishWithBlackDirectRule extends DirectRule { - public FinishWithBlackDirectRule() { - super( - "FPIX-BASC-0001", - "Finish with Black", - "The remaining unknowns around and on a cell must be black to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); - } + public FinishWithBlackDirectRule() { + super( + "FPIX-BASC-0001", + "Finish with Black", + "The remaining unknowns around and on a cell must be black to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithBlack.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == FillapixCellType.UNKNOWN - && cell.getType() == FillapixCellType.BLACK)) { - return super.getInvalidUseOfRuleMessage() - + ": This cell must be black to be applicable with this rule."; - } + if (!(parentCell.getType() == FillapixCellType.UNKNOWN + && cell.getType() == FillapixCellType.BLACK)) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must be black to be applicable with this rule."; + } - if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; + if (FillapixUtilities.isForcedBlack(parentBoard, cell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be black"; + } } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN - && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.BLACK); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } else { - return fillapixBoard; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN + && FillapixUtilities.isForcedBlack((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.BLACK); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } else { + return fillapixBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java index 0d8423c0c..6735fb8f4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/FinishWithWhiteDirectRule.java @@ -11,55 +11,56 @@ import edu.rpi.legup.puzzle.fillapix.FillapixUtilities; public class FinishWithWhiteDirectRule extends DirectRule { - public FinishWithWhiteDirectRule() { - super( - "FPIX-BASC-0002", - "Finish with White", - "The remaining unknowns around and on a cell must be white to satisfy the number", - "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); - } + public FinishWithWhiteDirectRule() { + super( + "FPIX-BASC-0002", + "Finish with White", + "The remaining unknowns around and on a cell must be white to satisfy the number", + "edu/rpi/legup/images/fillapix/rules/FinishWithWhite.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == FillapixCellType.UNKNOWN - && cell.getType() == FillapixCellType.WHITE)) { - return super.getInvalidUseOfRuleMessage() - + ": This cell must be white to be applicable with this rule"; - } + if (!(parentCell.getType() == FillapixCellType.UNKNOWN + && cell.getType() == FillapixCellType.WHITE)) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must be white to be applicable with this rule"; + } - if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; + if (FillapixUtilities.isForcedWhite(parentBoard, cell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be white"; + } } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); - for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) element; - if (cell.getType() == FillapixCellType.UNKNOWN - && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { - cell.setCellType(FillapixCellType.WHITE); - fillapixBoard.addModifiedData(cell); - } - } - if (fillapixBoard.getModifiedData().isEmpty()) { - return null; - } else { - return fillapixBoard; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + FillapixBoard fillapixBoard = (FillapixBoard) node.getBoard().copy(); + for (PuzzleElement element : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) element; + if (cell.getType() == FillapixCellType.UNKNOWN + && FillapixUtilities.isForcedWhite((FillapixBoard) node.getBoard(), cell)) { + cell.setCellType(FillapixCellType.WHITE); + fillapixBoard.addModifiedData(cell); + } + } + if (fillapixBoard.getModifiedData().isEmpty()) { + return null; + } else { + return fillapixBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java index 9ce860c33..e91931bd4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/MirrorDirectRule.java @@ -15,89 +15,93 @@ import java.util.List; public class MirrorDirectRule extends DirectRule { - public MirrorDirectRule() { - super( - "FPIX-BASC-0003", - "Mirror", - "Two adjacent clues with the same value must have the same number of black squares" - + " in their unshared regions", - "edu/rpi/legup/images/fillapix/rules/Mirror.png"); - } + public MirrorDirectRule() { + super( + "FPIX-BASC-0003", + "Mirror", + "Two adjacent clues with the same value must have the same number of black squares" + + " in their unshared regions", + "edu/rpi/legup/images/fillapix/rules/Mirror.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = + (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // find all cells adjacent to cell that are numbered - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - ArrayList adjNums = new ArrayList(); - for (int i = 0; i < adjCells.size(); i++) { - if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { - adjNums.add(adjCells.get(i)); - } - } - // the numbered cells must be next to another numbered cell of the same value - Iterator itr = adjNums.iterator(); - while (itr.hasNext()) { - FillapixCell adjNum = itr.next(); - adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); - boolean found = false; - for (FillapixCell adjCell : adjCells) { - if (adjCell.getNumber() == adjNum.getNumber() && adjCell.getIndex() != adjNum.getIndex()) { - found = true; + // find all cells adjacent to cell that are numbered + ArrayList adjCells = + FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + ArrayList adjNums = new ArrayList(); + for (int i = 0; i < adjCells.size(); i++) { + if ((adjCells.get(i)).getNumber() >= 0 && adjCells.get(i).getNumber() < 10) { + adjNums.add(adjCells.get(i)); + } + } + // the numbered cells must be next to another numbered cell of the same value + Iterator itr = adjNums.iterator(); + while (itr.hasNext()) { + FillapixCell adjNum = itr.next(); + adjCells = FillapixUtilities.getAdjacentCells(parentBoard, adjNum); + boolean found = false; + for (FillapixCell adjCell : adjCells) { + if (adjCell.getNumber() == adjNum.getNumber() + && adjCell.getIndex() != adjNum.getIndex()) { + found = true; + } + } + if (!found) { + itr.remove(); + } } - } - if (!found) { - itr.remove(); - } - } - // change the color of the parentCell, and check if there exists a valid board - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); - } - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjNum : adjNums) { - caseBoards = completeClue.getCases(parentBoard, adjNum); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; + // change the color of the parentCell, and check if there exists a valid board + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjNum : adjNums) { + caseBoards = completeClue.getCases(parentBoard, adjNum); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } } - } - if (found) { - return null; - } - } - return super.getInvalidUseOfRuleMessage(); - } + return super.getInvalidUseOfRuleMessage(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java index e38ec65e1..71a85a95b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/NonTouchingSharedDirectRule.java @@ -15,86 +15,89 @@ import java.util.List; public class NonTouchingSharedDirectRule extends DirectRule { - public NonTouchingSharedDirectRule() { - super( - "FPIX-BASC-0005", - "NonTouching Shared", - "Clues with shared cells have the same difference in black cells in their unshared" - + " regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } + public NonTouchingSharedDirectRule() { + super( + "FPIX-BASC-0005", + "NonTouching Shared", + "Clues with shared cells have the same difference in black cells in their unshared" + + " regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = + (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell not - * touching, but sharing cells */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - ArrayList sharingCells = - FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); - boolean found = false; - for (FillapixCell sharingCell : sharingCells) { - if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { - found = true; + // get all adjCells that have a number + ArrayList adjCells = + FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell not + * touching, but sharing cells */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + ArrayList sharingCells = + FillapixUtilities.getCellsAtDistance(parentBoard, parentCell, 1); + boolean found = false; + for (FillapixCell sharingCell : sharingCells) { + if (sharingCell.getNumber() >= 0 && sharingCell.getNumber() < 10) { + found = true; + } + } + if (!found) { + itr.remove(); + } } - } - if (!found) { - itr.remove(); - } - } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } } - } - if (found) { - return null; - } - } - return super.getInvalidUseOfRuleMessage(); - } + return super.getInvalidUseOfRuleMessage(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java index fdfe2e765..7db833f76 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/SatisfyClueCaseRule.java @@ -18,215 +18,216 @@ import java.util.TreeSet; public class SatisfyClueCaseRule extends CaseRule { - public SatisfyClueCaseRule() { - super( - "FPIX-CASE-0002", - "Satisfy Clue", - "Each clue must touch that number of squares.", - "edu/rpi/legup/images/fillapix/cases/SatisfyClue.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); - fillapixBoard.setModifiable(false); - for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { - FillapixCell cell = (FillapixCell) data; - if (cell.getNumber() >= 0 - && cell.getNumber() <= 9 - && FillapixUtilities.hasEmptyAdjacent(fillapixBoard, cell)) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; - } - - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - - // get value of cell - FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellMaxBlack = cell.getNumber(); - if (cellMaxBlack < 0 || cellMaxBlack > 9) { // cell is not valid cell - return null; + public SatisfyClueCaseRule() { + super( + "FPIX-CASE-0002", + "Satisfy Clue", + "Each clue must touch that number of squares.", + "edu/rpi/legup/images/fillapix/cases/SatisfyClue.png"); } - // find number of black & empty squares - int cellNumBlack = 0; - int cellNumEmpty = 0; - ArrayList emptyCells = new ArrayList(); - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - cellNumBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - cellNumEmpty++; - emptyCells.add(adjCell); - } - } - // no cases if no empty or if too many black already - if (cellNumBlack > cellMaxBlack || cellNumEmpty == 0) { - return cases; + @Override + public CaseBoard getCaseBoard(Board board) { + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(fillapixBoard, this); + fillapixBoard.setModifiable(false); + for (PuzzleElement data : fillapixBoard.getPuzzleElements()) { + FillapixCell cell = (FillapixCell) data; + if (cell.getNumber() >= 0 + && cell.getNumber() <= 9 + && FillapixUtilities.hasEmptyAdjacent(fillapixBoard, cell)) { + caseBoard.addPickableElement(data); + } + } + return caseBoard; } - // generate all cases as boolean expressions - ArrayList combinations; - combinations = FillapixUtilities.getCombinations(cellMaxBlack - cellNumBlack, cellNumEmpty); - - for (int i = 0; i < combinations.size(); i++) { - Board case_ = board.copy(); - for (int j = 0; j < combinations.get(i).length; j++) { - cell = (FillapixCell) case_.getPuzzleElement(emptyCells.get(j)); - if (combinations.get(i)[j]) { - cell.setCellType(FillapixCellType.BLACK); - } else { - cell.setCellType(FillapixCellType.WHITE); + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + + // get value of cell + FillapixBoard fillapixBoard = (FillapixBoard) board.copy(); + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + int cellMaxBlack = cell.getNumber(); + if (cellMaxBlack < 0 || cellMaxBlack > 9) { // cell is not valid cell + return null; } - case_.addModifiedData(cell); - } - cases.add(case_); - } - return cases; - } - - @Override - public String checkRuleRaw(TreeTransition transition) { - TreeNode parent = transition.getParents().get(0); - List childTransitions = parent.getChildren(); - - /* - * In order for the transition to be valid, it can only be applied to - * one cell, thus: - * * there must be modified cells - * * all modified cells must share at least one common adjacent - * cell - * * all modified cells must fit within a 3X3 square - * * the center of one of the possible squaress must be a cell - * with a number - * * that cells possible combinations must match the transitions - * If all the above is verified, then the transition is valid - */ - - /* ensure there are modified cells */ - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() <= 0) { - return super.getInvalidUseOfRuleMessage(); - } + // find number of black & empty squares + int cellNumBlack = 0; + int cellNumEmpty = 0; + ArrayList emptyCells = new ArrayList(); + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + cellNumBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + cellNumEmpty++; + emptyCells.add(adjCell); + } + } + // no cases if no empty or if too many black already + if (cellNumBlack > cellMaxBlack || cellNumEmpty == 0) { + return cases; + } - /* ensure modified cells occur within a 3X3 square */ - int minVertLoc = Integer.MAX_VALUE, maxVertLoc = Integer.MIN_VALUE; - int minHorzLoc = Integer.MAX_VALUE, maxHorzLoc = Integer.MIN_VALUE; - for (PuzzleElement modCell : modCells) { - Point loc = ((FillapixCell) modCell).getLocation(); - if (loc.x < minHorzLoc) { - minHorzLoc = loc.x; - } - if (loc.x > maxHorzLoc) { - maxHorzLoc = loc.x; - } - if (loc.y < minVertLoc) { - minVertLoc = loc.y; - } - if (loc.y > maxVertLoc) { - maxVertLoc = loc.y; - } - } - if (maxVertLoc - minVertLoc > 3 || maxHorzLoc - minHorzLoc > 3) { - return super.getInvalidUseOfRuleMessage(); - } + // generate all cases as boolean expressions + ArrayList combinations; + combinations = FillapixUtilities.getCombinations(cellMaxBlack - cellNumBlack, cellNumEmpty); + + for (int i = 0; i < combinations.size(); i++) { + Board case_ = board.copy(); + for (int j = 0; j < combinations.get(i).length; j++) { + cell = (FillapixCell) case_.getPuzzleElement(emptyCells.get(j)); + if (combinations.get(i)[j]) { + cell.setCellType(FillapixCellType.BLACK); + } else { + cell.setCellType(FillapixCellType.WHITE); + } + case_.addModifiedData(cell); + } + cases.add(case_); + } - /* get the center of all possible 3X3 squares, - * and collect all that have numbers */ - FillapixBoard board = (FillapixBoard) transition.getParents().get(0).getBoard(); - Set possibleCenters = new TreeSet(); - possibleCenters.addAll( - FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCells.iterator().next())); - for (PuzzleElement modCell : modCells) { - possibleCenters.retainAll( - (FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCell))); - } - // removing all elements without a valid number - possibleCenters.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - if (possibleCenters.isEmpty()) { - return super.getInvalidUseOfRuleMessage(); + return cases; } - /* Now go through the remaining centers, and check if their combinations - * match the transitions */ - for (FillapixCell possibleCenter : possibleCenters) { - int numBlack = 0; - int numEmpty = 0; - int maxBlack = possibleCenter.getNumber(); - for (FillapixCell adjCell : FillapixUtilities.getAdjacentCells(board, possibleCenter)) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - numEmpty++; + @Override + public String checkRuleRaw(TreeTransition transition) { + TreeNode parent = transition.getParents().get(0); + List childTransitions = parent.getChildren(); + + /* + * In order for the transition to be valid, it can only be applied to + * one cell, thus: + * * there must be modified cells + * * all modified cells must share at least one common adjacent + * cell + * * all modified cells must fit within a 3X3 square + * * the center of one of the possible squaress must be a cell + * with a number + * * that cells possible combinations must match the transitions + * If all the above is verified, then the transition is valid + */ + + /* ensure there are modified cells */ + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() <= 0) { + return super.getInvalidUseOfRuleMessage(); } - } - if (numEmpty <= 0 || numBlack > maxBlack) { - // this cell has no cases (no empty) or is already broken (too many black) - continue; - } - - ArrayList combinations = - FillapixUtilities.getCombinations(maxBlack - numBlack, numEmpty); - if (combinations.size() != childTransitions.size()) { - // not this center because combinations do not match transitions - continue; - } - boolean quitEarly = false; - for (TreeTransition trans : childTransitions) { - /* convert the transition board into boolean format, so that it - * can be compared to the combinations */ - FillapixBoard transBoard = (FillapixBoard) trans.getBoard(); - ArrayList transModCells = new ArrayList(); + + /* ensure modified cells occur within a 3X3 square */ + int minVertLoc = Integer.MAX_VALUE, maxVertLoc = Integer.MIN_VALUE; + int minHorzLoc = Integer.MAX_VALUE, maxHorzLoc = Integer.MIN_VALUE; for (PuzzleElement modCell : modCells) { - transModCells.add((FillapixCell) transBoard.getPuzzleElement(modCell)); + Point loc = ((FillapixCell) modCell).getLocation(); + if (loc.x < minHorzLoc) { + minHorzLoc = loc.x; + } + if (loc.x > maxHorzLoc) { + maxHorzLoc = loc.x; + } + if (loc.y < minVertLoc) { + minVertLoc = loc.y; + } + if (loc.y > maxVertLoc) { + maxVertLoc = loc.y; + } } - - boolean[] translatedModCells = new boolean[transModCells.size()]; - for (int i = 0; i < transModCells.size(); i++) { - if (transModCells.get(i).getType() == FillapixCellType.BLACK) { - translatedModCells[i] = true; - } else { - translatedModCells[i] = false; - } + if (maxVertLoc - minVertLoc > 3 || maxHorzLoc - minHorzLoc > 3) { + return super.getInvalidUseOfRuleMessage(); } - // try to find the above state in the combinations, remove if found - boolean removed = false; - for (boolean[] combination : combinations) { - if (Arrays.equals(combination, translatedModCells)) { - combinations.remove(combination); - removed = true; - break; - } + /* get the center of all possible 3X3 squares, + * and collect all that have numbers */ + FillapixBoard board = (FillapixBoard) transition.getParents().get(0).getBoard(); + Set possibleCenters = new TreeSet(); + possibleCenters.addAll( + FillapixUtilities.getAdjacentCells( + board, (FillapixCell) modCells.iterator().next())); + for (PuzzleElement modCell : modCells) { + possibleCenters.retainAll( + (FillapixUtilities.getAdjacentCells(board, (FillapixCell) modCell))); } - // if combination not found, no need to check further, just quit - if (!removed) { - quitEarly = true; - break; + // removing all elements without a valid number + possibleCenters.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + if (possibleCenters.isEmpty()) { + return super.getInvalidUseOfRuleMessage(); } - } - /* we found a center that is valid */ - if (combinations.isEmpty() && !quitEarly) { - return null; - } - } + /* Now go through the remaining centers, and check if their combinations + * match the transitions */ + for (FillapixCell possibleCenter : possibleCenters) { + int numBlack = 0; + int numEmpty = 0; + int maxBlack = possibleCenter.getNumber(); + for (FillapixCell adjCell : FillapixUtilities.getAdjacentCells(board, possibleCenter)) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + numEmpty++; + } + } + if (numEmpty <= 0 || numBlack > maxBlack) { + // this cell has no cases (no empty) or is already broken (too many black) + continue; + } + + ArrayList combinations = + FillapixUtilities.getCombinations(maxBlack - numBlack, numEmpty); + if (combinations.size() != childTransitions.size()) { + // not this center because combinations do not match transitions + continue; + } + boolean quitEarly = false; + for (TreeTransition trans : childTransitions) { + /* convert the transition board into boolean format, so that it + * can be compared to the combinations */ + FillapixBoard transBoard = (FillapixBoard) trans.getBoard(); + ArrayList transModCells = new ArrayList(); + for (PuzzleElement modCell : modCells) { + transModCells.add((FillapixCell) transBoard.getPuzzleElement(modCell)); + } + + boolean[] translatedModCells = new boolean[transModCells.size()]; + for (int i = 0; i < transModCells.size(); i++) { + if (transModCells.get(i).getType() == FillapixCellType.BLACK) { + translatedModCells[i] = true; + } else { + translatedModCells[i] = false; + } + } + + // try to find the above state in the combinations, remove if found + boolean removed = false; + for (boolean[] combination : combinations) { + if (Arrays.equals(combination, translatedModCells)) { + combinations.remove(combination); + removed = true; + break; + } + } + // if combination not found, no need to check further, just quit + if (!removed) { + quitEarly = true; + break; + } + } + + /* we found a center that is valid */ + if (combinations.isEmpty() && !quitEarly) { + return null; + } + } - return super.getInvalidUseOfRuleMessage(); - } + return super.getInvalidUseOfRuleMessage(); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java index 09d031421..df5954d63 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooFewBlackCellsContradictionRule.java @@ -11,46 +11,46 @@ public class TooFewBlackCellsContradictionRule extends ContradictionRule { - public TooFewBlackCellsContradictionRule() { - super( - "FPIX-CONT-0001", - "Too Few Black Cells", - "There may not be fewer black cells than the number.", - "edu/rpi/legup/images/fillapix/contradictions/TooFewBlackCells.png"); - } + public TooFewBlackCellsContradictionRule() { + super( + "FPIX-CONT-0001", + "Too Few Black Cells", + "There may not be fewer black cells than the number.", + "edu/rpi/legup/images/fillapix/contradictions/TooFewBlackCells.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellNum = cell.getNumber(); - if (cellNum < 0 || cellNum >= 10) { - return super.getNoContradictionMessage(); - } - int numBlack = 0, numEmpty = 0; - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - if (adjCell.getType() == FillapixCellType.UNKNOWN) { - numEmpty++; - } - } - if (numBlack + numEmpty < cellNum) { - return null; - } + int cellNum = cell.getNumber(); + if (cellNum < 0 || cellNum >= 10) { + return super.getNoContradictionMessage(); + } + int numBlack = 0, numEmpty = 0; + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } + if (adjCell.getType() == FillapixCellType.UNKNOWN) { + numEmpty++; + } + } + if (numBlack + numEmpty < cellNum) { + return null; + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java index 9184212bb..38b47c972 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TooManyBlackCellsContradictionRule.java @@ -11,43 +11,43 @@ public class TooManyBlackCellsContradictionRule extends ContradictionRule { - public TooManyBlackCellsContradictionRule() { - super( - "FPIX-CONT-0002", - "Too Many Black Cells", - "There may not be more black cells than the number", - "edu/rpi/legup/images/fillapix/contradictions/TooManyBlackCells.png"); - } + public TooManyBlackCellsContradictionRule() { + super( + "FPIX-CONT-0002", + "Too Many Black Cells", + "There may not be more black cells than the number", + "edu/rpi/legup/images/fillapix/contradictions/TooManyBlackCells.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - FillapixBoard fillapixBoard = (FillapixBoard) board; - FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + FillapixBoard fillapixBoard = (FillapixBoard) board; + FillapixCell cell = (FillapixCell) fillapixBoard.getPuzzleElement(puzzleElement); - int cellNum = cell.getNumber(); - if (cellNum < 0 || cellNum >= 10) { - return super.getNoContradictionMessage(); - } - int numBlack = 0; - ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); - for (FillapixCell adjCell : adjCells) { - if (adjCell.getType() == FillapixCellType.BLACK) { - numBlack++; - } - } - if (numBlack > cellNum) { - return null; - } + int cellNum = cell.getNumber(); + if (cellNum < 0 || cellNum >= 10) { + return super.getNoContradictionMessage(); + } + int numBlack = 0; + ArrayList adjCells = FillapixUtilities.getAdjacentCells(fillapixBoard, cell); + for (FillapixCell adjCell : adjCells) { + if (adjCell.getType() == FillapixCellType.BLACK) { + numBlack++; + } + } + if (numBlack > cellNum) { + return null; + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java index 78caf6a56..72e2def47 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingCornersDirectRule.java @@ -15,96 +15,99 @@ import java.util.List; public class TouchingCornersDirectRule extends DirectRule { - public TouchingCornersDirectRule() { - super( - "FPIX-BASC-0005", - "Touching Corners", - "Clues with touching corners have the same difference in black cells in their" - + " unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); - } + public TouchingCornersDirectRule() { + super( + "FPIX-BASC-0005", + "Touching Corners", + "Clues with touching corners have the same difference in black cells in their" + + " unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingCorners.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = + (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } + + // get all adjCells that have a number + ArrayList adjCells = + FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell diagonally + * adjacent to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + FillapixCell adjCell = itr.next(); - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell diagonally - * adjacent to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - FillapixCell adjCell = itr.next(); + boolean found = false; + ArrayList adjAdjCells = + FillapixUtilities.getAdjacentCells(parentBoard, adjCell); + for (FillapixCell adjAdjCell : adjAdjCells) { + if (adjAdjCell.getLocation().x != adjCell.getLocation().x + && adjAdjCell.getLocation().y != adjCell.getLocation().y + && adjAdjCell.getNumber() >= 0 + && adjAdjCell.getNumber() < 10 + && adjAdjCell.getIndex() != parentCell.getIndex()) { + // adjAdjCell is diagonally adjacent to adjCell && it has a + // number && it is not parentCell + found = true; + } + } - boolean found = false; - ArrayList adjAdjCells = - FillapixUtilities.getAdjacentCells(parentBoard, adjCell); - for (FillapixCell adjAdjCell : adjAdjCells) { - if (adjAdjCell.getLocation().x != adjCell.getLocation().x - && adjAdjCell.getLocation().y != adjCell.getLocation().y - && adjAdjCell.getNumber() >= 0 - && adjAdjCell.getNumber() < 10 - && adjAdjCell.getIndex() != parentCell.getIndex()) { - // adjAdjCell is diagonally adjacent to adjCell && it has a - // number && it is not parentCell - found = true; + // does not qualify for this rule + if (!found) { + itr.remove(); + } } - } - // does not qualify for this rule - if (!found) { - itr.remove(); - } - } + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } + } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); + return super.getInvalidUseOfRuleMessage(); } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { return null; - } } - - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java index c64202245..281dd5392 100644 --- a/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/fillapix/rules/TouchingSidesDirectRule.java @@ -15,109 +15,112 @@ import java.util.List; public class TouchingSidesDirectRule extends DirectRule { - public TouchingSidesDirectRule() { - super( - "FPIX-BASC-0004", - "Touching Sides", - "Clues with touching sides have the same difference in black cells in their" - + " unshared regions as the difference in their numbers", - "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); - } + public TouchingSidesDirectRule() { + super( + "FPIX-BASC-0004", + "Touching Sides", + "Clues with touching sides have the same difference in black cells in their" + + " unshared regions as the difference in their numbers", + "edu/rpi/legup/images/fillapix/rules/TouchingSides.png"); + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - FillapixBoard board = (FillapixBoard) transition.getBoard(); - FillapixBoard parentBoard = (FillapixBoard) transition.getParents().get(0).getBoard().copy(); - FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); - FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + FillapixBoard board = (FillapixBoard) transition.getBoard(); + FillapixBoard parentBoard = + (FillapixBoard) transition.getParents().get(0).getBoard().copy(); + FillapixCell cell = (FillapixCell) board.getPuzzleElement(puzzleElement); + FillapixCell parentCell = (FillapixCell) parentBoard.getPuzzleElement(puzzleElement); - // cell has to have been empty before - if (parentCell.getType() != FillapixCellType.UNKNOWN) { - return super.getInvalidUseOfRuleMessage(); - } + // cell has to have been empty before + if (parentCell.getType() != FillapixCellType.UNKNOWN) { + return super.getInvalidUseOfRuleMessage(); + } - // parentBoard cannot have any contradictions - if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { - return super.getInvalidUseOfRuleMessage(); - } + // parentBoard cannot have any contradictions + if (FillapixUtilities.checkBoardForContradiction(parentBoard)) { + return super.getInvalidUseOfRuleMessage(); + } + + // get all adjCells that have a number + ArrayList adjCells = + FillapixUtilities.getAdjacentCells(parentBoard, parentCell); + adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); + /* remove any number cell that does not have another number cell adjacent + * to it on the opposite side of the modified cell */ + Iterator itr = adjCells.iterator(); + while (itr.hasNext()) { + // calculate x and y offset of adjCell from cell + FillapixCell adjCell = itr.next(); + int xOffset = adjCell.getLocation().x - cell.getLocation().x; + int yOffset = adjCell.getLocation().y - cell.getLocation().y; - // get all adjCells that have a number - ArrayList adjCells = FillapixUtilities.getAdjacentCells(parentBoard, parentCell); - adjCells.removeIf(x -> x.getNumber() < 0 || x.getNumber() >= 10); - /* remove any number cell that does not have another number cell adjacent - * to it on the opposite side of the modified cell */ - Iterator itr = adjCells.iterator(); - while (itr.hasNext()) { - // calculate x and y offset of adjCell from cell - FillapixCell adjCell = itr.next(); - int xOffset = adjCell.getLocation().x - cell.getLocation().x; - int yOffset = adjCell.getLocation().y - cell.getLocation().y; + boolean found = false; + // check vertically for numbered cell in opposite direction of cell + if (adjCell.getLocation().x + xOffset >= 0 + && adjCell.getLocation().x < parentBoard.getWidth()) { + int adjNum = + parentBoard + .getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y) + .getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; + } + } + // check horizontally for numbered cell in opposite direction of cell + if (adjCell.getLocation().y + yOffset >= 0 + && adjCell.getLocation().y < parentBoard.getHeight()) { + int adjNum = + parentBoard + .getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset) + .getNumber(); + if (adjNum >= 0 && adjNum < 10) { + found = true; + } + } - boolean found = false; - // check vertically for numbered cell in opposite direction of cell - if (adjCell.getLocation().x + xOffset >= 0 - && adjCell.getLocation().x < parentBoard.getWidth()) { - int adjNum = - parentBoard - .getCell(adjCell.getLocation().x + xOffset, adjCell.getLocation().y) - .getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; + // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, + // then adjCell is not valid, so should be removed + if (!found) { + itr.remove(); + } } - } - // check horizontally for numbered cell in opposite direction of cell - if (adjCell.getLocation().y + yOffset >= 0 - && adjCell.getLocation().y < parentBoard.getHeight()) { - int adjNum = - parentBoard - .getCell(adjCell.getLocation().x, adjCell.getLocation().y + yOffset) - .getNumber(); - if (adjNum >= 0 && adjNum < 10) { - found = true; + + // change the cell to the opposite color + if (cell.getType() == FillapixCellType.BLACK) { + parentCell.setCellType(FillapixCellType.WHITE); + } else { + parentCell.setCellType(FillapixCellType.BLACK); + } + // check for some contradiction in all cases + parentBoard.addModifiedData(parentCell); + CaseRule completeClue = new SatisfyClueCaseRule(); + List caseBoards; + for (FillapixCell adjCell : adjCells) { + caseBoards = completeClue.getCases(parentBoard, adjCell); + boolean found = true; + for (Board b : caseBoards) { + if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { + found = false; + } + } + if (found) { + return null; + } } - } - // if no horizontally or vertically adjacent cell on opposite side of 'cell' has number, - // then adjCell is not valid, so should be removed - if (!found) { - itr.remove(); - } + return super.getInvalidUseOfRuleMessage(); } - // change the cell to the opposite color - if (cell.getType() == FillapixCellType.BLACK) { - parentCell.setCellType(FillapixCellType.WHITE); - } else { - parentCell.setCellType(FillapixCellType.BLACK); - } - // check for some contradiction in all cases - parentBoard.addModifiedData(parentCell); - CaseRule completeClue = new SatisfyClueCaseRule(); - List caseBoards; - for (FillapixCell adjCell : adjCells) { - caseBoards = completeClue.getCases(parentBoard, adjCell); - boolean found = true; - for (Board b : caseBoards) { - if (!FillapixUtilities.checkBoardForContradiction((FillapixBoard) b)) { - found = false; - } - } - if (found) { + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { return null; - } } - - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java index 119362a88..afe3dd652 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/Heyawake.java @@ -5,63 +5,63 @@ public class Heyawake extends Puzzle { - public Heyawake() { - super(); + public Heyawake() { + super(); - this.name = "Heyawake"; + this.name = "Heyawake"; - this.factory = new HeyawakeFactory(); + this.factory = new HeyawakeFactory(); - this.exporter = new HeyawakeExporter(this); - this.importer = new HeyawakeImporter(this); - } + this.exporter = new HeyawakeExporter(this); + this.importer = new HeyawakeImporter(this); + } - /** Initializes the view. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new HeyawakeView((HeyawakeBoard) currentBoard); - } + /** Initializes the view. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new HeyawakeView((HeyawakeBoard) currentBoard); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for HeyAwake - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for HeyAwake, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for HeyAwake + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for HeyAwake, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java index 2dfe35138..cedb3a91b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeBoard.java @@ -10,46 +10,46 @@ public class HeyawakeBoard extends GridBoard { - private Map> regions; - - public HeyawakeBoard(int width, int height) { - super(width, height); - this.regions = new HashMap<>(); - } - - public HeyawakeBoard(int size) { - this(size, size); - } - - @Override - public HeyawakeCell getCell(int x, int y) { - return (HeyawakeCell) super.getCell(x, y); - } - - public List getRegion(int regionIndex) { - return this.regions.get(regionIndex); - } - - public Map> getRegions() { - return this.regions; - } - - @Override - public HeyawakeBoard copy() { - HeyawakeBoard copy = new HeyawakeBoard(dimension.width, dimension.height); - for (List region : regions.values()) { - List newCpy = new ArrayList<>(); - for (HeyawakeCell cell : region) { - Point point = cell.getLocation(); - HeyawakeCell cellCpy = cell.copy(); - copy.setCell(point.x, point.y, cellCpy); - newCpy.add(cellCpy); - } - copy.regions.put(region.get(0).getRegionIndex(), newCpy); + private Map> regions; + + public HeyawakeBoard(int width, int height) { + super(width, height); + this.regions = new HashMap<>(); + } + + public HeyawakeBoard(int size) { + this(size, size); + } + + @Override + public HeyawakeCell getCell(int x, int y) { + return (HeyawakeCell) super.getCell(x, y); } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + public List getRegion(int regionIndex) { + return this.regions.get(regionIndex); + } + + public Map> getRegions() { + return this.regions; + } + + @Override + public HeyawakeBoard copy() { + HeyawakeBoard copy = new HeyawakeBoard(dimension.width, dimension.height); + for (List region : regions.values()) { + List newCpy = new ArrayList<>(); + for (HeyawakeCell cell : region) { + Point point = cell.getLocation(); + HeyawakeCell cellCpy = cell.copy(); + copy.setCell(point.x, point.y, cellCpy); + newCpy.add(cellCpy); + } + copy.regions.put(region.get(0).getRegionIndex(), newCpy); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; } - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java index e75271355..480e2e39b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeCell.java @@ -5,23 +5,23 @@ public class HeyawakeCell extends GridCell { - private int regionIndex; + private int regionIndex; - public HeyawakeCell(int valueInt, Point location, int regionIndex) { - super(valueInt, location); - this.regionIndex = regionIndex; - } + public HeyawakeCell(int valueInt, Point location, int regionIndex) { + super(valueInt, location); + this.regionIndex = regionIndex; + } - public int getRegionIndex() { - return this.regionIndex; - } + public int getRegionIndex() { + return this.regionIndex; + } - @Override - public HeyawakeCell copy() { - HeyawakeCell copy = new HeyawakeCell(data, (Point) location.clone(), regionIndex); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public HeyawakeCell copy() { + HeyawakeCell copy = new HeyawakeCell(data, (Point) location.clone(), regionIndex); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java index f1ca1c79e..d30159856 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeElementView.java @@ -5,41 +5,42 @@ public class HeyawakeElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); - - public HeyawakeElementView(HeyawakeCell cell) { - super(cell); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public HeyawakeCell getPuzzleElement() { - return (HeyawakeCell) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - - if (cell.getData() >= 0) { - graphics2D.setColor(BLACK_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); + + public HeyawakeElementView(HeyawakeCell cell) { + super(cell); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public HeyawakeCell getPuzzleElement() { + return (HeyawakeCell) super.getPuzzleElement(); + } + + @Override + public void drawElement(Graphics2D graphics2D) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + + if (cell.getData() >= 0) { + graphics2D.setColor(BLACK_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java index 0856bf0de..4470d77be 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeExporter.java @@ -6,34 +6,34 @@ public class HeyawakeExporter extends PuzzleExporter { - public HeyawakeExporter(Heyawake heyawake) { - super(heyawake); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - HeyawakeBoard board; - if (puzzle.getTree() != null) { - board = (HeyawakeBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (HeyawakeBoard) puzzle.getBoardView().getBoard(); + public HeyawakeExporter(Heyawake heyawake) { + super(heyawake); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + HeyawakeBoard board; + if (puzzle.getTree() != null) { + board = (HeyawakeBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (HeyawakeBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java index f6853d75f..8ecf24135 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeFactory.java @@ -10,68 +10,69 @@ import org.w3c.dom.Node; public class HeyawakeFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public HeyawakeCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Heyawake Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public HeyawakeCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Heyawake Factory: unknown puzzleElement puzzleElement"); + } - HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; - int width = heyawakeBoard.getWidth(); - int height = heyawakeBoard.getHeight(); + HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; + int width = heyawakeBoard.getWidth(); + int height = heyawakeBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - int regionIndex = Integer.valueOf(attributeList.getNamedItem("region").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Heyawake Factory: cell location out of bounds"); - } - if (value < -4 || value > 4) { - throw new InvalidFileFormatException("Heyawake Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + int regionIndex = Integer.valueOf(attributeList.getNamedItem("region").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "Heyawake Factory: cell location out of bounds"); + } + if (value < -4 || value > 4) { + throw new InvalidFileFormatException("Heyawake Factory: cell unknown value"); + } - HeyawakeCell cell = new HeyawakeCell(value, new Point(x, y), regionIndex); - cell.setIndex(y * height + x); - heyawakeBoard.getRegions(); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Heyawake Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Heyawake Factory: could not find attribute(s)"); + HeyawakeCell cell = new HeyawakeCell(value, new Point(x, y), regionIndex); + cell.setIndex(y * height + x); + heyawakeBoard.getRegions(); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Heyawake Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Heyawake Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - Point loc = cell.getLocation(); + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); - cellElement.setAttribute("region", String.valueOf(cell.getRegionIndex())); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("region", String.valueOf(cell.getRegionIndex())); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java index f85a0b46d..6bbabd54d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeImporter.java @@ -9,99 +9,103 @@ public class HeyawakeImporter extends PuzzleImporter { - public HeyawakeImporter(Heyawake heyawake) { - super(heyawake); - } + public HeyawakeImporter(Heyawake heyawake) { + super(heyawake); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Heyawake Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Heyawake Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Heyawake Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Heyawake Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - HeyawakeBoard heyawakeBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - heyawakeBoard = new HeyawakeBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - heyawakeBoard = new HeyawakeBoard(width, height); - } - } + HeyawakeBoard heyawakeBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + heyawakeBoard = new HeyawakeBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + heyawakeBoard = new HeyawakeBoard(width, height); + } + } - if (heyawakeBoard == null) { - throw new InvalidFileFormatException("Heyawake Importer: invalid board dimensions"); - } + if (heyawakeBoard == null) { + throw new InvalidFileFormatException("Heyawake Importer: invalid board dimensions"); + } - int width = heyawakeBoard.getWidth(); - int height = heyawakeBoard.getHeight(); + int width = heyawakeBoard.getWidth(); + int height = heyawakeBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - HeyawakeCell cell = - (HeyawakeCell) puzzle.getFactory().importCell(elementDataList.item(i), heyawakeBoard); - Point loc = cell.getLocation(); - if (cell.getData() != -2) { - cell.setModifiable(false); - cell.setGiven(true); - } - heyawakeBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + HeyawakeCell cell = + (HeyawakeCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), heyawakeBoard); + Point loc = cell.getLocation(); + if (cell.getData() != -2) { + cell.setModifiable(false); + cell.setGiven(true); + } + heyawakeBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (heyawakeBoard.getCell(x, y) == null) { - HeyawakeCell cell = new HeyawakeCell(0, new Point(x, y), -1); - cell.setIndex(y * height + x); - cell.setModifiable(false); - heyawakeBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (heyawakeBoard.getCell(x, y) == null) { + HeyawakeCell cell = new HeyawakeCell(0, new Point(x, y), -1); + cell.setIndex(y * height + x); + cell.setModifiable(false); + heyawakeBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(heyawakeBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Heyawake Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(heyawakeBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Heyawake Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Hey Awake cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Hey Awake cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java index 0c349ca87..fba5f0eb7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/HeyawakeView.java @@ -11,43 +11,44 @@ public class HeyawakeView extends GridBoardView { - private Map regionsBoundaries; - - public HeyawakeView(HeyawakeBoard board) { - super(new BoardController(), new HeyawakeController(), board.getDimension()); - - this.regionsBoundaries = new HashMap<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - HeyawakeCell cell = (HeyawakeCell) puzzleElement; - Point loc = cell.getLocation(); - HeyawakeElementView elementView = new HeyawakeElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); - - int regionIndex = cell.getRegionIndex(); - if (regionsBoundaries.get(regionIndex) == null) { - regionsBoundaries.put(regionIndex, new Area(elementView.getBounds())); - } else { - regionsBoundaries.get(regionIndex).add(new Area(elementView.getBounds())); - } + private Map regionsBoundaries; + + public HeyawakeView(HeyawakeBoard board) { + super(new BoardController(), new HeyawakeController(), board.getDimension()); + + this.regionsBoundaries = new HashMap<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + HeyawakeCell cell = (HeyawakeCell) puzzleElement; + Point loc = cell.getLocation(); + HeyawakeElementView elementView = new HeyawakeElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + + int regionIndex = cell.getRegionIndex(); + if (regionsBoundaries.get(regionIndex) == null) { + regionsBoundaries.put(regionIndex, new Area(elementView.getBounds())); + } else { + regionsBoundaries.get(regionIndex).add(new Area(elementView.getBounds())); + } + } } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; + @Override + public void drawBoard(Graphics2D graphics2D) { + HeyawakeBoard heyawakeBoard = (HeyawakeBoard) board; - for (ElementView elementView : elementViews) { - elementView.draw(graphics2D); - } + for (ElementView elementView : elementViews) { + elementView.draw(graphics2D); + } - graphics2D.setColor(Color.BLACK); - graphics2D.setStroke(new BasicStroke(3)); - for (Area s : regionsBoundaries.values()) { - graphics2D.draw(s); + graphics2D.setColor(Color.BLACK); + graphics2D.setStroke(new BasicStroke(3)); + for (Area s : regionsBoundaries.values()) { + graphics2D.draw(s); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java index 1a46e5265..88d293f5e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/AdjacentBlacksContradictionRule.java @@ -6,25 +6,25 @@ public class AdjacentBlacksContradictionRule extends ContradictionRule { - public AdjacentBlacksContradictionRule() { - super( - "HEYA-CONT-0001", - "Adjacent Blacks", - "", - "edu/rpi/legup/images/heyawake/contradictions/adjacentBlacks.png"); - } + public AdjacentBlacksContradictionRule() { + super( + "HEYA-CONT-0001", + "Adjacent Blacks", + "", + "edu/rpi/legup/images/heyawake/contradictions/adjacentBlacks.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java index 882372372..251be46ee 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackOrWhiteCaseRule.java @@ -9,63 +9,63 @@ public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "HEYA-CASE-0001", - "Black or White", - "", - "edu/rpi/legup/images/heyawake/cases/BlackOrWhite.png"); - } + public BlackOrWhiteCaseRule() { + super( + "HEYA-CASE-0001", + "Black or White", + "", + "edu/rpi/legup/images/heyawake/cases/BlackOrWhite.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java index d687569ff..1fc3d0776 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BlackPathDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class BlackPathDirectRule { - public BlackPathDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public BlackPathDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java index 033bce643..41d950378 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/BottleNeckDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class BottleNeckDirectRule { - public BottleNeckDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public BottleNeckDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java index 8fe0f66e5..aee1ae4bf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomBlackDirectRule.java @@ -8,37 +8,38 @@ public class FillRoomBlackDirectRule extends DirectRule { - public FillRoomBlackDirectRule() { - super( - "HEYA-BASC-0003", - "Fill Room Black", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); - } + public FillRoomBlackDirectRule() { + super( + "HEYA-BASC-0003", + "Fill Room Black", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java index 95473aa9c..c4609b239 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/FillRoomWhiteDirectRule.java @@ -8,37 +8,38 @@ public class FillRoomWhiteDirectRule extends DirectRule { - public FillRoomWhiteDirectRule() { - super( - "HEYA-BASC-0004", - "Fill Room White", - "", - "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); - } + public FillRoomWhiteDirectRule() { + super( + "HEYA-BASC-0004", + "Fill Room White", + "", + "edu/rpi/legup/images/heyawake/rules/FillRoomWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java index 233136061..8b6f21564 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/OneRowDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class OneRowDirectRule { - public OneRowDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public OneRowDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java index 14b3ef0a2..f5d4e78b7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/PreventWhiteLineDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class PreventWhiteLineDirectRule { - public PreventWhiteLineDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public PreventWhiteLineDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java index af2448b13..762b435a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooEmptyContradictionRule.java @@ -6,25 +6,25 @@ public class RoomTooEmptyContradictionRule extends ContradictionRule { - public RoomTooEmptyContradictionRule() { - super( - "HEYA-CONT-0002", - "Room too Empty", - "", - "edu/rpi/legup/images/heyawake/contradictions/RoomTooEmpty.png"); - } + public RoomTooEmptyContradictionRule() { + super( + "HEYA-CONT-0002", + "Room too Empty", + "", + "edu/rpi/legup/images/heyawake/contradictions/RoomTooEmpty.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java index d46ae27a0..643f75f13 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/RoomTooFullContradictionRule.java @@ -6,25 +6,25 @@ public class RoomTooFullContradictionRule extends ContradictionRule { - public RoomTooFullContradictionRule() { - super( - "HEYA-CONT-0003", - "Room too Full", - "", - "edu/rpi/legup/images/heyawake/contradictions/RoomTooFull.png"); - } + public RoomTooFullContradictionRule() { + super( + "HEYA-CONT-0003", + "Room too Full", + "", + "edu/rpi/legup/images/heyawake/contradictions/RoomTooFull.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java index b6782e380..cf2c241e3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ThreeByThreeDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ThreeByThreeDirectRule { - public ThreeByThreeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ThreeByThreeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java index 0af7fbc15..83f1ca72f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/TwoInCornerDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class TwoInCornerDirectRule { - public TwoInCornerDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public TwoInCornerDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java index 377ba5911..c0987d4f9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAreaContradictionRule.java @@ -6,25 +6,25 @@ public class WhiteAreaContradictionRule extends ContradictionRule { - public WhiteAreaContradictionRule() { - super( - "HEYA-CONT-0004", - "White Area", - "", - "edu/rpi/legup/images/heyawake/contradictions/WhiteArea.png"); - } + public WhiteAreaContradictionRule() { + super( + "HEYA-CONT-0004", + "White Area", + "", + "edu/rpi/legup/images/heyawake/contradictions/WhiteArea.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java index c6c7b7d6b..2e3bc1812 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteAroundBlackDirectRule.java @@ -8,37 +8,38 @@ public class WhiteAroundBlackDirectRule extends DirectRule { - public WhiteAroundBlackDirectRule() { - super( - "HEYA-BASC-0009", - "White Around Black", - "", - "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); - } + public WhiteAroundBlackDirectRule() { + super( + "HEYA-BASC-0009", + "White Around Black", + "", + "edu/rpi/legup/images/heyawake/rules/WhiteAroundBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java index d4d547677..f151ec12a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteEscapeDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class WhiteEscapeDirectRule { - public WhiteEscapeDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public WhiteEscapeDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java index 813dd45ed..b695b8206 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/WhiteLineContradictionRule.java @@ -6,25 +6,25 @@ public class WhiteLineContradictionRule extends ContradictionRule { - public WhiteLineContradictionRule() { - super( - "HEYA-CONT-0005", - "White Line", - "", - "edu/rpi/legup/images/heyawake/contradictions/WhiteLine.png"); - } + public WhiteLineContradictionRule() { + super( + "HEYA-CONT-0005", + "White Line", + "", + "edu/rpi/legup/images/heyawake/contradictions/WhiteLine.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java index 9f9212861..d44491a6e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagCaseRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ZigZagCaseRule { - public ZigZagCaseRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ZigZagCaseRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java index 531cf030e..9df735b0b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/heyawake/rules/ZigZagWhiteDirectRule.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.heyawake.rules; public class ZigZagWhiteDirectRule { - public ZigZagWhiteDirectRule() { - throw new RuntimeException("This rule has not been implemented"); - } + public ZigZagWhiteDirectRule() { + throw new RuntimeException("This rule has not been implemented"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java index 73878706f..ab95c4658 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUp.java @@ -9,79 +9,80 @@ @RegisterPuzzle public class LightUp extends Puzzle { - public LightUp() { - super(); - this.name = "LightUp"; + public LightUp() { + super(); + this.name = "LightUp"; - this.importer = new LightUpImporter(this); - this.exporter = new LightUpExporter(this); + this.importer = new LightUpImporter(this); + this.exporter = new LightUpExporter(this); - this.factory = new LightUpCellFactory(); - } + this.factory = new LightUpCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new LightUpView((LightUpBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new LightUpView((LightUpBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Light Up - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Light Up, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows > 0 && columns > 0; - } + @Override + /** + * Determines if the given dimensions are valid for Light Up + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Light Up, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows > 0 && columns > 0; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - lightUpBoard.fillWithLight(); + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + lightUpBoard.fillWithLight(); - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(lightUpBoard) == null) { - System.out.println(rule.getRuleName()); - return false; - } - } - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) data; - if ((cell.getType() == LightUpCellType.UNKNOWN || cell.getType() == LightUpCellType.EMPTY) - && !cell.isLite()) { - return false; - } + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(lightUpBoard) == null) { + System.out.println(rule.getRuleName()); + return false; + } + } + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) data; + if ((cell.getType() == LightUpCellType.UNKNOWN + || cell.getType() == LightUpCellType.EMPTY) + && !cell.isLite()) { + return false; + } + } + return true; } - return true; - } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java index 5d0d66648..217ef79a8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpBoard.java @@ -7,168 +7,172 @@ import java.util.Set; public class LightUpBoard extends GridBoard { - public LightUpBoard(int width, int height) { - super(width, height); - } - - public LightUpBoard(int size) { - super(size, size); - } + public LightUpBoard(int width, int height) { + super(width, height); + } - /** - * Sets cells in board to lite depending on whether there is a bulb cell in the current row or - * column - */ - public void fillWithLight() { - for (int y = 0; y < this.dimension.height; y++) { - for (int x = 0; x < this.dimension.width; x++) { - getCell(x, y).setLite(false); - } + public LightUpBoard(int size) { + super(size, size); } - for (int y = 0; y < this.dimension.height; y++) { - for (int x = 0; x < this.dimension.width; x++) { - LightUpCell cell = getCell(x, y); - if (cell.getType() == LightUpCellType.BULB) { - cell.setLite(true); - for (int i = x + 1; i < this.dimension.width; i++) { - LightUpCell c = getCell(i, y); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = x - 1; i >= 0; i--) { - LightUpCell c = getCell(i, y); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; - } - c.setLite(true); - } - for (int i = y + 1; i < this.dimension.height; i++) { - LightUpCell c = getCell(x, i); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; + /** + * Sets cells in board to lite depending on whether there is a bulb cell in the current row or + * column + */ + public void fillWithLight() { + for (int y = 0; y < this.dimension.height; y++) { + for (int x = 0; x < this.dimension.width; x++) { + getCell(x, y).setLite(false); } - c.setLite(true); - } - for (int i = y - 1; i >= 0; i--) { - LightUpCell c = getCell(x, i); - if (c.getType() == LightUpCellType.NUMBER || c.getType() == LightUpCellType.BLACK) { - break; + } + + for (int y = 0; y < this.dimension.height; y++) { + for (int x = 0; x < this.dimension.width; x++) { + LightUpCell cell = getCell(x, y); + if (cell.getType() == LightUpCellType.BULB) { + cell.setLite(true); + for (int i = x + 1; i < this.dimension.width; i++) { + LightUpCell c = getCell(i, y); + if (c.getType() == LightUpCellType.NUMBER + || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = x - 1; i >= 0; i--) { + LightUpCell c = getCell(i, y); + if (c.getType() == LightUpCellType.NUMBER + || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = y + 1; i < this.dimension.height; i++) { + LightUpCell c = getCell(x, i); + if (c.getType() == LightUpCellType.NUMBER + || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + for (int i = y - 1; i >= 0; i--) { + LightUpCell c = getCell(x, i); + if (c.getType() == LightUpCellType.NUMBER + || c.getType() == LightUpCellType.BLACK) { + break; + } + c.setLite(true); + } + } } - c.setLite(true); - } } - } } - } - /** - * Gets adjancent cells to the specified cell - * - * @param cell LightUpCell - * @return Set of adjacent LightUpCells - */ - public Set getAdj(LightUpCell cell) { - Set adjCells = new HashSet<>(); - cell = (LightUpCell) getPuzzleElement(cell); + /** + * Gets adjancent cells to the specified cell + * + * @param cell LightUpCell + * @return Set of adjacent LightUpCells + */ + public Set getAdj(LightUpCell cell) { + Set adjCells = new HashSet<>(); + cell = (LightUpCell) getPuzzleElement(cell); - Point loc = cell.getLocation(); - LightUpCell up = getCell(loc.x, loc.y + 1); - if (up != null) { - adjCells.add(up); - } - LightUpCell down = getCell(loc.x, loc.y - 1); - if (down != null) { - adjCells.add(down); - } - LightUpCell right = getCell(loc.x + 1, loc.y); - if (right != null) { - adjCells.add(right); - } - LightUpCell left = getCell(loc.x - 1, loc.y); - if (left != null) { - adjCells.add(left); + Point loc = cell.getLocation(); + LightUpCell up = getCell(loc.x, loc.y + 1); + if (up != null) { + adjCells.add(up); + } + LightUpCell down = getCell(loc.x, loc.y - 1); + if (down != null) { + adjCells.add(down); + } + LightUpCell right = getCell(loc.x + 1, loc.y); + if (right != null) { + adjCells.add(right); + } + LightUpCell left = getCell(loc.x - 1, loc.y); + if (left != null) { + adjCells.add(left); + } + return adjCells; } - return adjCells; - } - /** - * Gets the number of adjacent cells of the specified type - * - * @param cell base cell - * @param type specified type - * @return the number of adjacent cells - */ - public int getNumAdj(LightUpCell cell, LightUpCellType type) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.getType() == type) { - num++; - } + /** + * Gets the number of adjacent cells of the specified type + * + * @param cell base cell + * @param type specified type + * @return the number of adjacent cells + */ + public int getNumAdj(LightUpCell cell, LightUpCellType type) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.getType() == type) { + num++; + } + } + return num; } - return num; - } - /** - * Gets the number of adjacent cells - * - * @param cell LightUpCell - * @return number of adjacent cells - */ - public int getNumAdjLite(LightUpCell cell) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.isLite()) { - num++; - } + /** + * Gets the number of adjacent cells + * + * @param cell LightUpCell + * @return number of adjacent cells + */ + public int getNumAdjLite(LightUpCell cell) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.isLite()) { + num++; + } + } + return num; } - return num; - } - /** - * Gets the number of adjacent cells that are placable - * - * @param cell specified cell - * @return number of adjacent cells that are placable - */ - public int getNumPlacble(LightUpCell cell) { - int num = 0; - Set adjCells = getAdj(cell); - for (LightUpCell c : adjCells) { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - num++; - } + /** + * Gets the number of adjacent cells that are placable + * + * @param cell specified cell + * @return number of adjacent cells that are placable + */ + public int getNumPlacble(LightUpCell cell) { + int num = 0; + Set adjCells = getAdj(cell); + for (LightUpCell c : adjCells) { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + num++; + } + } + return num; } - return num; - } - @Override - public LightUpCell getCell(int x, int y) { - return (LightUpCell) super.getCell(x, y); - } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - super.notifyChange(puzzleElement); - fillWithLight(); - } + @Override + public LightUpCell getCell(int x, int y) { + return (LightUpCell) super.getCell(x, y); + } - @Override - public LightUpBoard copy() { - LightUpBoard copy = new LightUpBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + @Override + public void notifyChange(PuzzleElement puzzleElement) { + super.notifyChange(puzzleElement); + fillWithLight(); } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + @Override + public LightUpBoard copy() { + LightUpBoard copy = new LightUpBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.fillWithLight(); + return copy; } - copy.fillWithLight(); - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java index f21f42fd6..8adf84cb4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCell.java @@ -6,78 +6,78 @@ import java.awt.event.MouseEvent; public class LightUpCell extends GridCell { - private boolean isLite; + private boolean isLite; - public LightUpCell(int valueInt, Point location) { - super(valueInt, location); - this.isLite = false; - } + public LightUpCell(int valueInt, Point location) { + super(valueInt, location); + this.isLite = false; + } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "LTUP-PLAC-0001": - this.data = -4; - break; - case "LTUP-UNPL-0002": - this.data = -1; - break; - case "LTUP-UNPL-0003": - this.data = -2; - break; - case "LTUP-UNPL-0001": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data < 0 || this.data > 3) { - this.data = 0; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 0) { - this.data = this.data - 1; - } else { - this.data = 4; - } - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "LTUP-PLAC-0001": + this.data = -4; + break; + case "LTUP-UNPL-0002": + this.data = -1; + break; + case "LTUP-UNPL-0003": + this.data = -2; + break; + case "LTUP-UNPL-0001": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data < 0 || this.data > 3) { + this.data = 0; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 0) { + this.data = this.data - 1; + } else { + this.data = 4; + } + break; + } + break; } - break; } - } - public LightUpCellType getType() { - switch (data) { - case -4: - return LightUpCellType.BULB; - case -3: - return LightUpCellType.EMPTY; - case -2: - return LightUpCellType.UNKNOWN; - case -1: - return LightUpCellType.BLACK; - default: - if (data >= 0) { - return LightUpCellType.NUMBER; + public LightUpCellType getType() { + switch (data) { + case -4: + return LightUpCellType.BULB; + case -3: + return LightUpCellType.EMPTY; + case -2: + return LightUpCellType.UNKNOWN; + case -1: + return LightUpCellType.BLACK; + default: + if (data >= 0) { + return LightUpCellType.NUMBER; + } } + return null; } - return null; - } - public boolean isLite() { - return isLite; - } + public boolean isLite() { + return isLite; + } - public void setLite(boolean isLite) { - this.isLite = isLite; - } + public void setLite(boolean isLite) { + this.isLite = isLite; + } - @Override - public LightUpCell copy() { - LightUpCell copy = new LightUpCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public LightUpCell copy() { + LightUpCell copy = new LightUpCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java index 07217869e..d4049897d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellController.java @@ -5,40 +5,40 @@ import java.awt.event.MouseEvent; public class LightUpCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - LightUpCell cell = (LightUpCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == -2) { - data.setData(-4); + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + LightUpCell cell = (LightUpCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == -2) { + data.setData(-4); + } else { + if (cell.getData() == -4) { + data.setData(-3); + } else { + data.setData(-2); + } + } + } } else { - if (cell.getData() == -4) { - data.setData(-3); - } else { - data.setData(-2); - } + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == -4) { + data.setData(-2); + } else { + if (cell.getData() == -2) { + data.setData(-3); + } else { + data.setData(-4); + } + } + } } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == -4) { - data.setData(-2); - } else { - if (cell.getData() == -2) { - data.setData(-3); - } else { - data.setData(-4); - } - } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java index 10a44ca85..384aa2b74 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellFactory.java @@ -10,64 +10,66 @@ import org.w3c.dom.Node; public class LightUpCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public LightUpCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "lightup Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public LightUpCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "lightup Factory: unknown puzzleElement puzzleElement"); + } - LightUpBoard lightUpBoard = (LightUpBoard) board; - int width = lightUpBoard.getWidth(); - int height = lightUpBoard.getHeight(); + LightUpBoard lightUpBoard = (LightUpBoard) board; + int width = lightUpBoard.getWidth(); + int height = lightUpBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("lightup Factory: cell location out of bounds"); - } - if (value < -4 || value > 4) { - throw new InvalidFileFormatException("lightup Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "lightup Factory: cell location out of bounds"); + } + if (value < -4 || value > 4) { + throw new InvalidFileFormatException("lightup Factory: cell unknown value"); + } - LightUpCell cell = new LightUpCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("lightup Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("lightup Factory: could not find attribute(s)"); + LightUpCell cell = new LightUpCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "lightup Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("lightup Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java index 3d28a0604..8472be7a6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpCellType.java @@ -1,15 +1,15 @@ package edu.rpi.legup.puzzle.lightup; public enum LightUpCellType { - BULB(-4), - EMPTY(-3), - UNKNOWN(-2), - BLACK(-1), - NUMBER(0); + BULB(-4), + EMPTY(-3), + UNKNOWN(-2), + BLACK(-1), + NUMBER(0); - public int value; + public int value; - LightUpCellType(int value) { - this.value = value; - } + LightUpCellType(int value) { + this.value = value; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java index 6805d9d29..1b00b007d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpElementView.java @@ -4,85 +4,86 @@ import java.awt.*; public class LightUpElementView extends GridElementView { - private static final Color LITE = new Color(0xFFF176); - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color LITE = new Color(0xFFF176); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color BLACK_COLOR = new Color(0x212121); - private static final Color WHITE_COLOR = new Color(0xF5F5F5); - private static final Color GRAY_COLOR = new Color(0x9E9E9E); + private static final Color BLACK_COLOR = new Color(0x212121); + private static final Color WHITE_COLOR = new Color(0xF5F5F5); + private static final Color GRAY_COLOR = new Color(0x9E9E9E); - public LightUpElementView(LightUpCell cell) { - super(cell); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public LightUpCell getPuzzleElement() { - return (LightUpCell) super.getPuzzleElement(); - } + public LightUpElementView(LightUpCell cell) { + super(cell); + } - @Override - public void drawElement(Graphics2D graphics2D) { - LightUpCell cell = (LightUpCell) puzzleElement; - LightUpCellType type = cell.getType(); - if (type == LightUpCellType.NUMBER) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public LightUpCell getPuzzleElement() { + return (LightUpCell) super.getPuzzleElement(); + } - graphics2D.setColor(WHITE_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } else { - if (type == LightUpCellType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.EMPTY) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(cell.isLite() ? LITE : WHITE_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BLACK_COLOR); - graphics2D.fillRect( - location.x + size.width * 7 / 16, - location.y + size.height * 7 / 16, - size.width / 8, - size.height / 8); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.UNKNOWN) { + @Override + public void drawElement(Graphics2D graphics2D) { + LightUpCell cell = (LightUpCell) puzzleElement; + LightUpCellType type = cell.getType(); + if (type == LightUpCellType.NUMBER) { graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(cell.isLite() ? LITE : Color.LIGHT_GRAY); + graphics2D.setColor(BLACK_COLOR); graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == LightUpCellType.BULB) { - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.drawImage( - LightUpView.lightImage, - location.x, - location.y, - size.width, - size.height, - LITE, - null); - graphics2D.setColor(BLACK_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + + graphics2D.setColor(WHITE_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } else { + if (type == LightUpCellType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.EMPTY) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(cell.isLite() ? LITE : WHITE_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BLACK_COLOR); + graphics2D.fillRect( + location.x + size.width * 7 / 16, + location.y + size.height * 7 / 16, + size.width / 8, + size.height / 8); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(cell.isLite() ? LITE : Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == LightUpCellType.BULB) { + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.drawImage( + LightUpView.lightImage, + location.x, + location.y, + size.width, + size.height, + LITE, + null); + graphics2D.setColor(BLACK_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } + } + } } - } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java index d632879d5..0e8987020 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpExporter.java @@ -6,34 +6,34 @@ public class LightUpExporter extends PuzzleExporter { - public LightUpExporter(LightUp lightUp) { - super(lightUp); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - LightUpBoard board; - if (puzzle.getTree() != null) { - board = (LightUpBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (LightUpBoard) puzzle.getBoardView().getBoard(); + public LightUpExporter(LightUp lightUp) { + super(lightUp); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + LightUpBoard board; + if (puzzle.getTree() != null) { + board = (LightUpBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (LightUpBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java index bce9f10ee..336b063f6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpImporter.java @@ -8,113 +8,117 @@ import org.w3c.dom.NodeList; public class LightUpImporter extends PuzzleImporter { - public LightUpImporter(LightUp lightUp) { - super(lightUp); - } + public LightUpImporter(LightUp lightUp) { + super(lightUp); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - LightUpBoard lightUpBoard = new LightUpBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + LightUpBoard lightUpBoard = new LightUpBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - if (lightUpBoard.getCell(x, y) == null) { - LightUpCell cell = new LightUpCell(-2, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - lightUpBoard.setCell(x, y, cell); + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + if (lightUpBoard.getCell(x, y) == null) { + LightUpCell cell = new LightUpCell(-2, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + lightUpBoard.setCell(x, y, cell); + } + } } - } + puzzle.setCurrentBoard(lightUpBoard); } - puzzle.setCurrentBoard(lightUpBoard); - } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("lightup Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("lightup Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "lightup Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "lightup Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - LightUpBoard lightUpBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - lightUpBoard = new LightUpBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - lightUpBoard = new LightUpBoard(width, height); - } - } + LightUpBoard lightUpBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + lightUpBoard = new LightUpBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + lightUpBoard = new LightUpBoard(width, height); + } + } - if (lightUpBoard == null) { - throw new InvalidFileFormatException("lightup Importer: invalid board dimensions"); - } + if (lightUpBoard == null) { + throw new InvalidFileFormatException("lightup Importer: invalid board dimensions"); + } - int width = lightUpBoard.getWidth(); - int height = lightUpBoard.getHeight(); + int width = lightUpBoard.getWidth(); + int height = lightUpBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - LightUpCell cell = - (LightUpCell) puzzle.getFactory().importCell(elementDataList.item(i), lightUpBoard); - Point loc = cell.getLocation(); - if (cell.getData() != -2) { - cell.setModifiable(false); - cell.setGiven(true); - } - lightUpBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + LightUpCell cell = + (LightUpCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), lightUpBoard); + Point loc = cell.getLocation(); + if (cell.getData() != -2) { + cell.setModifiable(false); + cell.setGiven(true); + } + lightUpBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (lightUpBoard.getCell(x, y) == null) { - LightUpCell cell = new LightUpCell(-2, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - lightUpBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (lightUpBoard.getCell(x, y) == null) { + LightUpCell cell = new LightUpCell(-2, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + lightUpBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(lightUpBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "lightup Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(lightUpBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "lightup Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Light Up cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Light Up cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java index b8122ffff..ebce6a682 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/LightUpView.java @@ -15,86 +15,90 @@ import org.apache.logging.log4j.Logger; public class LightUpView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(LightUpView.class.getName()); - static Image lightImage; + private static final Logger LOGGER = LogManager.getLogger(LightUpView.class.getName()); + static Image lightImage; - static { - try { - lightImage = - ImageIO.read( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/lightup/light.png")); - } catch (IOException e) { - LOGGER.error("Failed to open TreeTent images"); + static { + try { + lightImage = + ImageIO.read( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/lightup/light.png")); + } catch (IOException e) { + LOGGER.error("Failed to open TreeTent images"); + } } - } - public LightUpView(LightUpBoard board) { - super(new BoardController(), new LightUpCellController(), board.getDimension()); + public LightUpView(LightUpBoard board) { + super(new BoardController(), new LightUpCellController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); - LightUpElementView elementView = new LightUpElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); + LightUpElementView elementView = new LightUpElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - super.onTreeElementChanged(treeElement); - LightUpBoard lightUpBoard = - board instanceof CaseBoard - ? (LightUpBoard) ((CaseBoard) board).getBaseBoard() - : (LightUpBoard) board; - lightUpBoard.fillWithLight(); - repaint(); - } + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + super.onTreeElementChanged(treeElement); + LightUpBoard lightUpBoard = + board instanceof CaseBoard + ? (LightUpBoard) ((CaseBoard) board).getBaseBoard() + : (LightUpBoard) board; + lightUpBoard.fillWithLight(); + repaint(); + } - /** Returns a DataSelectionView popup menu */ - public DataSelectionView getSelectionPopupMenu() { - DataSelectionView selectionView = new DataSelectionView(elementController); - GridLayout layout = new GridLayout(3, 1); - selectionView.setLayout(layout); + /** Returns a DataSelectionView popup menu */ + public DataSelectionView getSelectionPopupMenu() { + DataSelectionView selectionView = new DataSelectionView(elementController); + GridLayout layout = new GridLayout(3, 1); + selectionView.setLayout(layout); - Dimension iconSize = new Dimension(32, 32); - Point loc = new Point(0, 0); + Dimension iconSize = new Dimension(32, 32); + Point loc = new Point(0, 0); - LightUpElementView element1 = new LightUpElementView(new LightUpCell(-2, null)); - element1.setSize(iconSize); - element1.setLocation(loc); - SelectionItemView item1 = - new SelectionItemView(element1.getPuzzleElement(), new ImageIcon(element1.getImage())); - item1.addActionListener(elementController); - item1.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item1); + LightUpElementView element1 = new LightUpElementView(new LightUpCell(-2, null)); + element1.setSize(iconSize); + element1.setLocation(loc); + SelectionItemView item1 = + new SelectionItemView( + element1.getPuzzleElement(), new ImageIcon(element1.getImage())); + item1.addActionListener(elementController); + item1.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item1); - LightUpElementView element2 = new LightUpElementView(new LightUpCell(-4, null)); - element2.setSize(iconSize); - element2.setLocation(loc); - SelectionItemView item2 = - new SelectionItemView(element2.getPuzzleElement(), new ImageIcon(element2.getImage())); - item2.addActionListener(elementController); - item2.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item2); + LightUpElementView element2 = new LightUpElementView(new LightUpCell(-4, null)); + element2.setSize(iconSize); + element2.setLocation(loc); + SelectionItemView item2 = + new SelectionItemView( + element2.getPuzzleElement(), new ImageIcon(element2.getImage())); + item2.addActionListener(elementController); + item2.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item2); - LightUpElementView element3 = new LightUpElementView(new LightUpCell(-3, null)); - element3.setSize(iconSize); - element3.setLocation(loc); - SelectionItemView item3 = - new SelectionItemView(element3.getPuzzleElement(), new ImageIcon(element3.getImage())); - item3.addActionListener(elementController); - item3.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item3); + LightUpElementView element3 = new LightUpElementView(new LightUpCell(-3, null)); + element3.setSize(iconSize); + element3.setLocation(loc); + SelectionItemView item3 = + new SelectionItemView( + element3.getPuzzleElement(), new ImageIcon(element3.getImage())); + item3.addActionListener(elementController); + item3.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item3); - return selectionView; - } + return selectionView; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java index bac5aa4ba..2ddb4f754 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BlackTile.java @@ -3,8 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class BlackTile extends NonPlaceableElement { - public BlackTile() { - super( - "LTUP-UNPL-0002", "Black Tile", "The black tile", "edu/rpi/legup/images/lightup/black.gif"); - } + public BlackTile() { + super( + "LTUP-UNPL-0002", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/lightup/black.gif"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java index ce0629fbe..d238baa56 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/BulbTile.java @@ -3,7 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BulbTile extends PlaceableElement { - public BulbTile() { - super("LTUP-PLAC-0001", "Bulb Tile", "The bulb tile", "edu/rpi/legup/images/lightup/light.png"); - } + public BulbTile() { + super( + "LTUP-PLAC-0001", + "Bulb Tile", + "The bulb tile", + "edu/rpi/legup/images/lightup/light.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java index 9a2fba5c7..ae314a4cf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/NumberTile.java @@ -4,20 +4,24 @@ public class NumberTile extends NonPlaceableElement { - int object_number; + int object_number; - // Follow the default format and resolves the NoSuchMethod error - public NumberTile() { - super("LTUP-UNPL-0001", "Number Tile", "The number tile", "edu/rpi/legup/images/lightup/1.gif"); - } + // Follow the default format and resolves the NoSuchMethod error + public NumberTile() { + super( + "LTUP-UNPL-0001", + "Number Tile", + "The number tile", + "edu/rpi/legup/images/lightup/1.gif"); + } - public NumberTile(int num) { - super( - "LTUP-UNPL-0001", - "Number Tile", - "The number tile", - "edu/rpi/legup/images/lightup/" + num + ".gif"); - if (num > 3 || num < 1) num = 1; - object_number = num; - } + public NumberTile(int num) { + super( + "LTUP-UNPL-0001", + "Number Tile", + "The number tile", + "edu/rpi/legup/images/lightup/" + num + ".gif"); + if (num > 3 || num < 1) num = 1; + object_number = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java index 4e17c6b37..24d420fe8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "LTUP-UNPL-0003", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/lightup/UnknownTile.png"); - } + public UnknownTile() { + super( + "LTUP-UNPL-0003", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/lightup/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java index 1adf449d0..90652888c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/BulbsInPathContradictionRule.java @@ -10,72 +10,72 @@ public class BulbsInPathContradictionRule extends ContradictionRule { - public BulbsInPathContradictionRule() { - super( - "LTUP-CONT-0001", - "Bulbs In Path", - "A bulb cannot be placed in another bulb's path.", - "edu/rpi/legup/images/lightup/contradictions/BulbsInPath.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.BULB) { - return super.getNoContradictionMessage(); + public BulbsInPathContradictionRule() { + super( + "LTUP-CONT-0001", + "Bulbs In Path", + "A bulb cannot be placed in another bulb's path.", + "edu/rpi/legup/images/lightup/contradictions/BulbsInPath.png"); } - Point location = cell.getLocation(); - for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.BULB) { + return super.getNoContradictionMessage(); } - } - } - for (int i = location.x - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; + + Point location = cell.getLocation(); + for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; + } + } } - } - } - for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; + for (int i = location.x - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; + } + } } - } - } - for (int i = location.y - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.BULB) { - return null; + for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; + } + } + } + for (int i = location.y - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.BULB) { + return null; + } + } } - } + return super.getNoContradictionMessage(); } - return super.getNoContradictionMessage(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java index b9b93620a..0ed88636c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/CannotLightACellContradictionRule.java @@ -10,80 +10,80 @@ public class CannotLightACellContradictionRule extends ContradictionRule { - public CannotLightACellContradictionRule() { - super( - "LTUP-CONT-0002", - "Cannot Light A Cell", - "All cells must be able to be lit.", - "edu/rpi/legup/images/lightup/contradictions/CannotLightACell.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - /*if (cell.getType() == LightUpCellType.BLACK || cell.getType() == LightUpCellType.NUMBER || cell.isLite()) { - return "This cell does not contain a contradiction"; - }*/ - if (cell.getType() != LightUpCellType.EMPTY || cell.isLite()) { - return super.getNoContradictionMessage(); + public CannotLightACellContradictionRule() { + super( + "LTUP-CONT-0002", + "Cannot Light A Cell", + "All cells must be able to be lit.", + "edu/rpi/legup/images/lightup/contradictions/CannotLightACell.png"); } - Point location = cell.getLocation(); - int ver_count = 0; - int hor_count = 0; - for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - hor_count += 1; + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + /*if (cell.getType() == LightUpCellType.BLACK || cell.getType() == LightUpCellType.NUMBER || cell.isLite()) { + return "This cell does not contain a contradiction"; + }*/ + if (cell.getType() != LightUpCellType.EMPTY || cell.isLite()) { + return super.getNoContradictionMessage(); } - } - } - for (int i = location.x - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - hor_count += 1; + Point location = cell.getLocation(); + int ver_count = 0; + int hor_count = 0; + for (int i = location.x + 1; i < lightUpBoard.getWidth(); i++) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + hor_count += 1; + } + } } - } - } - for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - ver_count += 1; + for (int i = location.x - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + hor_count += 1; + } + } } - } - } - for (int i = location.y - 1; i >= 0; i--) { - LightUpCell c = lightUpBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { - ver_count += 1; + for (int i = location.y + 1; i < lightUpBoard.getHeight(); i++) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + ver_count += 1; + } + } } - } - } - System.out.printf("%d, %d, %d, %d\n", location.x, location.y, hor_count, ver_count); - if (hor_count == 0 && ver_count == 0) { - return null; + for (int i = location.y - 1; i >= 0; i--) { + LightUpCell c = lightUpBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.UNKNOWN && !c.isLite()) { + ver_count += 1; + } + } + } + System.out.printf("%d, %d, %d, %d\n", location.x, location.y, hor_count, ver_count); + if (hor_count == 0 && ver_count == 0) { + return null; + } + return super.getNoContradictionMessage(); } - return super.getNoContradictionMessage(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java index 857d2333d..269ef0ad5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCellinLightDirectRule.java @@ -11,57 +11,58 @@ public class EmptyCellinLightDirectRule extends DirectRule { - public EmptyCellinLightDirectRule() { - super( - "LTUP-BASC-0002", - "Empty Cells in Light", - "Cells in light must be empty.", - "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - initialBoard.fillWithLight(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); - if (finalCell.getType() == LightUpCellType.EMPTY - && initCell.getType() == LightUpCellType.UNKNOWN - && initCell.isLite()) { - return null; + public EmptyCellinLightDirectRule() { + super( + "LTUP-BASC-0002", + "Empty Cells in Light", + "Cells in light must be empty.", + "edu/rpi/legup/images/lightup/rules/EmptyCellInLight.png"); } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + initialBoard.fillWithLight(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) transition.getBoard().getPuzzleElement(puzzleElement); + if (finalCell.getType() == LightUpCellType.EMPTY + && initCell.getType() == LightUpCellType.UNKNOWN + && initCell.isLite()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced to be empty"; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java index f4da5a73e..702c116c1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/EmptyCornersDirectRule.java @@ -14,102 +14,104 @@ public class EmptyCornersDirectRule extends DirectRule { - public EmptyCornersDirectRule() { - super( - "LTUP-BASC-0003", - "Empty Corners", - "Cells on the corners of a number must be empty if placing bulbs would prevent the" - + " number from being satisfied.", - "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); - } + public EmptyCornersDirectRule() { + super( + "LTUP-BASC-0003", + "Empty Corners", + "Cells on the corners of a number must be empty if placing bulbs would prevent the" + + " number from being satisfied.", + "edu/rpi/legup/images/lightup/rules/EmptyCorners.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell cell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(cell.getType() == LightUpCellType.UNKNOWN - && finalCell.getType() == LightUpCellType.EMPTY)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; - } + if (!(cell.getType() == LightUpCellType.UNKNOWN + && finalCell.getType() == LightUpCellType.EMPTY)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be an empty cell"; + } - Point loc = finalCell.getLocation(); - List numberedCells = new ArrayList<>(); - LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); - if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperRight); - } - LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); - if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(upperLeft); - } - LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); - if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerRight); - } - LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); - if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { - numberedCells.add(lowerLeft); - } - if (numberedCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() + ": This cell must diagonal to a numbered cell"; - } + Point loc = finalCell.getLocation(); + List numberedCells = new ArrayList<>(); + LightUpCell upperRight = finalBoard.getCell(loc.x + 1, loc.y - 1); + if (upperRight != null && upperRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperRight); + } + LightUpCell upperLeft = finalBoard.getCell(loc.x - 1, loc.y - 1); + if (upperLeft != null && upperLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(upperLeft); + } + LightUpCell lowerRight = finalBoard.getCell(loc.x + 1, loc.y + 1); + if (lowerRight != null && lowerRight.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerRight); + } + LightUpCell lowerLeft = finalBoard.getCell(loc.x - 1, loc.y + 1); + if (lowerLeft != null && lowerLeft.getType() == LightUpCellType.NUMBER) { + numberedCells.add(lowerLeft); + } + if (numberedCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + + ": This cell must diagonal to a numbered cell"; + } - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - LightUpBoard bulbCaseBoard = finalBoard.copy(); - LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); - bulbCaseCell.setData(LightUpCellType.BULB.value); - bulbCaseBoard.fillWithLight(); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + LightUpBoard bulbCaseBoard = finalBoard.copy(); + LightUpCell bulbCaseCell = (LightUpCell) bulbCaseBoard.getPuzzleElement(puzzleElement); + bulbCaseCell.setData(LightUpCellType.BULB.value); + bulbCaseBoard.fillWithLight(); - boolean createsContra = false; - for (LightUpCell c : numberedCells) { - createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; + boolean createsContra = false; + for (LightUpCell c : numberedCells) { + createsContra |= tooFew.checkContradictionAt(bulbCaseBoard, c) == null; + } + if (createsContra) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; + } } - if (createsContra) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty"; - } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); - TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); - for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - int temp = cell.getData(); - cell.setData(LightUpCellType.EMPTY.value); - if (checkRuleRawAt(transition, cell) == null) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(modCell); - } else { - cell.setData(temp); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoardCopy = (LightUpBoard) node.getBoard().copy(); + TreeTransition transition = new TreeTransition(node, lightUpBoardCopy); + for (PuzzleElement element : lightUpBoardCopy.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + int temp = cell.getData(); + cell.setData(LightUpCellType.EMPTY.value); + if (checkRuleRawAt(transition, cell) == null) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(modCell); + } else { + cell.setData(temp); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java index b2ae63788..3f884d459 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithBulbsDirectRule.java @@ -12,97 +12,99 @@ public class FinishWithBulbsDirectRule extends DirectRule { - public FinishWithBulbsDirectRule() { - super( - "LTUP-BASC-0004", - "Finish with Bulbs", - "The remaining unknowns around a block must be bulbs to satisfy the number.", - "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == LightUpCellType.UNKNOWN - && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + public FinishWithBulbsDirectRule() { + super( + "LTUP-BASC-0004", + "Finish with Bulbs", + "The remaining unknowns around a block must be bulbs to satisfy the number.", + "edu/rpi/legup/images/lightup/rules/FinishWithBulbs.png"); } - Set adjCells = finalBoard.getAdj(finalCell); - adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return super.getInvalidUseOfRuleMessage() + ": This cell is not adjacent to a numbered cell"; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpCell initCell = (LightUpCell) initialBoard.getPuzzleElement(puzzleElement); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == LightUpCellType.UNKNOWN + && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } - LightUpBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return null; - } - } - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; - } + Set adjCells = finalBoard.getAdj(finalCell); + adjCells.removeIf(cell -> cell.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return super.getInvalidUseOfRuleMessage() + + ": This cell is not adjacent to a numbered cell"; + } - /** - * Determines whether the specified cell is forced to be a bulb or not - * - * @param board the entire board - * @param cell specified cell - * @return whether cell is forced to be a bulb or not - */ - private boolean isForced(LightUpBoard board, LightUpCell cell) { - Set adjCells = board.getAdj(cell); - adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); - if (adjCells.isEmpty()) { - return false; + LightUpBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return null; + } + } + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be a bulb"; } - LightUpBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); - TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); - for (LightUpCell c : adjCells) { - if (tooFew.checkContradictionAt(emptyCase, c) == null) { - return true; - } - } - return false; - } + /** + * Determines whether the specified cell is forced to be a bulb or not + * + * @param board the entire board + * @param cell specified cell + * @return whether cell is forced to be a bulb or not + */ + private boolean isForced(LightUpBoard board, LightUpCell cell) { + Set adjCells = board.getAdj(cell); + adjCells.removeIf(c -> c.getType() != LightUpCellType.NUMBER); + if (adjCells.isEmpty()) { + return false; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { - cell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + LightUpBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(LightUpCellType.EMPTY.value); + TooFewBulbsContradictionRule tooFew = new TooFewBulbsContradictionRule(); + for (LightUpCell c : adjCells) { + if (tooFew.checkContradictionAt(emptyCase, c) == null) { + return true; + } + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell)) { + cell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java index dc2647eb9..678ee67a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/FinishWithEmptyDirectRule.java @@ -12,108 +12,111 @@ public class FinishWithEmptyDirectRule extends DirectRule { - public FinishWithEmptyDirectRule() { - super( - "LTUP-BASC-0005", - "Finish with Empty", - "The remaining unknowns around a block must be empty if the number is satisfied.", - "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.EMPTY) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; - } - - if (isForced(initialBoard, cell.getLocation())) { - return null; + public FinishWithEmptyDirectRule() { + super( + "LTUP-BASC-0005", + "Finish with Empty", + "The remaining unknowns around a block must be empty if the number is satisfied.", + "edu/rpi/legup/images/lightup/rules/FinishWithEmpty.png"); } - return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; - } - /** - * Checks whether a certain cell is forced to not be a bulb - * - * @param board specified board - * @param location location of cell to check - * @return boolean value based on whether a certain cell has an adjacent cell that has the - * required amount of adjacent bulbs - */ - private boolean isForced(LightUpBoard board, Point location) { - return isForcedEmpty(board, new Point(location.x + 1, location.y)) - || isForcedEmpty(board, new Point(location.x, location.y + 1)) - || isForcedEmpty(board, new Point(location.x - 1, location.y)) - || isForcedEmpty(board, new Point(location.x, location.y - 1)); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard initialBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell cell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.EMPTY) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be empty"; + } - /** - * Checks whether a certain cell has the required amount of adjacent bulbs - * - * @param board specified board - * @param loc location of cell to check - * @return boolean value based on whether a certain cell has the required amount of adjacent bulbs - */ - private boolean isForcedEmpty(LightUpBoard board, Point loc) { - LightUpCell cell = board.getCell(loc.x, loc.y); - if (cell == null || cell.getType() != LightUpCellType.NUMBER) { - return false; + if (isForced(initialBoard, cell.getLocation())) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Empty is not forced"; } - int bulbs = 0; - int bulbsNeeded = cell.getData(); - cell = board.getCell(loc.x + 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y + 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; + /** + * Checks whether a certain cell is forced to not be a bulb + * + * @param board specified board + * @param location location of cell to check + * @return boolean value based on whether a certain cell has an adjacent cell that has the + * required amount of adjacent bulbs + */ + private boolean isForced(LightUpBoard board, Point location) { + return isForcedEmpty(board, new Point(location.x + 1, location.y)) + || isForcedEmpty(board, new Point(location.x, location.y + 1)) + || isForcedEmpty(board, new Point(location.x - 1, location.y)) + || isForcedEmpty(board, new Point(location.x, location.y - 1)); } - cell = board.getCell(loc.x - 1, loc.y); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - cell = board.getCell(loc.x, loc.y - 1); - if (cell != null && cell.getType() == LightUpCellType.BULB) { - bulbs++; - } - return bulbs == bulbsNeeded; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && isForced(initialBoard, cell.getLocation())) { - cell.setData(LightUpCellType.EMPTY.value); - lightUpBoard.addModifiedData(cell); - } + /** + * Checks whether a certain cell has the required amount of adjacent bulbs + * + * @param board specified board + * @param loc location of cell to check + * @return boolean value based on whether a certain cell has the required amount of adjacent + * bulbs + */ + private boolean isForcedEmpty(LightUpBoard board, Point loc) { + LightUpCell cell = board.getCell(loc.x, loc.y); + if (cell == null || cell.getType() != LightUpCellType.NUMBER) { + return false; + } + + int bulbs = 0; + int bulbsNeeded = cell.getData(); + cell = board.getCell(loc.x + 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y + 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x - 1, loc.y); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + cell = board.getCell(loc.x, loc.y - 1); + if (cell != null && cell.getType() == LightUpCellType.BULB) { + bulbs++; + } + return bulbs == bulbsNeeded; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN + && isForced(initialBoard, cell.getLocation())) { + cell.setData(LightUpCellType.EMPTY.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java index 39ad146a7..4ba754731 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/LightOrEmptyCaseRule.java @@ -13,100 +13,101 @@ public class LightOrEmptyCaseRule extends CaseRule { - public LightOrEmptyCaseRule() { - super( - "LTUP-CASE-0001", - "Light or Empty", - "Each blank cell is either a light or empty.", - "edu/rpi/legup/images/lightup/cases/LightOrEmpty.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); - lightUpBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((LightUpCell) data).getType() == LightUpCellType.UNKNOWN) { - caseBoard.addPickableElement(data); - } + public LightOrEmptyCaseRule() { + super( + "LTUP-CASE-0001", + "Light or Empty", + "Each blank cell is either a light or empty.", + "edu/rpi/legup/images/lightup/cases/LightOrEmpty.png"); } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(-4); - case1.addModifiedData(data1); - cases.add(case1); + @Override + public CaseBoard getCaseBoard(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); + lightUpBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((LightUpCell) data).getType() == LightUpCellType.UNKNOWN) { + caseBoard.addPickableElement(data); + } + } + return caseBoard; + } - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(-3); - case2.addModifiedData(data2); - cases.add(case2); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(-4); + case1.addModifiedData(data1); + cases.add(case1); - return cases; - } + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(-3); + case2.addModifiedData(data2); + cases.add(case2); - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children"; + return cases; } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children"; + } - LightUpCell mod1 = (LightUpCell) case1.getBoard().getModifiedData().iterator().next(); - LightUpCell mod2 = (LightUpCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case"; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; + } - if (!((mod1.getType() == LightUpCellType.EMPTY && mod2.getType() == LightUpCellType.BULB) - || (mod2.getType() == LightUpCellType.EMPTY && mod1.getType() == LightUpCellType.BULB))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty cell and a bulb cell"; - } + LightUpCell mod1 = (LightUpCell) case1.getBoard().getModifiedData().iterator().next(); + LightUpCell mod2 = (LightUpCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case"; + } + + if (!((mod1.getType() == LightUpCellType.EMPTY && mod2.getType() == LightUpCellType.BULB) + || (mod2.getType() == LightUpCellType.EMPTY + && mod1.getType() == LightUpCellType.BULB))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty cell and a bulb cell"; + } - return null; - } + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java index 272450959..bf1843728 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/MustLightDirectRule.java @@ -12,141 +12,142 @@ public class MustLightDirectRule extends DirectRule { - public MustLightDirectRule() { - super( - "LTUP-BASC-0006", - "Must Light", - "A cell must be a bulb if it is the only cell to be able to light another.", - "edu/rpi/legup/images/lightup/rules/MustLight.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); - LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); - LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); - LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(parentCell.getType() == LightUpCellType.UNKNOWN - && !parentCell.isLite() - && finalCell.getType() == LightUpCellType.BULB)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + public MustLightDirectRule() { + super( + "LTUP-BASC-0006", + "Must Light", + "A cell must be a bulb if it is the only cell to be able to light another.", + "edu/rpi/legup/images/lightup/rules/MustLight.png"); } - finalBoard.fillWithLight(); - boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); - finalCell.setData(LightUpCellType.BULB.value); - finalBoard.fillWithLight(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + LightUpBoard parentBoard = (LightUpBoard) transition.getParents().get(0).getBoard(); + LightUpBoard finalBoard = (LightUpBoard) transition.getBoard(); + LightUpCell parentCell = (LightUpCell) parentBoard.getPuzzleElement(puzzleElement); + LightUpCell finalCell = (LightUpCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(parentCell.getType() == LightUpCellType.UNKNOWN + && !parentCell.isLite() + && finalCell.getType() == LightUpCellType.BULB)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be bulbs"; + } - if (isForced) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; - } - } + finalBoard.fillWithLight(); + boolean isForced = isForcedBulb(parentBoard, parentCell.getLocation()); + finalCell.setData(LightUpCellType.BULB.value); + finalBoard.fillWithLight(); - private boolean isForcedBulb(LightUpBoard board, Point loc) { - CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); - LightUpBoard modifiedBoard = board.copy(); - LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); - modifiedCell.setData(LightUpCellType.EMPTY.value); - // Check if this cell itself (the one with the bulb) has no other lighting option - if ((modifiedCell.getType() == LightUpCellType.EMPTY - || modifiedCell.getType() == LightUpCellType.UNKNOWN) - && !modifiedCell.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { - return true; - } - // Look right - for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; + if (isForced) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell can be lit by another cell"; } - } } - // Look left - for (int i = loc.x - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(i, loc.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; + + private boolean isForcedBulb(LightUpBoard board, Point loc) { + CannotLightACellContradictionRule cannotLite = new CannotLightACellContradictionRule(); + LightUpBoard modifiedBoard = board.copy(); + LightUpCell modifiedCell = modifiedBoard.getCell(loc.x, loc.y); + modifiedCell.setData(LightUpCellType.EMPTY.value); + // Check if this cell itself (the one with the bulb) has no other lighting option + if ((modifiedCell.getType() == LightUpCellType.EMPTY + || modifiedCell.getType() == LightUpCellType.UNKNOWN) + && !modifiedCell.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, modifiedCell) == null) { + return true; } - } - } - // Look down - for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; + // Look right + for (int i = loc.x + 1; i < modifiedBoard.getWidth(); i++) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } } - } - } - // Look up - for (int i = loc.y - 1; i >= 0; i--) { - LightUpCell c = modifiedBoard.getCell(loc.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else { - if (c.getType() == LightUpCellType.EMPTY - && !c.isLite() - && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { - return true; + // Look left + for (int i = loc.x - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(i, loc.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } + } + // Look down + for (int i = loc.y + 1; i < modifiedBoard.getHeight(); i++) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } + } + // Look up + for (int i = loc.y - 1; i >= 0; i--) { + LightUpCell c = modifiedBoard.getCell(loc.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else { + if (c.getType() == LightUpCellType.EMPTY + && !c.isLite() + && cannotLite.checkContradictionAt(modifiedBoard, c) == null) { + return true; + } + } } - } + return false; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); - LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); - LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); - for (PuzzleElement element : tempBoard.getPuzzleElements()) { - LightUpCell cell = (LightUpCell) element; - if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { - cell.setData(LightUpCellType.EMPTY.value); - if (isForcedBulb(initialBoard, cell.getLocation())) { - LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); - modCell.setData(LightUpCellType.BULB.value); - lightUpBoard.addModifiedData(modCell); + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + LightUpBoard initialBoard = (LightUpBoard) node.getBoard(); + LightUpBoard tempBoard = (LightUpBoard) node.getBoard().copy(); + LightUpBoard lightUpBoard = (LightUpBoard) node.getBoard().copy(); + for (PuzzleElement element : tempBoard.getPuzzleElements()) { + LightUpCell cell = (LightUpCell) element; + if (cell.getType() == LightUpCellType.UNKNOWN && !cell.isLite()) { + cell.setData(LightUpCellType.EMPTY.value); + if (isForcedBulb(initialBoard, cell.getLocation())) { + LightUpCell modCell = (LightUpCell) lightUpBoard.getPuzzleElement(cell); + modCell.setData(LightUpCellType.BULB.value); + lightUpBoard.addModifiedData(modCell); + } + cell.setData(LightUpCellType.UNKNOWN.value); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; } - cell.setData(LightUpCellType.UNKNOWN.value); - } - } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java index 7e9f258a3..ac656721d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/SatisfyNumberCaseRule.java @@ -17,337 +17,341 @@ public class SatisfyNumberCaseRule extends CaseRule { - public SatisfyNumberCaseRule() { - super( - "LTUP-CASE-0002", - "Satisfy Number", - "The different ways a blocks number can be satisfied.", - "edu/rpi/legup/images/lightup/cases/SatisfyNumber.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - lightUpBoard.setModifiable(false); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((LightUpCell) data).getType() == LightUpCellType.NUMBER) { - caseBoard.addPickableElement(data); - } + public SatisfyNumberCaseRule() { + super( + "LTUP-CASE-0002", + "Satisfy Number", + "The different ways a blocks number can be satisfied.", + "edu/rpi/legup/images/lightup/cases/SatisfyNumber.png"); } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) puzzleElement; - Point loc = cell.getLocation(); - - List openSpots = new ArrayList<>(); - - int numNeeded = cell.getData(); - - LightUpCell checkCell = lightUpBoard.getCell(loc.x + 1, loc.y); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; + + @Override + public CaseBoard getCaseBoard(Board board) { + LightUpBoard lightUpBoard = (LightUpBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + lightUpBoard.setModifiable(false); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((LightUpCell) data).getType() == LightUpCellType.NUMBER) { + caseBoard.addPickableElement(data); + } } - } + return caseBoard; } - checkCell = lightUpBoard.getCell(loc.x, loc.y + 1); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) puzzleElement; + Point loc = cell.getLocation(); + + List openSpots = new ArrayList<>(); + + int numNeeded = cell.getData(); + + LightUpCell checkCell = lightUpBoard.getCell(loc.x + 1, loc.y); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; + } + } } - } - } - checkCell = lightUpBoard.getCell(loc.x - 1, loc.y); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; + checkCell = lightUpBoard.getCell(loc.x, loc.y + 1); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; + } + } } - } - } - checkCell = lightUpBoard.getCell(loc.x, loc.y - 1); - if (checkCell != null) { - if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { - openSpots.add(checkCell); - } else { - if (checkCell.getType() == LightUpCellType.BULB) { - numNeeded--; + checkCell = lightUpBoard.getCell(loc.x - 1, loc.y); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; + } + } + } + checkCell = lightUpBoard.getCell(loc.x, loc.y - 1); + if (checkCell != null) { + if (checkCell.getType() == LightUpCellType.UNKNOWN && !checkCell.isLite()) { + openSpots.add(checkCell); + } else { + if (checkCell.getType() == LightUpCellType.BULB) { + numNeeded--; + } + } } - } - } - - ArrayList cases = new ArrayList<>(); - if (numNeeded == 0) { - return cases; - } - generateCases(lightUpBoard, numNeeded, openSpots, cases); + ArrayList cases = new ArrayList<>(); + if (numNeeded == 0) { + return cases; + } - return cases; - } + generateCases(lightUpBoard, numNeeded, openSpots, cases); - private void generateCases( - final LightUpBoard board, final int num, List openSpots, List cases) { - if (num > openSpots.size()) { - return; + return cases; } - for (int i = 0; i < openSpots.size(); i++) { - LightUpCell c = openSpots.get(i); - LightUpBoard newCase = board.copy(); - LightUpCell newCell = c.copy(); - Point loc = c.getLocation(); + private void generateCases( + final LightUpBoard board, + final int num, + List openSpots, + List cases) { + if (num > openSpots.size()) { + return; + } - newCell.setData(-4); - newCase.setCell(loc.x, loc.y, newCell); - newCase.addModifiedData(newCell); + for (int i = 0; i < openSpots.size(); i++) { + LightUpCell c = openSpots.get(i); + LightUpBoard newCase = board.copy(); + LightUpCell newCell = c.copy(); + Point loc = c.getLocation(); - generateCases(board, num, openSpots, cases, newCase, i); - } - } - - private void generateCases( - final LightUpBoard board, - final int num, - List openSpots, - List cases, - LightUpBoard curBoard, - int index) { - if (num <= curBoard.getModifiedData().size()) { - cases.add(curBoard); - return; + newCell.setData(-4); + newCase.setCell(loc.x, loc.y, newCell); + newCase.addModifiedData(newCell); + + generateCases(board, num, openSpots, cases, newCase, i); + } } - for (int i = index + 1; i < openSpots.size(); i++) { - LightUpCell c = openSpots.get(i); - Point loc = c.getLocation(); - LightUpCell cc = curBoard.getCell(loc.x, loc.y); - if (!curBoard.getModifiedData().contains(cc)) { - LightUpBoard newCase = board.copy(); - LightUpCell newCell = c.copy(); + private void generateCases( + final LightUpBoard board, + final int num, + List openSpots, + List cases, + LightUpBoard curBoard, + int index) { + if (num <= curBoard.getModifiedData().size()) { + cases.add(curBoard); + return; + } - for (PuzzleElement mod : curBoard.getModifiedData()) { - LightUpCell modCell = (LightUpCell) mod.copy(); - Point modLoc = modCell.getLocation(); + for (int i = index + 1; i < openSpots.size(); i++) { + LightUpCell c = openSpots.get(i); + Point loc = c.getLocation(); + LightUpCell cc = curBoard.getCell(loc.x, loc.y); + if (!curBoard.getModifiedData().contains(cc)) { + LightUpBoard newCase = board.copy(); + LightUpCell newCell = c.copy(); - modCell.setData(-4); + for (PuzzleElement mod : curBoard.getModifiedData()) { + LightUpCell modCell = (LightUpCell) mod.copy(); + Point modLoc = modCell.getLocation(); - newCase.setCell(modLoc.x, modLoc.y, modCell); - newCase.addModifiedData(modCell); - } + modCell.setData(-4); - newCell.setData(-4); + newCase.setCell(modLoc.x, modLoc.y, modCell); + newCase.addModifiedData(modCell); + } - newCase.setCell(loc.x, loc.y, newCell); - newCase.addModifiedData(newCell); + newCell.setData(-4); - generateCases(board, num, openSpots, cases, newCase, i); - } - } - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - TreeNode parent = transition.getParents().get(0); - List childTransitions = parent.getChildren(); - - List spots = getPossibleSpots(transition); - if (spots == null) { - return super.getInvalidUseOfRuleMessage(); + newCase.setCell(loc.x, loc.y, newCell); + newCase.addModifiedData(newCell); + + generateCases(board, num, openSpots, cases, newCase, i); + } + } } - for (LightUpCell c : spots) { - ArrayList cases = getCases(parent.getBoard(), c); - - // We will allow case rules to have only one option - if (cases.size() == childTransitions.size() && cases.size() >= 1) { - boolean foundSpot = true; - for (TreeTransition childTrans : childTransitions) { - LightUpBoard actCase = (LightUpBoard) childTrans.getBoard(); - boolean foundBoard = false; - for (Board b : cases) { - LightUpBoard posCase = (LightUpBoard) b; - boolean foundAllCells = false; - if (posCase.getModifiedData().size() == actCase.getModifiedData().size()) { - foundAllCells = true; - for (PuzzleElement actEle : actCase.getModifiedData()) { - LightUpCell actCell = (LightUpCell) actEle; - boolean foundCell = false; - for (PuzzleElement posEle : posCase.getModifiedData()) { - LightUpCell posCell = (LightUpCell) posEle; - if (actCell.getType() == posCell.getType() - && actCell.getLocation().equals(posCell.getLocation())) { - foundCell = true; - break; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + TreeNode parent = transition.getParents().get(0); + List childTransitions = parent.getChildren(); + + List spots = getPossibleSpots(transition); + if (spots == null) { + return super.getInvalidUseOfRuleMessage(); + } + + for (LightUpCell c : spots) { + ArrayList cases = getCases(parent.getBoard(), c); + + // We will allow case rules to have only one option + if (cases.size() == childTransitions.size() && cases.size() >= 1) { + boolean foundSpot = true; + for (TreeTransition childTrans : childTransitions) { + LightUpBoard actCase = (LightUpBoard) childTrans.getBoard(); + boolean foundBoard = false; + for (Board b : cases) { + LightUpBoard posCase = (LightUpBoard) b; + boolean foundAllCells = false; + if (posCase.getModifiedData().size() == actCase.getModifiedData().size()) { + foundAllCells = true; + for (PuzzleElement actEle : actCase.getModifiedData()) { + LightUpCell actCell = (LightUpCell) actEle; + boolean foundCell = false; + for (PuzzleElement posEle : posCase.getModifiedData()) { + LightUpCell posCell = (LightUpCell) posEle; + if (actCell.getType() == posCell.getType() + && actCell.getLocation() + .equals(posCell.getLocation())) { + foundCell = true; + break; + } + } + if (!foundCell) { + foundAllCells = false; + break; + } + } + } + if (foundAllCells) { + foundBoard = true; + break; + } + } + if (!foundBoard) { + foundSpot = false; + break; + } } - if (!foundCell) { - foundAllCells = false; - break; + if (foundSpot) { + return null; } - } - } - if (foundAllCells) { - foundBoard = true; - break; } - } - if (!foundBoard) { - foundSpot = false; - break; - } } - if (foundSpot) { - return null; - } - } - } - return super.getInvalidUseOfRuleMessage(); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Gets all cells in the TreeTransition board that are adjacent to all modified cells - * - * @param transition TreeTransition object - * @return list of cells that are adjacent to all modified cells, returns null if the number of - * modified cells is =0 || >4 - */ - private List getPossibleSpots(TreeTransition transition) { - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Set modCells = transition.getBoard().getModifiedData(); - - int size = modCells.size(); - if (size == 0 || size > 4) { - return null; - } else { - Iterator it = modCells.iterator(); - List spots = getAdjacentCells(board, (LightUpCell) it.next()); - - while (it.hasNext()) { - spots.retainAll(getAdjacentCells(board, (LightUpCell) it.next())); - } - return spots; - } - } - - private List getAdjacentCells(LightUpBoard board, LightUpCell cell) { - List cells = new ArrayList<>(); - Point point = cell.getLocation(); - LightUpCell right = board.getCell(point.x + 1, point.y); - if (right != null) { - cells.add(right); + return super.getInvalidUseOfRuleMessage(); } - LightUpCell down = board.getCell(point.x, point.y + 1); - if (down != null) { - cells.add(down); - } - LightUpCell left = board.getCell(point.x - 1, point.y); - if (left != null) { - cells.add(left); + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; } - LightUpCell up = board.getCell(point.x, point.y - 1); - if (up != null) { - cells.add(up); + + /** + * Gets all cells in the TreeTransition board that are adjacent to all modified cells + * + * @param transition TreeTransition object + * @return list of cells that are adjacent to all modified cells, returns null if the number of + * modified cells is =0 || >4 + */ + private List getPossibleSpots(TreeTransition transition) { + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Set modCells = transition.getBoard().getModifiedData(); + + int size = modCells.size(); + if (size == 0 || size > 4) { + return null; + } else { + Iterator it = modCells.iterator(); + List spots = getAdjacentCells(board, (LightUpCell) it.next()); + + while (it.hasNext()) { + spots.retainAll(getAdjacentCells(board, (LightUpCell) it.next())); + } + return spots; + } } - return cells; - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - LightUpBoard puzzleBoard = (LightUpBoard) board; - LightUpCell point = (LightUpCell) puzzleBoard.getPuzzleElement(puzzleElement); - - List cells = getAdjacentCells(puzzleBoard, point); - - for (LightUpCell cell : cells) { - // add cells that can light adjacents from any direction - Point location = cell.getLocation(); - for (int i = location.x; i < puzzleBoard.getWidth(); i++) { - System.out.println(i); - LightUpCell c = puzzleBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); + + private List getAdjacentCells(LightUpBoard board, LightUpCell cell) { + List cells = new ArrayList<>(); + Point point = cell.getLocation(); + LightUpCell right = board.getCell(point.x + 1, point.y); + if (right != null) { + cells.add(right); } - } - for (int i = location.x; i >= 0; i--) { - LightUpCell c = puzzleBoard.getCell(i, location.y); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); + LightUpCell down = board.getCell(point.x, point.y + 1); + if (down != null) { + cells.add(down); } - } - for (int i = location.y; i < puzzleBoard.getHeight(); i++) { - LightUpCell c = puzzleBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); + LightUpCell left = board.getCell(point.x - 1, point.y); + if (left != null) { + cells.add(left); } - } - for (int i = location.y; i >= 0; i--) { - LightUpCell c = puzzleBoard.getCell(location.x, i); - if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { - break; - } else if (!elements.contains(board.getPuzzleElement(c))) { - elements.add(board.getPuzzleElement(c)); + LightUpCell up = board.getCell(point.x, point.y - 1); + if (up != null) { + cells.add(up); } - } + return cells; } - return elements; - } + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + LightUpBoard puzzleBoard = (LightUpBoard) board; + LightUpCell point = (LightUpCell) puzzleBoard.getPuzzleElement(puzzleElement); + + List cells = getAdjacentCells(puzzleBoard, point); + + for (LightUpCell cell : cells) { + // add cells that can light adjacents from any direction + Point location = cell.getLocation(); + for (int i = location.x; i < puzzleBoard.getWidth(); i++) { + System.out.println(i); + LightUpCell c = puzzleBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); + } + } + for (int i = location.x; i >= 0; i--) { + LightUpCell c = puzzleBoard.getCell(i, location.y); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); + } + } + for (int i = location.y; i < puzzleBoard.getHeight(); i++) { + LightUpCell c = puzzleBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); + } + } + for (int i = location.y; i >= 0; i--) { + LightUpCell c = puzzleBoard.getCell(location.x, i); + if (c.getType() == LightUpCellType.BLACK || c.getType() == LightUpCellType.NUMBER) { + break; + } else if (!elements.contains(board.getPuzzleElement(c))) { + elements.add(board.getPuzzleElement(c)); + } + } + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java index 8b00e537e..8cf68e570 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooFewBulbsContradictionRule.java @@ -10,37 +10,37 @@ public class TooFewBulbsContradictionRule extends ContradictionRule { - public TooFewBulbsContradictionRule() { - super( - "LTUP-CONT-0003", - "Too Few Bulbs", - "There cannot be less bulbs around a block than its number states.", - "edu/rpi/legup/images/lightup/contradictions/TooFewBulbs.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.NUMBER) { - return super.getNoContradictionMessage(); + public TooFewBulbsContradictionRule() { + super( + "LTUP-CONT-0003", + "Too Few Bulbs", + "There cannot be less bulbs around a block than its number states.", + "edu/rpi/legup/images/lightup/contradictions/TooFewBulbs.png"); } - int bulbs = lightUpBoard.getNumAdj(cell, LightUpCellType.BULB); - int placeable = lightUpBoard.getNumPlacble(cell); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.NUMBER) { + return super.getNoContradictionMessage(); + } + + int bulbs = lightUpBoard.getNumAdj(cell, LightUpCellType.BULB); + int placeable = lightUpBoard.getNumPlacble(cell); - if (bulbs + placeable < cell.getData()) { - return null; + if (bulbs + placeable < cell.getData()) { + return null; + } + return super.getNoContradictionMessage(); } - return super.getNoContradictionMessage(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java index 8d1403663..64cd4adcb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/lightup/rules/TooManyBulbsContradictionRule.java @@ -10,55 +10,55 @@ public class TooManyBulbsContradictionRule extends ContradictionRule { - public TooManyBulbsContradictionRule() { - super( - "LTUP-CONT-0004", - "Too Many Bulbs", - "There cannot be more bulbs around a block than its number states.", - "edu/rpi/legup/images/lightup/contradictions/TooManyBulbs.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - LightUpBoard lightUpBoard = (LightUpBoard) board; - LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != LightUpCellType.NUMBER) { - return super.getNoContradictionMessage(); + public TooManyBulbsContradictionRule() { + super( + "LTUP-CONT-0004", + "Too Many Bulbs", + "There cannot be more bulbs around a block than its number states.", + "edu/rpi/legup/images/lightup/contradictions/TooManyBulbs.png"); } - Point location = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + LightUpBoard lightUpBoard = (LightUpBoard) board; + LightUpCell cell = (LightUpCell) lightUpBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != LightUpCellType.NUMBER) { + return super.getNoContradictionMessage(); + } - int bulbs = 0; + Point location = cell.getLocation(); - LightUpCell up = lightUpBoard.getCell(location.x, location.y + 1); - if (up != null && up.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell down = lightUpBoard.getCell(location.x, location.y - 1); - if (down != null && down.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell right = lightUpBoard.getCell(location.x + 1, location.y); - if (right != null && right.getType() == LightUpCellType.BULB) { - bulbs++; - } - LightUpCell left = lightUpBoard.getCell(location.x - 1, location.y); - if (left != null && left.getType() == LightUpCellType.BULB) { - bulbs++; - } + int bulbs = 0; + + LightUpCell up = lightUpBoard.getCell(location.x, location.y + 1); + if (up != null && up.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell down = lightUpBoard.getCell(location.x, location.y - 1); + if (down != null && down.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell right = lightUpBoard.getCell(location.x + 1, location.y); + if (right != null && right.getType() == LightUpCellType.BULB) { + bulbs++; + } + LightUpCell left = lightUpBoard.getCell(location.x - 1, location.y); + if (left != null && left.getType() == LightUpCellType.BULB) { + bulbs++; + } - if (bulbs > cell.getData()) { - return null; + if (bulbs > cell.getData()) { + return null; + } + return super.getNoContradictionMessage(); } - return super.getNoContradictionMessage(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java b/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java index 98e22173e..9986a1eda 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/EditLineCommand.java @@ -17,154 +17,157 @@ import java.awt.event.MouseEvent; public class EditLineCommand extends PuzzleCommand { - private TreeTransition transition; - private PuzzleElement oldData; - private PuzzleElement newData; - - private ElementView elementView; - private TreeElementView selectedView; - private TreeElementView newSelectedView; - private MouseEvent event; - - private TreeTransitionView transitionView; - - public EditLineCommand( - ElementView elementView, TreeElementView selectedView, MouseEvent event, MasyuLine line) { - this.elementView = elementView; - this.selectedView = selectedView; - this.event = event; - this.newData = line; - this.oldData = newData.copy(); - this.transition = null; - } - - /** Executes a command */ - @Override - public void executeCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - Puzzle puzzle = getInstance().getPuzzleModule(); - - MasyuBoard board = (MasyuBoard) selectedView.getTreeElement().getBoard(); - int index = elementView.getIndex(); - - if (selectedView.getType() == TreeElementType.NODE) { - TreeNodeView nodeView = (TreeNodeView) selectedView; - TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); - - if (transition == null) { - transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); - } - - treeNode.getChildren().add(transition); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeElementAdded(transition)); - transitionView = (TreeTransitionView) treeView.getElementView(transition); - - selection.newSelection(transitionView); - puzzle.notifyTreeListeners( - (ITreeListener listener) -> listener.onTreeSelectionChanged(selection)); - - getInstance().getLegupUI().repaintTree(); - board = (MasyuBoard) transition.getBoard(); - getInstance().getPuzzleModule().setCurrentBoard(board); - oldData = newData.copy(); - } else { - transitionView = (TreeTransitionView) selectedView; - transition = transitionView.getTreeElement(); + private TreeTransition transition; + private PuzzleElement oldData; + private PuzzleElement newData; + + private ElementView elementView; + private TreeElementView selectedView; + private TreeElementView newSelectedView; + private MouseEvent event; + + private TreeTransitionView transitionView; + + public EditLineCommand( + ElementView elementView, + TreeElementView selectedView, + MouseEvent event, + MasyuLine line) { + this.elementView = elementView; + this.selectedView = selectedView; + this.event = event; + this.newData = line; + this.oldData = newData.copy(); + this.transition = null; } - newSelectedView = transitionView; - PuzzleElement dup_line = null; - boolean mod_contains = false; - boolean contains = false; - final MasyuBoard editBoard = board; - System.out.println("Size: " + board.getModifiedData().size()); - for (PuzzleElement puzzleElement : board.getModifiedData()) { - if (puzzleElement instanceof MasyuLine) { - if (((MasyuLine) newData).compare((MasyuLine) puzzleElement)) { - System.out.println("contains"); - dup_line = puzzleElement; - mod_contains = true; + + /** Executes a command */ + @Override + public void executeCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + Puzzle puzzle = getInstance().getPuzzleModule(); + + MasyuBoard board = (MasyuBoard) selectedView.getTreeElement().getBoard(); + int index = elementView.getIndex(); + + if (selectedView.getType() == TreeElementType.NODE) { + TreeNodeView nodeView = (TreeNodeView) selectedView; + TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); + + if (transition == null) { + transition = new TreeTransition(treeNode, treeNode.getBoard().copy()); + } + + treeNode.getChildren().add(transition); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeElementAdded(transition)); + transitionView = (TreeTransitionView) treeView.getElementView(transition); + + selection.newSelection(transitionView); + puzzle.notifyTreeListeners( + (ITreeListener listener) -> listener.onTreeSelectionChanged(selection)); + + getInstance().getLegupUI().repaintTree(); + board = (MasyuBoard) transition.getBoard(); + getInstance().getPuzzleModule().setCurrentBoard(board); + oldData = newData.copy(); + } else { + transitionView = (TreeTransitionView) selectedView; + transition = transitionView.getTreeElement(); } - } - } - for (int i = 0; i < board.getLines().size(); i++) { - if (board.getLines().get(i).compare((MasyuLine) newData)) { - contains = true; - } - } - if (contains || mod_contains) { - System.out.println("delete"); - board.getModifiedData().remove(dup_line); - board.getLines().remove(dup_line); - // puzzle.notifyBoardListeners((IBoardListener listener) -> - // listener.onTreeElementChanged(editBoard)); - } else { - System.out.println("adding"); - board.getModifiedData().add(newData); - board.getLines().add((MasyuLine) newData); - // puzzle.notifyBoardListeners((IBoardListener listener) -> - // listener.onTreeElementChanged(editBoard)); + newSelectedView = transitionView; + PuzzleElement dup_line = null; + boolean mod_contains = false; + boolean contains = false; + final MasyuBoard editBoard = board; + System.out.println("Size: " + board.getModifiedData().size()); + for (PuzzleElement puzzleElement : board.getModifiedData()) { + if (puzzleElement instanceof MasyuLine) { + if (((MasyuLine) newData).compare((MasyuLine) puzzleElement)) { + System.out.println("contains"); + dup_line = puzzleElement; + mod_contains = true; + } + } + } + for (int i = 0; i < board.getLines().size(); i++) { + if (board.getLines().get(i).compare((MasyuLine) newData)) { + contains = true; + } + } + if (contains || mod_contains) { + System.out.println("delete"); + board.getModifiedData().remove(dup_line); + board.getLines().remove(dup_line); + // puzzle.notifyBoardListeners((IBoardListener listener) -> + // listener.onTreeElementChanged(editBoard)); + } else { + System.out.println("adding"); + board.getModifiedData().add(newData); + board.getLines().add((MasyuLine) newData); + // puzzle.notifyBoardListeners((IBoardListener listener) -> + // listener.onTreeElementChanged(editBoard)); + } + + transition.propagateChange(newData); } - transition.propagateChange(newData); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - Board board = selectedView.getTreeElement().getBoard(); - if (!board.isModifiable()) { - return "Board is not modifiable"; - } else { - if (!board.getPuzzleElement(elementView.getPuzzleElement()).isModifiable()) { - return "Data is not modifiable"; - } + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + Board board = selectedView.getTreeElement().getBoard(); + if (!board.isModifiable()) { + return "Board is not modifiable"; + } else { + if (!board.getPuzzleElement(elementView.getPuzzleElement()).isModifiable()) { + return "Data is not modifiable"; + } + } + return null; } - return null; - } - /** Undoes an command */ - @Override - public void undoCommand() { - Tree tree = getInstance().getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeViewSelection selection = treeView.getSelection(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); + /** Undoes an command */ + @Override + public void undoCommand() { + Tree tree = getInstance().getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeViewSelection selection = treeView.getSelection(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); - Board board = transition.getBoard(); + Board board = transition.getBoard(); - if (selectedView.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); + if (selectedView.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) selectedView.getTreeElement(); - tree.removeTreeElement(transition); - treeView.removeTreeElement(newSelectedView); + tree.removeTreeElement(transition); + treeView.removeTreeElement(newSelectedView); - selection.newSelection(selectedView); + selection.newSelection(selectedView); - getInstance().getLegupUI().repaintTree(); - getInstance().getPuzzleModule().setCurrentBoard(treeNode.getBoard()); - } + getInstance().getLegupUI().repaintTree(); + getInstance().getPuzzleModule().setCurrentBoard(treeNode.getBoard()); + } - Board prevBoard = null; // transition.getParentNode().getBoard(); + Board prevBoard = null; // transition.getParentNode().getBoard(); - newData.setData(oldData.getData()); - board.notifyChange(newData); + newData.setData(oldData.getData()); + board.notifyChange(newData); - // System.err.println(newData.getData() + " : " + oldData.getData()); + // System.err.println(newData.getData() + " : " + oldData.getData()); - if (prevBoard.getPuzzleElement(elementView.getPuzzleElement()).equalsData(newData)) { - board.removeModifiedData(newData); - } else { - board.addModifiedData(newData); + if (prevBoard.getPuzzleElement(elementView.getPuzzleElement()).equalsData(newData)) { + board.removeModifiedData(newData); + } else { + board.addModifiedData(newData); + } + transition.propagateChange(newData); } - transition.propagateChange(newData); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java b/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java index 1c5d19e08..1ab74d56b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/Masyu.java @@ -5,63 +5,63 @@ public class Masyu extends Puzzle { - public Masyu() { - super(); + public Masyu() { + super(); - this.name = "Masyu"; + this.name = "Masyu"; - this.importer = new MasyuImporter(this); - this.exporter = new MasyuExporter(this); + this.importer = new MasyuImporter(this); + this.exporter = new MasyuExporter(this); - this.factory = new MasyuCellFactory(); - } + this.factory = new MasyuCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new MasyuView((MasyuBoard) currentBoard); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new MasyuView((MasyuBoard) currentBoard); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Masyu - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Masyu, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - throw new UnsupportedOperationException(); - } + @Override + /** + * Determines if the given dimensions are valid for Masyu + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Masyu, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + throw new UnsupportedOperationException(); + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java index 554408dd3..f347ff4c4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuBoard.java @@ -7,53 +7,53 @@ public class MasyuBoard extends GridBoard { - private List lines; - - public MasyuBoard(int width, int height) { - super(width, height); - this.lines = new ArrayList<>(); - } - - public MasyuBoard(int size) { - this(size, size); - } - - @Override - public MasyuCell getCell(int x, int y) { - return (MasyuCell) super.getCell(x, y); - } - - public List getLines() { - return lines; - } - - public void setLines(List lines) { - this.lines = lines; - } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - if (puzzleElement instanceof MasyuLine) { - lines.add((MasyuLine) puzzleElement); - } else { - super.notifyChange(puzzleElement); + private List lines; + + public MasyuBoard(int width, int height) { + super(width, height); + this.lines = new ArrayList<>(); + } + + public MasyuBoard(int size) { + this(size, size); + } + + @Override + public MasyuCell getCell(int x, int y) { + return (MasyuCell) super.getCell(x, y); } - } - - @Override - public MasyuBoard copy() { - MasyuBoard copy = new MasyuBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + + public List getLines() { + return lines; } - for (MasyuLine line : lines) { - copy.lines.add(line.copy()); + + public void setLines(List lines) { + this.lines = lines; } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + if (puzzleElement instanceof MasyuLine) { + lines.add((MasyuLine) puzzleElement); + } else { + super.notifyChange(puzzleElement); + } + } + + @Override + public MasyuBoard copy() { + MasyuBoard copy = new MasyuBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (MasyuLine line : lines) { + copy.lines.add(line.copy()); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; } - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java index 7d23cdf37..af0811c55 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCell.java @@ -5,20 +5,20 @@ public class MasyuCell extends GridCell { - public MasyuCell(MasyuType value, Point location) { - super(value, location); - } + public MasyuCell(MasyuType value, Point location) { + super(value, location); + } - public MasyuType getType() { - return data; - } + public MasyuType getType() { + return data; + } - @Override - public MasyuCell copy() { - MasyuCell copy = new MasyuCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public MasyuCell copy() { + MasyuCell copy = new MasyuCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java index 803edfbea..50e3c4cc0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuCellFactory.java @@ -10,63 +10,65 @@ import org.w3c.dom.Node; public class MasyuCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public MasyuCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Masyu Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public MasyuCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Masyu Factory: unknown puzzleElement puzzleElement"); + } - MasyuBoard masyuBoard = (MasyuBoard) board; - int width = masyuBoard.getWidth(); - int height = masyuBoard.getHeight(); + MasyuBoard masyuBoard = (MasyuBoard) board; + int width = masyuBoard.getWidth(); + int height = masyuBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("Masyu Factory: cell location out of bounds"); - } - if (value < 0 || value > 2) { - throw new InvalidFileFormatException("Masyu Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException("Masyu Factory: cell location out of bounds"); + } + if (value < 0 || value > 2) { + throw new InvalidFileFormatException("Masyu Factory: cell unknown value"); + } - MasyuCell cell = new MasyuCell(MasyuType.convertToMasyuType(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("Masyu Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Masyu Factory: could not find attribute(s)"); + MasyuCell cell = new MasyuCell(MasyuType.convertToMasyuType(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Masyu Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Masyu Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - MasyuCell cell = (MasyuCell) puzzleElement; - Point loc = cell.getLocation(); + MasyuCell cell = (MasyuCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java index 1644e4d11..202c43a1e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuController.java @@ -14,89 +14,93 @@ public class MasyuController extends ElementController { - private MasyuElementView mousePressedCell; - private MasyuElementView mouseDraggedCell; - private List masyuLine; + private MasyuElementView mousePressedCell; + private MasyuElementView mouseDraggedCell; + private List masyuLine; - public MasyuController() { - super(); - this.mousePressedCell = null; - this.mouseDraggedCell = null; - this.masyuLine = new ArrayList<>(); - } + public MasyuController() { + super(); + this.mousePressedCell = null; + this.mouseDraggedCell = null; + this.masyuLine = new ArrayList<>(); + } - /** - * Invoked when a mouse button has been pressed on a component. - * - * @param e the event to be processed - */ - @Override - public void mousePressed(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - this.masyuLine.clear(); - mousePressedCell = (MasyuElementView) boardView.getElement(e.getPoint()); - masyuLine.add(mousePressedCell); - } + /** + * Invoked when a mouse button has been pressed on a component. + * + * @param e the event to be processed + */ + @Override + public void mousePressed(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + this.masyuLine.clear(); + mousePressedCell = (MasyuElementView) boardView.getElement(e.getPoint()); + masyuLine.add(mousePressedCell); + } - @Override - public void mouseDragged(MouseEvent e) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - MasyuElementView elementView = (MasyuElementView) boardView.getElement(e.getPoint()); - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (mousePressedCell != null && elementView != null) { - if (mouseDraggedCell == null) { - mouseDraggedCell = elementView; - Point p1 = mousePressedCell.getPuzzleElement().getLocation(); - Point p2 = mouseDraggedCell.getPuzzleElement().getLocation(); + @Override + public void mouseDragged(MouseEvent e) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + MasyuElementView elementView = (MasyuElementView) boardView.getElement(e.getPoint()); + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (mousePressedCell != null && elementView != null) { + if (mouseDraggedCell == null) { + mouseDraggedCell = elementView; + Point p1 = mousePressedCell.getPuzzleElement().getLocation(); + Point p2 = mouseDraggedCell.getPuzzleElement().getLocation(); - if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { - masyuLine.add(elementView); - MasyuLine newLine = - new MasyuLine( - mousePressedCell.getPuzzleElement(), mouseDraggedCell.getPuzzleElement()); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); - } - } else { - if (mouseDraggedCell != elementView) { - Point p1 = mouseDraggedCell.getPuzzleElement().getLocation(); - Point p2 = elementView.getPuzzleElement().getLocation(); + if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { + masyuLine.add(elementView); + MasyuLine newLine = + new MasyuLine( + mousePressedCell.getPuzzleElement(), + mouseDraggedCell.getPuzzleElement()); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); + } + } else { + if (mouseDraggedCell != elementView) { + Point p1 = mouseDraggedCell.getPuzzleElement().getLocation(); + Point p2 = elementView.getPuzzleElement().getLocation(); - if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { - masyuLine.add(elementView); - MasyuLine newLine = - new MasyuLine(mouseDraggedCell.getPuzzleElement(), elementView.getPuzzleElement()); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(newLine)); - } - mouseDraggedCell = elementView; + if (Math.abs(p1.x - p2.x) == 1 ^ Math.abs(p1.y - p2.y) == 1) { + masyuLine.add(elementView); + MasyuLine newLine = + new MasyuLine( + mouseDraggedCell.getPuzzleElement(), + elementView.getPuzzleElement()); + puzzle.notifyBoardListeners( + listener -> listener.onBoardDataChanged(newLine)); + } + mouseDraggedCell = elementView; + } + } } - } } - } - - @Override - public void mouseReleased(MouseEvent e) { - super.mouseReleased(e); - mousePressedCell = null; - mouseDraggedCell = null; - masyuLine.clear(); - } - /** - * Alters the cells as they are being dragged over or clicked - * - * @param e Mouse event being used - * @param data Data of selected cell - */ - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - MasyuCell cell = (MasyuCell) data; - if (cell.getData() == MasyuType.BLACK || cell.getData() == MasyuType.WHITE) { - return; + @Override + public void mouseReleased(MouseEvent e) { + super.mouseReleased(e); + mousePressedCell = null; + mouseDraggedCell = null; + masyuLine.clear(); } - if (cell.getData() == MasyuType.UNKNOWN) { - data.setData(3); - } else { - data.setData(0); + + /** + * Alters the cells as they are being dragged over or clicked + * + * @param e Mouse event being used + * @param data Data of selected cell + */ + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + MasyuCell cell = (MasyuCell) data; + if (cell.getData() == MasyuType.BLACK || cell.getData() == MasyuType.WHITE) { + return; + } + if (cell.getData() == MasyuType.UNKNOWN) { + data.setData(3); + } else { + data.setData(0); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java index d01e74033..942e1ffd2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuElementView.java @@ -4,48 +4,48 @@ import java.awt.*; public class MasyuElementView extends GridElementView { - public MasyuElementView(MasyuCell masyuCell) { - super(masyuCell); - } + public MasyuElementView(MasyuCell masyuCell) { + super(masyuCell); + } - @Override - public MasyuCell getPuzzleElement() { - return (MasyuCell) super.getPuzzleElement(); - } + @Override + public MasyuCell getPuzzleElement() { + return (MasyuCell) super.getPuzzleElement(); + } - @Override - public void drawElement(Graphics2D graphics2D) { - MasyuCell cell = (MasyuCell) puzzleElement; - MasyuType type = cell.getType(); - if (type == MasyuType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == MasyuType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == MasyuType.WHITE) { - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.WHITE); - graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); - graphics2D.setColor(Color.BLACK); - graphics2D.drawOval(location.x + 6, location.y + 6, 18, 18); - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + MasyuCell cell = (MasyuCell) puzzleElement; + MasyuType type = cell.getType(); + if (type == MasyuType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == MasyuType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == MasyuType.WHITE) { + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.WHITE); + graphics2D.fillOval(location.x + 5, location.y + 5, 20, 20); + graphics2D.setColor(Color.BLACK); + graphics2D.drawOval(location.x + 6, location.y + 6, 18, 18); + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java index 0f8555ce0..0c692193a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuExporter.java @@ -6,31 +6,32 @@ public class MasyuExporter extends PuzzleExporter { - public MasyuExporter(Masyu masyu) { - super(masyu); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - MasyuBoard board; - if (puzzle.getTree() != null) { - board = (MasyuBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (MasyuBoard) puzzle.getBoardView().getBoard(); + public MasyuExporter(Masyu masyu) { + super(masyu); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + MasyuBoard board; + if (puzzle.getTree() != null) { + board = (MasyuBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (MasyuBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - MasyuCell cell = (MasyuCell) puzzleElement; - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + MasyuCell cell = (MasyuCell) puzzleElement; + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java index b5db71234..2170da3ee 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuImporter.java @@ -8,98 +8,102 @@ import org.w3c.dom.NodeList; public class MasyuImporter extends PuzzleImporter { - public MasyuImporter(Masyu masyu) { - super(masyu); - } + public MasyuImporter(Masyu masyu) { + super(masyu); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) {} + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) {} - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Masyu Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Masyu Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Masyu Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Masyu Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - MasyuBoard masyuBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - masyuBoard = new MasyuBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - masyuBoard = new MasyuBoard(width, height); - } - } + MasyuBoard masyuBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + masyuBoard = new MasyuBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + masyuBoard = new MasyuBoard(width, height); + } + } - if (masyuBoard == null) { - throw new InvalidFileFormatException("Masyu Importer: invalid board dimensions"); - } + if (masyuBoard == null) { + throw new InvalidFileFormatException("Masyu Importer: invalid board dimensions"); + } - int width = masyuBoard.getWidth(); - int height = masyuBoard.getHeight(); + int width = masyuBoard.getWidth(); + int height = masyuBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - MasyuCell cell = - (MasyuCell) puzzle.getFactory().importCell(elementDataList.item(i), masyuBoard); - Point loc = cell.getLocation(); - if (cell.getData() != MasyuType.UNKNOWN) { - cell.setModifiable(false); - cell.setGiven(true); - } - masyuBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + MasyuCell cell = + (MasyuCell) + puzzle.getFactory().importCell(elementDataList.item(i), masyuBoard); + Point loc = cell.getLocation(); + if (cell.getData() != MasyuType.UNKNOWN) { + cell.setModifiable(false); + cell.setGiven(true); + } + masyuBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (masyuBoard.getCell(x, y) == null) { - MasyuCell cell = new MasyuCell(MasyuType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - masyuBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (masyuBoard.getCell(x, y) == null) { + MasyuCell cell = new MasyuCell(MasyuType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + masyuBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(masyuBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Masyu Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(masyuBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("Masyu Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Masyu cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Masyu cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java index 30924ea57..eda51c839 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLine.java @@ -4,40 +4,40 @@ import edu.rpi.legup.utility.Entry; public class MasyuLine extends PuzzleElement> { - public MasyuLine(MasyuCell c1, MasyuCell c2) { - this.data = new Entry<>(c1, c2); - } - - public MasyuCell getC1() { - return data.getKey(); - } - - public void setC1(MasyuCell c1) { - this.data.setKey(c1); - } - - public MasyuCell getC2() { - return data.getValue(); - } - - public void setC2(MasyuCell c2) { - this.data.setValue(c2); - } - - public boolean compare(MasyuLine line) { - return ((line.getC1().getLocation().equals(data.getKey().getLocation()) - && line.getC2().getLocation().equals(data.getValue().getLocation())) - || (line.getC1().getLocation().equals(data.getValue().getLocation()) - && line.getC2().getLocation().equals(data.getKey().getLocation()))); - } - - /** - * Copies this elements puzzleElement to a new PuzzleElement object - * - * @return copied PuzzleElement object - */ - @Override - public MasyuLine copy() { - return new MasyuLine(data.getKey().copy(), data.getValue().copy()); - } + public MasyuLine(MasyuCell c1, MasyuCell c2) { + this.data = new Entry<>(c1, c2); + } + + public MasyuCell getC1() { + return data.getKey(); + } + + public void setC1(MasyuCell c1) { + this.data.setKey(c1); + } + + public MasyuCell getC2() { + return data.getValue(); + } + + public void setC2(MasyuCell c2) { + this.data.setValue(c2); + } + + public boolean compare(MasyuLine line) { + return ((line.getC1().getLocation().equals(data.getKey().getLocation()) + && line.getC2().getLocation().equals(data.getValue().getLocation())) + || (line.getC1().getLocation().equals(data.getValue().getLocation()) + && line.getC2().getLocation().equals(data.getKey().getLocation()))); + } + + /** + * Copies this elements puzzleElement to a new PuzzleElement object + * + * @return copied PuzzleElement object + */ + @Override + public MasyuLine copy() { + return new MasyuLine(data.getKey().copy(), data.getValue().copy()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java index 54efc335f..c967f4865 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuLineView.java @@ -4,27 +4,27 @@ import java.awt.*; public class MasyuLineView extends ElementView { - private final Color LINE_COLOR = Color.GREEN; + private final Color LINE_COLOR = Color.GREEN; - private final Stroke LINE_STROKE = new BasicStroke(3); + private final Stroke LINE_STROKE = new BasicStroke(3); - public MasyuLineView(MasyuLine line) { - super(line); - } + public MasyuLineView(MasyuLine line) { + super(line); + } - @Override - public void draw(Graphics2D graphics2D) { - MasyuLine line = (MasyuLine) puzzleElement; - Point p1 = line.getC1().getLocation(); - Point p2 = line.getC2().getLocation(); - int x1 = p1.x * size.width + size.width / 2; - int y1 = p1.y * size.height + size.height / 2; + @Override + public void draw(Graphics2D graphics2D) { + MasyuLine line = (MasyuLine) puzzleElement; + Point p1 = line.getC1().getLocation(); + Point p2 = line.getC2().getLocation(); + int x1 = p1.x * size.width + size.width / 2; + int y1 = p1.y * size.height + size.height / 2; - int x2 = p2.x * size.width + size.width / 2; - int y2 = p2.y * size.height + size.height / 2; + int x2 = p2.x * size.width + size.width / 2; + int y2 = p2.y * size.height + size.height / 2; - graphics2D.setColor(line.isModified() ? Color.GREEN : Color.BLACK); - graphics2D.setStroke(LINE_STROKE); - graphics2D.drawLine(x1, y1, x2, y2); - } + graphics2D.setColor(line.isModified() ? Color.GREEN : Color.BLACK); + graphics2D.setStroke(LINE_STROKE); + graphics2D.drawLine(x1, y1, x2, y2); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java index 114e4bf71..4029d259d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuType.java @@ -1,21 +1,21 @@ package edu.rpi.legup.puzzle.masyu; public enum MasyuType { - UNKNOWN, - BLACK, - WHITE, - LINE; + UNKNOWN, + BLACK, + WHITE, + LINE; - public static MasyuType convertToMasyuType(int num) { - switch (num) { - case 1: - return BLACK; - case 2: - return WHITE; - case 3: - return LINE; - default: - return UNKNOWN; + public static MasyuType convertToMasyuType(int num) { + switch (num) { + case 1: + return BLACK; + case 2: + return WHITE; + case 3: + return LINE; + default: + return UNKNOWN; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java index dc81b24cd..e962a6ebf 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/MasyuView.java @@ -8,47 +8,49 @@ import java.util.List; public class MasyuView extends GridBoardView { - private List lineViews; + private List lineViews; - public MasyuView(MasyuBoard board) { - super(new BoardController(), new MasyuController(), board.getDimension()); + public MasyuView(MasyuBoard board) { + super(new BoardController(), new MasyuController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - MasyuCell cell = (MasyuCell) puzzleElement; - Point loc = cell.getLocation(); - MasyuElementView elementView = new MasyuElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + MasyuCell cell = (MasyuCell) puzzleElement; + Point loc = cell.getLocation(); + MasyuElementView elementView = new MasyuElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } + lineViews = new ArrayList<>(); + for (MasyuLine line : board.getLines()) { + MasyuLineView lineView = new MasyuLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } } - lineViews = new ArrayList<>(); - for (MasyuLine line : board.getLines()) { - MasyuLineView lineView = new MasyuLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - super.drawBoard(graphics2D); - lineViews.forEach(masyuLineView -> masyuLineView.draw(graphics2D)); - } + @Override + public void drawBoard(Graphics2D graphics2D) { + graphics2D.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + super.drawBoard(graphics2D); + lineViews.forEach(masyuLineView -> masyuLineView.draw(graphics2D)); + } - /** - * Called when the board puzzleElement changed - * - * @param puzzleElement puzzleElement of the puzzleElement that changed - */ - @Override - public void onBoardDataChanged(PuzzleElement puzzleElement) { - if (puzzleElement instanceof MasyuLine) { - MasyuLineView lineView = new MasyuLineView((MasyuLine) puzzleElement); - lineView.setSize(elementSize); - lineViews.add(lineView); + /** + * Called when the board puzzleElement changed + * + * @param puzzleElement puzzleElement of the puzzleElement that changed + */ + @Override + public void onBoardDataChanged(PuzzleElement puzzleElement) { + if (puzzleElement instanceof MasyuLine) { + MasyuLineView lineView = new MasyuLineView((MasyuLine) puzzleElement); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + repaint(); } - repaint(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java index f4dd95268..1681446cd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BadLoopingContradictionRule.java @@ -6,25 +6,25 @@ public class BadLoopingContradictionRule extends ContradictionRule { - public BadLoopingContradictionRule() { - super( - "MASY-CONT-0001", - "Bad Looping", - "", - "edu/rpi/legup/images/masyu/ContradictionBadLooping.png"); - } + public BadLoopingContradictionRule() { + super( + "MASY-CONT-0001", + "Bad Looping", + "", + "edu/rpi/legup/images/masyu/ContradictionBadLooping.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java index f4e95eb14..c219eeaa3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackContradictionRule.java @@ -6,21 +6,21 @@ public class BlackContradictionRule extends ContradictionRule { - public BlackContradictionRule() { - super("MASY-CONT-0002", "Black", "", "edu/rpi/legup/images/masyu/ContradictionBlack.png"); - } + public BlackContradictionRule() { + super("MASY-CONT-0002", "Black", "", "edu/rpi/legup/images/masyu/ContradictionBlack.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java index 63b40d7f3..665a74204 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackEdgeDirectRule.java @@ -8,33 +8,34 @@ public class BlackEdgeDirectRule extends DirectRule { - public BlackEdgeDirectRule() { - super("MASY-BASC-0001", "Black Edge", "", "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); - } + public BlackEdgeDirectRule() { + super("MASY-BASC-0001", "Black Edge", "", "edu/rpi/legup/images/masyu/RuleBlackEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java index 2b598321c..c7e3ff500 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlackSplitCaseRule.java @@ -9,59 +9,59 @@ public class BlackSplitCaseRule extends CaseRule { - public BlackSplitCaseRule() { - super("MASY-CASE-0001", "Black Split", "", "edu/rpi/legup/images/masyu/CaseBlackSplit.png"); - } + public BlackSplitCaseRule() { + super("MASY-CASE-0001", "Black Split", "", "edu/rpi/legup/images/masyu/CaseBlackSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java index faa311450..5c284eb45 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/BlockedBlackDirectRule.java @@ -8,33 +8,38 @@ public class BlockedBlackDirectRule extends DirectRule { - public BlockedBlackDirectRule() { - super("MASY-BASC-0002", "Blocked Black", "", "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); - } + public BlockedBlackDirectRule() { + super( + "MASY-BASC-0002", + "Blocked Black", + "", + "edu/rpi/legup/images/masyu/RuleBlockedBlack.gif"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java index 1a49b83a1..6aee8ba5f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/ConnectedCellsDirectRule.java @@ -8,37 +8,38 @@ public class ConnectedCellsDirectRule extends DirectRule { - public ConnectedCellsDirectRule() { - super( - "MASY-BASC-0003", - "Connected Cells", - "", - "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); - } + public ConnectedCellsDirectRule() { + super( + "MASY-BASC-0003", + "Connected Cells", + "", + "edu/rpi/legup/images/masyu/RuleConnectedCells.gif"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java index f6c95050b..27b39bc04 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/FinishPathDirectRule.java @@ -8,33 +8,38 @@ public class FinishPathDirectRule extends DirectRule { - public FinishPathDirectRule() { - super("MASY-BASC-0004", "Finished Path", "", "edu/rpi/legup/images/masyu/RuleFinishPath.png"); - } + public FinishPathDirectRule() { + super( + "MASY-BASC-0004", + "Finished Path", + "", + "edu/rpi/legup/images/masyu/RuleFinishPath.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java index 67ed25d64..6a565bc82 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NearWhiteDirectRule.java @@ -8,33 +8,34 @@ public class NearWhiteDirectRule extends DirectRule { - public NearWhiteDirectRule() { - super("MASY-BASC-0005", "Near White", "", "edu/rpi/legup/images/masyu/RuleNearWhite.png"); - } + public NearWhiteDirectRule() { + super("MASY-BASC-0005", "Near White", "", "edu/rpi/legup/images/masyu/RuleNearWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java index f068c6503..c41999b9c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NoOptionsContradictionRule.java @@ -6,25 +6,25 @@ public class NoOptionsContradictionRule extends ContradictionRule { - public NoOptionsContradictionRule() { - super( - "MASY-CONT-0003", - "No Options", - "", - "edu/rpi/legup/images/masyu/ContradictionNoOptions.png"); - } + public NoOptionsContradictionRule() { + super( + "MASY-CONT-0003", + "No Options", + "", + "edu/rpi/legup/images/masyu/ContradictionNoOptions.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java index 015a7dcf9..382ac6466 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/NormalSplitCaseRule.java @@ -9,59 +9,63 @@ public class NormalSplitCaseRule extends CaseRule { - public NormalSplitCaseRule() { - super("MASY-CASE-0002", "Normal Split", "", "edu/rpi/legup/images/masyu/CaseNormalSplit.png"); - } + public NormalSplitCaseRule() { + super( + "MASY-CASE-0002", + "Normal Split", + "", + "edu/rpi/legup/images/masyu/CaseNormalSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java index b25ac8c09..bc7353e5d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyOneChoiceDirectRule.java @@ -8,37 +8,38 @@ public class OnlyOneChoiceDirectRule extends DirectRule { - public OnlyOneChoiceDirectRule() { - super( - "MASY-BASC-0006", - "Only One Choice", - "", - "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); - } + public OnlyOneChoiceDirectRule() { + super( + "MASY-BASC-0006", + "Only One Choice", + "", + "edu/rpi/legup/images/masyu/RuleOnlyOneChoice.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java index bda563b2e..ee71ee2bc 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/OnlyTwoContradictionRule.java @@ -6,21 +6,25 @@ public class OnlyTwoContradictionRule extends ContradictionRule { - public OnlyTwoContradictionRule() { - super("MASY-CONT-0004", "Only Two", "", "edu/rpi/legup/images/masyu/ContradictionOnly2.png"); - } + public OnlyTwoContradictionRule() { + super( + "MASY-CONT-0004", + "Only Two", + "", + "edu/rpi/legup/images/masyu/ContradictionOnly2.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java index 4ae418c36..efc523b8d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteContradictionRule.java @@ -6,21 +6,21 @@ public class WhiteContradictionRule extends ContradictionRule { - public WhiteContradictionRule() { - super("MASY-CONT-0005", "White", "", "edu/rpi/legup/images/masyu/ContradictionWhite.png"); - } + public WhiteContradictionRule() { + super("MASY-CONT-0005", "White", "", "edu/rpi/legup/images/masyu/ContradictionWhite.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java index e653c96b0..4d2982d00 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteEdgeDirectRule.java @@ -7,33 +7,34 @@ import edu.rpi.legup.model.tree.TreeTransition; public class WhiteEdgeDirectRule extends DirectRule { - public WhiteEdgeDirectRule() { - super("MASY-BASC-0007", "White Edge", "", "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); - } + public WhiteEdgeDirectRule() { + super("MASY-BASC-0007", "White Edge", "", "edu/rpi/legup/images/masyu/RuleWhiteEdge.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule This method is the one that should overridden in child - * classes - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule This method is the one that should overridden in child + * classes + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java index e8eb97cd8..d50ddacfa 100644 --- a/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/masyu/rules/WhiteSplitCaseRule.java @@ -9,59 +9,59 @@ public class WhiteSplitCaseRule extends CaseRule { - public WhiteSplitCaseRule() { - super("MASY-CASE-0003", "White Split", "", "edu/rpi/legup/images/masyu/CaseWhiteSplit.png"); - } + public WhiteSplitCaseRule() { + super("MASY-CASE-0003", "White Split", "", "edu/rpi/legup/images/masyu/CaseWhiteSplit.png"); + } - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule. This method is the one that should overridden in child - * classes. - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule. This method is the one that should overridden in child + * classes. + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - /** - * Gets the case board that indicates where this case rule can be applied on the given {@link - * Board}. - * - * @param board board to find locations where this case rule can be applied - * @return a case board - */ - @Override - public CaseBoard getCaseBoard(Board board) { - return null; - } + /** + * Gets the case board that indicates where this case rule can be applied on the given {@link + * Board}. + * + * @param board board to find locations where this case rule can be applied + * @return a case board + */ + @Override + public CaseBoard getCaseBoard(Board board) { + return null; + } - /** - * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on - * this case rule. - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public List getCases(Board board, PuzzleElement puzzleElement) { - return null; - } + /** + * Gets the possible cases for this {@link Board} at a specific {@link PuzzleElement} based on + * this case rule. + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public List getCases(Board board, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java index c8aa80012..8366d905f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/Nurikabe.java @@ -6,77 +6,77 @@ import edu.rpi.legup.model.rules.ContradictionRule; public class Nurikabe extends Puzzle { - public Nurikabe() { - super(); + public Nurikabe() { + super(); - this.name = "Nurikabe"; + this.name = "Nurikabe"; - this.importer = new NurikabeImporter(this); - this.exporter = new NurikabeExporter(this); + this.importer = new NurikabeImporter(this); + this.exporter = new NurikabeExporter(this); - this.factory = new NurikabeCellFactory(); - } + this.factory = new NurikabeCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new NurikabeView((NurikabeBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new NurikabeView((NurikabeBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Nurikabe - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Nurikabe, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows >= 2 && columns >= 2; - } + @Override + /** + * Determines if the given dimensions are valid for Nurikabe + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Nurikabe, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows >= 2 && columns >= 2; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(nurikabeBoard) == null) { - return false; - } - } - for (PuzzleElement data : nurikabeBoard.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.UNKNOWN) { - return false; - } + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(nurikabeBoard) == null) { + return false; + } + } + for (PuzzleElement data : nurikabeBoard.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.UNKNOWN) { + return false; + } + } + return true; } - return true; - } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java index 7be7813ac..1f80611e8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeBoard.java @@ -4,53 +4,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class NurikabeBoard extends GridBoard { - public NurikabeBoard(int width, int height) { - super(width, height); - } - - public NurikabeBoard(int size) { - super(size, size); - } + public NurikabeBoard(int width, int height) { + super(width, height); + } - @Override - public NurikabeCell getCell(int x, int y) { - if (y * dimension.width + x >= puzzleElements.size() - || x >= dimension.width - || y >= dimension.height - || x < 0 - || y < 0) { - return null; + public NurikabeBoard(int size) { + super(size, size); } - return (NurikabeCell) super.getCell(x, y); - } - /** - * Gets the cells as an int array - * - * @return int array of values - */ - public int[][] getIntArray() { - int[][] arr = new int[dimension.height][dimension.width]; - for (int i = 0; i < dimension.height; i++) { - for (int k = 0; k < dimension.width; k++) { - arr[i][k] = getCell(k, i).getData(); - } + @Override + public NurikabeCell getCell(int x, int y) { + if (y * dimension.width + x >= puzzleElements.size() + || x >= dimension.width + || y >= dimension.height + || x < 0 + || y < 0) { + return null; + } + return (NurikabeCell) super.getCell(x, y); } - return arr; - } - @Override - public NurikabeBoard copy() { - // System.out.println("NurikabeBoard copy()"); - NurikabeBoard copy = new NurikabeBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + /** + * Gets the cells as an int array + * + * @return int array of values + */ + public int[][] getIntArray() { + int[][] arr = new int[dimension.height][dimension.width]; + for (int i = 0; i < dimension.height; i++) { + for (int k = 0; k < dimension.width; k++) { + arr[i][k] = getCell(k, i).getData(); + } + } + return arr; } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + @Override + public NurikabeBoard copy() { + // System.out.println("NurikabeBoard copy()"); + NurikabeBoard copy = new NurikabeBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; } - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java index 4f92c6227..c6cd2c64e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCell.java @@ -7,86 +7,86 @@ public class NurikabeCell extends GridCell { - /** - * NurikabeCell Constructor - creates a NurikabeCell from the specified value and location - * - * @param value value of the NurikabeCell - * @param location position of the NurikabeCell - */ - public NurikabeCell(int value, Point location) { - super(value, location); - } + /** + * NurikabeCell Constructor - creates a NurikabeCell from the specified value and location + * + * @param value value of the NurikabeCell + * @param location position of the NurikabeCell + */ + public NurikabeCell(int value, Point location) { + super(value, location); + } - /** - * Gets the type of this NurikabeCell - * - * @return type of NurikabeCell - */ - public NurikabeType getType() { - switch (data) { - case -2: - return NurikabeType.UNKNOWN; - case -1: - return NurikabeType.BLACK; - case 0: - return NurikabeType.WHITE; - default: - if (data > 0) { - return NurikabeType.NUMBER; + /** + * Gets the type of this NurikabeCell + * + * @return type of NurikabeCell + */ + public NurikabeType getType() { + switch (data) { + case -2: + return NurikabeType.UNKNOWN; + case -1: + return NurikabeType.BLACK; + case 0: + return NurikabeType.WHITE; + default: + if (data > 0) { + return NurikabeType.NUMBER; + } } + return null; } - return null; - } - /** - * Sets the type of this NurikabeCell - * - * @param e element to set the type of this nurikabe cell to - */ - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "NURI-PLAC-0001": - this.data = -1; - break; - case "NURI-PLAC-0002": - this.data = 0; - break; - case "NURI-UNPL-0001": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data <= 0 || this.data > 8) { - this.data = 1; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 1) { - this.data = this.data - 1; - } else { - this.data = 9; - } - break; + /** + * Sets the type of this NurikabeCell + * + * @param e element to set the type of this nurikabe cell to + */ + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "NURI-PLAC-0001": + this.data = -1; + break; + case "NURI-PLAC-0002": + this.data = 0; + break; + case "NURI-UNPL-0001": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data <= 0 || this.data > 8) { + this.data = 1; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 1) { + this.data = this.data - 1; + } else { + this.data = 9; + } + break; + } + break; + default: + this.data = -2; + break; } - break; - default: - this.data = -2; - break; } - } - /** - * Performs a deep copy on the NurikabeCell - * - * @return a new copy of the NurikabeCell that is independent of this one - */ - @Override - public NurikabeCell copy() { - NurikabeCell copy = new NurikabeCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + /** + * Performs a deep copy on the NurikabeCell + * + * @return a new copy of the NurikabeCell that is independent of this one + */ + @Override + public NurikabeCell copy() { + NurikabeCell copy = new NurikabeCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java index 298acfb7b..7241608ac 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeCellFactory.java @@ -10,65 +10,66 @@ import org.w3c.dom.Node; public class NurikabeCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public NurikabeCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public NurikabeCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown puzzleElement puzzleElement"); + } - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int width = nurikabeBoard.getWidth(); - int height = nurikabeBoard.getHeight(); + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("nurikabe Factory: cell location out of bounds"); - } - if (value < -2) { - throw new InvalidFileFormatException("nurikabe Factory: cell unknown value"); - } + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "nurikabe Factory: cell location out of bounds"); + } + if (value < -2) { + throw new InvalidFileFormatException("nurikabe Factory: cell unknown value"); + } - NurikabeCell cell = new NurikabeCell(value, new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); + NurikabeCell cell = new NurikabeCell(value, new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - NurikabeCell cell = (NurikabeCell) puzzleElement; - Point loc = cell.getLocation(); + NurikabeCell cell = (NurikabeCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java index e87f661eb..158abe7b4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeController.java @@ -6,40 +6,40 @@ public class NurikabeController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - NurikabeCell cell = (NurikabeCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() == -2) { - data.setData(0); + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + NurikabeCell cell = (NurikabeCell) data; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() == -2) { + data.setData(0); + } else { + if (cell.getData() == 0) { + data.setData(-1); + } else { + data.setData(-2); + } + } + } } else { - if (cell.getData() == 0) { - data.setData(-1); - } else { - data.setData(-2); - } + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == -2) { + data.setData(-1); + } else { + if (cell.getData() == 0) { + data.setData(-2); + } else { + data.setData(0); + } + } + } } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == -2) { - data.setData(-1); - } else { - if (cell.getData() == 0) { - data.setData(-2); - } else { - data.setData(0); - } - } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java index 6569cfaf7..116b727d2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeElementView.java @@ -5,64 +5,65 @@ public class NurikabeElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; - public NurikabeElementView(NurikabeCell cell) { - super(cell); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public NurikabeCell getPuzzleElement() { - return (NurikabeCell) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - NurikabeType type = cell.getType(); - if (type == NurikabeType.NUMBER) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.WHITE); - graphics2D.fillRect(location.x, location.y, size.width, size.height); + public NurikabeElementView(NurikabeCell cell) { + super(cell); + } - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public NurikabeCell getPuzzleElement() { + return (NurikabeCell) super.getPuzzleElement(); + } - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } else { - if (type == NurikabeType.BLACK) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.BLACK); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } else { - if (type == NurikabeType.WHITE) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.WHITE); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == NurikabeType.UNKNOWN) { + @Override + public void drawElement(Graphics2D graphics2D) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + NurikabeType type = cell.getType(); + if (type == NurikabeType.NUMBER) { graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.setColor(Color.WHITE); graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); graphics2D.drawRect(location.x, location.y, size.width, size.height); - } + + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } else { + if (type == NurikabeType.BLACK) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.BLACK); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } else { + if (type == NurikabeType.WHITE) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.WHITE); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == NurikabeType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java index 1a0f06bb2..23efd4724 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeExporter.java @@ -6,34 +6,34 @@ public class NurikabeExporter extends PuzzleExporter { - public NurikabeExporter(Nurikabe nurikabe) { - super(nurikabe); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - NurikabeBoard board; - if (puzzle.getTree() != null) { - board = (NurikabeBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (NurikabeBoard) puzzle.getBoardView().getBoard(); + public NurikabeExporter(Nurikabe nurikabe) { + super(nurikabe); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + NurikabeBoard board; + if (puzzle.getTree() != null) { + board = (NurikabeBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (NurikabeBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - if (cell.getData() != -2) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + if (cell.getData() != -2) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java index 2be1ba899..ec4ed3ac1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeImporter.java @@ -8,111 +8,117 @@ import org.w3c.dom.NodeList; public class NurikabeImporter extends PuzzleImporter { - public NurikabeImporter(Nurikabe nurikabe) { - super(nurikabe); - } + public NurikabeImporter(Nurikabe nurikabe) { + super(nurikabe); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - NurikabeBoard nurikabeBoard = new NurikabeBoard(columns, rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + NurikabeBoard nurikabeBoard = new NurikabeBoard(columns, rows); - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - nurikabeBoard.setCell(x, y, cell); - } + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + NurikabeCell cell = + new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + nurikabeBoard.setCell(x, y, cell); + } + } + puzzle.setCurrentBoard(nurikabeBoard); } - puzzle.setCurrentBoard(nurikabeBoard); - } - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("nurikabe Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("nurikabe Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "nurikabe Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "nurikabe Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - NurikabeBoard nurikabeBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - nurikabeBoard = new NurikabeBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - nurikabeBoard = new NurikabeBoard(width, height); - } - } + NurikabeBoard nurikabeBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + nurikabeBoard = new NurikabeBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + nurikabeBoard = new NurikabeBoard(width, height); + } + } - if (nurikabeBoard == null) { - throw new InvalidFileFormatException("nurikabe Importer: invalid board dimensions"); - } + if (nurikabeBoard == null) { + throw new InvalidFileFormatException("nurikabe Importer: invalid board dimensions"); + } - int width = nurikabeBoard.getWidth(); - int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); - for (int i = 0; i < elementDataList.getLength(); i++) { - NurikabeCell cell = - (NurikabeCell) puzzle.getFactory().importCell(elementDataList.item(i), nurikabeBoard); - Point loc = cell.getLocation(); - if (cell.getData() != NurikabeType.UNKNOWN.toValue()) { - cell.setModifiable(false); - cell.setGiven(true); - } - nurikabeBoard.setCell(loc.x, loc.y, cell); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + NurikabeCell cell = + (NurikabeCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), nurikabeBoard); + Point loc = cell.getLocation(); + if (cell.getData() != NurikabeType.UNKNOWN.toValue()) { + cell.setModifiable(false); + cell.setGiven(true); + } + nurikabeBoard.setCell(loc.x, loc.y, cell); + } - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (nurikabeBoard.getCell(x, y) == null) { - NurikabeCell cell = new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - nurikabeBoard.setCell(x, y, cell); - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (nurikabeBoard.getCell(x, y) == null) { + NurikabeCell cell = + new NurikabeCell(NurikabeType.UNKNOWN.toValue(), new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + nurikabeBoard.setCell(x, y, cell); + } + } + } + puzzle.setCurrentBoard(nurikabeBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Importer: unknown value where integer expected"); } - } - puzzle.setCurrentBoard(nurikabeBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Nurikabe cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Nurikabe cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java index a692a27fe..8acf9fc02 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeType.java @@ -1,12 +1,12 @@ package edu.rpi.legup.puzzle.nurikabe; public enum NurikabeType { - UNKNOWN, - BLACK, - WHITE, - NUMBER; + UNKNOWN, + BLACK, + WHITE, + NUMBER; - public int toValue() { - return this.ordinal() - 2; - } + public int toValue() { + return this.ordinal() - 2; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java index f6b1a02a4..71ffa08e5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeUtilities.java @@ -10,303 +10,305 @@ public class NurikabeUtilities { - /** - * Gets all of the numbered cells in the Nurikabe board - * - * @param board nurikabe board - * @return a list of all of the numbered cells - */ - public static Set getNurikabeNumberedCells(NurikabeBoard board) { - Set numberedCells = new HashSet<>(); + /** + * Gets all of the numbered cells in the Nurikabe board + * + * @param board nurikabe board + * @return a list of all of the numbered cells + */ + public static Set getNurikabeNumberedCells(NurikabeBoard board) { + Set numberedCells = new HashSet<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.NUMBER) { - numberedCells.add(cell); - } + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.NUMBER) { + numberedCells.add(cell); + } + } + return numberedCells; } - return numberedCells; - } - /** - * Gets nurikabe regions of black, white, and unknown cells - * - * @param board nurikabe board - * @return a disjoint set of the regions - */ - public static DisjointSets getNurikabeRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets nurikabe regions of black, white, and unknown cells + * + * @param board nurikabe board + * @return a disjoint set of the regions + */ + public static DisjointSets getNurikabeRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets regions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - regions.createSet((NurikabeCell) data); - } + DisjointSets regions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + regions.createSet((NurikabeCell) data); + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.NUMBER || cell.getType() == NurikabeType.WHITE) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.NUMBER - || rightCell.getType() == NurikabeType.WHITE)) { - regions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.NUMBER - || downCell.getType() == NurikabeType.WHITE)) { - regions.union(cell, downCell); - } - } else { - if (cell.getType() == NurikabeType.BLACK) { - if (rightCell != null && rightCell.getType() == NurikabeType.BLACK) { - regions.union(cell, rightCell); + if (cell.getType() == NurikabeType.NUMBER || cell.getType() == NurikabeType.WHITE) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.NUMBER + || rightCell.getType() == NurikabeType.WHITE)) { + regions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.NUMBER + || downCell.getType() == NurikabeType.WHITE)) { + regions.union(cell, downCell); + } + } else { + if (cell.getType() == NurikabeType.BLACK) { + if (rightCell != null && rightCell.getType() == NurikabeType.BLACK) { + regions.union(cell, rightCell); + } + if (downCell != null && downCell.getType() == NurikabeType.BLACK) { + regions.union(cell, downCell); + } + } else { + if (cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null && rightCell.getType() == NurikabeType.UNKNOWN) { + regions.union(cell, rightCell); + } + if (downCell != null && downCell.getType() == NurikabeType.UNKNOWN) { + regions.union(cell, downCell); + } + } + } + } } - if (downCell != null && downCell.getType() == NurikabeType.BLACK) { - regions.union(cell, downCell); - } - } else { - if (cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null && rightCell.getType() == NurikabeType.UNKNOWN) { - regions.union(cell, rightCell); - } - if (downCell != null && downCell.getType() == NurikabeType.UNKNOWN) { - regions.union(cell, downCell); - } - } - } } - } + return regions; } - return regions; - } - /** - * Gets the disjoint set containing the possible black regions be interpreting all unknown cells - * as black cells - * - * @param board nurikabe board - * @return the disjoint set containing the possible black regions - */ - public static DisjointSets getPossibleBlackRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets the disjoint set containing the possible black regions be interpreting all unknown cells + * as black cells + * + * @param board nurikabe board + * @return the disjoint set containing the possible black regions + */ + public static DisjointSets getPossibleBlackRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets blackRegions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { - blackRegions.createSet(cell); - } - } + DisjointSets blackRegions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { + blackRegions.createSet(cell); + } + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.BLACK || cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.BLACK - || rightCell.getType() == NurikabeType.UNKNOWN)) { - blackRegions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.BLACK - || downCell.getType() == NurikabeType.UNKNOWN)) { - blackRegions.union(cell, downCell); - } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + if (cell.getType() == NurikabeType.BLACK + || cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.BLACK + || rightCell.getType() == NurikabeType.UNKNOWN)) { + blackRegions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.BLACK + || downCell.getType() == NurikabeType.UNKNOWN)) { + blackRegions.union(cell, downCell); + } + } + } } - } + return blackRegions; } - return blackRegions; - } - /** - * Gets the disjoint set containing the possible white regions be interpreting all unknown cells - * as white cells - * - * @param board nurikabe board - * @return the disjoint set containing the possible white regions - */ - public static DisjointSets getPossibleWhiteRegions(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets the disjoint set containing the possible white regions be interpreting all unknown cells + * as white cells + * + * @param board nurikabe board + * @return the disjoint set containing the possible white regions + */ + public static DisjointSets getPossibleWhiteRegions(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - DisjointSets whiteRegions = new DisjointSets<>(); - for (PuzzleElement data : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) data; - if (cell.getType() == NurikabeType.WHITE - || cell.getType() == NurikabeType.NUMBER - || cell.getType() == NurikabeType.UNKNOWN) { - whiteRegions.createSet(cell); - } - } + DisjointSets whiteRegions = new DisjointSets<>(); + for (PuzzleElement data : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) data; + if (cell.getType() == NurikabeType.WHITE + || cell.getType() == NurikabeType.NUMBER + || cell.getType() == NurikabeType.UNKNOWN) { + whiteRegions.createSet(cell); + } + } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - NurikabeCell cell = board.getCell(x, y); - NurikabeCell rightCell = board.getCell(x + 1, y); - NurikabeCell downCell = board.getCell(x, y + 1); - if (cell.getType() == NurikabeType.WHITE - || cell.getType() == NurikabeType.NUMBER - || cell.getType() == NurikabeType.UNKNOWN) { - if (rightCell != null - && (rightCell.getType() == NurikabeType.WHITE - || rightCell.getType() == NurikabeType.NUMBER - || rightCell.getType() == NurikabeType.UNKNOWN)) { - whiteRegions.union(cell, rightCell); - } - if (downCell != null - && (downCell.getType() == NurikabeType.WHITE - || downCell.getType() == NurikabeType.NUMBER - || downCell.getType() == NurikabeType.UNKNOWN)) { - whiteRegions.union(cell, downCell); - } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + NurikabeCell cell = board.getCell(x, y); + NurikabeCell rightCell = board.getCell(x + 1, y); + NurikabeCell downCell = board.getCell(x, y + 1); + if (cell.getType() == NurikabeType.WHITE + || cell.getType() == NurikabeType.NUMBER + || cell.getType() == NurikabeType.UNKNOWN) { + if (rightCell != null + && (rightCell.getType() == NurikabeType.WHITE + || rightCell.getType() == NurikabeType.NUMBER + || rightCell.getType() == NurikabeType.UNKNOWN)) { + whiteRegions.union(cell, rightCell); + } + if (downCell != null + && (downCell.getType() == NurikabeType.WHITE + || downCell.getType() == NurikabeType.NUMBER + || downCell.getType() == NurikabeType.UNKNOWN)) { + whiteRegions.union(cell, downCell); + } + } + } } - } + return whiteRegions; } - return whiteRegions; - } - /** - * Makes a map where the keys are white/numbered cells and the values are the amount of cells that - * need to be added to the region - * - * @param board nurikabe board - * @return a map of cell keys to integer values - */ - public static HashMap getWhiteRegionMap(NurikabeBoard board) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Makes a map where the keys are white/numbered cells and the values are the amount of cells + * that need to be added to the region + * + * @param board nurikabe board + * @return a map of cell keys to integer values + */ + public static HashMap getWhiteRegionMap(NurikabeBoard board) { + int width = board.getWidth(); + int height = board.getHeight(); - Set numberedCells = getNurikabeNumberedCells(board); - // Final mapping of cell to size - HashMap whiteRegionMap = new HashMap<>(); - for (NurikabeCell center : numberedCells) { - // BFS for each center to find the size of the region - int size = 1; - // Mark all the vertices as not visited(By default - // set as false) - HashMap visited = new HashMap<>(); + Set numberedCells = getNurikabeNumberedCells(board); + // Final mapping of cell to size + HashMap whiteRegionMap = new HashMap<>(); + for (NurikabeCell center : numberedCells) { + // BFS for each center to find the size of the region + int size = 1; + // Mark all the vertices as not visited(By default + // set as false) + HashMap visited = new HashMap<>(); - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - // Mark the current node as visited and enqueue it - visited.put(center, true); - queue.add(center); + // Mark the current node as visited and enqueue it + visited.put(center, true); + queue.add(center); - // Set of cells in the current region - Set connected = new HashSet<>(); + // Set of cells in the current region + Set connected = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - // s is the source node in the graph - NurikabeCell s = queue.poll(); - System.out.print(s + " "); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + // s is the source node in the graph + NurikabeCell s = queue.poll(); + System.out.print(s + " "); - // Make a linked list of all adjacent squares - Set adj = new HashSet<>(); + // Make a linked list of all adjacent squares + Set adj = new HashSet<>(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(board.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(board.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(board.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(board.getCell(loc.x, loc.y + 1)); - } - // Get all adjacent vertices of the dequeued vertex s - // If a adjacent has not been visited, then mark it - // visited and enqueue it - for (NurikabeCell n : adj) { - if (!visited.getOrDefault(n, false) && n.getType() == NurikabeType.WHITE) { - connected.add(n); - visited.put(n, true); - queue.add(n); - ++size; - } + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(board.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(board.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(board.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(board.getCell(loc.x, loc.y + 1)); + } + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (NurikabeCell n : adj) { + if (!visited.getOrDefault(n, false) && n.getType() == NurikabeType.WHITE) { + connected.add(n); + visited.put(n, true); + queue.add(n); + ++size; + } + } + } + // Map the cells to the center-size (including the center) + whiteRegionMap.put(center, center.getData() - size); + for (NurikabeCell member : connected) { + whiteRegionMap.put(member, center.getData() - size); + } } - } - // Map the cells to the center-size (including the center) - whiteRegionMap.put(center, center.getData() - size); - for (NurikabeCell member : connected) { - whiteRegionMap.put(member, center.getData() - size); - } + return whiteRegionMap; } - return whiteRegionMap; - } - /** - * Gets all the non-black cells connected to the given cell - * - * @param board nurikabe board - * @param center nurikabe cell - * @return a set of all white/numbered cells in the region - */ - public static Set getSurroundedRegionOf(NurikabeBoard board, NurikabeCell center) { - int width = board.getWidth(); - int height = board.getHeight(); + /** + * Gets all the non-black cells connected to the given cell + * + * @param board nurikabe board + * @param center nurikabe cell + * @return a set of all white/numbered cells in the region + */ + public static Set getSurroundedRegionOf( + NurikabeBoard board, NurikabeCell center) { + int width = board.getWidth(); + int height = board.getHeight(); - // Mark all the vertices as not visited(By default - // set as false) - Set visited = new HashSet<>(); + // Mark all the vertices as not visited(By default + // set as false) + Set visited = new HashSet<>(); - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - // Mark the current node as visited and enqueue it - visited.add(center); - queue.add(center); + // Mark the current node as visited and enqueue it + visited.add(center); + queue.add(center); - // Set of cells in the current region - Set connected = new HashSet<>(); + // Set of cells in the current region + Set connected = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - // s is the source node in the graph - NurikabeCell s = queue.poll(); - System.out.print(s + " "); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + // s is the source node in the graph + NurikabeCell s = queue.poll(); + System.out.print(s + " "); - // Make a set of all adjacent squares - Set adj = new HashSet<>(); + // Make a set of all adjacent squares + Set adj = new HashSet<>(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(board.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(board.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(board.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(board.getCell(loc.x, loc.y + 1)); - } - // Get all adjacent vertices of the dequeued vertex s - // If a adjacent has not been visited, then mark it - // visited and enqueue it - for (NurikabeCell n : adj) { - if (!visited.contains(n) && n.getType() != NurikabeType.BLACK) { - connected.add(n); - visited.add(n); - queue.add(n); + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(board.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(board.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(board.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(board.getCell(loc.x, loc.y + 1)); + } + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (NurikabeCell n : adj) { + if (!visited.contains(n) && n.getType() != NurikabeType.BLACK) { + connected.add(n); + visited.add(n); + queue.add(n); + } + } } - } - } - return connected; - } + return connected; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java index 04e1910e4..0bac7e3e5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/NurikabeView.java @@ -7,17 +7,18 @@ public class NurikabeView extends GridBoardView { - public NurikabeView(NurikabeBoard board) { - super(new BoardController(), new NurikabeController(), board.getDimension()); + public NurikabeView(NurikabeBoard board) { + super(new BoardController(), new NurikabeController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - NurikabeCell cell = (NurikabeCell) puzzleElement; - Point loc = cell.getLocation(); - NurikabeElementView elementView = new NurikabeElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + NurikabeCell cell = (NurikabeCell) puzzleElement; + Point loc = cell.getLocation(); + NurikabeElementView elementView = new NurikabeElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java index 25f817ff2..459a809e0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/BlackTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class BlackTile extends PlaceableElement { - public BlackTile() { - super( - "NURI-PLAC-0001", - "Black Tile", - "The black tile", - "edu/rpi/legup/images/nurikabe/tiles/BlackTile.png"); - } + public BlackTile() { + super( + "NURI-PLAC-0001", + "Black Tile", + "The black tile", + "edu/rpi/legup/images/nurikabe/tiles/BlackTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java index 9c0f3ff94..475b278da 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/NumberTile.java @@ -3,28 +3,28 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super( - "NURI-UNPL-0001", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/nurikabe/tiles/NumberTile.png"); - object_num = 0; - } + public NumberTile() { + super( + "NURI-UNPL-0001", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/nurikabe/tiles/NumberTile.png"); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java index 0b16d4a17..85d47e208 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "NURI-UNPL-0002", - "Unknown Tile", - "A blank tile", - "edu/rpi/legup/images/nurikabe/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "NURI-UNPL-0002", + "Unknown Tile", + "A blank tile", + "edu/rpi/legup/images/nurikabe/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java index c086ce55c..35eb63b81 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/elements/WhiteTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class WhiteTile extends PlaceableElement { - public WhiteTile() { - super( - "NURI-PLAC-0002", - "White Tile", - "The white tile", - "edu/rpi/legup/images/nurikabe/tiles/WhiteTile.png"); - } + public WhiteTile() { + super( + "NURI-PLAC-0002", + "White Tile", + "The white tile", + "edu/rpi/legup/images/nurikabe/tiles/WhiteTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java index f8fb66110..7428ac204 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBetweenRegionsDirectRule.java @@ -17,103 +17,106 @@ public class BlackBetweenRegionsDirectRule extends DirectRule { - public BlackBetweenRegionsDirectRule() { - super( - "NURI-BASC-0001", - "Black Between Regions", - "Any unknowns between two regions must be black.", - "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); - } + public BlackBetweenRegionsDirectRule() { + super( + "NURI-BASC-0001", + "Black Between Regions", + "Any unknowns between two regions must be black.", + "edu/rpi/legup/images/nurikabe/rules/BetweenRegions.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new MultipleNumbersContradictionRule()); - contras.add(new TooManySpacesContradictionRule()); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new MultipleNumbersContradictionRule()); + contras.add(new TooManySpacesContradictionRule()); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + + ": Only black cells are allowed for this rule!"; + } - int x = cell.getLocation().x; - int y = cell.getLocation().y; + int x = cell.getLocation().x; + int y = cell.getLocation().y; - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adjacentWhiteRegions = new HashSet<>(); - NurikabeCell upCell = destBoardState.getCell(x, y - 1); - NurikabeCell rightCell = destBoardState.getCell(x + 1, y); - NurikabeCell downCell = destBoardState.getCell(x, y + 1); - NurikabeCell leftCell = destBoardState.getCell(x - 1, y); + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adjacentWhiteRegions = new HashSet<>(); + NurikabeCell upCell = destBoardState.getCell(x, y - 1); + NurikabeCell rightCell = destBoardState.getCell(x + 1, y); + NurikabeCell downCell = destBoardState.getCell(x, y + 1); + NurikabeCell leftCell = destBoardState.getCell(x - 1, y); - if (upCell != null - && (upCell.getType() == NurikabeType.WHITE || upCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(upCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (rightCell != null - && (rightCell.getType() == NurikabeType.WHITE - || rightCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(rightCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (downCell != null - && (downCell.getType() == NurikabeType.WHITE - || downCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(downCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } - if (leftCell != null - && (leftCell.getType() == NurikabeType.WHITE - || leftCell.getType() == NurikabeType.NUMBER)) { - NurikabeCell repCell = regions.find(leftCell); - if (!adjacentWhiteRegions.contains(repCell)) { - adjacentWhiteRegions.add(repCell); - } - } + if (upCell != null + && (upCell.getType() == NurikabeType.WHITE + || upCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(upCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (rightCell != null + && (rightCell.getType() == NurikabeType.WHITE + || rightCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(rightCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (downCell != null + && (downCell.getType() == NurikabeType.WHITE + || downCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(downCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } + if (leftCell != null + && (leftCell.getType() == NurikabeType.WHITE + || leftCell.getType() == NurikabeType.NUMBER)) { + NurikabeCell repCell = regions.find(leftCell); + if (!adjacentWhiteRegions.contains(repCell)) { + adjacentWhiteRegions.add(repCell); + } + } - if (adjacentWhiteRegions.size() < 2) { - return "The new black cell must separate two white regions for this rule!"; - } + if (adjacentWhiteRegions.size() < 2) { + return "The new black cell must separate two white regions for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); + NurikabeBoard modified = origBoardState.copy(); + modified.getCell(x, y).setData(NurikabeType.WHITE.toValue()); - for (ContradictionRule c : contras) { - if (c.checkContradiction(modified) == null) { - return null; - } + for (ContradictionRule c : contras) { + if (c.checkContradiction(modified) == null) { + return null; + } + } + return "Does not follow from the rule"; } - return "Does not follow from the rule"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java index 31c05f9b4..a8a94178b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackBottleNeckDirectRule.java @@ -12,54 +12,58 @@ public class BlackBottleNeckDirectRule extends DirectRule { - public BlackBottleNeckDirectRule() { - super( - "NURI-BASC-0002", - "Black Bottle Neck", - "If there is only one path for a black to escape, then those unknowns must be" + " black.", - "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); - } + public BlackBottleNeckDirectRule() { + super( + "NURI-BASC-0002", + "Black Bottle Neck", + "If there is only one path for a black to escape, then those unknowns must be" + + " black.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new IsolateBlackContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new IsolateBlackContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + + ": Only black cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradiction(modified) == null) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This is not the only way for black to escape!"; + if (contraRule.checkContradiction(modified) == null) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This is not the only way for black to escape!"; + } } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java index 9c6bf1a63..fe1ffcf91 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackOrWhiteCaseRule.java @@ -13,101 +13,102 @@ public class BlackOrWhiteCaseRule extends CaseRule { - public BlackOrWhiteCaseRule() { - super( - "NURI-CASE-0001", - "Black or White", - "Each blank cell is either black or white.", - "edu/rpi/legup/images/nurikabe/cases/BlackOrWhite.png"); - } - - /** - * Checks whether the {@link TreeTransition} logically follows from the parent node using this - * rule. This method is the one that should overridden in child classes. - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + public BlackOrWhiteCaseRule() { + super( + "NURI-CASE-0001", + "Black or White", + "Each blank cell is either black or white.", + "edu/rpi/legup/images/nurikabe/cases/BlackOrWhite.png"); } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + /** + * Checks whether the {@link TreeTransition} logically follows from the parent node using this + * rule. This method is the one that should overridden in child classes. + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - NurikabeCell mod1 = (NurikabeCell) case1.getBoard().getModifiedData().iterator().next(); - NurikabeCell mod2 = (NurikabeCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - if (!((mod1.getType() == NurikabeType.WHITE && mod2.getType() == NurikabeType.BLACK) - || (mod2.getType() == NurikabeType.WHITE && mod1.getType() == NurikabeType.BLACK))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must an empty white and black cell."; - } + NurikabeCell mod1 = (NurikabeCell) case1.getBoard().getModifiedData().iterator().next(); + NurikabeCell mod2 = (NurikabeCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } - return null; - } + if (!((mod1.getType() == NurikabeType.WHITE && mod2.getType() == NurikabeType.BLACK) + || (mod2.getType() == NurikabeType.WHITE + && mod1.getType() == NurikabeType.BLACK))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must an empty white and black cell."; + } - @Override - public CaseBoard getCaseBoard(Board board) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(nurikabeBoard, this); - nurikabeBoard.setModifiable(false); - for (PuzzleElement element : nurikabeBoard.getPuzzleElements()) { - if (((NurikabeCell) element).getType() == NurikabeType.UNKNOWN) { - caseBoard.addPickableElement(element); - } + return null; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(NurikabeType.WHITE.toValue()); - case1.addModifiedData(data1); - cases.add(case1); + @Override + public CaseBoard getCaseBoard(Board board) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(nurikabeBoard, this); + nurikabeBoard.setModifiable(false); + for (PuzzleElement element : nurikabeBoard.getPuzzleElements()) { + if (((NurikabeCell) element).getType() == NurikabeType.UNKNOWN) { + caseBoard.addPickableElement(element); + } + } + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(NurikabeType.WHITE.toValue()); + case1.addModifiedData(data1); + cases.add(case1); - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(NurikabeType.BLACK.toValue()); - case2.addModifiedData(data2); - cases.add(case2); + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(NurikabeType.BLACK.toValue()); + case2.addModifiedData(data2); + cases.add(case2); - return cases; - } + return cases; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java index bdc72d921..751c88881 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/BlackSquareContradictionRule.java @@ -9,52 +9,52 @@ public class BlackSquareContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "No 2x2 square of black exists."; - private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - - public BlackSquareContradictionRule() { - super( - "NURI-CONT-0001", - "Black Square", - "There cannot be a 2x2 square of black.", - "edu/rpi/legup/images/nurikabe/contradictions/BlackSquare.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - int height = nurikabeBoard.getHeight(); - int width = nurikabeBoard.getWidth(); - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + private final String NO_CONTRADICTION_MESSAGE = "No 2x2 square of black exists."; + private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; + + public BlackSquareContradictionRule() { + super( + "NURI-CONT-0001", + "Black Square", + "There cannot be a 2x2 square of black.", + "edu/rpi/legup/images/nurikabe/contradictions/BlackSquare.png"); } - for (int x = cell.getLocation().x - 1; - x >= 0 && x < cell.getLocation().x + 1 && x < width - 1; - x++) { - for (int y = cell.getLocation().y - 1; - y >= 0 && y < cell.getLocation().y + 1 && y < height - 1; - y++) { - if (nurikabeBoard.getCell(x, y).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x + 1, y).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x, y + 1).getType() == NurikabeType.BLACK - && nurikabeBoard.getCell(x + 1, y + 1).getType() == NurikabeType.BLACK) { - return null; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } + + for (int x = cell.getLocation().x - 1; + x >= 0 && x < cell.getLocation().x + 1 && x < width - 1; + x++) { + for (int y = cell.getLocation().y - 1; + y >= 0 && y < cell.getLocation().y + 1 && y < height - 1; + y++) { + if (nurikabeBoard.getCell(x, y).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x + 1, y).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x, y + 1).getType() == NurikabeType.BLACK + && nurikabeBoard.getCell(x + 1, y + 1).getType() == NurikabeType.BLACK) { + return null; + } + } } - } - } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java index 0b699b7bd..f3d3ee8f2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CannotReachCellDirectRule.java @@ -11,52 +11,54 @@ import edu.rpi.legup.puzzle.nurikabe.NurikabeType; public class CannotReachCellDirectRule extends DirectRule { - public CannotReachCellDirectRule() { - super( - "NURI-BASC-0008", - "Can't Reach Cell", - "A cell must be black if it cannot be reached by any white region", - "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); - } + public CannotReachCellDirectRule() { + super( + "NURI-BASC-0008", + "Can't Reach Cell", + "A cell must be black if it cannot be reached by any white region", + "edu/rpi/legup/images/nurikabe/rules/Unreachable.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + protected String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new UnreachableWhiteCellContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": Only black cells are allowed for this rule!"; - } + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + + ": Only black cells are allowed for this rule!"; + } - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeBoard modified = origBoardState.copy(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modifiedCell.setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { - return null; + NurikabeCell modifiedCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modifiedCell.setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, modifiedCell) == null) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; } - return super.getInvalidUseOfRuleMessage() + ": Cell at this index can be reached"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java index 7c974eba7..84ec45e99 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/CornerBlackDirectRule.java @@ -15,117 +15,119 @@ public class CornerBlackDirectRule extends DirectRule { - public CornerBlackDirectRule() { - super( - "NURI-BASC-0003", - "Corners Black", - "If there is only one white square connected to unknowns and one more white is" - + " needed then the angles of that white square are black", - "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; + public CornerBlackDirectRule() { + super( + "NURI-BASC-0003", + "Corners Black", + "If there is only one white square connected to unknowns and one more white is" + + " needed then the angles of that white square are black", + "edu/rpi/legup/images/nurikabe/rules/CornerBlack.png"); } - ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); - Point cellLocation = cell.getLocation(); - // 1. Find the coordinates of the white space (should be a corner of cell) - for (int i = -1; i < 2; i += 2) { - for (int j = -1; j < 2; j += 2) { - // If the corner does not exist, skip the corner - if (!(cellLocation.x + i >= 0 - && cellLocation.x + i < board.getWidth() - && cellLocation.y + j >= 0 - && cellLocation.y + j < board.getHeight())) { - continue; + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; } - NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); - NurikabeType cornerType = corner.getType(); - if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { - Point cornerLocation = corner.getLocation(); - // 2. Check if the intersecting adjacent spaces of the white space and the black - // corner - // are empty - if (board.getCell(cornerLocation.x, cellLocation.y).getType() == NurikabeType.UNKNOWN - && board.getCell(cellLocation.x, cornerLocation.y).getType() - == NurikabeType.UNKNOWN) { - // System.out.println("Went inside if statement"); - NurikabeBoard modified = board.copy(); - modified - .getCell(cornerLocation.x, cellLocation.y) - .setData(NurikabeType.BLACK.toValue()); - modified - .getCell(cellLocation.x, cornerLocation.y) - .setData(NurikabeType.BLACK.toValue()); - boolean containsContradiction = tooFewContra.checkContradiction(modified) == null; - if (containsContradiction) { - // 3. Check if the connected region is 1 under what is needed - Set region = - ConnectedRegions.getRegionAroundPoint( - cornerLocation, - NurikabeType.BLACK.toValue(), - modified.getIntArray(), - modified.getWidth(), - modified.getHeight()); - int regionNumber = 0; - // System.out.println("Region set size: " + region.size()); - for (Point p : region) { - NurikabeCell pCell = modified.getCell(p.x, p.y); - if (pCell.getType() == NurikabeType.NUMBER) { - if (regionNumber == 0) { - regionNumber = pCell.getData(); - } else { - return "There is a MultipleNumbers Contradiction on the" + " board."; - } + ContradictionRule tooFewContra = new TooFewSpacesContradictionRule(); + Point cellLocation = cell.getLocation(); + // 1. Find the coordinates of the white space (should be a corner of cell) + for (int i = -1; i < 2; i += 2) { + for (int j = -1; j < 2; j += 2) { + // If the corner does not exist, skip the corner + if (!(cellLocation.x + i >= 0 + && cellLocation.x + i < board.getWidth() + && cellLocation.y + j >= 0 + && cellLocation.y + j < board.getHeight())) { + continue; + } + + NurikabeCell corner = board.getCell(cellLocation.x + i, cellLocation.y + j); + NurikabeType cornerType = corner.getType(); + if (cornerType == NurikabeType.WHITE || cornerType == NurikabeType.NUMBER) { + Point cornerLocation = corner.getLocation(); + // 2. Check if the intersecting adjacent spaces of the white space and the black + // corner + // are empty + if (board.getCell(cornerLocation.x, cellLocation.y).getType() + == NurikabeType.UNKNOWN + && board.getCell(cellLocation.x, cornerLocation.y).getType() + == NurikabeType.UNKNOWN) { + // System.out.println("Went inside if statement"); + NurikabeBoard modified = board.copy(); + modified.getCell(cornerLocation.x, cellLocation.y) + .setData(NurikabeType.BLACK.toValue()); + modified.getCell(cellLocation.x, cornerLocation.y) + .setData(NurikabeType.BLACK.toValue()); + boolean containsContradiction = + tooFewContra.checkContradiction(modified) == null; + if (containsContradiction) { + // 3. Check if the connected region is 1 under what is needed + Set region = + ConnectedRegions.getRegionAroundPoint( + cornerLocation, + NurikabeType.BLACK.toValue(), + modified.getIntArray(), + modified.getWidth(), + modified.getHeight()); + int regionNumber = 0; + // System.out.println("Region set size: " + region.size()); + for (Point p : region) { + NurikabeCell pCell = modified.getCell(p.x, p.y); + if (pCell.getType() == NurikabeType.NUMBER) { + if (regionNumber == 0) { + regionNumber = pCell.getData(); + } else { + return "There is a MultipleNumbers Contradiction on the" + + " board."; + } + } + } + // If the region size is 0, there is a possibility that there was only 1 + // cell in the + // white + // region, and that white cell was a NurikabeType.NUMBER cell + if (regionNumber == 0 + && corner.getType() == NurikabeType.NUMBER + && corner.getData() == 2) { + return null; + } + // If the region size is not 0, make sure the regionNumber and the + // region size match + // (need + // to add 1 to account for the cell that was surrounded + if (regionNumber != 0 && region.size() + 1 == regionNumber) { + return null; + } + } + } } - } - // If the region size is 0, there is a possibility that there was only 1 - // cell in the - // white - // region, and that white cell was a NurikabeType.NUMBER cell - if (regionNumber == 0 - && corner.getType() == NurikabeType.NUMBER - && corner.getData() == 2) { - return null; - } - // If the region size is not 0, make sure the regionNumber and the - // region size match - // (need - // to add 1 to account for the cell that was surrounded - if (regionNumber != 0 && region.size() + 1 == regionNumber) { - return null; - } } - } } - } + return "This is not a valid use of the corner black rule!"; } - return "This is not a valid use of the corner black rule!"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java index 3507d0a7f..7c4629f65 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinBlackDirectRule.java @@ -12,50 +12,51 @@ public class FillinBlackDirectRule extends DirectRule { - public FillinBlackDirectRule() { - super( - "NURI-BASC-0004", - "Fill In Black", - "If there an unknown region surrounded by black, it must be black.", - "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); - } + public FillinBlackDirectRule() { + super( + "NURI-BASC-0004", + "Fill In Black", + "If there an unknown region surrounded by black, it must be black.", + "edu/rpi/legup/images/nurikabe/rules/FillInBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new NoNumberContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new NoNumberContradictionRule(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "Black cells must be placed in a region of black cells!"; + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.WHITE.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "Black cells must be placed in a region of black cells!"; + } + return null; } - return null; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java index 30d5a3a51..05bb2f046 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/FillinWhiteDirectRule.java @@ -12,50 +12,51 @@ public class FillinWhiteDirectRule extends DirectRule { - public FillinWhiteDirectRule() { - super( - "NURI-BASC-0005", - "Fill In White", - "If there an unknown region surrounded by white, it must be white.", - "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); - } + public FillinWhiteDirectRule() { + super( + "NURI-BASC-0005", + "Fill In White", + "If there an unknown region surrounded by white, it must be white.", + "edu/rpi/legup/images/nurikabe/rules/FillInWhite.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); - ContradictionRule contraRule = new IsolateBlackContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoard = (NurikabeBoard) transition.getParents().get(0).getBoard(); + ContradictionRule contraRule = new IsolateBlackContradictionRule(); - NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) board.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } - NurikabeBoard modified = origBoard.copy(); - modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { - return "white cells must be placed in a region of white cells!"; + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoard.copy(); + modified.getPuzzleElement(puzzleElement).setData(NurikabeType.BLACK.toValue()); + if (contraRule.checkContradictionAt(modified, puzzleElement) != null) { + return "white cells must be placed in a region of white cells!"; + } + return null; } - return null; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java index 831dd134b..f26f0c3fe 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/IsolateBlackContradictionRule.java @@ -12,50 +12,50 @@ public class IsolateBlackContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = - "Contradiction applied incorrectly. No isolated Blacks."; - private final String INVALID_USE_MESSAGE = "Contradiction must be a black cell"; + private final String NO_CONTRADICTION_MESSAGE = + "Contradiction applied incorrectly. No isolated Blacks."; + private final String INVALID_USE_MESSAGE = "Contradiction must be a black cell"; - public IsolateBlackContradictionRule() { - super( - "NURI-CONT-0003", - "Isolated Black", - "There must still be a possibility to connect every Black cell", - "edu/rpi/legup/images/nurikabe/contradictions/BlackArea.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule. - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified {@link - * PuzzleElement}, otherwise return a no contradiction message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + public IsolateBlackContradictionRule() { + super( + "NURI-CONT-0003", + "Isolated Black", + "There must still be a possibility to connect every Black cell", + "edu/rpi/legup/images/nurikabe/contradictions/BlackArea.png"); } - DisjointSets blackRegions = - NurikabeUtilities.getPossibleBlackRegions(nurikabeBoard); - boolean oneRegion = false; - for (Set region : blackRegions.getAllSets()) { - for (NurikabeCell c : region) { - if (c.getType() == NurikabeType.BLACK) { - if (oneRegion) { - return null; - } else { - oneRegion = true; - break; - } + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule. + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified {@link + * PuzzleElement}, otherwise return a no contradiction message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.BLACK) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } + + DisjointSets blackRegions = + NurikabeUtilities.getPossibleBlackRegions(nurikabeBoard); + boolean oneRegion = false; + for (Set region : blackRegions.getAllSets()) { + for (NurikabeCell c : region) { + if (c.getType() == NurikabeType.BLACK) { + if (oneRegion) { + return null; + } else { + oneRegion = true; + break; + } + } + } } - } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java index d19cde25a..1925a68ec 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/MultipleNumbersContradictionRule.java @@ -12,41 +12,42 @@ public class MultipleNumbersContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a numbered cell"; + private final String NO_CONTRADICTION_MESSAGE = + "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a numbered cell"; - public MultipleNumbersContradictionRule() { - super( - "NURI-CONT-0004", - "Multiple Numbers", - "All white regions cannot have more than one number.", - "edu/rpi/legup/images/nurikabe/contradictions/MultipleNumbers.png"); - } + public MultipleNumbersContradictionRule() { + super( + "NURI-CONT-0004", + "Multiple Numbers", + "All white regions cannot have more than one number.", + "edu/rpi/legup/images/nurikabe/contradictions/MultipleNumbers.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + INVALID_USE_MESSAGE; - } - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); - Set numberedRegion = regions.getSet(cell); - for (NurikabeCell c : numberedRegion) { - if (c != cell && c.getType() == NurikabeType.NUMBER) { - return null; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + INVALID_USE_MESSAGE; + } + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); + Set numberedRegion = regions.getSet(cell); + for (NurikabeCell c : numberedRegion) { + if (c != cell && c.getType() == NurikabeType.NUMBER) { + return null; + } + } + return super.getNoContradictionMessage() + ": " + NO_CONTRADICTION_MESSAGE; } - return super.getNoContradictionMessage() + ": " + NO_CONTRADICTION_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java index 64d3383e1..6c69136b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/NoNumberContradictionRule.java @@ -11,62 +11,63 @@ public class NoNumberContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white cell"; - private final String NOT_SURROUNDED_BY_BLACK_MESSAGE = "Must be surrounded by black cells"; + private final String NO_CONTRADICTION_MESSAGE = + "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white cell"; + private final String NOT_SURROUNDED_BY_BLACK_MESSAGE = "Must be surrounded by black cells"; - public NoNumberContradictionRule() { - super( - "NURI-CONT-0005", - "No Number", - "All enclosed white regions must have a number.", - "edu/rpi/legup/images/nurikabe/contradictions/NoNumber.png"); - } + public NoNumberContradictionRule() { + super( + "NURI-CONT-0005", + "No Number", + "All enclosed white regions must have a number.", + "edu/rpi/legup/images/nurikabe/contradictions/NoNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - Set region = NurikabeUtilities.getSurroundedRegionOf(nurikabeBoard, cell); + Set region = NurikabeUtilities.getSurroundedRegionOf(nurikabeBoard, cell); - boolean numberExists = false; - for (NurikabeCell c : region) { - if (c.getType() == NurikabeType.NUMBER) { - numberExists = true; - break; - } - } - if (!numberExists) { - return null; + boolean numberExists = false; + for (NurikabeCell c : region) { + if (c.getType() == NurikabeType.NUMBER) { + numberExists = true; + break; + } + } + if (!numberExists) { + return null; + } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - /** - * Checks whether a give NurikabeCell is empty. - * - * @param cell NurikabeCell to check if empty - * @return false if the NurikabeCell is not empty or null, true otherwise - */ - private boolean isEmptyCell(NurikabeCell cell) { - if (cell == null) { - return false; + /** + * Checks whether a give NurikabeCell is empty. + * + * @param cell NurikabeCell to check if empty + * @return false if the NurikabeCell is not empty or null, true otherwise + */ + private boolean isEmptyCell(NurikabeCell cell) { + if (cell == null) { + return false; + } + NurikabeType cellType = cell.getType(); + return cellType != NurikabeType.BLACK && cellType != NurikabeType.WHITE; } - NurikabeType cellType = cell.getType(); - return cellType != NurikabeType.BLACK && cellType != NurikabeType.WHITE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java index a9ae5441f..106c22f7a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/PreventBlackSquareDirectRule.java @@ -12,55 +12,56 @@ public class PreventBlackSquareDirectRule extends DirectRule { - public PreventBlackSquareDirectRule() { - super( - "NURI-BASC-0006", - "Prevent Black Square", - "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", - "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); - } + public PreventBlackSquareDirectRule() { + super( + "NURI-BASC-0006", + "Prevent Black Square", + "There cannot be a 2x2 square of black. (3 blacks = fill in last corner white)", + "edu/rpi/legup/images/nurikabe/rules/NoBlackSquare.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - ContradictionRule contraRule = new BlackSquareContradictionRule(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + ContradictionRule contraRule = new BlackSquareContradictionRule(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); - if (contraRule.checkContradiction(modified) == null) { - return null; - } else { - return "Does not contain a contradiction at this index"; + if (contraRule.checkContradiction(modified) == null) { + return null; + } else { + return "Does not contain a contradiction at this index"; + } } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java index e471de3b1..8e260cf42 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/SurroundRegionDirectRule.java @@ -19,80 +19,85 @@ public class SurroundRegionDirectRule extends DirectRule { - public SurroundRegionDirectRule() { - super( - "NURI-BASC-0007", - "Surround Region", - "Surround Region", - "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); - } + public SurroundRegionDirectRule() { + super( + "NURI-BASC-0007", + "Surround Region", + "Surround Region", + "edu/rpi/legup/images/nurikabe/rules/SurroundBlack.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.BLACK) { - return "Only black cells are allowed for this rule!"; - } + if (cell.getType() != NurikabeType.BLACK) { + return "Only black cells are allowed for this rule!"; + } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.WHITE.toValue()); + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.WHITE.toValue()); - if (cell.getType() == NurikabeType.BLACK) { - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(destBoardState); - Set adj = new HashSet<>(); // set to hold adjacent cells - Point loc = cell.getLocation(); // position of placed cell - List directions = - Arrays.asList(new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); - for (Point direction : directions) { - NurikabeCell curr = destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); - if (curr != null) { - if (curr.getType() == NurikabeType.WHITE || curr.getType() == NurikabeType.NUMBER) { - adj.add(curr); // adds cells to adj only if they are white or number blocks - } + if (cell.getType() == NurikabeType.BLACK) { + DisjointSets regions = + NurikabeUtilities.getNurikabeRegions(destBoardState); + Set adj = new HashSet<>(); // set to hold adjacent cells + Point loc = cell.getLocation(); // position of placed cell + List directions = + Arrays.asList( + new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1)); + for (Point direction : directions) { + NurikabeCell curr = + destBoardState.getCell(loc.x + direction.x, loc.y + direction.y); + if (curr != null) { + if (curr.getType() == NurikabeType.WHITE + || curr.getType() == NurikabeType.NUMBER) { + adj.add(curr); // adds cells to adj only if they are white or number blocks + } + } + } + List numberedCells = new ArrayList<>(); // number value of number cells + for (NurikabeCell c : adj) { // loops through adjacent cells + Set disRow = regions.getSet(c); // set of white spaces + for (NurikabeCell d : disRow) { // loops through white spaces + if (d.getType() == NurikabeType.NUMBER) { // if the white space is a number + numberedCells.add(d); // add that number to numberedCells + } + } + } + for (NurikabeCell number : numberedCells) { // loops through numberedCells + if (regions.getSet(number).size() + == number.getData()) { // if that cells white area is the exact + return null; // size of the number of one of the number cells within that set + } + } } - } - List numberedCells = new ArrayList<>(); // number value of number cells - for (NurikabeCell c : adj) { // loops through adjacent cells - Set disRow = regions.getSet(c); // set of white spaces - for (NurikabeCell d : disRow) { // loops through white spaces - if (d.getType() == NurikabeType.NUMBER) { // if the white space is a number - numberedCells.add(d); // add that number to numberedCells - } - } - } - for (NurikabeCell number : numberedCells) { // loops through numberedCells - if (regions.getSet(number).size() - == number.getData()) { // if that cells white area is the exact - return null; // size of the number of one of the number cells within that set - } - } + return "Does not follow from this rule at this index"; } - return "Does not follow from this rule at this index"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java index e05b72b7c..e7995165b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooFewSpacesContradictionRule.java @@ -12,51 +12,53 @@ public class TooFewSpacesContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; - - public TooFewSpacesContradictionRule() { - super( - "NURI-CONT-0006", - "Too Few Spaces", - "A region cannot contain less spaces than its number.", - "edu/rpi/legup/images/nurikabe/contradictions/TooFewSpaces.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + private final String NO_CONTRADICTION_MESSAGE = + "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; - DisjointSets regions = NurikabeUtilities.getPossibleWhiteRegions(nurikabeBoard); - Set whiteRegion = regions.getSet(cell); - NurikabeCell numberedCell = null; - for (NurikabeCell c : whiteRegion) { - if (c.getType() == NurikabeType.NUMBER) { - numberedCell = c; - break; - } + public TooFewSpacesContradictionRule() { + super( + "NURI-CONT-0006", + "Too Few Spaces", + "A region cannot contain less spaces than its number.", + "edu/rpi/legup/images/nurikabe/contradictions/TooFewSpaces.png"); } - if (numberedCell != null && whiteRegion.size() < numberedCell.getData()) { - // System.err.println("Cell Value: " + numberedCell.getData() + ", Loc: " + - // cell.getLocation() - // + ", region: " + whiteRegion.size()); - return null; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } + + DisjointSets regions = + NurikabeUtilities.getPossibleWhiteRegions(nurikabeBoard); + Set whiteRegion = regions.getSet(cell); + NurikabeCell numberedCell = null; + for (NurikabeCell c : whiteRegion) { + if (c.getType() == NurikabeType.NUMBER) { + numberedCell = c; + break; + } + } + + if (numberedCell != null && whiteRegion.size() < numberedCell.getData()) { + // System.err.println("Cell Value: " + numberedCell.getData() + ", Loc: " + + // cell.getLocation() + // + ", region: " + whiteRegion.size()); + return null; + } + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; } - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java index 550c07f57..7bd0883ef 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/TooManySpacesContradictionRule.java @@ -13,49 +13,50 @@ public class TooManySpacesContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Does not contain a contradiction at this index"; - private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; - - public TooManySpacesContradictionRule() { - super( - "NURI-CONT-0007", - "Too Many Spaces", - "A region cannot contain more spaces than its number.", - "edu/rpi/legup/images/nurikabe/contradictions/TooManySpaces.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + private final String NO_CONTRADICTION_MESSAGE = + "Does not contain a contradiction at this index"; + private final String INVALID_USE_MESSAGE = "Contradiction must be a white or a numbered cell"; + + public TooManySpacesContradictionRule() { + super( + "NURI-CONT-0007", + "Too Many Spaces", + "A region cannot contain more spaces than its number.", + "edu/rpi/legup/images/nurikabe/contradictions/TooManySpaces.png"); } - DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); - Set whiteRegion = regions.getSet(cell); - ArrayList numberedCells = new ArrayList<>(); - for (NurikabeCell c : whiteRegion) { - if (c.getType() == NurikabeType.NUMBER) { - numberedCells.add(c); - } + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE && cell.getType() != NurikabeType.NUMBER) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } + + DisjointSets regions = NurikabeUtilities.getNurikabeRegions(nurikabeBoard); + Set whiteRegion = regions.getSet(cell); + ArrayList numberedCells = new ArrayList<>(); + for (NurikabeCell c : whiteRegion) { + if (c.getType() == NurikabeType.NUMBER) { + numberedCells.add(c); + } + } + + for (NurikabeCell number : numberedCells) { + if (whiteRegion.size() > number.getData()) { + return null; + } + } + return super.getNoContradictionMessage() + ":" + this.NO_CONTRADICTION_MESSAGE; } - - for (NurikabeCell number : numberedCells) { - if (whiteRegion.size() > number.getData()) { - return null; - } - } - return super.getNoContradictionMessage() + ":" + this.NO_CONTRADICTION_MESSAGE; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java index 92b6f8d3e..c578d317f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/UnreachableWhiteCellContradictionRule.java @@ -12,94 +12,97 @@ public class UnreachableWhiteCellContradictionRule extends ContradictionRule { - private final String NO_CONTRADICTION_MESSAGE = "Cell at this index can be reached"; - private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; + private final String NO_CONTRADICTION_MESSAGE = "Cell at this index can be reached"; + private final String INVALID_USE_MESSAGE = "Does not contain a contradiction at this index"; - public UnreachableWhiteCellContradictionRule() { - super( - "NURI-CONT-0002", - "Unreachable White Cell", - "A white cell must be able to reach a white region", - "edu/rpi/legup/images/nurikabe/contradictions/CantReach.png"); - } + public UnreachableWhiteCellContradictionRule() { + super( + "NURI-CONT-0002", + "Unreachable White Cell", + "A white cell must be able to reach a white region", + "edu/rpi/legup/images/nurikabe/contradictions/CantReach.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NurikabeBoard nurikabeBoard = (NurikabeBoard) board; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + NurikabeBoard nurikabeBoard = (NurikabeBoard) board; - NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); - if (cell.getType() != NurikabeType.WHITE) { - return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; - } + NurikabeCell cell = (NurikabeCell) nurikabeBoard.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return super.getInvalidUseOfRuleMessage() + ": " + this.INVALID_USE_MESSAGE; + } - int height = nurikabeBoard.getHeight(); - int width = nurikabeBoard.getWidth(); + int height = nurikabeBoard.getHeight(); + int width = nurikabeBoard.getWidth(); - // Get regions - HashMap whiteRegionMap = - NurikabeUtilities.getWhiteRegionMap(nurikabeBoard); - if (whiteRegionMap.containsKey(cell)) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - // BFS to a region + // Get regions + HashMap whiteRegionMap = + NurikabeUtilities.getWhiteRegionMap(nurikabeBoard); + if (whiteRegionMap.containsKey(cell)) { + return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; + } + // BFS to a region - // Create a queue for BFS - LinkedList queue = new LinkedList<>(); + // Create a queue for BFS + LinkedList queue = new LinkedList<>(); - // Mark the current node as visited and enqueue it - HashMap visited = new HashMap<>(); - visited.put(cell, true); - queue.add(cell); - int pathLength = 1; - while (queue.size() != 0) { - // Set of adjacent squares - Set adj = new HashSet<>(); - while (queue.size() != 0) { - // Dequeue a vertex from queue and print it - NurikabeCell s = queue.poll(); + // Mark the current node as visited and enqueue it + HashMap visited = new HashMap<>(); + visited.put(cell, true); + queue.add(cell); + int pathLength = 1; + while (queue.size() != 0) { + // Set of adjacent squares + Set adj = new HashSet<>(); + while (queue.size() != 0) { + // Dequeue a vertex from queue and print it + NurikabeCell s = queue.poll(); - Point loc = s.getLocation(); - // First check if the side is on the board - if (loc.x >= 1) { - adj.add(nurikabeBoard.getCell(loc.x - 1, loc.y)); - } - if (loc.x < width - 1) { - adj.add(nurikabeBoard.getCell(loc.x + 1, loc.y)); - } - if (loc.y >= 1) { - adj.add(nurikabeBoard.getCell(loc.x, loc.y - 1)); - } - if (loc.y < height - 1) { - adj.add(nurikabeBoard.getCell(loc.x, loc.y + 1)); - } + Point loc = s.getLocation(); + // First check if the side is on the board + if (loc.x >= 1) { + adj.add(nurikabeBoard.getCell(loc.x - 1, loc.y)); + } + if (loc.x < width - 1) { + adj.add(nurikabeBoard.getCell(loc.x + 1, loc.y)); + } + if (loc.y >= 1) { + adj.add(nurikabeBoard.getCell(loc.x, loc.y - 1)); + } + if (loc.y < height - 1) { + adj.add(nurikabeBoard.getCell(loc.x, loc.y + 1)); + } - for (NurikabeCell n : adj) { - int regionNeed = whiteRegionMap.getOrDefault(n, -1); - if (pathLength <= regionNeed) { - return super.getNoContradictionMessage() + ": " + this.NO_CONTRADICTION_MESSAGE; - } - } - } + for (NurikabeCell n : adj) { + int regionNeed = whiteRegionMap.getOrDefault(n, -1); + if (pathLength <= regionNeed) { + return super.getNoContradictionMessage() + + ": " + + this.NO_CONTRADICTION_MESSAGE; + } + } + } - for (NurikabeCell n : adj) { - if (!visited.getOrDefault(n, false) - && (n.getType() == NurikabeType.UNKNOWN || n.getType() == NurikabeType.WHITE)) { - visited.put(n, true); - queue.add(n); + for (NurikabeCell n : adj) { + if (!visited.getOrDefault(n, false) + && (n.getType() == NurikabeType.UNKNOWN + || n.getType() == NurikabeType.WHITE)) { + visited.put(n, true); + queue.add(n); + } + } + ++pathLength; } - } - ++pathLength; - } - return null; - } + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java index 2299b4c46..434e7ccde 100644 --- a/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/nurikabe/rules/WhiteBottleNeckDirectRule.java @@ -14,58 +14,59 @@ public class WhiteBottleNeckDirectRule extends DirectRule { - public WhiteBottleNeckDirectRule() { - super( - "NURI-BASC-0009", - "White Bottle Neck", - "If a region needs more whites and there is only one path for the region to expand," - + " then those unknowns must be white.", - "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); - } + public WhiteBottleNeckDirectRule() { + super( + "NURI-BASC-0009", + "White Bottle Neck", + "If a region needs more whites and there is only one path for the region to expand," + + " then those unknowns must be white.", + "edu/rpi/legup/images/nurikabe/rules/OneUnknownWhite.png"); + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + Set contras = new LinkedHashSet<>(); + contras.add(new NoNumberContradictionRule()); + contras.add(new TooFewSpacesContradictionRule()); - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - Set contras = new LinkedHashSet<>(); - contras.add(new NoNumberContradictionRule()); - contras.add(new TooFewSpacesContradictionRule()); + NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); + NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); - NurikabeBoard destBoardState = (NurikabeBoard) transition.getBoard(); - NurikabeBoard origBoardState = (NurikabeBoard) transition.getParents().get(0).getBoard(); + NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); - NurikabeCell cell = (NurikabeCell) destBoardState.getPuzzleElement(puzzleElement); + if (cell.getType() != NurikabeType.WHITE) { + return "Only white cells are allowed for this rule!"; + } + NurikabeBoard modified = origBoardState.copy(); + NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); + modCell.setData(NurikabeType.BLACK.toValue()); - if (cell.getType() != NurikabeType.WHITE) { - return "Only white cells are allowed for this rule!"; + for (ContradictionRule contraRule : contras) { + if (contraRule.checkContradiction(modified) == null) { + return null; + } + } + return "This is not the only way for white to escape!"; } - NurikabeBoard modified = origBoardState.copy(); - NurikabeCell modCell = (NurikabeCell) modified.getPuzzleElement(puzzleElement); - modCell.setData(NurikabeType.BLACK.toValue()); - for (ContradictionRule contraRule : contras) { - if (contraRule.checkContradiction(modified) == null) { + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { return null; - } } - return "This is not the only way for white to escape!"; - } - - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java index 4e6f25cba..8b0b8e6d5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTable.java @@ -7,104 +7,104 @@ public class ShortTruthTable extends Puzzle { - public ShortTruthTable() { - super(); - - this.name = "ShortTruthTable"; - - this.importer = new ShortTruthTableImporter(this); - this.exporter = new ShortTruthTableExporter(this); - - this.factory = new ShortTruthTableCellFactory(); - } - - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) currentBoard; - boardView = new ShortTruthTableView(sttBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } - - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } - - @Override - /** - * Determines if the given dimensions are valid for Short Truth Table - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Short Truth Table, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // Number of rows must be odd to allow for proper spacing between the statements - if (rows % 2 != 1) { - return false; + public ShortTruthTable() { + super(); + + this.name = "ShortTruthTable"; + + this.importer = new ShortTruthTableImporter(this); + this.exporter = new ShortTruthTableExporter(this); + + this.factory = new ShortTruthTableCellFactory(); + } + + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) currentBoard; + boardView = new ShortTruthTableView(sttBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); } - return true; - } - - /** - * Determines if the given statements are valid for Short Truth Table - * - * @param statements - * @return true if the statements are valid for Short Truth Table, false otherwise - */ - public boolean isValidTextInput(String[] statements) { - if (statements.length == 0) { - return false; + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; } - ShortTruthTableImporter importer = (ShortTruthTableImporter) this.getImporter(); - for (String s : statements) { - if (!importer.validGrammar(s)) { - return false; - } + @Override + /** + * Determines if the given dimensions are valid for Short Truth Table + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Short Truth Table, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // Number of rows must be odd to allow for proper spacing between the statements + if (rows % 2 != 1) { + return false; + } + + return true; } - return true; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - - ShortTruthTableBoard sttboard = (ShortTruthTableBoard) board; - - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(sttboard) == null) { - return false; - } + + /** + * Determines if the given statements are valid for Short Truth Table + * + * @param statements + * @return true if the statements are valid for Short Truth Table, false otherwise + */ + public boolean isValidTextInput(String[] statements) { + if (statements.length == 0) { + return false; + } + + ShortTruthTableImporter importer = (ShortTruthTableImporter) this.getImporter(); + for (String s : statements) { + if (!importer.validGrammar(s)) { + return false; + } + } + return true; } - for (PuzzleElement data : sttboard.getPuzzleElements()) { - ShortTruthTableCell cell = (ShortTruthTableCell) data; - if (cell.getType() == ShortTruthTableCellType.UNKNOWN) { - return false; - } + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + + ShortTruthTableBoard sttboard = (ShortTruthTableBoard) board; + + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(sttboard) == null) { + return false; + } + } + for (PuzzleElement data : sttboard.getPuzzleElements()) { + ShortTruthTableCell cell = (ShortTruthTableCell) data; + if (cell.getType() == ShortTruthTableCellType.UNKNOWN) { + return false; + } + } + return true; } - return true; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java index 2876523f8..519a61974 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableBoard.java @@ -10,115 +10,115 @@ public class ShortTruthTableBoard extends GridBoard { - private ShortTruthTableStatement[] statements; + private ShortTruthTableStatement[] statements; - public ShortTruthTableBoard(int width, int height, ShortTruthTableStatement[] statements) { + public ShortTruthTableBoard(int width, int height, ShortTruthTableStatement[] statements) { - super(width, height); + super(width, height); - this.statements = statements; - } + this.statements = statements; + } - public Set getCellsWithSymbol(char symbol) { - Set cells = new HashSet(); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - ShortTruthTableCell cell = (ShortTruthTableCell) getCell(x, y); - if (cell.getSymbol() == symbol) { - cells.add(cell); + public Set getCellsWithSymbol(char symbol) { + Set cells = new HashSet(); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + ShortTruthTableCell cell = (ShortTruthTableCell) getCell(x, y); + if (cell.getSymbol() == symbol) { + cells.add(cell); + } + } } - } + return cells; + } + + public ShortTruthTableCell getCellFromElement(PuzzleElement element) { + return (ShortTruthTableCell) getPuzzleElement(element); } - return cells; - } - - public ShortTruthTableCell getCellFromElement(PuzzleElement element) { - return (ShortTruthTableCell) getPuzzleElement(element); - } - - @Override - public ShortTruthTableCell getCell(int x, int y) { - return (ShortTruthTableCell) super.getCell(x, y); - } - - @Override - public ShortTruthTableBoard copy() { - - // Copy the statements - ShortTruthTableStatement[] statementsCopy = - new ShortTruthTableStatement[this.statements.length]; - for (int i = 0; i < statements.length; i++) { - statementsCopy[i] = this.statements[i].copy(); + + @Override + public ShortTruthTableCell getCell(int x, int y) { + return (ShortTruthTableCell) super.getCell(x, y); } - // copy the board and set the cells - ShortTruthTableBoard boardCopy = - new ShortTruthTableBoard(getWidth(), getHeight(), statementsCopy); - for (int r = 0; r < this.dimension.height; r++) { - for (int c = 0; c < this.dimension.width; c++) { - if (r % 2 == 0 && c < statementsCopy[r / 2].getLength()) { - boardCopy.setCell(c, r, statementsCopy[r / 2].getCell(c)); - } else { - boardCopy.setCell(c, r, getCell(c, r).copy()); + + @Override + public ShortTruthTableBoard copy() { + + // Copy the statements + ShortTruthTableStatement[] statementsCopy = + new ShortTruthTableStatement[this.statements.length]; + for (int i = 0; i < statements.length; i++) { + statementsCopy[i] = this.statements[i].copy(); + } + // copy the board and set the cells + ShortTruthTableBoard boardCopy = + new ShortTruthTableBoard(getWidth(), getHeight(), statementsCopy); + for (int r = 0; r < this.dimension.height; r++) { + for (int c = 0; c < this.dimension.width; c++) { + if (r % 2 == 0 && c < statementsCopy[r / 2].getLength()) { + boardCopy.setCell(c, r, statementsCopy[r / 2].getCell(c)); + } else { + boardCopy.setCell(c, r, getCell(c, r).copy()); + } + } + } + for (PuzzleElement e : modifiedData) { + boardCopy.getPuzzleElement(e).setModifiable(false); } - } + System.out.println("Board.copy()"); + System.out.println("original:\n" + this); + System.out.println("copy:\n" + boardCopy); + return boardCopy; } - for (PuzzleElement e : modifiedData) { - boardCopy.getPuzzleElement(e).setModifiable(false); + + public ShortTruthTableStatement[] getStatements() { + return statements; } - System.out.println("Board.copy()"); - System.out.println("original:\n" + this); - System.out.println("copy:\n" + boardCopy); - return boardCopy; - } - - public ShortTruthTableStatement[] getStatements() { - return statements; - } - - public static List copyStatementList( - List statements) { - List copy = new ArrayList(); - for (int i = 0; i < statements.size(); i++) { - copy.add(statements.get(i).copy()); + + public static List copyStatementList( + List statements) { + List copy = new ArrayList(); + for (int i = 0; i < statements.size(); i++) { + copy.add(statements.get(i).copy()); + } + return copy; } - return copy; - } - - // @Override - // public void setPuzzleElement(int index, PuzzleElement element){ - // ShortTruthTableCell cellElement = (ShortTruthTableCell) element; - // ShortTruthTableCell cell = getCell(cellElement.getX(), cellElement.getY()); - // cell.setType(cellElement.getType()); - // } - - @Override - public void notifyChange(PuzzleElement puzzleElement) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - int r = cell.getY(); - int c = cell.getX(); - if (r % 2 == 0 && c < statements[r / 2].getLength()) { - statements[r / 2] = statements[r / 2].replace(c, cell); - setCell(c, r, statements[r / 2].getCell(c)); + + // @Override + // public void setPuzzleElement(int index, PuzzleElement element){ + // ShortTruthTableCell cellElement = (ShortTruthTableCell) element; + // ShortTruthTableCell cell = getCell(cellElement.getX(), cellElement.getY()); + // cell.setType(cellElement.getType()); + // } + + @Override + public void notifyChange(PuzzleElement puzzleElement) { + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + int r = cell.getY(); + int c = cell.getX(); + if (r % 2 == 0 && c < statements[r / 2].getLength()) { + statements[r / 2] = statements[r / 2].replace(c, cell); + setCell(c, r, statements[r / 2].getCell(c)); + } + super.notifyChange(cell); } - super.notifyChange(cell); - } - - @Override - public String toString() { - System.out.println("ShortTruthTableBoard toString() called"); - StringBuilder str = new StringBuilder(); - for (int i = 0; i < dimension.height; i += 2) { - for (int j = 0; j < dimension.width; j++) { - ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); - str.append(c.getSymbol()); - } - str.append(" "); - for (int j = 0; j < dimension.width; j++) { - ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); - str.append(ShortTruthTableCellType.toChar(c.getType())); - } - str.append('\n'); + + @Override + public String toString() { + System.out.println("ShortTruthTableBoard toString() called"); + StringBuilder str = new StringBuilder(); + for (int i = 0; i < dimension.height; i += 2) { + for (int j = 0; j < dimension.width; j++) { + ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); + str.append(c.getSymbol()); + } + str.append(" "); + for (int j = 0; j < dimension.width; j++) { + ShortTruthTableCell c = (ShortTruthTableCell) getCell(j, i); + str.append(ShortTruthTableCellType.toChar(c.getType())); + } + str.append('\n'); + } + return str.toString(); } - return str.toString(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java index a432fe5e4..75bba369f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCell.java @@ -7,210 +7,211 @@ public class ShortTruthTableCell extends GridCell { - // The symbol on the cell - private char symbol; - - // This is a reference to the statement that contains this cell - private ShortTruthTableStatement statement; - - // Constructors - - public ShortTruthTableCell(char symbol, ShortTruthTableCellType cellType, Point location) { - super(cellType, location); - this.symbol = symbol; - } - - /** - * Constructs a new NOT_IN_PLAY Cell - * - * @param location the location of this cell on the board - */ - public ShortTruthTableCell(Point location) { - this(' ', ShortTruthTableCellType.NOT_IN_PLAY, location); - } - - // Getters - - public ShortTruthTableStatement getStatementReference() { - return statement; - } - - public ShortTruthTableCellType getType() { - return data; - } - - public char getSymbol() { - return symbol; - } - - /** - * Returns true if this cell is a letter; false if it is an operation, paren, unused, etc - * - * @return true if cell is a variable; false otherwise - */ - public boolean isVariable() { - return Character.isLetter(symbol); - } - - public int getX() { - return (int) location.getX(); - } - - public int getY() { - return (int) location.getY(); - } - - public boolean isAssigned() { - return getType() == ShortTruthTableCellType.TRUE || getType() == ShortTruthTableCellType.FALSE; - } - - // Setters - - void setStatementReference(ShortTruthTableStatement statement) { - this.statement = statement; - } - - public void setType(ShortTruthTableCellType type) { - data = type; - } - - public void setGiven(ShortTruthTableCellType type) { - setType(type); - setModifiable(false); - setGiven(true); - } - - // Modifiers - - public void cycleTypeForward() { - switch (data) { - case UNKNOWN: - data = ShortTruthTableCellType.TRUE; - break; - case TRUE: - data = ShortTruthTableCellType.FALSE; - break; - case FALSE: - data = ShortTruthTableCellType.UNKNOWN; - break; - default: - break; - } - } - - public void cycleTypeBackward() { - cycleTypeForward(); - cycleTypeForward(); - } - - // TO STRING - - @Override - public String toString() { - return String.format("STTCell: %c %2d %-11s %s", symbol, index, data, location.toString()); - } - - // Copy function - - @Override - public ShortTruthTableCell copy() { - ShortTruthTableCell copy = new ShortTruthTableCell(symbol, data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } - - /** - * Sets the type of this ShortTruthTableCell - * - * @param e element to set the type of this Short Truth Table cell to - */ - @Override - public void setType(Element e, MouseEvent m) { - // Do not allow odd rows to be modified since they are spacer rows - if (this.getLocation().getY() % 2 == 1) { - return; - } - - // Red Element - if (e.getElementID().equals("STTT-PLAC-0002")) { - this.data = ShortTruthTableCellType.FALSE; - } - // Green Element - else { - if (e.getElementID().equals("STTT-PLAC-0001")) { - this.data = ShortTruthTableCellType.TRUE; - } - // Unknown Element - else { - if (e.getElementID().equals("STTT-PLAC-0003")) { - this.data = ShortTruthTableCellType.UNKNOWN; + // The symbol on the cell + private char symbol; + + // This is a reference to the statement that contains this cell + private ShortTruthTableStatement statement; + + // Constructors + + public ShortTruthTableCell(char symbol, ShortTruthTableCellType cellType, Point location) { + super(cellType, location); + this.symbol = symbol; + } + + /** + * Constructs a new NOT_IN_PLAY Cell + * + * @param location the location of this cell on the board + */ + public ShortTruthTableCell(Point location) { + this(' ', ShortTruthTableCellType.NOT_IN_PLAY, location); + } + + // Getters + + public ShortTruthTableStatement getStatementReference() { + return statement; + } + + public ShortTruthTableCellType getType() { + return data; + } + + public char getSymbol() { + return symbol; + } + + /** + * Returns true if this cell is a letter; false if it is an operation, paren, unused, etc + * + * @return true if cell is a variable; false otherwise + */ + public boolean isVariable() { + return Character.isLetter(symbol); + } + + public int getX() { + return (int) location.getX(); + } + + public int getY() { + return (int) location.getY(); + } + + public boolean isAssigned() { + return getType() == ShortTruthTableCellType.TRUE + || getType() == ShortTruthTableCellType.FALSE; + } + + // Setters + + void setStatementReference(ShortTruthTableStatement statement) { + this.statement = statement; + } + + public void setType(ShortTruthTableCellType type) { + data = type; + } + + public void setGiven(ShortTruthTableCellType type) { + setType(type); + setModifiable(false); + setGiven(true); + } + + // Modifiers + + public void cycleTypeForward() { + switch (data) { + case UNKNOWN: + data = ShortTruthTableCellType.TRUE; + break; + case TRUE: + data = ShortTruthTableCellType.FALSE; + break; + case FALSE: + data = ShortTruthTableCellType.UNKNOWN; + break; + default: + break; + } + } + + public void cycleTypeBackward() { + cycleTypeForward(); + cycleTypeForward(); + } + + // TO STRING + + @Override + public String toString() { + return String.format("STTCell: %c %2d %-11s %s", symbol, index, data, location.toString()); + } + + // Copy function + + @Override + public ShortTruthTableCell copy() { + ShortTruthTableCell copy = new ShortTruthTableCell(symbol, data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } + + /** + * Sets the type of this ShortTruthTableCell + * + * @param e element to set the type of this Short Truth Table cell to + */ + @Override + public void setType(Element e, MouseEvent m) { + // Do not allow odd rows to be modified since they are spacer rows + if (this.getLocation().getY() % 2 == 1) { + return; + } + + // Red Element + if (e.getElementID().equals("STTT-PLAC-0002")) { + this.data = ShortTruthTableCellType.FALSE; } - // Argument Element + // Green Element else { - if (e.getElementID().equals("STTT-UNPL-0001")) { - // Prevents non-argument symbols from being changed - if (!(this.symbol >= 'A' && this.symbol <= 'Z')) { - return; + if (e.getElementID().equals("STTT-PLAC-0001")) { + this.data = ShortTruthTableCellType.TRUE; } - - if (m.getButton() == MouseEvent.BUTTON1) { - this.symbol += 1; - if (this.symbol > 'Z') { - this.symbol = 'A'; - } - } else { - if (m.getButton() == MouseEvent.BUTTON3) { - this.symbol -= 1; - if (this.symbol < 'A') { - this.symbol = 'Z'; + // Unknown Element + else { + if (e.getElementID().equals("STTT-PLAC-0003")) { + this.data = ShortTruthTableCellType.UNKNOWN; } - } - } - } - // And/Or Element - else { - if (e.getElementID().equals("STTT-UNPL-0002")) { - if (m.getButton() == MouseEvent.BUTTON1) { - if (this.symbol == '^') { - this.symbol = '|'; - } else { - if (this.symbol == '|') { - this.symbol = '>'; - } else { - if (this.symbol == '>') { - this.symbol = '-'; - } else { - if (this.symbol == '-') { - this.symbol = '^'; - } + // Argument Element + else { + if (e.getElementID().equals("STTT-UNPL-0001")) { + // Prevents non-argument symbols from being changed + if (!(this.symbol >= 'A' && this.symbol <= 'Z')) { + return; + } + + if (m.getButton() == MouseEvent.BUTTON1) { + this.symbol += 1; + if (this.symbol > 'Z') { + this.symbol = 'A'; + } + } else { + if (m.getButton() == MouseEvent.BUTTON3) { + this.symbol -= 1; + if (this.symbol < 'A') { + this.symbol = 'Z'; + } + } + } } - } - } - } else { - if (m.getButton() == MouseEvent.BUTTON3) { - if (this.symbol == '^') { - this.symbol = '-'; - } else { - if (this.symbol == '|') { - this.symbol = '^'; - } else { - if (this.symbol == '>') { - this.symbol = '|'; - } else { - if (this.symbol == '-') { - this.symbol = '>'; + // And/Or Element + else { + if (e.getElementID().equals("STTT-UNPL-0002")) { + if (m.getButton() == MouseEvent.BUTTON1) { + if (this.symbol == '^') { + this.symbol = '|'; + } else { + if (this.symbol == '|') { + this.symbol = '>'; + } else { + if (this.symbol == '>') { + this.symbol = '-'; + } else { + if (this.symbol == '-') { + this.symbol = '^'; + } + } + } + } + } else { + if (m.getButton() == MouseEvent.BUTTON3) { + if (this.symbol == '^') { + this.symbol = '-'; + } else { + if (this.symbol == '|') { + this.symbol = '^'; + } else { + if (this.symbol == '>') { + this.symbol = '|'; + } else { + if (this.symbol == '-') { + this.symbol = '>'; + } + } + } + } + } + } } - } } - } } - } } - } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java index 288fd11f9..df74afdc9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellFactory.java @@ -10,61 +10,64 @@ import org.w3c.dom.Node; public class ShortTruthTableCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public ShortTruthTableCell importCell(Node node, Board board) throws InvalidFileFormatException { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public ShortTruthTableCell importCell(Node node, Board board) + throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "ShortTruthTable Factory: unknown puzzleElement puzzleElement"); - } + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "ShortTruthTable Factory: unknown puzzleElement puzzleElement"); + } - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board; + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board; - // get the attributes for the cell - NamedNodeMap attributeList = node.getAttributes(); - int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); - int charIndex = Integer.valueOf(attributeList.getNamedItem("char_index").getNodeValue()); - String cellType = attributeList.getNamedItem("type").getNodeValue(); + // get the attributes for the cell + NamedNodeMap attributeList = node.getAttributes(); + int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); + int charIndex = + Integer.valueOf(attributeList.getNamedItem("char_index").getNodeValue()); + String cellType = attributeList.getNamedItem("type").getNodeValue(); - // modify the appropriate cell - ShortTruthTableCell cell = (ShortTruthTableCell) sttBoard.getCell(charIndex, rowIndex * 2); - cell.setData(ShortTruthTableCellType.valueOf(cellType)); + // modify the appropriate cell + ShortTruthTableCell cell = + (ShortTruthTableCell) sttBoard.getCell(charIndex, rowIndex * 2); + cell.setData(ShortTruthTableCellType.valueOf(cellType)); - return cell; + return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "nurikabe Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "nurikabe Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("nurikabe Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - org.w3c.dom.Element cellElement = document.createElement("cell"); - cellElement.setAttribute("row_index", String.valueOf(cell.getY() / 2)); - cellElement.setAttribute("char_index", String.valueOf(cell.getX())); - cellElement.setAttribute("type", String.valueOf(cell.getType())); + org.w3c.dom.Element cellElement = document.createElement("cell"); + cellElement.setAttribute("row_index", String.valueOf(cell.getY() / 2)); + cellElement.setAttribute("char_index", String.valueOf(cell.getX())); + cellElement.setAttribute("type", String.valueOf(cell.getType())); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java index fde55ee3c..d5a8292a2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableCellType.java @@ -4,64 +4,64 @@ import java.util.Map; public enum ShortTruthTableCellType { - FALSE(0), - TRUE(1), - UNKNOWN(-1), - NOT_IN_PLAY(-2), - PARENTHESIS(-3); + FALSE(0), + TRUE(1), + UNKNOWN(-1), + NOT_IN_PLAY(-2), + PARENTHESIS(-3); - public int value; - private static Map map = new HashMap<>(); + public int value; + private static Map map = new HashMap<>(); - ShortTruthTableCellType(int value) { - this.value = value; - } + ShortTruthTableCellType(int value) { + this.value = value; + } - static { - for (ShortTruthTableCellType cellType : ShortTruthTableCellType.values()) { - map.put(cellType.value, cellType); + static { + for (ShortTruthTableCellType cellType : ShortTruthTableCellType.values()) { + map.put(cellType.value, cellType); + } } - } - public static ShortTruthTableCellType valueOf(int cellType) { - return (ShortTruthTableCellType) map.get(cellType); - } + public static ShortTruthTableCellType valueOf(int cellType) { + return (ShortTruthTableCellType) map.get(cellType); + } - /** - * Gets the char value of a cell, Used for debugging - * - * @param type cell type input - * @return true if value is 1, false if value is 0, ? if value is -1, or blank otherwise - */ - public static char toChar(ShortTruthTableCellType type) { - if (type == TRUE) return 'T'; - if (type == FALSE) return 'F'; - if (type == UNKNOWN) return '?'; - return ' '; - } + /** + * Gets the char value of a cell, Used for debugging + * + * @param type cell type input + * @return true if value is 1, false if value is 0, ? if value is -1, or blank otherwise + */ + public static char toChar(ShortTruthTableCellType type) { + if (type == TRUE) return 'T'; + if (type == FALSE) return 'F'; + if (type == UNKNOWN) return '?'; + return ' '; + } - /** - * Returns true if this cell holds the value either TRUE or FALSE - * - * @return true if this cell holds the value either TRUE or FALSE - */ - public boolean isTrueOrFalse() { - return value == 0 || value == 1; - } + /** + * Returns true if this cell holds the value either TRUE or FALSE + * + * @return true if this cell holds the value either TRUE or FALSE + */ + public boolean isTrueOrFalse() { + return value == 0 || value == 1; + } - public ShortTruthTableCellType getNegation() { - switch (value) { - case 1: - return ShortTruthTableCellType.FALSE; - case 0: - return ShortTruthTableCellType.TRUE; - default: - throw new RuntimeException("Trying to negate a cell not assigned to true or false"); + public ShortTruthTableCellType getNegation() { + switch (value) { + case 1: + return ShortTruthTableCellType.FALSE; + case 0: + return ShortTruthTableCellType.TRUE; + default: + throw new RuntimeException("Trying to negate a cell not assigned to true or false"); + } } - } - public static ShortTruthTableCellType getDefaultType(char c) { - if (c == '(' || c == ')') return PARENTHESIS; - return UNKNOWN; - } + public static ShortTruthTableCellType getDefaultType(char c) { + if (c == '(' || c == ')') return PARENTHESIS; + return UNKNOWN; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java index e83c7b358..172867f5a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableController.java @@ -6,29 +6,29 @@ public class ShortTruthTableController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { - System.out.println("STTController: Cell change"); + System.out.println("STTController: Cell change"); - // cast the data to a short truth table cell - ShortTruthTableCell cell = (ShortTruthTableCell) data; + // cast the data to a short truth table cell + ShortTruthTableCell cell = (ShortTruthTableCell) data; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - cell.cycleTypeForward(); - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - cell.cycleTypeBackward(); - } + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + cell.cycleTypeForward(); + } + } else { + if (e.getButton() == MouseEvent.BUTTON3) { + cell.cycleTypeBackward(); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java index af6e412ba..43e1d2299 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableElementView.java @@ -6,73 +6,74 @@ public class ShortTruthTableElementView extends GridElementView { - // Font - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; + // Font + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; - // Square Colors - private static final Color TRUE_COLOR = new Color(0, 130, 0); // green - private static final Color TRUE_COLOR_COLORBLIND = new Color(0, 0, 255); - private static final Color FALSE_COLOR = new Color(200, 0, 0); // red + // Square Colors + private static final Color TRUE_COLOR = new Color(0, 130, 0); // green + private static final Color TRUE_COLOR_COLORBLIND = new Color(0, 0, 255); + private static final Color FALSE_COLOR = new Color(200, 0, 0); // red - private static final Color FALSE_COLOR_COLORBLIND = new Color(255, 0, 0); - private static final Color UNKNOWN_COLOR = Color.WHITE; + private static final Color FALSE_COLOR_COLORBLIND = new Color(255, 0, 0); + private static final Color UNKNOWN_COLOR = Color.WHITE; - public ShortTruthTableElementView(ShortTruthTableCell cell) { - super(cell); - } + public ShortTruthTableElementView(ShortTruthTableCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public ShortTruthTableCell getPuzzleElement() { - return (ShortTruthTableCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public ShortTruthTableCell getPuzzleElement() { + return (ShortTruthTableCell) super.getPuzzleElement(); + } - @Override - public void drawElement(Graphics2D graphics2D) { + @Override + public void drawElement(Graphics2D graphics2D) { - // get information about the cell - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - ShortTruthTableCellType type = cell.getData(); + // get information about the cell + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + ShortTruthTableCellType type = cell.getData(); - // do not draw the cell if it is not in play - if (type == ShortTruthTableCellType.NOT_IN_PLAY) return; + // do not draw the cell if it is not in play + if (type == ShortTruthTableCellType.NOT_IN_PLAY) return; - // fill in background color of the cell - graphics2D.setStroke(new BasicStroke(1)); - LegupPreferences prefs = LegupPreferences.getInstance(); - switch (type) { - case TRUE: - if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - graphics2D.setColor(TRUE_COLOR_COLORBLIND); - break; - } - graphics2D.setColor(TRUE_COLOR); - break; - case FALSE: - if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { - graphics2D.setColor(FALSE_COLOR_COLORBLIND); - break; + // fill in background color of the cell + graphics2D.setStroke(new BasicStroke(1)); + LegupPreferences prefs = LegupPreferences.getInstance(); + switch (type) { + case TRUE: + if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + graphics2D.setColor(TRUE_COLOR_COLORBLIND); + break; + } + graphics2D.setColor(TRUE_COLOR); + break; + case FALSE: + if (prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true")) { + graphics2D.setColor(FALSE_COLOR_COLORBLIND); + break; + } + graphics2D.setColor(FALSE_COLOR); + break; + default: + graphics2D.setColor(UNKNOWN_COLOR); + break; } - graphics2D.setColor(FALSE_COLOR); - break; - default: - graphics2D.setColor(UNKNOWN_COLOR); - break; - } - graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.fillRect(location.x, location.y, size.width, size.height); - // Draw the symbol on the cell - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getSymbol()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(ShortTruthTableOperation.getLogicSymbol(cell.getSymbol()), xText, yText); - } + // Draw the symbol on the cell + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getSymbol()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString( + ShortTruthTableOperation.getLogicSymbol(cell.getSymbol()), xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java index a3c2c6918..0914c159a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableExporter.java @@ -6,40 +6,41 @@ public class ShortTruthTableExporter extends PuzzleExporter { - public ShortTruthTableExporter(ShortTruthTable stt) { - super(stt); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - ShortTruthTableBoard board; - if (puzzle.getTree() != null) { - board = (ShortTruthTableBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (ShortTruthTableBoard) puzzle.getBoardView().getBoard(); + public ShortTruthTableExporter(ShortTruthTable stt) { + super(stt); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - - org.w3c.dom.Element dataElement = newDocument.createElement("data"); - - ShortTruthTableStatement[] statements = board.getStatements(); - for (int i = 0; i < statements.length; i++) { - org.w3c.dom.Element statementElement = newDocument.createElement("statement"); - statementElement.setAttribute("representation", statements[i].getStringRep()); - statementElement.setAttribute("row_index", String.valueOf(i)); - dataElement.appendChild(statementElement); - } - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - ShortTruthTableCell cell = board.getCellFromElement(puzzleElement); - if (!cell.getType().isTrueOrFalse()) continue; - - org.w3c.dom.Element cellElement = puzzle.getFactory().exportCell(newDocument, puzzleElement); - dataElement.appendChild(cellElement); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + ShortTruthTableBoard board; + if (puzzle.getTree() != null) { + board = (ShortTruthTableBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (ShortTruthTableBoard) puzzle.getBoardView().getBoard(); + } + + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + + org.w3c.dom.Element dataElement = newDocument.createElement("data"); + + ShortTruthTableStatement[] statements = board.getStatements(); + for (int i = 0; i < statements.length; i++) { + org.w3c.dom.Element statementElement = newDocument.createElement("statement"); + statementElement.setAttribute("representation", statements[i].getStringRep()); + statementElement.setAttribute("row_index", String.valueOf(i)); + dataElement.appendChild(statementElement); + } + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + ShortTruthTableCell cell = board.getCellFromElement(puzzleElement); + if (!cell.getType().isTrueOrFalse()) continue; + + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + dataElement.appendChild(cellElement); + } + + boardElement.appendChild(dataElement); + return boardElement; } - - boardElement.appendChild(dataElement); - return boardElement; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java index 979bd8d30..396668380 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableImporter.java @@ -14,335 +14,347 @@ class ShortTruthTableImporter extends PuzzleImporter { - public ShortTruthTableImporter(ShortTruthTable stt) { - super(stt); - } - - /** - * Parse a string into all the cells, the y position of the statement is passed so the y position - * can be set - * - * @param statement - * @param y - * @return - */ - private List getCells(String statement, int y) { - List cells = new ArrayList(); - // go through each char in the statement and make a cell for it - for (int i = 0; i < statement.length(); i++) { - char c = statement.charAt(i); - ShortTruthTableCell cell = - new ShortTruthTableCell(c, ShortTruthTableCellType.getDefaultType(c), new Point(i, y)); - // it is modifiable if the type is unknown - cell.setModifiable(cell.getType() == ShortTruthTableCellType.UNKNOWN); - cells.add(cell); - } - return cells; - } - - /** - * Parses the statementData into all the cells (with symbols) and statements for the puzzle. All - * cells are set to UNKNWON, it their value is given, it will be set later in the import process. - * - *

Both allCells and statements act as returns, They should be passed as empty arrays - * - * @param statementData The data to be imported - * @param allCells returns all the cells as a jagged 2d array - * @param statements returns all the statements - * @return the length, in chars, of the longest statement - */ - private int parseAllStatementsAndCells( - final NodeList statementData, - List> allCells, - List statements) - throws InvalidFileFormatException { - - int maxStatementLength = 0; - - // get a 2D arraylist of all the cells - for (int i = 0; i < statementData.getLength(); i++) { - - // Get the atributes from the statement i in the file - NamedNodeMap attributeList = statementData.item(i).getAttributes(); - - String statementRep = attributeList.getNamedItem("representation").getNodeValue(); - System.out.println("STATEMENT REP: " + statementRep); - System.out.println("ROW INDEX: " + attributeList.getNamedItem("row_index").getNodeValue()); - // parser time (on statementRep) - // if (!validGrammar(statementRep)) throw some error - if (!validGrammar(statementRep)) { - JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); - throw new InvalidFileFormatException("shorttruthtable importer: invalid sentence syntax"); - } - int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); - - // get the cells for the statement - List rowOfCells = getCells(statementRep, rowIndex * 2); - allCells.add(rowOfCells); - statements.add(new ShortTruthTableStatement(statementRep, rowOfCells)); - - // keep track of the length of the longest statement - maxStatementLength = Math.max(maxStatementLength, statementRep.length()); + public ShortTruthTableImporter(ShortTruthTable stt) { + super(stt); } - return maxStatementLength; - } - - private int parseAllStatementsAndCells( - String[] statementData, - List> allCells, - List statements) - throws IllegalArgumentException { - int maxStatementLength = 0; - - for (int i = 0; i < statementData.length; i++) { - if (!validGrammar(statementData[i])) { - JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); - throw new IllegalArgumentException("shorttruthtable importer: invalid sentence syntax"); - } - - // get the cells for the statement - List rowOfCells = getCells(statementData[i], i * 2); - allCells.add(rowOfCells); - statements.add(new ShortTruthTableStatement(statementData[i], rowOfCells)); - - // keep track of the length of the longest statement - maxStatementLength = Math.max(maxStatementLength, statementData[i].length()); + /** + * Parse a string into all the cells, the y position of the statement is passed so the y + * position can be set + * + * @param statement + * @param y + * @return + */ + private List getCells(String statement, int y) { + List cells = new ArrayList(); + // go through each char in the statement and make a cell for it + for (int i = 0; i < statement.length(); i++) { + char c = statement.charAt(i); + ShortTruthTableCell cell = + new ShortTruthTableCell( + c, ShortTruthTableCellType.getDefaultType(c), new Point(i, y)); + // it is modifiable if the type is unknown + cell.setModifiable(cell.getType() == ShortTruthTableCellType.UNKNOWN); + cells.add(cell); + } + return cells; } - return maxStatementLength; - } - - protected boolean validGrammar(String sentence) { - int open = 0; - int close = 0; - char[] valid_characters = new char[] {'^', 'v', '!', '>', '-', '&', '|', '~', '$', '%'}; - for (int i = 0; i < sentence.length(); i++) { - char s = sentence.charAt(i); - if (s == '(' || s == ')') { - switch (s) { - case ')': - close++; - break; - case '(': - open++; - break; - } - continue; - } - if (!Character.isLetter(s)) { - boolean valid = false; - for (char c : valid_characters) { - if (c == s) { - valid = true; - break; - } - } - if (!valid) { - System.out.println("Invalid character"); - System.out.println(s); - return false; + /** + * Parses the statementData into all the cells (with symbols) and statements for the puzzle. All + * cells are set to UNKNWON, it their value is given, it will be set later in the import + * process. + * + *

Both allCells and statements act as returns, They should be passed as empty arrays + * + * @param statementData The data to be imported + * @param allCells returns all the cells as a jagged 2d array + * @param statements returns all the statements + * @return the length, in chars, of the longest statement + */ + private int parseAllStatementsAndCells( + final NodeList statementData, + List> allCells, + List statements) + throws InvalidFileFormatException { + + int maxStatementLength = 0; + + // get a 2D arraylist of all the cells + for (int i = 0; i < statementData.getLength(); i++) { + + // Get the atributes from the statement i in the file + NamedNodeMap attributeList = statementData.item(i).getAttributes(); + + String statementRep = attributeList.getNamedItem("representation").getNodeValue(); + System.out.println("STATEMENT REP: " + statementRep); + System.out.println( + "ROW INDEX: " + attributeList.getNamedItem("row_index").getNodeValue()); + // parser time (on statementRep) + // if (!validGrammar(statementRep)) throw some error + if (!validGrammar(statementRep)) { + JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); + throw new InvalidFileFormatException( + "shorttruthtable importer: invalid sentence syntax"); + } + int rowIndex = Integer.valueOf(attributeList.getNamedItem("row_index").getNodeValue()); + + // get the cells for the statement + List rowOfCells = getCells(statementRep, rowIndex * 2); + allCells.add(rowOfCells); + statements.add(new ShortTruthTableStatement(statementRep, rowOfCells)); + + // keep track of the length of the longest statement + maxStatementLength = Math.max(maxStatementLength, statementRep.length()); } - if (i != sentence.length() - 1) { - char next = sentence.charAt(i + 1); - if (next != '!' && next != '~') { - for (char c : valid_characters) { - if (c == next) { - System.out.println("Invalid next character"); - System.out.println(s); - System.out.println(next); - return false; - } + + return maxStatementLength; + } + + private int parseAllStatementsAndCells( + String[] statementData, + List> allCells, + List statements) + throws IllegalArgumentException { + int maxStatementLength = 0; + + for (int i = 0; i < statementData.length; i++) { + if (!validGrammar(statementData[i])) { + JOptionPane.showMessageDialog(null, "ERROR: Invalid file syntax"); + throw new IllegalArgumentException( + "shorttruthtable importer: invalid sentence syntax"); } - } + + // get the cells for the statement + List rowOfCells = getCells(statementData[i], i * 2); + allCells.add(rowOfCells); + statements.add(new ShortTruthTableStatement(statementData[i], rowOfCells)); + + // keep track of the length of the longest statement + maxStatementLength = Math.max(maxStatementLength, statementData[i].length()); } - } else { - if (i != sentence.length() - 1) { - if (Character.isLetter(sentence.charAt(i + 1))) { - System.out.println("Invalid next character"); - System.out.println(s); - System.out.println(sentence.charAt(i + 1)); - return false; - } + + return maxStatementLength; + } + + protected boolean validGrammar(String sentence) { + int open = 0; + int close = 0; + char[] valid_characters = new char[] {'^', 'v', '!', '>', '-', '&', '|', '~', '$', '%'}; + for (int i = 0; i < sentence.length(); i++) { + char s = sentence.charAt(i); + if (s == '(' || s == ')') { + switch (s) { + case ')': + close++; + break; + case '(': + open++; + break; + } + continue; + } + if (!Character.isLetter(s)) { + boolean valid = false; + for (char c : valid_characters) { + if (c == s) { + valid = true; + break; + } + } + if (!valid) { + System.out.println("Invalid character"); + System.out.println(s); + return false; + } + if (i != sentence.length() - 1) { + char next = sentence.charAt(i + 1); + if (next != '!' && next != '~') { + for (char c : valid_characters) { + if (c == next) { + System.out.println("Invalid next character"); + System.out.println(s); + System.out.println(next); + return false; + } + } + } + } + } else { + if (i != sentence.length() - 1) { + if (Character.isLetter(sentence.charAt(i + 1))) { + System.out.println("Invalid next character"); + System.out.println(s); + System.out.println(sentence.charAt(i + 1)); + return false; + } + } + } } - } + return open == close; } - return open == close; - } - - private ShortTruthTableBoard generateBoard( - List> allCells, - List statements, - int width) { - - // calculate the height for the board - int height = statements.size() * 2 - 1; - - // instantiate the board with the correct width and height - ShortTruthTableBoard sttBoard = - new ShortTruthTableBoard( - width, height, statements.toArray(new ShortTruthTableStatement[statements.size()])); - - // set the cells in the board. create not_in_play cells where needed - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - - // get the statement index for this row of the table - int statementIndex = y / 2; - - // get the cell at this location; or create a not_in_play one if necessary - ShortTruthTableCell cell = null; - - // for a cell to exist at (x, y), it must be a valid row and within the statement - // length - if (y % 2 == 0 && x < statements.get(statementIndex).getLength()) { - cell = allCells.get(statementIndex).get(x); - System.out.println("Importer: check cell statement ref: " + cell.getStatementReference()); - } else { - // if it is not a valid cell space, add a NOT_IN_PLAY cell - cell = new ShortTruthTableCell(' ', ShortTruthTableCellType.NOT_IN_PLAY, new Point(x, y)); - cell.setModifiable(false); + + private ShortTruthTableBoard generateBoard( + List> allCells, + List statements, + int width) { + + // calculate the height for the board + int height = statements.size() * 2 - 1; + + // instantiate the board with the correct width and height + ShortTruthTableBoard sttBoard = + new ShortTruthTableBoard( + width, + height, + statements.toArray(new ShortTruthTableStatement[statements.size()])); + + // set the cells in the board. create not_in_play cells where needed + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + + // get the statement index for this row of the table + int statementIndex = y / 2; + + // get the cell at this location; or create a not_in_play one if necessary + ShortTruthTableCell cell = null; + + // for a cell to exist at (x, y), it must be a valid row and within the statement + // length + if (y % 2 == 0 && x < statements.get(statementIndex).getLength()) { + cell = allCells.get(statementIndex).get(x); + System.out.println( + "Importer: check cell statement ref: " + cell.getStatementReference()); + } else { + // if it is not a valid cell space, add a NOT_IN_PLAY cell + cell = + new ShortTruthTableCell( + ' ', ShortTruthTableCellType.NOT_IN_PLAY, new Point(x, y)); + cell.setModifiable(false); + } + + // add the cell to the table + cell.setIndex(y * width + x); + sttBoard.setCell(x, y, cell); + } } - // add the cell to the table - cell.setIndex(y * width + x); - sttBoard.setCell(x, y, cell); - } + return sttBoard; } - return sttBoard; - } - - private void setGivenCells( - ShortTruthTableBoard sttBoard, - Element dataElement, - NodeList cellData, - List statements) - throws InvalidFileFormatException { - - // if it is normal, set all predicates to true and the conclusion to false - if (dataElement.getAttribute("normal").equalsIgnoreCase("true")) { - // set all predicates to true (all but the last one) - for (int i = 0; i < statements.size() - 1; i++) { - statements.get(i).getCell().setGiven(ShortTruthTableCellType.TRUE); - } - // set the conclusion to false (the last one) - statements.get(statements.size() - 1).getCell().setGiven(ShortTruthTableCellType.FALSE); - } + private void setGivenCells( + ShortTruthTableBoard sttBoard, + Element dataElement, + NodeList cellData, + List statements) + throws InvalidFileFormatException { + + // if it is normal, set all predicates to true and the conclusion to false + if (dataElement.getAttribute("normal").equalsIgnoreCase("true")) { + // set all predicates to true (all but the last one) + for (int i = 0; i < statements.size() - 1; i++) { + statements.get(i).getCell().setGiven(ShortTruthTableCellType.TRUE); + } + // set the conclusion to false (the last one) + statements.get(statements.size() - 1).getCell().setGiven(ShortTruthTableCellType.FALSE); + } - // set the given cell values - for (int i = 0; i < cellData.getLength(); i++) { - // set the value with the factory importer - ShortTruthTableCell cell = - (ShortTruthTableCell) puzzle.getFactory().importCell(cellData.item(i), sttBoard); - // set the modifiable and given flags - cell.setModifiable(false); - cell.setGiven(true); + // set the given cell values + for (int i = 0; i < cellData.getLength(); i++) { + // set the value with the factory importer + ShortTruthTableCell cell = + (ShortTruthTableCell) + puzzle.getFactory().importCell(cellData.item(i), sttBoard); + // set the modifiable and given flags + cell.setModifiable(false); + cell.setGiven(true); + } } - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return false; - } - - @Override - public boolean acceptsTextInput() { - return true; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException - */ - @Override - public void initializeBoard(int rows, int columns) {} - - // STATEMENT IMPORTER - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - - try { - - // Check File formatting - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "short truth table Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("data").getLength() == 0) { - throw new InvalidFileFormatException( - "short truth table Importer: no statements found for board"); - } - - // get all the cells in a 2D arraylist - List> allCells = new ArrayList>(); - // store the statement data structors - List statements = new ArrayList(); - - // get the elements from the file - Element dataElement = (Element) boardElement.getElementsByTagName("data").item(0); - NodeList statementData = dataElement.getElementsByTagName("statement"); - NodeList cellData = dataElement.getElementsByTagName("cell"); - - // Parse the data - int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); - - // generate the board - ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); - - // set the given cell values - setGivenCells(sttBoard, dataElement, cellData, statements); - - puzzle.setCurrentBoard(sttBoard); - - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "short truth table Importer: unknown value where integer expected"); + + @Override + public boolean acceptsRowsAndColumnsInput() { + return false; } - } - - /** - * Creates the board for building using statements - * - * @param statementInput - * @throws UnsupportedOperationException - * @throws IllegalArgumentException - */ - public void initializeBoard(String[] statementInput) - throws UnsupportedOperationException, IllegalArgumentException { - List statementsList = new LinkedList<>(); - for (String s : statementInput) { - if (s.strip().length() > 0) { - statementsList.add(s); - } + + @Override + public boolean acceptsTextInput() { + return true; } - String[] statementData = statementsList.toArray(new String[statementsList.size()]); - if (statementData.length == 0) { - throw new IllegalArgumentException( - "short truth table Importer: no statements found for board"); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException + */ + @Override + public void initializeBoard(int rows, int columns) {} + + // STATEMENT IMPORTER + + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + + try { + + // Check File formatting + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "short truth table Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("data").getLength() == 0) { + throw new InvalidFileFormatException( + "short truth table Importer: no statements found for board"); + } + + // get all the cells in a 2D arraylist + List> allCells = new ArrayList>(); + // store the statement data structors + List statements = new ArrayList(); + + // get the elements from the file + Element dataElement = (Element) boardElement.getElementsByTagName("data").item(0); + NodeList statementData = dataElement.getElementsByTagName("statement"); + NodeList cellData = dataElement.getElementsByTagName("cell"); + + // Parse the data + int maxStatementLength = + parseAllStatementsAndCells(statementData, allCells, statements); + + // generate the board + ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); + + // set the given cell values + setGivenCells(sttBoard, dataElement, cellData, statements); + + puzzle.setCurrentBoard(sttBoard); + + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "short truth table Importer: unknown value where integer expected"); + } } - // Store all cells and statements - List> allCells = new ArrayList<>(); - List statements = new ArrayList<>(); + /** + * Creates the board for building using statements + * + * @param statementInput + * @throws UnsupportedOperationException + * @throws IllegalArgumentException + */ + public void initializeBoard(String[] statementInput) + throws UnsupportedOperationException, IllegalArgumentException { + List statementsList = new LinkedList<>(); + for (String s : statementInput) { + if (s.strip().length() > 0) { + statementsList.add(s); + } + } + String[] statementData = statementsList.toArray(new String[statementsList.size()]); + + if (statementData.length == 0) { + throw new IllegalArgumentException( + "short truth table Importer: no statements found for board"); + } - // Parse the data - int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); + // Store all cells and statements + List> allCells = new ArrayList<>(); + List statements = new ArrayList<>(); - // Generate and set the board - don't set given cell values since none are given - ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); - puzzle.setCurrentBoard(sttBoard); - } + // Parse the data + int maxStatementLength = parseAllStatementsAndCells(statementData, allCells, statements); + + // Generate and set the board - don't set given cell values since none are given + ShortTruthTableBoard sttBoard = generateBoard(allCells, statements, maxStatementLength); + puzzle.setCurrentBoard(sttBoard); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java index 1a5fd3a12..8284474da 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableOperation.java @@ -2,47 +2,47 @@ public class ShortTruthTableOperation { - public static final char AND = '^'; - public static final char OR = '|'; - public static final char NOT = '~'; - public static final char CONDITIONAL = '>'; - public static final char BICONDITIONAL = '-'; + public static final char AND = '^'; + public static final char OR = '|'; + public static final char NOT = '~'; + public static final char CONDITIONAL = '>'; + public static final char BICONDITIONAL = '-'; - private ShortTruthTableOperation() {} + private ShortTruthTableOperation() {} - public static String getLogicSymbol(char c) { - switch (c) { - case AND: - return "\u2227"; - case OR: - return "\u2228"; - case NOT: - return "\u00AC"; - case CONDITIONAL: - return "\u2192"; - case BICONDITIONAL: - return "\u2194"; + public static String getLogicSymbol(char c) { + switch (c) { + case AND: + return "\u2227"; + case OR: + return "\u2228"; + case NOT: + return "\u00AC"; + case CONDITIONAL: + return "\u2192"; + case BICONDITIONAL: + return "\u2194"; + } + return "" + c; } - return "" + c; - } - public static String getRuleName(char operation) { - switch (operation) { - case AND: - return "And"; - case OR: - return "Or"; - case NOT: - return "Not"; - case CONDITIONAL: - return "Conditional"; - case BICONDITIONAL: - return "Biconditional"; + public static String getRuleName(char operation) { + switch (operation) { + case AND: + return "And"; + case OR: + return "Or"; + case NOT: + return "Not"; + case CONDITIONAL: + return "Conditional"; + case BICONDITIONAL: + return "Biconditional"; + } + return null; } - return null; - } - public static boolean isOperation(char c) { - return c == AND || c == OR || c == NOT || c == CONDITIONAL || c == BICONDITIONAL; - } + public static boolean isOperation(char c) { + return c == AND || c == OR || c == NOT || c == CONDITIONAL || c == BICONDITIONAL; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java index 2733b07ee..2059e3ca5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableStatement.java @@ -9,292 +9,292 @@ public class ShortTruthTableStatement extends PuzzleElement { - // the cell that this statement holds - private final ShortTruthTableCell cell; - - // child nodes of the tree - private final ShortTruthTableStatement parentStatement; - private final ShortTruthTableStatement leftStatement; - private final ShortTruthTableStatement rightStatement; - - // the representation string for this statement - private final String stringRep; - private final List cells; - - // constructor for root statement, sets parent to null - public ShortTruthTableStatement(String statement, List cells) { - this(statement, null, cells); - } - - // recursive constructor; constructs child statement nodes if necessary - private ShortTruthTableStatement( - String statement, ShortTruthTableStatement parent, List cells) { - - this.parentStatement = parent; - - // set the string rep to the statement (include parens in case this is a sub statement) - this.stringRep = statement; - this.cells = new ArrayList(cells); - - // remove the parens for parsing the statement - statement = removeParens(statement); - removeParens(cells); - - // get the index of the char that this statement represents - int index = parse(statement); - - // construct the cell for this node in the tree - cell = cells.get(index); - // give the cell a reference back to this statement - cell.setStatementReference(this); - - // get the strings on either side of this char in the string rep - String left = statement.substring(0, index); - String right = statement.substring(index + 1); - - List leftCells = - new ArrayList(cells.subList(0, index)); - List rightCells = - new ArrayList(cells.subList(index + 1, cells.size())); - - // construct sub-statements if necessary - if (left.length() > 0) { - leftStatement = new ShortTruthTableStatement(left, this, leftCells); - } else { - leftStatement = null; - } + // the cell that this statement holds + private final ShortTruthTableCell cell; - if (right.length() > 0) { - rightStatement = new ShortTruthTableStatement(right, this, rightCells); - } else { - rightStatement = null; - } - } + // child nodes of the tree + private final ShortTruthTableStatement parentStatement; + private final ShortTruthTableStatement leftStatement; + private final ShortTruthTableStatement rightStatement; - // parsing for the constructor - static String removeParens(String statement) { + // the representation string for this statement + private final String stringRep; + private final List cells; - if (statement.charAt(0) != '(') { - return statement; + // constructor for root statement, sets parent to null + public ShortTruthTableStatement(String statement, List cells) { + this(statement, null, cells); } - // if the statement does start with a paren, check that it matches with the last paren - int openParenCount = 1; - int i = 1; - while (i < statement.length() - 1) { - char c = statement.charAt(i); - if (c == '(') { - openParenCount++; - } else { - if (c == ')') openParenCount--; - } - - // if the first paren has been closed, and it is not the end of the string, - // then there is no whole statement parens to remove - if (openParenCount == 0 && i != statement.length() - 1) { - return statement; - } - - i++; - } - // if the while loop made it through the entire statement, there are parens around the whole - // thing - return statement.substring(1, statement.length() - 1); - } - - int parse(String statement) { - - // Split by and, or, CONDITIONAL, or biconditional - // keep track of the parens, it must be equal to zero to split - int openParenCount = 0; - // index for stepping through the string - int i = 0; - // step through each char in the statement - while (i < statement.length()) { - // get the char - char c = statement.charAt(i); - // keep track of the open parens - if (c == '(') { - openParenCount++; - } else { - if (c == ')') { - openParenCount--; + // recursive constructor; constructs child statement nodes if necessary + private ShortTruthTableStatement( + String statement, ShortTruthTableStatement parent, List cells) { + + this.parentStatement = parent; + + // set the string rep to the statement (include parens in case this is a sub statement) + this.stringRep = statement; + this.cells = new ArrayList(cells); + + // remove the parens for parsing the statement + statement = removeParens(statement); + removeParens(cells); + + // get the index of the char that this statement represents + int index = parse(statement); + + // construct the cell for this node in the tree + cell = cells.get(index); + // give the cell a reference back to this statement + cell.setStatementReference(this); + + // get the strings on either side of this char in the string rep + String left = statement.substring(0, index); + String right = statement.substring(index + 1); + + List leftCells = + new ArrayList(cells.subList(0, index)); + List rightCells = + new ArrayList(cells.subList(index + 1, cells.size())); + + // construct sub-statements if necessary + if (left.length() > 0) { + leftStatement = new ShortTruthTableStatement(left, this, leftCells); + } else { + leftStatement = null; } - // if the char is an operator, and there are no open parens, split the statement - // here - else { - if (openParenCount == 0 - && ShortTruthTableOperation.isOperation(c) - && c != ShortTruthTableOperation.NOT) { - return i; - } + + if (right.length() > 0) { + rightStatement = new ShortTruthTableStatement(right, this, rightCells); + } else { + rightStatement = null; } - } - // increment the index - i++; } - // if it made it through the while loop: - // this is an atomic statement or a negation - // either way, the important char is the first character in the string - return 0; - } + // parsing for the constructor + static String removeParens(String statement) { - static void removeParens(List cells) { + if (statement.charAt(0) != '(') { + return statement; + } - if (cells.get(0).getSymbol() != '(') { - return; + // if the statement does start with a paren, check that it matches with the last paren + int openParenCount = 1; + int i = 1; + while (i < statement.length() - 1) { + char c = statement.charAt(i); + if (c == '(') { + openParenCount++; + } else { + if (c == ')') openParenCount--; + } + + // if the first paren has been closed, and it is not the end of the string, + // then there is no whole statement parens to remove + if (openParenCount == 0 && i != statement.length() - 1) { + return statement; + } + + i++; + } + // if the while loop made it through the entire statement, there are parens around the whole + // thing + return statement.substring(1, statement.length() - 1); } - // if the statement does start with a paren, check that it matches with the last paren - int openParenCount = 1; - int i = 1; - while (i < cells.size() - 1) { - char c = cells.get(i).getSymbol(); - if (c == '(') { - openParenCount++; - } else { - if (c == ')') openParenCount--; - } - - // if the first paren has been closed, and it is not the end of the string, - // then there is no whole statement parens to remove - if (openParenCount == 0 && i != cells.size() - 1) { - return; - } - - i++; + int parse(String statement) { + + // Split by and, or, CONDITIONAL, or biconditional + // keep track of the parens, it must be equal to zero to split + int openParenCount = 0; + // index for stepping through the string + int i = 0; + // step through each char in the statement + while (i < statement.length()) { + // get the char + char c = statement.charAt(i); + // keep track of the open parens + if (c == '(') { + openParenCount++; + } else { + if (c == ')') { + openParenCount--; + } + // if the char is an operator, and there are no open parens, split the statement + // here + else { + if (openParenCount == 0 + && ShortTruthTableOperation.isOperation(c) + && c != ShortTruthTableOperation.NOT) { + return i; + } + } + } + // increment the index + i++; + } + + // if it made it through the while loop: + // this is an atomic statement or a negation + // either way, the important char is the first character in the string + return 0; + } + + static void removeParens(List cells) { + + if (cells.get(0).getSymbol() != '(') { + return; + } + + // if the statement does start with a paren, check that it matches with the last paren + int openParenCount = 1; + int i = 1; + while (i < cells.size() - 1) { + char c = cells.get(i).getSymbol(); + if (c == '(') { + openParenCount++; + } else { + if (c == ')') openParenCount--; + } + + // if the first paren has been closed, and it is not the end of the string, + // then there is no whole statement parens to remove + if (openParenCount == 0 && i != cells.size() - 1) { + return; + } + + i++; + } + + // if the while loop made it through the entire statement, there are parens around the whole + // thing + cells.remove(cells.size() - 1); + cells.remove(0); } - // if the while loop made it through the entire statement, there are parens around the whole - // thing - cells.remove(cells.size() - 1); - cells.remove(0); - } + // Getters - // Getters + public ShortTruthTableCell getCell() { + return cell; + } - public ShortTruthTableCell getCell() { - return cell; - } + public ShortTruthTableStatement getLeftStatement() { + return leftStatement; + } - public ShortTruthTableStatement getLeftStatement() { - return leftStatement; - } + public ShortTruthTableStatement getRightStatement() { + return rightStatement; + } - public ShortTruthTableStatement getRightStatement() { - return rightStatement; - } + public ShortTruthTableStatement getParentStatement() { + return parentStatement; + } - public ShortTruthTableStatement getParentStatement() { - return parentStatement; - } + @Override + public String toString() { + if (this.parentStatement == null) { + return "SST_Statement: " + stringRep + " parent: null"; + } + return "SST_Statement: " + stringRep + " parent: " + parentStatement.stringRep; + } - @Override - public String toString() { - if (this.parentStatement == null) { - return "SST_Statement: " + stringRep + " parent: null"; + public String getStringRep() { + return this.stringRep; } - return "SST_Statement: " + stringRep + " parent: " + parentStatement.stringRep; - } - - public String getStringRep() { - return this.stringRep; - } - - /** - * Returns the length of the statement in cells. This includes all cells used for parenthesis - * - * @return the number of cells contained in this statement - */ - public int getLength() { - return stringRep.length(); - } - - public ShortTruthTableCell getCell(int i) { - return cells.get(i); - } - - // Getters (recursive) - - // returns all cells in this statement with the symbol 'symbol'; runs recursively on both sides - // of - // the tree - public Set getCellsWithSymbol(char symbol) { - Set set = new HashSet(getLength()); - if (cell.getSymbol() == symbol) set.add(cell); - if (leftStatement != null) set.addAll(leftStatement.getCellsWithSymbol(symbol)); - if (rightStatement != null) set.addAll(rightStatement.getCellsWithSymbol(symbol)); - return set; - } - - /** - * Returns an array of three elements where [0] is the left statement type, [1] is this statement - * type, and [2] is the right statement type. null means either the statement doesn't exist or is - * an unknown value. - * - * @return the assigned values to this statement and its sub-statements - */ - public ShortTruthTableCellType[] getCellTypePattern() { - // get this type and the right type, they will always be used - ShortTruthTableCellType type = this.cell.getType(); - System.out.println("Right statement: " + rightStatement.getCell()); - ShortTruthTableCellType rightType = this.rightStatement.getCell().getType(); - System.out.println("Right type: " + rightType); - // if this is a not statement, there is no left side - if (cell.getSymbol() == ShortTruthTableOperation.NOT) { - return new ShortTruthTableCellType[] {null, type, rightType}; + + /** + * Returns the length of the statement in cells. This includes all cells used for parenthesis + * + * @return the number of cells contained in this statement + */ + public int getLength() { + return stringRep.length(); } - // if it is any other operation, get the left side too and return it - ShortTruthTableCellType leftType = this.leftStatement.getCell().getType(); - return new ShortTruthTableCellType[] {leftType, type, rightType}; - } - - // Setters - - private void setCellLocations(int rowIndex, int offset) { - // set the location of this cell - int xLoc = offset; - if (leftStatement != null) { - xLoc += leftStatement.getLength(); + + public ShortTruthTableCell getCell(int i) { + return cells.get(i); + } + + // Getters (recursive) + + // returns all cells in this statement with the symbol 'symbol'; runs recursively on both sides + // of + // the tree + public Set getCellsWithSymbol(char symbol) { + Set set = new HashSet(getLength()); + if (cell.getSymbol() == symbol) set.add(cell); + if (leftStatement != null) set.addAll(leftStatement.getCellsWithSymbol(symbol)); + if (rightStatement != null) set.addAll(rightStatement.getCellsWithSymbol(symbol)); + return set; } - cell.setLocation(new Point(xLoc, rowIndex)); - // recurse on both sides of the tree - if (leftStatement != null) { - leftStatement.setCellLocations(rowIndex, offset); + + /** + * Returns an array of three elements where [0] is the left statement type, [1] is this + * statement type, and [2] is the right statement type. null means either the statement doesn't + * exist or is an unknown value. + * + * @return the assigned values to this statement and its sub-statements + */ + public ShortTruthTableCellType[] getCellTypePattern() { + // get this type and the right type, they will always be used + ShortTruthTableCellType type = this.cell.getType(); + System.out.println("Right statement: " + rightStatement.getCell()); + ShortTruthTableCellType rightType = this.rightStatement.getCell().getType(); + System.out.println("Right type: " + rightType); + // if this is a not statement, there is no left side + if (cell.getSymbol() == ShortTruthTableOperation.NOT) { + return new ShortTruthTableCellType[] {null, type, rightType}; + } + // if it is any other operation, get the left side too and return it + ShortTruthTableCellType leftType = this.leftStatement.getCell().getType(); + return new ShortTruthTableCellType[] {leftType, type, rightType}; } - if (rightStatement != null) { - rightStatement.setCellLocations(rowIndex, xLoc + 1); + + // Setters + + private void setCellLocations(int rowIndex, int offset) { + // set the location of this cell + int xLoc = offset; + if (leftStatement != null) { + xLoc += leftStatement.getLength(); + } + cell.setLocation(new Point(xLoc, rowIndex)); + // recurse on both sides of the tree + if (leftStatement != null) { + leftStatement.setCellLocations(rowIndex, offset); + } + if (rightStatement != null) { + rightStatement.setCellLocations(rowIndex, xLoc + 1); + } } - } - public void setCellLocations(int rowIndex) { - setCellLocations(rowIndex, 0); - } + public void setCellLocations(int rowIndex) { + setCellLocations(rowIndex, 0); + } - public ShortTruthTableStatement copy() { - // copy all the cells - List cellsCopy = new ArrayList<>(); - for (ShortTruthTableCell c : cells) { - cellsCopy.add(c.copy()); + public ShortTruthTableStatement copy() { + // copy all the cells + List cellsCopy = new ArrayList<>(); + for (ShortTruthTableCell c : cells) { + cellsCopy.add(c.copy()); + } + // make a copy of the statement with all the copied cells + // return the new statement + return new ShortTruthTableStatement(stringRep, cellsCopy); } - // make a copy of the statement with all the copied cells - // return the new statement - return new ShortTruthTableStatement(stringRep, cellsCopy); - } - - public ShortTruthTableStatement replace(int column, ShortTruthTableCell cell) { - // copy all the cells (replacing one) - List cellsCopy = new ArrayList<>(); - for (ShortTruthTableCell c : cells) { - if (c.getX() == column) { - cellsCopy.add(cell); - } else { - cellsCopy.add(c); - } + + public ShortTruthTableStatement replace(int column, ShortTruthTableCell cell) { + // copy all the cells (replacing one) + List cellsCopy = new ArrayList<>(); + for (ShortTruthTableCell c : cells) { + if (c.getX() == column) { + cellsCopy.add(cell); + } else { + cellsCopy.add(c); + } + } + // make a copy of the statement with all the copied cells + // return the new statement + return new ShortTruthTableStatement(stringRep, cellsCopy); } - // make a copy of the statement with all the copied cells - // return the new statement - return new ShortTruthTableStatement(stringRep, cellsCopy); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java index e15f5b928..15becf443 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/ShortTruthTableView.java @@ -7,18 +7,19 @@ public class ShortTruthTableView extends GridBoardView { - public ShortTruthTableView(ShortTruthTableBoard board) { - super(new BoardController(), new ShortTruthTableController(), board.getDimension()); + public ShortTruthTableView(ShortTruthTableBoard board) { + super(new BoardController(), new ShortTruthTableController(), board.getDimension()); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; - // System.out.println("STTView :"+cell); - Point loc = cell.getLocation(); - ShortTruthTableElementView elementView = new ShortTruthTableElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation(new Point(loc.x * elementSize.width, loc.y * elementSize.height)); - elementViews.add(elementView); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + ShortTruthTableCell cell = (ShortTruthTableCell) puzzleElement; + // System.out.println("STTView :"+cell); + Point loc = cell.getLocation(); + ShortTruthTableElementView elementView = new ShortTruthTableElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point(loc.x * elementSize.width, loc.y * elementSize.height)); + elementViews.add(elementView); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java index ed53dc3bf..9294fba4e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/ArgumentElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class ArgumentElement extends NonPlaceableElement { - public ArgumentElement() { - super( - "STTT-UNPL-0001", - "Argument Element", - "Argument of logic statement element", - "edu/rpi/legup/images/shorttruthtable/tiles/LetterTile.png"); - } + public ArgumentElement() { + super( + "STTT-UNPL-0001", + "Argument Element", + "Argument of logic statement element", + "edu/rpi/legup/images/shorttruthtable/tiles/LetterTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java index eb6b9996c..783186baa 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/GreenElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class GreenElement extends PlaceableElement { - public GreenElement() { - super( - "STTT-PLAC-0001", - "Green Element", - "A green tile to set certain tiles to true", - "edu/rpi/legup/images/shorttruthtable/tiles/GreenTile.png"); - } + public GreenElement() { + super( + "STTT-PLAC-0001", + "Green Element", + "A green tile to set certain tiles to true", + "edu/rpi/legup/images/shorttruthtable/tiles/GreenTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java index 8336e0a41..5fed4b1df 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/LogicSymbolElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class LogicSymbolElement extends NonPlaceableElement { - public LogicSymbolElement() { - super( - "STTT-UNPL-0002", - "Logic Symbol Element", - "Logic symbol element", - "edu/rpi/legup/images/shorttruthtable/tiles/ConditionalBiconditionalTile.png"); - } + public LogicSymbolElement() { + super( + "STTT-UNPL-0002", + "Logic Symbol Element", + "Logic symbol element", + "edu/rpi/legup/images/shorttruthtable/tiles/ConditionalBiconditionalTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java index c9e0472ae..e2a589b65 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/RedElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class RedElement extends PlaceableElement { - public RedElement() { - super( - "STTT-PLAC-0002", - "Red Element", - "A red tile to set certain tiles to false", - "edu/rpi/legup/images/shorttruthtable/tiles/RedTile.png"); - } + public RedElement() { + super( + "STTT-PLAC-0002", + "Red Element", + "A red tile to set certain tiles to false", + "edu/rpi/legup/images/shorttruthtable/tiles/RedTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java index 87feed9ed..d475bc05d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/elements/UnknownElement.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class UnknownElement extends PlaceableElement { - public UnknownElement() { - super( - "STTT-PLAC-0003", - "Unknown Element", - "A blank tile", - "edu/rpi/legup/images/shorttruthtable/tiles/UnknownTile.png"); - } + public UnknownElement() { + super( + "STTT-PLAC-0003", + "Unknown Element", + "A blank tile", + "edu/rpi/legup/images/shorttruthtable/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java index f8421da08..38048b5b0 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRuleAtomic.java @@ -4,13 +4,13 @@ public class DirectRuleAtomic extends DirectRule_Generic { - public DirectRuleAtomic() { - super( - "STTT-BASC-0001", - "Atomic Rule", - "All identical atoms have the same T/F value", - "Atomic", - new ContradictionRuleAtomic(), - false); - } + public DirectRuleAtomic() { + super( + "STTT-BASC-0001", + "Atomic Rule", + "All identical atoms have the same T/F value", + "Atomic", + new ContradictionRuleAtomic(), + false); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java index 84b49d135..470ba7c29 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/DirectRule_Generic.java @@ -11,79 +11,82 @@ public abstract class DirectRule_Generic extends DirectRule { - final ContradictionRule CORRESPONDING_CONTRADICTION_RULE; - final boolean ELIMINATION_RULE; + final ContradictionRule CORRESPONDING_CONTRADICTION_RULE; + final boolean ELIMINATION_RULE; - public DirectRule_Generic( - String ruleID, - String ruleName, - String description, - String imageName, - ContradictionRule contraRule, - boolean eliminationRule) { - super( - ruleID, - ruleName, - description, - "edu/rpi/legup/images/shorttruthtable/ruleimages/basic/" + imageName + ".png"); - this.CORRESPONDING_CONTRADICTION_RULE = contraRule; - this.ELIMINATION_RULE = eliminationRule; - } + public DirectRule_Generic( + String ruleID, + String ruleName, + String description, + String imageName, + ContradictionRule contraRule, + boolean eliminationRule) { + super( + ruleID, + ruleName, + description, + "edu/rpi/legup/images/shorttruthtable/ruleimages/basic/" + imageName + ".png"); + this.CORRESPONDING_CONTRADICTION_RULE = contraRule; + this.ELIMINATION_RULE = eliminationRule; + } - public String checkRuleRawAt(TreeTransition transition, PuzzleElement element) { - // Rule must have cell to evaluate on - if (element == null) return super.getInvalidUseOfRuleMessage() + ": Must have painted cell"; + public String checkRuleRawAt(TreeTransition transition, PuzzleElement element) { + // Rule must have cell to evaluate on + if (element == null) return super.getInvalidUseOfRuleMessage() + ": Must have painted cell"; - // Check that the puzzle element is not unknown - ShortTruthTableBoard parentBoard = - (ShortTruthTableBoard) transition.getParents().get(0).getBoard(); - ShortTruthTableBoard finalBoard = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell parentCell = (ShortTruthTableCell) parentBoard.getPuzzleElement(element); - ShortTruthTableCell finalCell = (ShortTruthTableCell) finalBoard.getPuzzleElement(element); + // Check that the puzzle element is not unknown + ShortTruthTableBoard parentBoard = + (ShortTruthTableBoard) transition.getParents().get(0).getBoard(); + ShortTruthTableBoard finalBoard = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell parentCell = + (ShortTruthTableCell) parentBoard.getPuzzleElement(element); + ShortTruthTableCell finalCell = (ShortTruthTableCell) finalBoard.getPuzzleElement(element); - if (!finalCell.isAssigned()) { - return super.getInvalidUseOfRuleMessage() - + ": Only assigned cells are allowed for basic rules"; - } + if (!finalCell.isAssigned()) { + return super.getInvalidUseOfRuleMessage() + + ": Only assigned cells are allowed for basic rules"; + } - // Strategy: Negate the modified cell and check if there is a contradiction. If there is - // one, - // then the - // original statement must be true. If there isn't one, then the original statement must be - // false. + // Strategy: Negate the modified cell and check if there is a contradiction. If there is + // one, + // then the + // original statement must be true. If there isn't one, then the original statement must be + // false. - ShortTruthTableBoard modifiedBoard = parentBoard.copy(); + ShortTruthTableBoard modifiedBoard = parentBoard.copy(); - PuzzleElement checkElement = - this.ELIMINATION_RULE - ? parentCell.getStatementReference().getParentStatement().getCell() - : element; + PuzzleElement checkElement = + this.ELIMINATION_RULE + ? parentCell.getStatementReference().getParentStatement().getCell() + : element; - ShortTruthTableCell checkCell = - this.ELIMINATION_RULE - ? (ShortTruthTableCell) modifiedBoard.getCell(parentCell.getX(), parentCell.getY()) - : (ShortTruthTableCell) modifiedBoard.getPuzzleElement(element); + ShortTruthTableCell checkCell = + this.ELIMINATION_RULE + ? (ShortTruthTableCell) + modifiedBoard.getCell(parentCell.getX(), parentCell.getY()) + : (ShortTruthTableCell) modifiedBoard.getPuzzleElement(element); - checkCell.setType(finalCell.getType().getNegation()); + checkCell.setType(finalCell.getType().getNegation()); - String contradictionMessage = - CORRESPONDING_CONTRADICTION_RULE.checkContradictionAt(modifiedBoard, checkElement); - if (contradictionMessage - == null) { // A contradiction exists in the modified statement; this is good! - return null; - } + String contradictionMessage = + CORRESPONDING_CONTRADICTION_RULE.checkContradictionAt(modifiedBoard, checkElement); + if (contradictionMessage + == null) { // A contradiction exists in the modified statement; this is good! + return null; + } - return super.getInvalidUseOfRuleMessage(); - } + return super.getInvalidUseOfRuleMessage(); + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node short truth table board used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node short truth table board used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java index b6e88fa65..6f48784a3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleAndElimination.java @@ -4,7 +4,7 @@ public class DirectRuleAndElimination extends DirectRule_GenericElimination { - public DirectRuleAndElimination() { - super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); - } + public DirectRuleAndElimination() { + super("STTT-BASC-0002", "And", new ContradictionRuleAnd()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java index 8c12882a7..168877ca6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleBiconditionalElimination.java @@ -4,7 +4,7 @@ public class DirectRuleBiconditionalElimination extends DirectRule_GenericElimination { - public DirectRuleBiconditionalElimination() { - super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); - } + public DirectRuleBiconditionalElimination() { + super("STTT-BASC-0003", "Biconditional", new ContradictionRuleBiconditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java index a316b4566..4a287b195 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleConditionalElimination.java @@ -4,7 +4,7 @@ public class DirectRuleConditionalElimination extends DirectRule_GenericElimination { - public DirectRuleConditionalElimination() { - super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); - } + public DirectRuleConditionalElimination() { + super("STTT-BASC-0004", "Conditional", new ContradictionRuleConditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java index f15a4d2b2..5acff5837 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleNotElimination.java @@ -4,7 +4,7 @@ public class DirectRuleNotElimination extends DirectRule_GenericElimination { - public DirectRuleNotElimination() { - super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); - } + public DirectRuleNotElimination() { + super("STTT-BASC-0005", "Not", new ContradictionRuleNot()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java index 77d507764..fba43762a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRuleOrElimination.java @@ -4,7 +4,7 @@ public class DirectRuleOrElimination extends DirectRule_GenericElimination { - public DirectRuleOrElimination() { - super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); - } + public DirectRuleOrElimination() { + super("STTT-BASC-0006", "Or", new ContradictionRuleOr()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java index b741f47b9..1f85e5b79 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/elimination/DirectRule_GenericElimination.java @@ -5,15 +5,15 @@ public abstract class DirectRule_GenericElimination extends DirectRule_Generic { - public DirectRule_GenericElimination( - String ruleID, String ruleName, ContradictionRule contradictionRule) { + public DirectRule_GenericElimination( + String ruleID, String ruleName, ContradictionRule contradictionRule) { - super( - ruleID, - ruleName + " Elimination", - ruleName + " statements must have a valid pattern", - "elimination/" + ruleName, - contradictionRule, - true); - } + super( + ruleID, + ruleName + " Elimination", + ruleName + " statements must have a valid pattern", + "elimination/" + ruleName, + contradictionRule, + true); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java index 838f28e4c..667b97a0f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleAndIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleAndIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleAndIntroduction() { - super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); - } + public DirectRuleAndIntroduction() { + super("STTT-BASC-0007", "And", new ContradictionRuleAnd()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java index 5e332c355..c2dfeebba 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleBiconditionalIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleBiconditionalIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleBiconditionalIntroduction() { - super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); - } + public DirectRuleBiconditionalIntroduction() { + super("STTT-BASC-0008", "Biconditional", new ContradictionRuleBiconditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java index 7b3843fde..728d7f244 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleConditionalIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleConditionalIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleConditionalIntroduction() { - super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); - } + public DirectRuleConditionalIntroduction() { + super("STTT-BASC-0009", "Conditional", new ContradictionRuleConditional()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java index be6926915..80b963a56 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleNotIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleNotIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleNotIntroduction() { - super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); - } + public DirectRuleNotIntroduction() { + super("STTT-BASC-0010", "Not", new ContradictionRuleNot()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java index 887b1bff0..66a569655 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRuleOrIntroduction.java @@ -4,7 +4,7 @@ public class DirectRuleOrIntroduction extends DirectRule_GenericIntroduction { - public DirectRuleOrIntroduction() { - super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); - } + public DirectRuleOrIntroduction() { + super("STTT-BASC-0011", "Or", new ContradictionRuleOr()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java index 5b6803dc2..8469ff0b9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/basic/introduction/DirectRule_GenericIntroduction.java @@ -5,15 +5,15 @@ public abstract class DirectRule_GenericIntroduction extends DirectRule_Generic { - protected DirectRule_GenericIntroduction( - String ruleID, String ruleName, ContradictionRule contradictionRule) { + protected DirectRule_GenericIntroduction( + String ruleID, String ruleName, ContradictionRule contradictionRule) { - super( - ruleID, - ruleName + " Introduction", - ruleName + " statements must have a valid pattern", - "introduction/" + ruleName, - contradictionRule, - false); - } + super( + ruleID, + ruleName + " Introduction", + ruleName + " statements must have a valid pattern", + "introduction/" + ruleName, + contradictionRule, + false); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java index 60c9ab49e..9b589f14e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAnd.java @@ -5,13 +5,13 @@ public class CaseRuleAnd extends CaseRule_GenericStatement { - public CaseRuleAnd() { - super("STTT-CASE-0001", ShortTruthTableOperation.AND, "And", trueCases, falseCases); - } + public CaseRuleAnd() { + super("STTT-CASE-0001", ShortTruthTableOperation.AND, "And", trueCases, falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = {{T, T}}; - private static final ShortTruthTableCellType[][] falseCases = { - {F, U}, - {U, F} - }; + private static final ShortTruthTableCellType[][] trueCases = {{T, T}}; + private static final ShortTruthTableCellType[][] falseCases = { + {F, U}, + {U, F} + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java index 46975b7df..58d2068b2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleAtomic.java @@ -11,57 +11,57 @@ public class CaseRuleAtomic extends CaseRule_Generic { - public CaseRuleAtomic() { - super( - "STTT-CASE-0002", - "Atomic", - "True or False", - "Each unknown cell must either be true or false"); - } + public CaseRuleAtomic() { + super( + "STTT-CASE-0002", + "Atomic", + "True or False", + "Each unknown cell must either be true or false"); + } - // Adds all elements that can be selected for this case rule - @Override - public CaseBoard getCaseBoard(Board board) { - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); - sttBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(sttBoard, this); - for (PuzzleElement element : sttBoard.getPuzzleElements()) { - if (((ShortTruthTableCell) element).getType() == ShortTruthTableCellType.UNKNOWN) { - caseBoard.addPickableElement(element); - } + // Adds all elements that can be selected for this case rule + @Override + public CaseBoard getCaseBoard(Board board) { + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); + sttBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(sttBoard, this); + for (PuzzleElement element : sttBoard.getPuzzleElements()) { + if (((ShortTruthTableCell) element).getType() == ShortTruthTableCellType.UNKNOWN) { + caseBoard.addPickableElement(element); + } + } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(ShortTruthTableCellType.TRUE); - case1.addModifiedData(data1); - cases.add(case1); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(ShortTruthTableCellType.TRUE); + case1.addModifiedData(data1); + cases.add(case1); - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(ShortTruthTableCellType.FALSE); - case2.addModifiedData(data2); - cases.add(case2); + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(ShortTruthTableCellType.FALSE); + case2.addModifiedData(data2); + cases.add(case2); - return cases; - } + return cases; + } - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java index 52058a6f5..1bb5f0332 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleBiconditional.java @@ -5,21 +5,21 @@ public class CaseRuleBiconditional extends CaseRule_GenericStatement { - public CaseRuleBiconditional() { - super( - "STTT-CASE-0003", - ShortTruthTableOperation.BICONDITIONAL, - "Biconditional", - trueCases, - falseCases); - } + public CaseRuleBiconditional() { + super( + "STTT-CASE-0003", + ShortTruthTableOperation.BICONDITIONAL, + "Biconditional", + trueCases, + falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {T, T}, - {F, F} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - {F, T} - }; + private static final ShortTruthTableCellType[][] trueCases = { + {T, T}, + {F, F} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + {F, T} + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java index ea1f78408..397341f0e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleConditional.java @@ -5,20 +5,20 @@ public class CaseRuleConditional extends CaseRule_GenericStatement { - public CaseRuleConditional() { - super( - "STTT-CASE-0004", - ShortTruthTableOperation.CONDITIONAL, - "Conditional", - trueCases, - falseCases); - } + public CaseRuleConditional() { + super( + "STTT-CASE-0004", + ShortTruthTableOperation.CONDITIONAL, + "Conditional", + trueCases, + falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {U, T}, - {F, U} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {T, F}, - }; + private static final ShortTruthTableCellType[][] trueCases = { + {U, T}, + {F, U} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {T, F}, + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java index a9b2abb65..36f4e6f87 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRuleOr.java @@ -5,15 +5,15 @@ public class CaseRuleOr extends CaseRule_GenericStatement { - public CaseRuleOr() { - super("STTT-CASE-0005", ShortTruthTableOperation.OR, "Or", trueCases, falseCases); - } + public CaseRuleOr() { + super("STTT-CASE-0005", ShortTruthTableOperation.OR, "Or", trueCases, falseCases); + } - private static final ShortTruthTableCellType[][] trueCases = { - {T, U}, - {U, T} - }; - private static final ShortTruthTableCellType[][] falseCases = { - {F, F}, - }; + private static final ShortTruthTableCellType[][] trueCases = { + {T, U}, + {U, T} + }; + private static final ShortTruthTableCellType[][] falseCases = { + {F, F}, + }; } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java index 09eca7d8e..5885f98f8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_Generic.java @@ -7,57 +7,57 @@ public abstract class CaseRule_Generic extends CaseRule { - public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { - super( - ruleID, - title, - description, - "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - // Validate that two children are generated - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "ERROR: This case rule must spawn at least 1 child."; + public CaseRule_Generic(String ruleID, String ruleName, String title, String description) { + super( + ruleID, + title, + description, + "edu/rpi/legup/images/shorttruthtable/ruleimages/case/" + ruleName + ".png"); } - // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE - // List cases = Arrays.asList(childTransitions.get(0), - // childTransitions.get(1)); - // for (TreeTransition c : cases) { - // ShortTruthTableCell mod1 = - // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // ShortTruthTableCell mod2 = - // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); - // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == - // ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && - // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == - // ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { - // return "ERROR: This case rule must be an unknown, true, or false cell."; - // } - // } - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + // Validate that two children are generated + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "ERROR: This case rule must spawn at least 1 child."; + } + + // // Validate that the modified cells are of type UNKNOWN, TRUE, or FALSE + // List cases = Arrays.asList(childTransitions.get(0), + // childTransitions.get(1)); + // for (TreeTransition c : cases) { + // ShortTruthTableCell mod1 = + // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // ShortTruthTableCell mod2 = + // (ShortTruthTableCell)c.getBoard().getModifiedData().iterator().next(); + // if (!(mod1.getType() == ShortTruthTableCellType.TRUE || mod1.getType() == + // ShortTruthTableCellType.FALSE || mod1.getType() == ShortTruthTableCellType.UNKNOWN) && + // (mod2.getType() == ShortTruthTableCellType.TRUE || mod2.getType() == + // ShortTruthTableCellType.FALSE || mod2.getType() == ShortTruthTableCellType.UNKNOWN)) { + // return "ERROR: This case rule must be an unknown, true, or false cell."; + // } + // } + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java index 68dd33b16..99f771246 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/caserule/CaseRule_GenericStatement.java @@ -13,133 +13,140 @@ public abstract class CaseRule_GenericStatement extends CaseRule_Generic { - public CaseRule_GenericStatement( - String ruleID, - char operation, - String title, - ShortTruthTableCellType[][] trueCases, - ShortTruthTableCellType[][] falseCases) { - super( - ruleID, - ShortTruthTableOperation.getRuleName(operation), - title + " case", - "A known " + title.toUpperCase() + " statement can have multiple forms"); - - this.operation = operation; - - this.trueCases = trueCases; - this.falseCases = falseCases; - } - - private final char operation; - - private final ShortTruthTableCellType[][] trueCases; - private final ShortTruthTableCellType[][] falseCases; - - protected static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; - protected static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; - protected static final ShortTruthTableCellType U = ShortTruthTableCellType.UNKNOWN; - - // Adds all elements that can be selected for this caserule - @Override - public CaseBoard getCaseBoard(Board board) { - // copy the board and add all elements that can be selected - ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); - sttBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(sttBoard, this); - - // add all elements that can be selected for the case rule statement - for (PuzzleElement element : sttBoard.getPuzzleElements()) { - // get the cell object - ShortTruthTableCell cell = sttBoard.getCellFromElement(element); - // the cell must match the symbol - if (cell.getSymbol() != this.operation) continue; - // the statement must be assigned with unassigned sub-statements - if (!cell.getType().isTrueOrFalse()) continue; - if (cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) - continue; - if (this.operation != ShortTruthTableOperation.NOT - && cell.getStatementReference().getRightStatement().getCell().getType().isTrueOrFalse()) { - continue; - } - // if the element has passed all the checks, it can be selected - caseBoard.addPickableElement(element); + public CaseRule_GenericStatement( + String ruleID, + char operation, + String title, + ShortTruthTableCellType[][] trueCases, + ShortTruthTableCellType[][] falseCases) { + super( + ruleID, + ShortTruthTableOperation.getRuleName(operation), + title + " case", + "A known " + title.toUpperCase() + " statement can have multiple forms"); + + this.operation = operation; + + this.trueCases = trueCases; + this.falseCases = falseCases; } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ShortTruthTableBoard sttBoard = ((ShortTruthTableBoard) board); - ShortTruthTableCell cell = sttBoard.getCellFromElement(puzzleElement); - - // If the statement is set to true, collect true cases. Otherwise, collect the false cases - if (cell.getType() == ShortTruthTableCellType.TRUE) { - return getCasesFromCell(sttBoard, puzzleElement, trueCases); + + private final char operation; + + private final ShortTruthTableCellType[][] trueCases; + private final ShortTruthTableCellType[][] falseCases; + + protected static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; + protected static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; + protected static final ShortTruthTableCellType U = ShortTruthTableCellType.UNKNOWN; + + // Adds all elements that can be selected for this caserule + @Override + public CaseBoard getCaseBoard(Board board) { + // copy the board and add all elements that can be selected + ShortTruthTableBoard sttBoard = (ShortTruthTableBoard) board.copy(); + sttBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(sttBoard, this); + + // add all elements that can be selected for the case rule statement + for (PuzzleElement element : sttBoard.getPuzzleElements()) { + // get the cell object + ShortTruthTableCell cell = sttBoard.getCellFromElement(element); + // the cell must match the symbol + if (cell.getSymbol() != this.operation) continue; + // the statement must be assigned with unassigned sub-statements + if (!cell.getType().isTrueOrFalse()) continue; + if (cell.getStatementReference() + .getRightStatement() + .getCell() + .getType() + .isTrueOrFalse()) continue; + if (this.operation != ShortTruthTableOperation.NOT + && cell.getStatementReference() + .getRightStatement() + .getCell() + .getType() + .isTrueOrFalse()) { + continue; + } + // if the element has passed all the checks, it can be selected + caseBoard.addPickableElement(element); + } + return caseBoard; + } + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ShortTruthTableBoard sttBoard = ((ShortTruthTableBoard) board); + ShortTruthTableCell cell = sttBoard.getCellFromElement(puzzleElement); + + // If the statement is set to true, collect true cases. Otherwise, collect the false cases + if (cell.getType() == ShortTruthTableCellType.TRUE) { + return getCasesFromCell(sttBoard, puzzleElement, trueCases); + } + return getCasesFromCell(sttBoard, puzzleElement, falseCases); } - return getCasesFromCell(sttBoard, puzzleElement, falseCases); - } - - /** - * Collects a list of boards for each possible outcome of case-rule application - * - * @param board current board state - * @param puzzleElement case rule operator - * @param possibilities list of possibilities for operator state - * @return ArrayList of Boards - */ - private ArrayList getCasesFromCell( - ShortTruthTableBoard board, - PuzzleElement puzzleElement, - ShortTruthTableCellType[][] possibilities) { - // Create branch case for each possibility - ArrayList cases = new ArrayList<>(); - for (int i = 0; i < possibilities.length; i++) { - // Create a new board to modify and get statement of selected square - ShortTruthTableBoard b = board.copy(); - ShortTruthTableCell cell = b.getCellFromElement(puzzleElement); - ShortTruthTableStatement statement = cell.getStatementReference(); - - // Modify neighboring cells of case-rule application by the provided logical cases - if (possibilities[i][0] != ShortTruthTableCellType.UNKNOWN) { - ShortTruthTableCell leftCell = statement.getLeftStatement().getCell(); - leftCell.setData(possibilities[i][0]); - b.addModifiedData(leftCell); - } - if (possibilities[i][1] != ShortTruthTableCellType.UNKNOWN) { - ShortTruthTableCell rightCell = statement.getRightStatement().getCell(); - rightCell.setData(possibilities[i][1]); - b.addModifiedData(rightCell); - } - - cases.add(b); + + /** + * Collects a list of boards for each possible outcome of case-rule application + * + * @param board current board state + * @param puzzleElement case rule operator + * @param possibilities list of possibilities for operator state + * @return ArrayList of Boards + */ + private ArrayList getCasesFromCell( + ShortTruthTableBoard board, + PuzzleElement puzzleElement, + ShortTruthTableCellType[][] possibilities) { + // Create branch case for each possibility + ArrayList cases = new ArrayList<>(); + for (int i = 0; i < possibilities.length; i++) { + // Create a new board to modify and get statement of selected square + ShortTruthTableBoard b = board.copy(); + ShortTruthTableCell cell = b.getCellFromElement(puzzleElement); + ShortTruthTableStatement statement = cell.getStatementReference(); + + // Modify neighboring cells of case-rule application by the provided logical cases + if (possibilities[i][0] != ShortTruthTableCellType.UNKNOWN) { + ShortTruthTableCell leftCell = statement.getLeftStatement().getCell(); + leftCell.setData(possibilities[i][0]); + b.addModifiedData(leftCell); + } + if (possibilities[i][1] != ShortTruthTableCellType.UNKNOWN) { + ShortTruthTableCell rightCell = statement.getRightStatement().getCell(); + rightCell.setData(possibilities[i][1]); + b.addModifiedData(rightCell); + } + + cases.add(b); + } + return cases; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = super.dependentElements(board, puzzleElement); + + elements.add(board.getPuzzleElement(puzzleElement)); + + return elements; } - return cases; - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = super.dependentElements(board, puzzleElement); - - elements.add(board.getPuzzleElement(puzzleElement)); - - return elements; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java index 0549b5f99..595dd0cb2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAnd.java @@ -5,18 +5,18 @@ public class ContradictionRuleAnd extends ContradictionRule_GenericStatement { - public ContradictionRuleAnd() { - super( - "STTT-CONT-0001", - "Contradicting And", - "An AND statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/And.png", - ShortTruthTableOperation.AND, - new ShortTruthTableCellType[][] { - {n, T, F}, - {F, T, n}, - // {F, T, F}, - {T, F, T}, - }); - } + public ContradictionRuleAnd() { + super( + "STTT-CONT-0001", + "Contradicting And", + "An AND statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/And.png", + ShortTruthTableOperation.AND, + new ShortTruthTableCellType[][] { + {n, T, F}, + {F, T, n}, + // {F, T, F}, + {T, F, T}, + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java index 16256ec6a..879b7c9a5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleAtomic.java @@ -11,49 +11,49 @@ public class ContradictionRuleAtomic extends ContradictionRule { - public ContradictionRuleAtomic() { - super( - "STTT-CONT-0002", - "Contradicting Variable", - "A single variable can not be both True and False", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Atomic.png"); - } - - @Override - public String checkContradictionAt(Board puzzleBoard, PuzzleElement puzzleElement) { - - // cast the board toa shortTruthTableBoard - ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - - // get the cell that contradicts another cell in the board - ShortTruthTableCell cell = (ShortTruthTableCell) board.getPuzzleElement(puzzleElement); - - if (!cell.isVariable()) { - System.out.println(" Not Var"); - return "Can not check for contradiction on a non-variable element"; + public ContradictionRuleAtomic() { + super( + "STTT-CONT-0002", + "Contradicting Variable", + "A single variable can not be both True and False", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Atomic.png"); } - ShortTruthTableCellType cellType = cell.getType(); - if (!cellType.isTrueOrFalse()) { - return "Can only check for a contradiction against a cell that is assigned a value of" - + " True or False"; + @Override + public String checkContradictionAt(Board puzzleBoard, PuzzleElement puzzleElement) { + + // cast the board toa shortTruthTableBoard + ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; + + // get the cell that contradicts another cell in the board + ShortTruthTableCell cell = (ShortTruthTableCell) board.getPuzzleElement(puzzleElement); + + if (!cell.isVariable()) { + System.out.println(" Not Var"); + return "Can not check for contradiction on a non-variable element"; + } + + ShortTruthTableCellType cellType = cell.getType(); + if (!cellType.isTrueOrFalse()) { + return "Can only check for a contradiction against a cell that is assigned a value of" + + " True or False"; + } + + // get all the cells with the same value + Set varCells = board.getCellsWithSymbol(cell.getSymbol()); + + // check if there are any contradictions + Iterator itr = varCells.iterator(); + while (itr.hasNext()) { + ShortTruthTableCell checkCell = itr.next(); + ShortTruthTableCellType checkCellType = checkCell.getType(); + // if there is an assigned contradiction, return null + if (checkCellType.isTrueOrFalse() && checkCellType != cellType) { + return null; + } + } + + // if it made it through the while loop, thene there is no contradiction + return "There is no contradiction for the variable " + cell.getSymbol(); } - - // get all the cells with the same value - Set varCells = board.getCellsWithSymbol(cell.getSymbol()); - - // check if there are any contradictions - Iterator itr = varCells.iterator(); - while (itr.hasNext()) { - ShortTruthTableCell checkCell = itr.next(); - ShortTruthTableCellType checkCellType = checkCell.getType(); - // if there is an assigned contradiction, return null - if (checkCellType.isTrueOrFalse() && checkCellType != cellType) { - return null; - } - } - - // if it made it through the while loop, thene there is no contradiction - return "There is no contradiction for the variable " + cell.getSymbol(); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java index 2be92ffb1..bae07acce 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleBiconditional.java @@ -5,18 +5,18 @@ public class ContradictionRuleBiconditional extends ContradictionRule_GenericStatement { - public ContradictionRuleBiconditional() { - super( - "STTT-CONT-0003", - "Contradicting Biconditional", - "A Biconditional statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Biconditional.png", - ShortTruthTableOperation.BICONDITIONAL, - new ShortTruthTableCellType[][] { - {T, T, F}, - {F, T, T}, - {T, F, T}, - {F, F, F} - }); - } + public ContradictionRuleBiconditional() { + super( + "STTT-CONT-0003", + "Contradicting Biconditional", + "A Biconditional statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Biconditional.png", + ShortTruthTableOperation.BICONDITIONAL, + new ShortTruthTableCellType[][] { + {T, T, F}, + {F, T, T}, + {T, F, T}, + {F, F, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java index b9ce9b74e..e3a51a00e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleConditional.java @@ -5,17 +5,17 @@ public class ContradictionRuleConditional extends ContradictionRule_GenericStatement { - public ContradictionRuleConditional() { - super( - "STTT-CONT-0004", - "Contradicting Conditional", - "A Conditional statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Conditional.png", - ShortTruthTableOperation.CONDITIONAL, - new ShortTruthTableCellType[][] { - {n, F, T}, - {F, F, n}, - {T, T, F} - }); - } + public ContradictionRuleConditional() { + super( + "STTT-CONT-0004", + "Contradicting Conditional", + "A Conditional statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Conditional.png", + ShortTruthTableOperation.CONDITIONAL, + new ShortTruthTableCellType[][] { + {n, F, T}, + {F, F, n}, + {T, T, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java index 6c4bb40e0..4e20485bc 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleNot.java @@ -5,16 +5,16 @@ public class ContradictionRuleNot extends ContradictionRule_GenericStatement { - public ContradictionRuleNot() { - super( - "STTT-CONT-0005", - "Contradicting Negation", - "A negation and its following statement can not have the same truth value", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Not.png", - ShortTruthTableOperation.NOT, - new ShortTruthTableCellType[][] { - {n, T, T}, - {n, F, F} - }); - } + public ContradictionRuleNot() { + super( + "STTT-CONT-0005", + "Contradicting Negation", + "A negation and its following statement can not have the same truth value", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Not.png", + ShortTruthTableOperation.NOT, + new ShortTruthTableCellType[][] { + {n, T, T}, + {n, F, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java index 85f29ca3f..2ab197dad 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRuleOr.java @@ -5,17 +5,17 @@ public class ContradictionRuleOr extends ContradictionRule_GenericStatement { - public ContradictionRuleOr() { - super( - "STTT-CONT-0006", - "Contradicting Or", - "An OR statement must have a contradicting pattern", - "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Or.png", - ShortTruthTableOperation.OR, - new ShortTruthTableCellType[][] { - {n, F, T}, - {T, F, n}, - {F, T, F} - }); - } + public ContradictionRuleOr() { + super( + "STTT-CONT-0006", + "Contradicting Or", + "An OR statement must have a contradicting pattern", + "edu/rpi/legup/images/shorttruthtable/ruleimages/contradiction/Or.png", + ShortTruthTableOperation.OR, + new ShortTruthTableCellType[][] { + {n, F, T}, + {T, F, n}, + {F, T, F} + }); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java index 7ddc053ca..87b1ba628 100644 --- a/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java +++ b/src/main/java/edu/rpi/legup/puzzle/shorttruthtable/rules/contradiction/ContradictionRule_GenericStatement.java @@ -10,76 +10,79 @@ public abstract class ContradictionRule_GenericStatement extends ContradictionRule { - private final char operationSymbol; - - private final ShortTruthTableCellType[][] contradictionPatterns; - - static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; - static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; - static final ShortTruthTableCellType n = null; - - private final String NOT_RIGHT_OPERATOR_ERROR_MESSAGE = - "This cell does not contain the correct operation"; - private final String NOT_TRUE_FALSE_ERROR_MESSAGE = - "Can only check for a contradiction on a cell that is assigned a value of True or" + " False"; - - public ContradictionRule_GenericStatement( - String ruleID, - String ruleName, - String description, - String imageName, - char operationSymbol, - ShortTruthTableCellType[][] contradictionPatterns) { - super(ruleID, ruleName, description, imageName); - this.operationSymbol = operationSymbol; - this.contradictionPatterns = contradictionPatterns; - } - - @Override - public String checkContradictionAt(Board puzzleBoard, PuzzleElement operatorPuzzleElement) { - - // cast the board to a shortTruthTableBoard - ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - - // get the cell that contradicts another cell in the board - ShortTruthTableCell cell = board.getCellFromElement(operatorPuzzleElement); - ShortTruthTableStatement statement = cell.getStatementReference(); - - if (cell.getSymbol() != this.operationSymbol) { - return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_RIGHT_OPERATOR_ERROR_MESSAGE; + private final char operationSymbol; + + private final ShortTruthTableCellType[][] contradictionPatterns; + + static final ShortTruthTableCellType T = ShortTruthTableCellType.TRUE; + static final ShortTruthTableCellType F = ShortTruthTableCellType.FALSE; + static final ShortTruthTableCellType n = null; + + private final String NOT_RIGHT_OPERATOR_ERROR_MESSAGE = + "This cell does not contain the correct operation"; + private final String NOT_TRUE_FALSE_ERROR_MESSAGE = + "Can only check for a contradiction on a cell that is assigned a value of True or" + + " False"; + + public ContradictionRule_GenericStatement( + String ruleID, + String ruleName, + String description, + String imageName, + char operationSymbol, + ShortTruthTableCellType[][] contradictionPatterns) { + super(ruleID, ruleName, description, imageName); + this.operationSymbol = operationSymbol; + this.contradictionPatterns = contradictionPatterns; } - // check that the initial statement is assigned - ShortTruthTableCellType cellType = cell.getType(); + @Override + public String checkContradictionAt(Board puzzleBoard, PuzzleElement operatorPuzzleElement) { - if (!cellType.isTrueOrFalse()) { - return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_TRUE_FALSE_ERROR_MESSAGE; - } + // cast the board to a shortTruthTableBoard + ShortTruthTableBoard board = (ShortTruthTableBoard) puzzleBoard; - // get the pattern for this sub-statement - ShortTruthTableCellType[] testPattern = statement.getCellTypePattern(); + // get the cell that contradicts another cell in the board + ShortTruthTableCell cell = board.getCellFromElement(operatorPuzzleElement); + ShortTruthTableStatement statement = cell.getStatementReference(); - // if the board pattern matches any contradiction pattern, it is a valid contradiction - for (ShortTruthTableCellType[] pattern : contradictionPatterns) { - boolean matches = true; - for (int i = 0; i < 3; i++) { - // ull means that part does not affect the statement - if (pattern[i] == null) { - continue; + if (cell.getSymbol() != this.operationSymbol) { + return super.getInvalidUseOfRuleMessage() + + ": " + + this.NOT_RIGHT_OPERATOR_ERROR_MESSAGE; } - // if it is not null, it must match the test pattern - if (pattern[i] != testPattern[i]) { - matches = false; - break; + + // check that the initial statement is assigned + ShortTruthTableCellType cellType = cell.getType(); + + if (!cellType.isTrueOrFalse()) { + return super.getInvalidUseOfRuleMessage() + ": " + this.NOT_TRUE_FALSE_ERROR_MESSAGE; } - } - // if testPattern matches one of the valid contradiction patterns, the contradiction is - // correct - if (matches) { - return null; - } - } - return super.getNoContradictionMessage(); - } + // get the pattern for this sub-statement + ShortTruthTableCellType[] testPattern = statement.getCellTypePattern(); + + // if the board pattern matches any contradiction pattern, it is a valid contradiction + for (ShortTruthTableCellType[] pattern : contradictionPatterns) { + boolean matches = true; + for (int i = 0; i < 3; i++) { + // ull means that part does not affect the statement + if (pattern[i] == null) { + continue; + } + // if it is not null, it must match the test pattern + if (pattern[i] != testPattern[i]) { + matches = false; + break; + } + } + // if testPattern matches one of the valid contradiction patterns, the contradiction is + // correct + if (matches) { + return null; + } + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java index 4dd2781e0..df5ba78a3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/Skyscrapers.java @@ -7,78 +7,78 @@ public class Skyscrapers extends Puzzle { - public Skyscrapers() { - super(); + public Skyscrapers() { + super(); - this.name = "Skyscrapers"; + this.name = "Skyscrapers"; - this.importer = new SkyscrapersImporter(this); - this.exporter = new SkyscrapersExporter(this); + this.importer = new SkyscrapersImporter(this); + this.exporter = new SkyscrapersExporter(this); - this.factory = new SkyscrapersCellFactory(); - } + this.factory = new SkyscrapersCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - boardView = new SkyscrapersView((SkyscrapersBoard) currentBoard); - boardView.setBoard(currentBoard); - addBoardListener(boardView); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + boardView = new SkyscrapersView((SkyscrapersBoard) currentBoard); + boardView.setBoard(currentBoard); + addBoardListener(boardView); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Skyscrapers - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Skyscrapers, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - return rows >= 4 && rows == columns; - } + @Override + /** + * Determines if the given dimensions are valid for Skyscrapers + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Skyscrapers, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + return rows >= 4 && rows == columns; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - SkyscrapersBoard SkyscraperBoard = (SkyscrapersBoard) board; + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + SkyscrapersBoard SkyscraperBoard = (SkyscrapersBoard) board; - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(SkyscraperBoard) == null) { - System.out.println(rule.getRuleName()); - return false; - } - } - for (PuzzleElement data : SkyscraperBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) data; - if (cell.getType() == SkyscrapersType.UNKNOWN) { - return false; - } + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(SkyscraperBoard) == null) { + System.out.println(rule.getRuleName()); + return false; + } + } + for (PuzzleElement data : SkyscraperBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) data; + if (cell.getType() == SkyscrapersType.UNKNOWN) { + return false; + } + } + return true; } - return true; - } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java index 7bc754cb4..4cd09b254 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersBoard.java @@ -10,264 +10,264 @@ public class SkyscrapersBoard extends GridBoard { - private ArrayList eastClues; - // EAST clues - private ArrayList southClues; - // SOUTH clues - private ArrayList westClues; - // WEST clues - private ArrayList northClues; - // NORTH clues + private ArrayList eastClues; + // EAST clues + private ArrayList southClues; + // SOUTH clues + private ArrayList westClues; + // WEST clues + private ArrayList northClues; + // NORTH clues - private boolean viewFlag = false; - private boolean dupeFlag = false; + private boolean viewFlag = false; + private boolean dupeFlag = false; - public SkyscrapersBoard(int size) { - super(size, size); + public SkyscrapersBoard(int size) { + super(size, size); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + this.northClues = new ArrayList<>(); - for (int i = 0; i < size; i++) { - eastClues.add(null); - southClues.add(null); - westClues.add(null); - northClues.add(null); + for (int i = 0; i < size; i++) { + eastClues.add(null); + southClues.add(null); + westClues.add(null); + northClues.add(null); + } } - } - - /** - * @return eastClues a list of the eastern clues ordered from loc.y = 0 to max - */ - public ArrayList getEastClues() { - return eastClues; - } - - /** - * @return southClues a list of the southern clues ordered from loc.x = 0 to max - */ - public ArrayList getSouthClues() { - return southClues; - } - - /** - * @return westClues a list of the western clues ordered from loc.y = 0 to max - */ - public ArrayList getWestClues() { - return westClues; - } - - /** - * @return northClues a list of the northern clues ordered from loc.x = 0 to max - */ - public ArrayList getNorthClues() { - return northClues; - } - public boolean getDupeFlag() { - return dupeFlag; - } - - public boolean getViewFlag() { - return viewFlag; - } - - public void setDupeFlag(boolean newFlag) { - dupeFlag = newFlag; - } + /** + * @return eastClues a list of the eastern clues ordered from loc.y = 0 to max + */ + public ArrayList getEastClues() { + return eastClues; + } - public void setViewFlag(boolean newFlag) { - viewFlag = newFlag; - } + /** + * @return southClues a list of the southern clues ordered from loc.x = 0 to max + */ + public ArrayList getSouthClues() { + return southClues; + } - @Override - public SkyscrapersCell getCell(int x, int y) { - return (SkyscrapersCell) super.getCell(x, y); - } + /** + * @return westClues a list of the western clues ordered from loc.y = 0 to max + */ + public ArrayList getWestClues() { + return westClues; + } - public int getSize() { - return this.getWidth(); - } + /** + * @return northClues a list of the northern clues ordered from loc.x = 0 to max + */ + public ArrayList getNorthClues() { + return northClues; + } - @Override - public PuzzleElement getPuzzleElement(PuzzleElement element) { - // If the element index is -2, it is a clue and should be returned separately - if (element.getIndex() == -2) { - return element; + public boolean getDupeFlag() { + return dupeFlag; } - return super.getPuzzleElement(element); - } - /** - * Gets the cells of a certain type directly adjacent to a given cell - * - * @param cell at the center, - * @param type of cell to collect - * @return list of cells of the given type - */ - public List getAdjacent(SkyscrapersCell cell, SkyscrapersType type) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - SkyscrapersCell up = getCell(loc.x, loc.y - 1); - SkyscrapersCell right = getCell(loc.x + 1, loc.y); - SkyscrapersCell down = getCell(loc.x, loc.y + 1); - SkyscrapersCell left = getCell(loc.x - 1, loc.y); - if (up != null && (up.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(up); + public boolean getViewFlag() { + return viewFlag; } - if (right != null && (right.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(right); + + public void setDupeFlag(boolean newFlag) { + dupeFlag = newFlag; } - if (down != null && (down.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(down); + + public void setViewFlag(boolean newFlag) { + viewFlag = newFlag; } - if (left != null && (left.getType() == type || type == SkyscrapersType.ANY)) { - adj.add(left); + + @Override + public SkyscrapersCell getCell(int x, int y) { + return (SkyscrapersCell) super.getCell(x, y); } - return adj; - } - /** - * Gets the cells of a certain type directly diagonal to a given cell - * - * @param cell at the center, - * @param type of cell to collect - * @return list of cells of the given type - */ - public List getDiagonals(SkyscrapersCell cell, SkyscrapersType type) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - SkyscrapersCell upRight = getCell(loc.x + 1, loc.y - 1); - SkyscrapersCell downRight = getCell(loc.x + 1, loc.y + 1); - SkyscrapersCell downLeft = getCell(loc.x - 1, loc.y + 1); - SkyscrapersCell upLeft = getCell(loc.x - 1, loc.y - 1); - if (upRight != null && (upRight.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(upRight); + public int getSize() { + return this.getWidth(); } - if (downLeft != null && (downLeft.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(downLeft); + + @Override + public PuzzleElement getPuzzleElement(PuzzleElement element) { + // If the element index is -2, it is a clue and should be returned separately + if (element.getIndex() == -2) { + return element; + } + return super.getPuzzleElement(element); } - if (downRight != null && (downRight.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(downRight); + + /** + * Gets the cells of a certain type directly adjacent to a given cell + * + * @param cell at the center, + * @param type of cell to collect + * @return list of cells of the given type + */ + public List getAdjacent(SkyscrapersCell cell, SkyscrapersType type) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + SkyscrapersCell up = getCell(loc.x, loc.y - 1); + SkyscrapersCell right = getCell(loc.x + 1, loc.y); + SkyscrapersCell down = getCell(loc.x, loc.y + 1); + SkyscrapersCell left = getCell(loc.x - 1, loc.y); + if (up != null && (up.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(up); + } + if (right != null && (right.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(right); + } + if (down != null && (down.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(down); + } + if (left != null && (left.getType() == type || type == SkyscrapersType.ANY)) { + adj.add(left); + } + return adj; } - if (upLeft != null && (upLeft.getType() == type || type == SkyscrapersType.ANY)) { - dia.add(upLeft); + + /** + * Gets the cells of a certain type directly diagonal to a given cell + * + * @param cell at the center, + * @param type of cell to collect + * @return list of cells of the given type + */ + public List getDiagonals(SkyscrapersCell cell, SkyscrapersType type) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + SkyscrapersCell upRight = getCell(loc.x + 1, loc.y - 1); + SkyscrapersCell downRight = getCell(loc.x + 1, loc.y + 1); + SkyscrapersCell downLeft = getCell(loc.x - 1, loc.y + 1); + SkyscrapersCell upLeft = getCell(loc.x - 1, loc.y - 1); + if (upRight != null && (upRight.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(upRight); + } + if (downLeft != null && (downLeft.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(downLeft); + } + if (downRight != null && (downRight.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(downRight); + } + if (upLeft != null && (upLeft.getType() == type || type == SkyscrapersType.ANY)) { + dia.add(upLeft); + } + return dia; } - return dia; - } - /** - * Gets the cells of a certain type in a given row/column - * - * @param index: y pos of row or x pos of col, - * @param type of cell to collect, - * @param isRow true if row, false if col - * @return list of cells of the given type, ordered west to east or north to south - */ - public List getRowCol(int index, SkyscrapersType type, boolean isRow) { - List list = new ArrayList<>(); - for (int i = 0; i < dimension.height; i++) { - SkyscrapersCell cell; - if (isRow) { - cell = getCell(i, index); - } else { - cell = getCell(index, i); - } + /** + * Gets the cells of a certain type in a given row/column + * + * @param index: y pos of row or x pos of col, + * @param type of cell to collect, + * @param isRow true if row, false if col + * @return list of cells of the given type, ordered west to east or north to south + */ + public List getRowCol(int index, SkyscrapersType type, boolean isRow) { + List list = new ArrayList<>(); + for (int i = 0; i < dimension.height; i++) { + SkyscrapersCell cell; + if (isRow) { + cell = getCell(i, index); + } else { + cell = getCell(index, i); + } - if (cell.getType() == type || type == SkyscrapersType.ANY) { - list.add(cell); - } + if (cell.getType() == type || type == SkyscrapersType.ANY) { + list.add(cell); + } + } + return list; } - return list; - } - /** Prints a semblance of the board to console (helps in debugging) */ - public void printBoard() { - for (int i = 0; i < this.dimension.height; i++) { - for (SkyscrapersCell cell : this.getRowCol(i, SkyscrapersType.ANY, true)) { - if (cell.getType() == SkyscrapersType.Number) { - System.out.print(cell.getData() + " "); - } else { - System.out.print(0 + " "); + /** Prints a semblance of the board to console (helps in debugging) */ + public void printBoard() { + for (int i = 0; i < this.dimension.height; i++) { + for (SkyscrapersCell cell : this.getRowCol(i, SkyscrapersType.ANY, true)) { + if (cell.getType() == SkyscrapersType.Number) { + System.out.print(cell.getData() + " "); + } else { + System.out.print(0 + " "); + } + } + System.out.println(); } - } - System.out.println(); } - } - /** - * @param x position of cell - * @param y position of cell - * @param e Element to be placed (null if nothing selected) - * @param m MouseEvent Increases clue values if in editor mode. Currently allows for presetting - * tile values, though they will not be saved. - */ - @Override - public void setCell(int x, int y, Element e, MouseEvent m) { - SkyscrapersClue clue = this.getClue(x, y); - if (e == null) return; - if (clue != null) { - if (!e.getElementID().equals("SKYS-UNPL-0003")) { - return; - } + /** + * @param x position of cell + * @param y position of cell + * @param e Element to be placed (null if nothing selected) + * @param m MouseEvent Increases clue values if in editor mode. Currently allows for presetting + * tile values, though they will not be saved. + */ + @Override + public void setCell(int x, int y, Element e, MouseEvent m) { + SkyscrapersClue clue = this.getClue(x, y); + if (e == null) return; + if (clue != null) { + if (!e.getElementID().equals("SKYS-UNPL-0003")) { + return; + } - if (m.getButton() == MouseEvent.BUTTON1) { - if (clue.getData() < dimension.height) { - clue.setData(clue.getData() + 1); - } else { - clue.setData(0); - } - } else { - if (clue.getData() > 0) { - clue.setData(clue.getData() - 1); + if (m.getButton() == MouseEvent.BUTTON1) { + if (clue.getData() < dimension.height) { + clue.setData(clue.getData() + 1); + } else { + clue.setData(0); + } + } else { + if (clue.getData() > 0) { + clue.setData(clue.getData() - 1); + } else { + clue.setData(dimension.height); + } + } } else { - clue.setData(dimension.height); + super.setCell(x - 1, y - 1, e, m); } - } - } else { - super.setCell(x - 1, y - 1, e, m); } - } - /** - * @param x position of element on boardView - * @param y position of element on boardView - * @return The clue at the given position - */ - public SkyscrapersClue getClue(int x, int y) { - int viewIndex = getSize() + 1; - if (x == 0 && y > 0 && y < viewIndex) { - return westClues.get(y - 1); - } else if (x == viewIndex && y > 0 && y < viewIndex) { - return eastClues.get(y - 1); - } else if (y == 0 && x > 0 && x < viewIndex) { - return northClues.get(x - 1); - } else if (y == viewIndex && x > 0 && x < viewIndex) { - return southClues.get(x - 1); + /** + * @param x position of element on boardView + * @param y position of element on boardView + * @return The clue at the given position + */ + public SkyscrapersClue getClue(int x, int y) { + int viewIndex = getSize() + 1; + if (x == 0 && y > 0 && y < viewIndex) { + return westClues.get(y - 1); + } else if (x == viewIndex && y > 0 && y < viewIndex) { + return eastClues.get(y - 1); + } else if (y == 0 && x > 0 && x < viewIndex) { + return northClues.get(x - 1); + } else if (y == viewIndex && x > 0 && x < viewIndex) { + return southClues.get(x - 1); + } + return null; } - return null; - } - @Override - public SkyscrapersBoard copy() { - SkyscrapersBoard copy = new SkyscrapersBoard(dimension.width); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } - } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); - } - copy.eastClues = eastClues; - copy.southClues = southClues; - copy.westClues = westClues; - copy.northClues = northClues; + @Override + public SkyscrapersBoard copy() { + SkyscrapersBoard copy = new SkyscrapersBoard(dimension.width); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.eastClues = eastClues; + copy.southClues = southClues; + copy.westClues = westClues; + copy.northClues = northClues; - copy.dupeFlag = dupeFlag; - copy.viewFlag = viewFlag; - return copy; - } + copy.dupeFlag = dupeFlag; + copy.viewFlag = viewFlag; + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java index a315ac788..1cf9a357b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCell.java @@ -8,59 +8,59 @@ import java.awt.event.MouseEvent; public class SkyscrapersCell extends GridCell { - private int max; + private int max; - public SkyscrapersCell(Integer value, Point location, int size) { - super(value, location); - this.max = size; - } + public SkyscrapersCell(Integer value, Point location, int size) { + super(value, location); + this.max = size; + } - public SkyscrapersType getType() { - switch (convertToSkyType(data)) { - case UNKNOWN: - return SkyscrapersType.UNKNOWN; - default: - return SkyscrapersType.Number; + public SkyscrapersType getType() { + switch (convertToSkyType(data)) { + case UNKNOWN: + return SkyscrapersType.UNKNOWN; + default: + return SkyscrapersType.Number; + } } - } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementID()) { - case "SKYS-UNPL-0001": - this.data = 0; - break; - case "SKYS-UNPL-0002": - switch (m.getButton()) { - case MouseEvent.BUTTON1: - if (this.data <= 0 || this.data >= this.max) { - this.data = 1; - } else { - this.data = this.data + 1; - } - break; - case MouseEvent.BUTTON3: - if (this.data > 1) { - this.data = this.data - 1; - } else { - this.data = this.max; - } - break; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementID()) { + case "SKYS-UNPL-0001": + this.data = 0; + break; + case "SKYS-UNPL-0002": + switch (m.getButton()) { + case MouseEvent.BUTTON1: + if (this.data <= 0 || this.data >= this.max) { + this.data = 1; + } else { + this.data = this.data + 1; + } + break; + case MouseEvent.BUTTON3: + if (this.data > 1) { + this.data = this.data - 1; + } else { + this.data = this.max; + } + break; + } + break; } - break; } - } - public int getMax() { - return max; - } + public int getMax() { + return max; + } - @Override - public SkyscrapersCell copy() { - SkyscrapersCell copy = new SkyscrapersCell(data, (Point) location.clone(), max); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public SkyscrapersCell copy() { + SkyscrapersCell copy = new SkyscrapersCell(data, (Point) location.clone(), max); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java index 1f10b31d3..03572b816 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersCellFactory.java @@ -10,65 +10,67 @@ import org.w3c.dom.Node; public class SkyscrapersCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if input is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException( - "Skyscrapers Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if input is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: unknown puzzleElement puzzleElement"); + } - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - int size = skyscrapersBoard.getSize(); - NamedNodeMap attributeList = node.getAttributes(); + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + int size = skyscrapersBoard.getSize(); + NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= size || y >= size) { - throw new InvalidFileFormatException("Skyscrapers Factory: cell location out of bounds"); - } - if (value < 0 || value > size) { - throw new InvalidFileFormatException("Skyscrapers Factory: cell unknown value"); - } + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= size || y >= size) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: cell location out of bounds"); + } + if (value < 0 || value > size) { + throw new InvalidFileFormatException("Skyscrapers Factory: cell unknown value"); + } - SkyscrapersCell cell = new SkyscrapersCell(value, new Point(x, y), size); - cell.setIndex(y * size + x); + SkyscrapersCell cell = new SkyscrapersCell(value, new Point(x, y), size); + cell.setIndex(y * size + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Skyscrapers Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Skyscrapers Factory: could not find attribute(s)"); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException( + "Skyscrapers Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java index dd2bc5412..7b8bf635b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClue.java @@ -3,53 +3,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class SkyscrapersClue extends PuzzleElement { - private SkyscrapersType type; - private int clueIndex; - - public SkyscrapersClue(int value, int clueIndex, SkyscrapersType type) { - super(value); - this.index = -2; - this.clueIndex = clueIndex; // index in list - this.type = type; - this.setModifiable(false); - } - - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; + private SkyscrapersType type; + private int clueIndex; + + public SkyscrapersClue(int value, int clueIndex, SkyscrapersType type) { + super(value); + this.index = -2; + this.clueIndex = clueIndex; // index in list + this.type = type; + this.setModifiable(false); } - return sb.reverse().toString(); - } - - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; + + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; + } + return sb.reverse().toString(); + } + + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; + } + return result; + } + + public int getClueIndex() { + return clueIndex; + } + + public SkyscrapersType getType() { + return type; + } + + public void setType(SkyscrapersType type) { + this.type = type; + } + + public SkyscrapersClue copy() { + SkyscrapersClue copy = new SkyscrapersClue(data, clueIndex, type); + copy.setIndex(index); + copy.setModifiable(isModifiable); + return copy; } - return result; - } - - public int getClueIndex() { - return clueIndex; - } - - public SkyscrapersType getType() { - return type; - } - - public void setType(SkyscrapersType type) { - this.type = type; - } - - public SkyscrapersClue copy() { - SkyscrapersClue copy = new SkyscrapersClue(data, clueIndex, type); - copy.setIndex(index); - copy.setModifiable(isModifiable); - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java index bd9abc162..5a49a1476 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersClueView.java @@ -5,55 +5,55 @@ public class SkyscrapersClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public SkyscrapersClueView(SkyscrapersClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public SkyscrapersClue getPuzzleElement() { - return (SkyscrapersClue) super.getPuzzleElement(); - } - - @Override - public void draw(Graphics2D graphics2D) { - drawElement(graphics2D); - if (this.isShowCasePicker() && this.isCaseRulePickable()) { - drawCase(graphics2D); - if (this.isHover()) { - drawHover(graphics2D); - } + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public SkyscrapersClueView(SkyscrapersClue clue) { + super(clue); } - } - - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - SkyscrapersClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - case CLUE_EAST: - case CLUE_SOUTH: - case CLUE_WEST: - value = String.valueOf(clue.getData()); - break; - default: - value = ""; + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public SkyscrapersClue getPuzzleElement() { + return (SkyscrapersClue) super.getPuzzleElement(); } - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + @Override + public void draw(Graphics2D graphics2D) { + drawElement(graphics2D); + if (this.isShowCasePicker() && this.isCaseRulePickable()) { + drawCase(graphics2D); + if (this.isHover()) { + drawHover(graphics2D); + } + } + } + + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + SkyscrapersClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + case CLUE_EAST: + case CLUE_SOUTH: + case CLUE_WEST: + value = String.valueOf(clue.getData()); + break; + default: + value = ""; + } + + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java index e0503382e..f78774e35 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersController.java @@ -6,29 +6,29 @@ public class SkyscrapersController extends ElementController { - public SkyscrapersController() { - super(); - } + public SkyscrapersController() { + super(); + } - @Override - public void changeCell(MouseEvent e, PuzzleElement element) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (e.getButton() == MouseEvent.BUTTON1) { - if (cell.getData() < cell.getMax()) { - int num = cell.getData() + 1; - cell.setData(num); - } else { - cell.setData(SkyscrapersType.UNKNOWN.toValue()); - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() > 0) { - int num = cell.getData() - 1; - cell.setData(num); + @Override + public void changeCell(MouseEvent e, PuzzleElement element) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (e.getButton() == MouseEvent.BUTTON1) { + if (cell.getData() < cell.getMax()) { + int num = cell.getData() + 1; + cell.setData(num); + } else { + cell.setData(SkyscrapersType.UNKNOWN.toValue()); + } } else { - cell.setData(cell.getMax()); + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() > 0) { + int num = cell.getData() - 1; + cell.setData(num); + } else { + cell.setData(cell.getMax()); + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java index 397ab5a93..2f33017c3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersElementView.java @@ -4,33 +4,34 @@ import java.awt.*; public class SkyscrapersElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = new Color(0x212121); - private static final Color BORDER_COLOR = new Color(0x424242); - private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = new Color(0x212121); + private static final Color BORDER_COLOR = new Color(0x424242); + private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); - public SkyscrapersElementView(SkyscrapersCell cell) { - super(cell); - } + public SkyscrapersElementView(SkyscrapersCell cell) { + super(cell); + } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BACKGROUND_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BORDER_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BACKGROUND_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BORDER_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - int val = cell.getData(); - if (val != 0) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(val); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + int val = cell.getData(); + if (val != 0) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(val); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java index 5d85d950e..75d2bd04f 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersExporter.java @@ -6,58 +6,62 @@ public class SkyscrapersExporter extends PuzzleExporter { - public SkyscrapersExporter(Skyscrapers skyscrapers) { - super(skyscrapers); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - SkyscrapersBoard board; - if (puzzle.getTree() != null) { - board = (SkyscrapersBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (SkyscrapersBoard) puzzle.getBoardView().getBoard(); + public SkyscrapersExporter(Skyscrapers skyscrapers) { + super(skyscrapers); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("size", String.valueOf(board.getWidth())); - - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - if (cell.getData() != 0) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); - - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (int i = 0; i < board.getWidth(); i++) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(board.getEastClues().get(i).getData())); - clueElement.setAttribute("index", String.valueOf(board.getWestClues().get(i).getData())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); - - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (int i = 0; i < board.getWidth(); i++) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(board.getSouthClues().get(i).getData())); - clueElement.setAttribute("index", String.valueOf(board.getNorthClues().get(i).getData())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + SkyscrapersBoard board; + if (puzzle.getTree() != null) { + board = (SkyscrapersBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (SkyscrapersBoard) puzzle.getBoardView().getBoard(); + } + + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("size", String.valueOf(board.getWidth())); - org.w3c.dom.Element flagsElement = newDocument.createElement("flags"); - flagsElement.setAttribute("dupe", String.valueOf(board.getDupeFlag())); - flagsElement.setAttribute("view", String.valueOf(board.getViewFlag())); - boardElement.appendChild(flagsElement); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + if (cell.getData() != 0) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (int i = 0; i < board.getWidth(); i++) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute( + "value", String.valueOf(board.getEastClues().get(i).getData())); + clueElement.setAttribute( + "index", String.valueOf(board.getWestClues().get(i).getData())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); + + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (int i = 0; i < board.getWidth(); i++) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute( + "value", String.valueOf(board.getSouthClues().get(i).getData())); + clueElement.setAttribute( + "index", String.valueOf(board.getNorthClues().get(i).getData())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); + + org.w3c.dom.Element flagsElement = newDocument.createElement("flags"); + flagsElement.setAttribute("dupe", String.valueOf(board.getDupeFlag())); + flagsElement.setAttribute("view", String.valueOf(board.getViewFlag())); + boardElement.appendChild(flagsElement); + + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java index 23b9a03a2..0fc7e6c39 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersImporter.java @@ -8,205 +8,217 @@ import org.w3c.dom.NodeList; public class SkyscrapersImporter extends PuzzleImporter { - public SkyscrapersImporter(Skyscrapers skyscrapers) { - super(skyscrapers); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } - - @Override - public boolean acceptsTextInput() { - return false; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - // assert(rows == columns); - int size = rows; - SkyscrapersBoard skyscrapersBoard = new SkyscrapersBoard(size); - - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - SkyscrapersCell cell = - new SkyscrapersCell(SkyscrapersType.UNKNOWN.toValue(), new Point(x, y), size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - skyscrapersBoard.setCell(x, y, cell); - } + public SkyscrapersImporter(Skyscrapers skyscrapers) { + super(skyscrapers); } - for (int i = 0; i < size; i++) { - skyscrapersBoard - .getWestClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_WEST)); - skyscrapersBoard - .getEastClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_EAST)); + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; } - for (int i = 0; i < size; i++) { - skyscrapersBoard - .getNorthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_NORTH)); - skyscrapersBoard - .getSouthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_SOUTH)); + @Override + public boolean acceptsTextInput() { + return false; } - puzzle.setCurrentBoard(skyscrapersBoard); - } - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException( - "Skyscrapers Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - - SkyscrapersBoard skyscrapersBoard = null; - - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - skyscrapersBoard = new SkyscrapersBoard(size); - } - - if (skyscrapersBoard == null) { - throw new InvalidFileFormatException("Skyscraper Importer: invalid board dimensions"); - } - - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException( - "Skyscrapers Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - int size = skyscrapersBoard.getSize(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - SkyscrapersCell cell = - (SkyscrapersCell) - puzzle.getFactory().importCell(elementDataList.item(i), skyscrapersBoard); - Point loc = cell.getLocation(); - if (cell.getData() != 0) { - cell.setModifiable(false); - cell.setGiven(true); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + // assert(rows == columns); + int size = rows; + SkyscrapersBoard skyscrapersBoard = new SkyscrapersBoard(size); + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + SkyscrapersCell cell = + new SkyscrapersCell( + SkyscrapersType.UNKNOWN.toValue(), new Point(x, y), size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + skyscrapersBoard.setCell(x, y, cell); + } } - skyscrapersBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - if (skyscrapersBoard.getCell(x, y) == null) { - SkyscrapersCell cell = - new SkyscrapersCell(SkyscrapersType.UNKNOWN.value, new Point(x, y), size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - skyscrapersBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("Skyscraper Importer: cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { - throw new InvalidFileFormatException( - "Skyscraper Importer: side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "Skyscraper Importer: axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != skyscrapersBoard.getHeight() - || southClues.getLength() != skyscrapersBoard.getWidth()) { - throw new InvalidFileFormatException( - "Skyscraper Importer: there must be same number of clues as the dimension" - + " of the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - skyscrapersBoard - .getWestClues() - .set(/*index - 1*/ i, new SkyscrapersClue(index, i, SkyscrapersType.CLUE_WEST)); - skyscrapersBoard - .getEastClues() - .set(/*index - 1*/ i, new SkyscrapersClue(value, i, SkyscrapersType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - skyscrapersBoard - .getNorthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(index, i, SkyscrapersType.CLUE_NORTH)); - skyscrapersBoard - .getSouthClues() - .set(/*index - 1*/ i, new SkyscrapersClue(value, i, SkyscrapersType.CLUE_SOUTH)); - } - - NodeList flagList = boardElement.getElementsByTagName("flags"); - if (flagList.getLength() == 1) { - Element flags = (Element) flagList.item(0); - if (flags.hasAttribute("dupe")) { - skyscrapersBoard.setDupeFlag(Boolean.parseBoolean(flags.getAttribute("dupe"))); + + for (int i = 0; i < size; i++) { + skyscrapersBoard + .getWestClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_WEST)); + skyscrapersBoard + .getEastClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_EAST)); } - if (flags.hasAttribute("view")) { - skyscrapersBoard.setViewFlag(Boolean.parseBoolean(flags.getAttribute("view"))); + + for (int i = 0; i < size; i++) { + skyscrapersBoard + .getNorthClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_NORTH)); + skyscrapersBoard + .getSouthClues() + .set(/*index - 1*/ i, new SkyscrapersClue(0, i, SkyscrapersType.CLUE_SOUTH)); } - } - puzzle.setCurrentBoard(skyscrapersBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "Skyscraper Importer: unknown value where integer expected"); + puzzle.setCurrentBoard(skyscrapersBoard); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Skyscrapers cannot accept text input"); - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Skyscrapers Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + + SkyscrapersBoard skyscrapersBoard = null; + + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + skyscrapersBoard = new SkyscrapersBoard(size); + } + + if (skyscrapersBoard == null) { + throw new InvalidFileFormatException( + "Skyscraper Importer: invalid board dimensions"); + } + + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Skyscrapers Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + int size = skyscrapersBoard.getSize(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + SkyscrapersCell cell = + (SkyscrapersCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), skyscrapersBoard); + Point loc = cell.getLocation(); + if (cell.getData() != 0) { + cell.setModifiable(false); + cell.setGiven(true); + } + skyscrapersBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + if (skyscrapersBoard.getCell(x, y) == null) { + SkyscrapersCell cell = + new SkyscrapersCell( + SkyscrapersType.UNKNOWN.value, new Point(x, y), size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + skyscrapersBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("Skyscraper Importer: cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { + throw new InvalidFileFormatException( + "Skyscraper Importer: side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "Skyscraper Importer: axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != skyscrapersBoard.getHeight() + || southClues.getLength() != skyscrapersBoard.getWidth()) { + throw new InvalidFileFormatException( + "Skyscraper Importer: there must be same number of clues as the dimension" + + " of the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + skyscrapersBoard + .getWestClues() + .set( + /*index - 1*/ i, + new SkyscrapersClue(index, i, SkyscrapersType.CLUE_WEST)); + skyscrapersBoard + .getEastClues() + .set( + /*index - 1*/ i, + new SkyscrapersClue(value, i, SkyscrapersType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + skyscrapersBoard + .getNorthClues() + .set( + /*index - 1*/ i, + new SkyscrapersClue(index, i, SkyscrapersType.CLUE_NORTH)); + skyscrapersBoard + .getSouthClues() + .set( + /*index - 1*/ i, + new SkyscrapersClue(value, i, SkyscrapersType.CLUE_SOUTH)); + } + + NodeList flagList = boardElement.getElementsByTagName("flags"); + if (flagList.getLength() == 1) { + Element flags = (Element) flagList.item(0); + if (flags.hasAttribute("dupe")) { + skyscrapersBoard.setDupeFlag(Boolean.parseBoolean(flags.getAttribute("dupe"))); + } + if (flags.hasAttribute("view")) { + skyscrapersBoard.setViewFlag(Boolean.parseBoolean(flags.getAttribute("view"))); + } + } + + puzzle.setCurrentBoard(skyscrapersBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Skyscraper Importer: unknown value where integer expected"); + } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Skyscrapers cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java index e9feeed47..4c150e8ae 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersType.java @@ -1,40 +1,40 @@ package edu.rpi.legup.puzzle.skyscrapers; public enum SkyscrapersType { - UNKNOWN(0), - Number(1), - CLUE_NORTH(-1), - CLUE_EAST(-2), - CLUE_SOUTH(-3), - CLUE_WEST(-4), - ANY(-5); + UNKNOWN(0), + Number(1), + CLUE_NORTH(-1), + CLUE_EAST(-2), + CLUE_SOUTH(-3), + CLUE_WEST(-4), + ANY(-5); - public int value; + public int value; - SkyscrapersType(int value) { - this.value = value; - } + SkyscrapersType(int value) { + this.value = value; + } - public int toValue() { - return value; - } + public int toValue() { + return value; + } - public static SkyscrapersType convertToSkyType(int num) { - switch (num) { - case 0: - return UNKNOWN; - case -1: - return CLUE_NORTH; - case -2: - return CLUE_EAST; - case -3: - return CLUE_SOUTH; - case -4: - return CLUE_WEST; - case -5: - return ANY; - default: - return Number; + public static SkyscrapersType convertToSkyType(int num) { + switch (num) { + case 0: + return UNKNOWN; + case -1: + return CLUE_NORTH; + case -2: + return CLUE_EAST; + case -3: + return CLUE_SOUTH; + case -4: + return CLUE_WEST; + case -5: + return ANY; + default: + return Number; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java index b922c808a..edd2cdbf5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/SkyscrapersView.java @@ -12,188 +12,195 @@ import org.apache.logging.log4j.Logger; public class SkyscrapersView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(SkyscrapersView.class.getName()); - - private ArrayList northClues; - private ArrayList eastClues; - private ArrayList southClues; - private ArrayList westClues; - - public SkyscrapersView(SkyscrapersBoard board) { - super(new BoardController(), new SkyscrapersController(), board.getDimension()); - - this.northClues = new ArrayList<>(); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); - SkyscrapersElementView elementView = new SkyscrapersElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); - elementViews.add(elementView); - } + private static final Logger LOGGER = LogManager.getLogger(SkyscrapersView.class.getName()); + + private ArrayList northClues; + private ArrayList eastClues; + private ArrayList southClues; + private ArrayList westClues; + + public SkyscrapersView(SkyscrapersBoard board) { + super(new BoardController(), new SkyscrapersController(), board.getDimension()); + + this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); + SkyscrapersElementView elementView = new SkyscrapersElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); + elementViews.add(elementView); + } - for (int i = 0; i < gridSize.height; i++) { - SkyscrapersClueView row = new SkyscrapersClueView(board.getWestClues().get(i)); - row.setLocation(new Point(0, (i + 1) * elementSize.height)); - row.setSize(elementSize); + for (int i = 0; i < gridSize.height; i++) { + SkyscrapersClueView row = new SkyscrapersClueView(board.getWestClues().get(i)); + row.setLocation(new Point(0, (i + 1) * elementSize.height)); + row.setSize(elementSize); - SkyscrapersClueView clue = new SkyscrapersClueView(board.getEastClues().get(i)); - clue.setLocation( - new Point((gridSize.height + 1) * elementSize.height, (i + 1) * elementSize.height)); - clue.setSize(elementSize); + SkyscrapersClueView clue = new SkyscrapersClueView(board.getEastClues().get(i)); + clue.setLocation( + new Point( + (gridSize.height + 1) * elementSize.height, + (i + 1) * elementSize.height)); + clue.setSize(elementSize); - westClues.add(row); - eastClues.add(clue); - } + westClues.add(row); + eastClues.add(clue); + } - for (int i = 0; i < gridSize.width; i++) { - SkyscrapersClueView col = new SkyscrapersClueView(board.getNorthClues().get(i)); - col.setLocation(new Point((i + 1) * elementSize.width, 0)); - col.setSize(elementSize); + for (int i = 0; i < gridSize.width; i++) { + SkyscrapersClueView col = new SkyscrapersClueView(board.getNorthClues().get(i)); + col.setLocation(new Point((i + 1) * elementSize.width, 0)); + col.setSize(elementSize); - SkyscrapersClueView clue = new SkyscrapersClueView(board.getSouthClues().get(i)); - clue.setLocation( - new Point((i + 1) * elementSize.width, (gridSize.width + 1) * elementSize.width)); - clue.setSize(elementSize); + SkyscrapersClueView clue = new SkyscrapersClueView(board.getSouthClues().get(i)); + clue.setLocation( + new Point( + (i + 1) * elementSize.width, (gridSize.width + 1) * elementSize.width)); + clue.setSize(elementSize); - northClues.add(col); - southClues.add(clue); - } - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - @Override - public ElementView getElement(Point point) { - Point scaledPoint = - new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - for (SkyscrapersClueView clueView : northClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : eastClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (SkyscrapersClueView clueView : southClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } + northClues.add(col); + southClues.add(clue); + } } - for (SkyscrapersClueView clueView : westClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + @Override + public ElementView getElement(Point point) { + Point scaledPoint = + new Point( + (int) Math.round(point.x / getScale()), + (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + for (SkyscrapersClueView clueView : northClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : eastClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : southClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (SkyscrapersClueView clueView : westClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + return null; + } + + public ArrayList getNorthClues() { + return northClues; + } + + public ArrayList getWestClues() { + return westClues; + } + + @Override + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = (gridSize.width + 2) * elementSize.width; + boardViewSize.height = (gridSize.height + 2) * elementSize.height; + return boardViewSize; + } + + /** + * Sets the board associated with this view + * + * @param board board + */ + @Override + public void setBoard(Board board) { + if (this.board != board) { + this.board = board; + + if (board instanceof CaseBoard) { + setCasePickable(); + } else { + for (ElementView elementView : elementViews) { + elementView.setPuzzleElement( + board.getPuzzleElement(elementView.getPuzzleElement())); + elementView.setShowCasePicker(false); + } + for (SkyscrapersClueView clueView : northClues) { + clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); + clueView.setShowCasePicker(false); + } + for (SkyscrapersClueView clueView : westClues) { + clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); + clueView.setShowCasePicker(false); + } + } + } } - return null; - } - - public ArrayList getNorthClues() { - return northClues; - } - - public ArrayList getWestClues() { - return westClues; - } - - @Override - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = (gridSize.width + 2) * elementSize.width; - boardViewSize.height = (gridSize.height + 2) * elementSize.height; - return boardViewSize; - } - - /** - * Sets the board associated with this view - * - * @param board board - */ - @Override - public void setBoard(Board board) { - if (this.board != board) { - this.board = board; - - if (board instanceof CaseBoard) { - setCasePickable(); - } else { + + @Override + protected void setCasePickable() { + CaseBoard caseBoard = (CaseBoard) board; + Board baseBoard = caseBoard.getBaseBoard(); + for (ElementView elementView : elementViews) { - elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); - elementView.setShowCasePicker(false); + PuzzleElement puzzleElement = + baseBoard.getPuzzleElement(elementView.getPuzzleElement()); + elementView.setPuzzleElement(puzzleElement); + elementView.setShowCasePicker(true); + elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); } for (SkyscrapersClueView clueView : northClues) { - clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); - clueView.setShowCasePicker(false); + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); + clueView.setPuzzleElement(puzzleElement); + clueView.setShowCasePicker(true); + clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); } for (SkyscrapersClueView clueView : westClues) { - clueView.setPuzzleElement(board.getPuzzleElement(clueView.getPuzzleElement())); - clueView.setShowCasePicker(false); + PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); + clueView.setPuzzleElement(puzzleElement); + clueView.setShowCasePicker(true); + clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); } - } } - } - - @Override - protected void setCasePickable() { - CaseBoard caseBoard = (CaseBoard) board; - Board baseBoard = caseBoard.getBaseBoard(); - - for (ElementView elementView : elementViews) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); - elementView.setPuzzleElement(puzzleElement); - elementView.setShowCasePicker(true); - elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - for (SkyscrapersClueView clueView : northClues) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); - clueView.setPuzzleElement(puzzleElement); - clueView.setShowCasePicker(true); - clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - for (SkyscrapersClueView clueView : westClues) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(clueView.getPuzzleElement()); - clueView.setPuzzleElement(puzzleElement); - clueView.setShowCasePicker(true); - clueView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); - for (SkyscrapersClueView clueView : northClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : northClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : eastClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : eastClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : southClues) { - clueView.draw(graphics2D); - } + for (SkyscrapersClueView clueView : southClues) { + clueView.draw(graphics2D); + } - for (SkyscrapersClueView clueView : westClues) { - clueView.draw(graphics2D); + for (SkyscrapersClueView clueView : westClues) { + clueView.draw(graphics2D); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java index e66e67f1c..64c9033e6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/ClueTile.java @@ -4,11 +4,11 @@ public class ClueTile extends NonPlaceableElement { - public ClueTile() { - super( - "SKYS-UNPL-0003", - "Clue Tile", - "Clue Updater", - "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); - } + public ClueTile() { + super( + "SKYS-UNPL-0003", + "Clue Tile", + "Clue Updater", + "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java index 6df519c96..4d6b37c9a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/NumberTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class NumberTile extends NonPlaceableElement { - public NumberTile() { - super( - "SKYS-UNPL-0002", - "Number Tile", - "A numbered tile", - "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); - } + public NumberTile() { + super( + "SKYS-UNPL-0002", + "Number Tile", + "A numbered tile", + "edu/rpi/legup/images/skyscrapers/tiles/ClueTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java index ee25f38c0..2fb21193a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "SKYS-UNPL-0001", - "Unknown", - "A blank tile", - "edu/rpi/legup/images/skyscrapers/tiles/UnknownTile.png"); - } + public UnknownTile() { + super( + "SKYS-UNPL-0001", + "Unknown", + "A blank tile", + "edu/rpi/legup/images/skyscrapers/tiles/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java index 0889b0c25..45bdadea3 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/CellForNumberCaseRule.java @@ -12,184 +12,189 @@ import javax.swing.*; public class CellForNumberCaseRule extends CaseRule { - public CellForNumberCaseRule() { - super( - "SKYS-CASE-0002", - "Cell For Number", - "A number (1-n) must appear in any given row/column", - "edu/rpi/legup/images/skyscrapers/cases/CellForNumber.png"); - } - - private Integer selectedNumber; - - @Override - public CaseBoard getCaseBoard(Board board) { - SkyscrapersBoard currentBoard = (SkyscrapersBoard) board.copy(); - currentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(currentBoard, this); - for (SkyscrapersClue data : currentBoard.getWestClues()) { - // System.out.println(data.getType()); - caseBoard.addPickableElement(data); - } - for (SkyscrapersClue data : currentBoard.getNorthClues()) { - // System.out.println(data.getType()); - caseBoard.addPickableElement(data); + public CellForNumberCaseRule() { + super( + "SKYS-CASE-0002", + "Cell For Number", + "A number (1-n) must appear in any given row/column", + "edu/rpi/legup/images/skyscrapers/cases/CellForNumber.png"); } - // selects integer before checking Command.canExecute for use in Command.getErrorString - int size = ((SkyscrapersBoard) board).getWidth(); - Object[] possibleValues = new Object[size]; - for (int i = 0; i < size; i++) { - possibleValues[i] = i + 1; - } - Object selectedValue; - do { - selectedValue = - JOptionPane.showInputDialog( - null, - "Pick the number to be added", - "Cell For Number", - JOptionPane.INFORMATION_MESSAGE, - null, - possibleValues, - possibleValues[0]); - } while (selectedValue == null); - selectedNumber = (Integer) selectedValue; - - return caseBoard; - } - - public ArrayList getCasesFor(Board board, PuzzleElement puzzleElement, Integer number) { - ArrayList cases = new ArrayList<>(); - - SkyscrapersClue clue = (SkyscrapersClue) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - - List openCells = - skyscrapersboard.getRowCol( - clue.getClueIndex(), - SkyscrapersType.UNKNOWN, - clue.getType() == SkyscrapersType.CLUE_WEST); - for (SkyscrapersCell cell : openCells) { - SkyscrapersBoard newCase = skyscrapersboard.copy(); - PuzzleElement newCell = newCase.getPuzzleElement(cell); - newCell.setData(number); - newCase.addModifiedData(newCell); - - // if flags - boolean passed = true; - if (skyscrapersboard.getDupeFlag()) { - DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); - passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; - } - if (skyscrapersboard.getViewFlag()) { - PreemptiveVisibilityContradictionRule ViewRule = - new PreemptiveVisibilityContradictionRule(); - passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; - } - if (passed) { - cases.add(newCase); - } - } - return cases; - } - - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - return getCasesFor(board, puzzleElement, selectedNumber); - } - - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - SkyscrapersBoard oldBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - if (childTransitions.size() == 0) { - return "This case rule must have at least one child."; + private Integer selectedNumber; + + @Override + public CaseBoard getCaseBoard(Board board) { + SkyscrapersBoard currentBoard = (SkyscrapersBoard) board.copy(); + currentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(currentBoard, this); + for (SkyscrapersClue data : currentBoard.getWestClues()) { + // System.out.println(data.getType()); + caseBoard.addPickableElement(data); + } + for (SkyscrapersClue data : currentBoard.getNorthClues()) { + // System.out.println(data.getType()); + caseBoard.addPickableElement(data); + } + + // selects integer before checking Command.canExecute for use in Command.getErrorString + int size = ((SkyscrapersBoard) board).getWidth(); + Object[] possibleValues = new Object[size]; + for (int i = 0; i < size; i++) { + possibleValues[i] = i + 1; + } + Object selectedValue; + do { + selectedValue = + JOptionPane.showInputDialog( + null, + "Pick the number to be added", + "Cell For Number", + JOptionPane.INFORMATION_MESSAGE, + null, + possibleValues, + possibleValues[0]); + } while (selectedValue == null); + selectedNumber = (Integer) selectedValue; + + return caseBoard; } - if (childTransitions.size() - != getCasesFor( - oldBoard, - oldBoard.getPuzzleElement(transition.getSelection()), - (Integer) - childTransitions - .get(0) - .getBoard() - .getModifiedData() - .iterator() - .next() - .getData()) - .size()) { - // System.out.println("Wrong number of cases."); - return "Wrong number of cases."; + public ArrayList getCasesFor(Board board, PuzzleElement puzzleElement, Integer number) { + ArrayList cases = new ArrayList<>(); + + SkyscrapersClue clue = (SkyscrapersClue) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + + List openCells = + skyscrapersboard.getRowCol( + clue.getClueIndex(), + SkyscrapersType.UNKNOWN, + clue.getType() == SkyscrapersType.CLUE_WEST); + for (SkyscrapersCell cell : openCells) { + SkyscrapersBoard newCase = skyscrapersboard.copy(); + PuzzleElement newCell = newCase.getPuzzleElement(cell); + newCell.setData(number); + newCase.addModifiedData(newCell); + + // if flags + boolean passed = true; + if (skyscrapersboard.getDupeFlag()) { + DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); + passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; + } + if (skyscrapersboard.getViewFlag()) { + PreemptiveVisibilityContradictionRule ViewRule = + new PreemptiveVisibilityContradictionRule(); + passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; + } + if (passed) { + cases.add(newCase); + } + } + return cases; } - for (TreeTransition newTree : childTransitions) { - SkyscrapersBoard newBoard = (SkyscrapersBoard) newTree.getBoard(); - if (newBoard.getModifiedData().size() != 1) { - // System.out.println("Only one cell should be modified."); - return "Only one cell should be modified."; - } - SkyscrapersCell newCell = (SkyscrapersCell) newBoard.getModifiedData().iterator().next(); - if (newCell.getType() != SkyscrapersType.Number) { - // System.out.println("Changed value should be a number."); - return "Changed value should be a number."; - } + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + return getCasesFor(board, puzzleElement, selectedNumber); } - return null; - } - - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; - SkyscrapersClue clue = (SkyscrapersClue) puzzleBoard.getPuzzleElement(puzzleElement); - - // check each point in modified row/col - List data = - puzzleBoard.getRowCol( - clue.getClueIndex(), SkyscrapersType.ANY, clue.getType() == SkyscrapersType.CLUE_WEST); - for (SkyscrapersCell point : data) { - List cells = new ArrayList<>(List.of(point)); - - // if dependent on row/col - if ((puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) - && point.getType() == SkyscrapersType.UNKNOWN) { - // get perpendicular row/col intersecting this point - int index; - if (clue.getType() == SkyscrapersType.CLUE_WEST) { - index = point.getLocation().x; - } else { - index = point.getLocation().y; + + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + SkyscrapersBoard oldBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + if (childTransitions.size() == 0) { + return "This case rule must have at least one child."; } - cells.addAll( - puzzleBoard.getRowCol( - index, SkyscrapersType.ANY, clue.getType() != SkyscrapersType.CLUE_WEST)); - } - - // add all to result - for (SkyscrapersCell cell : cells) { - if (!elements.contains(board.getPuzzleElement(cell))) { - elements.add(board.getPuzzleElement(cell)); + + if (childTransitions.size() + != getCasesFor( + oldBoard, + oldBoard.getPuzzleElement(transition.getSelection()), + (Integer) + childTransitions + .get(0) + .getBoard() + .getModifiedData() + .iterator() + .next() + .getData()) + .size()) { + // System.out.println("Wrong number of cases."); + return "Wrong number of cases."; } - } + + for (TreeTransition newTree : childTransitions) { + SkyscrapersBoard newBoard = (SkyscrapersBoard) newTree.getBoard(); + if (newBoard.getModifiedData().size() != 1) { + // System.out.println("Only one cell should be modified."); + return "Only one cell should be modified."; + } + SkyscrapersCell newCell = + (SkyscrapersCell) newBoard.getModifiedData().iterator().next(); + if (newCell.getType() != SkyscrapersType.Number) { + // System.out.println("Changed value should be a number."); + return "Changed value should be a number."; + } + } + return null; } - return elements; - } + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; + SkyscrapersClue clue = (SkyscrapersClue) puzzleBoard.getPuzzleElement(puzzleElement); + + // check each point in modified row/col + List data = + puzzleBoard.getRowCol( + clue.getClueIndex(), + SkyscrapersType.ANY, + clue.getType() == SkyscrapersType.CLUE_WEST); + for (SkyscrapersCell point : data) { + List cells = new ArrayList<>(List.of(point)); + + // if dependent on row/col + if ((puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) + && point.getType() == SkyscrapersType.UNKNOWN) { + // get perpendicular row/col intersecting this point + int index; + if (clue.getType() == SkyscrapersType.CLUE_WEST) { + index = point.getLocation().x; + } else { + index = point.getLocation().y; + } + cells.addAll( + puzzleBoard.getRowCol( + index, + SkyscrapersType.ANY, + clue.getType() != SkyscrapersType.CLUE_WEST)); + } + + // add all to result + for (SkyscrapersCell cell : cells) { + if (!elements.contains(board.getPuzzleElement(cell))) { + elements.add(board.getPuzzleElement(cell)); + } + } + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java index 194bb905b..b13a62bc6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/DuplicateNumberContradictionRule.java @@ -12,57 +12,57 @@ public class DuplicateNumberContradictionRule extends ContradictionRule { - public DuplicateNumberContradictionRule() { - super( - "SKYS-CONT-0001", - "Duplicate Number", - "Skyscrapers of same height cannot be placed in the same row or column.", - "edu/rpi/legup/images/skyscrapers/contradictions/DuplicateNumber.png"); - } + public DuplicateNumberContradictionRule() { + super( + "SKYS-CONT-0001", + "Duplicate Number", + "Skyscrapers of same height cannot be placed in the same row or column.", + "edu/rpi/legup/images/skyscrapers/contradictions/DuplicateNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - Set candidates = new HashSet(); + Set candidates = new HashSet(); - // check row - for (int i = 0; i < skyscrapersboard.getWidth(); i++) { - SkyscrapersCell c = skyscrapersboard.getCell(i, loc.y); - if (i != loc.x - && cell.getType() == SkyscrapersType.Number - && c.getType() == SkyscrapersType.Number - && c.getData() == cell.getData()) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - return null; - } - } + // check row + for (int i = 0; i < skyscrapersboard.getWidth(); i++) { + SkyscrapersCell c = skyscrapersboard.getCell(i, loc.y); + if (i != loc.x + && cell.getType() == SkyscrapersType.Number + && c.getType() == SkyscrapersType.Number + && c.getData() == cell.getData()) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + return null; + } + } - // check column - for (int i = 0; i < skyscrapersboard.getHeight(); i++) { - SkyscrapersCell c = skyscrapersboard.getCell(loc.x, i); - if (i != loc.y - && cell.getType() == SkyscrapersType.Number - && c.getType() == SkyscrapersType.Number - && c.getData() == cell.getData()) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - return null; - } - } + // check column + for (int i = 0; i < skyscrapersboard.getHeight(); i++) { + SkyscrapersCell c = skyscrapersboard.getCell(loc.x, i); + if (i != loc.y + && cell.getType() == SkyscrapersType.Number + && c.getType() == SkyscrapersType.Number + && c.getData() == cell.getData()) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + return null; + } + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java index 08929e856..742bdb253 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/ExceedingVisibilityContradictionRule.java @@ -12,127 +12,128 @@ public class ExceedingVisibilityContradictionRule extends ContradictionRule { - public ExceedingVisibilityContradictionRule() { - super( - "SKYS-CONT-0002", - "Exceeding Visibility", - "More skyscrapers are visible than there should be.", - "edu/rpi/legup/images/skyscrapers/contradictions/ExceedingVisibility.png"); - } + public ExceedingVisibilityContradictionRule() { + super( + "SKYS-CONT-0002", + "Exceeding Visibility", + "More skyscrapers are visible than there should be.", + "edu/rpi/legup/images/skyscrapers/contradictions/ExceedingVisibility.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - // get borders - int west = skyscrapersboard.getWestClues().get(loc.y).getData(); - int east = skyscrapersboard.getEastClues().get(loc.y).getData(); - int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); - int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); + // get borders + int west = skyscrapersboard.getWestClues().get(loc.y).getData(); + int east = skyscrapersboard.getEastClues().get(loc.y).getData(); + int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); + int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); - // check row - int max = 0; - int count = 0; - List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); - if (row.size() == skyscrapersboard.getWidth()) { - // from west border - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > west) { - return null; - } + // check row + int max = 0; + int count = 0; + List row = skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); + if (row.size() == skyscrapersboard.getWidth()) { + // from west border + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > west) { + return null; + } - max = 0; - count = 0; - // from east border - Collections.reverse(row); - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; + max = 0; + count = 0; + // from east border + Collections.reverse(row); + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > east) { + return null; + } } - } - if (count > east) { - return null; - } - } - // check column - List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); - if (col.size() == skyscrapersboard.getHeight()) { - // from north border - max = 0; - count = 0; - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // check column + List col = + skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); + if (col.size() == skyscrapersboard.getHeight()) { + // from north border + max = 0; + count = 0; + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count > north) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > north) { + return null; + } - // from south border - max = 0; - count = 0; - Collections.reverse(col); - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // from south border + max = 0; + count = 0; + Collections.reverse(col); + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count > south) { + return null; + } } - } - if (count > south) { - return null; - } - } - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); - } + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } - /** - * Checks whether the Skyscraper cell has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the Skyscraper cell contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } + /** + * Checks whether the Skyscraper cell has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the Skyscraper cell contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; } - return "No instance of the contradiction " + this.ruleName + " here"; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java index d969a3415..fa7c9074e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/InsufficientVisibilityContradictionRule.java @@ -12,128 +12,129 @@ public class InsufficientVisibilityContradictionRule extends ContradictionRule { - public InsufficientVisibilityContradictionRule() { - super( - "SKYS-CONT-0003", - "Insufficient Visibility", - "Less skyscrapers are visible than there should be.", - "edu/rpi/legup/images/skyscrapers/contradictions/InsufficientVisibility.png"); - } + public InsufficientVisibilityContradictionRule() { + super( + "SKYS-CONT-0003", + "Insufficient Visibility", + "Less skyscrapers are visible than there should be.", + "edu/rpi/legup/images/skyscrapers/contradictions/InsufficientVisibility.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); - // get borders - int west = skyscrapersboard.getWestClues().get(loc.y).getData(); - int east = skyscrapersboard.getEastClues().get(loc.y).getData(); - int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); - int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); + // get borders + int west = skyscrapersboard.getWestClues().get(loc.y).getData(); + int east = skyscrapersboard.getEastClues().get(loc.y).getData(); + int north = skyscrapersboard.getNorthClues().get(loc.x).getData(); + int south = skyscrapersboard.getSouthClues().get(loc.x).getData(); - // check row - int max = 0; - int count = 0; - java.util.List row = - skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); - if (row.size() == skyscrapersboard.getWidth()) { - // from west border - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < west) { - return null; - } + // check row + int max = 0; + int count = 0; + java.util.List row = + skyscrapersboard.getRowCol(loc.y, SkyscrapersType.Number, true); + if (row.size() == skyscrapersboard.getWidth()) { + // from west border + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < west) { + return null; + } - max = 0; - count = 0; - // from east border - Collections.reverse(row); - for (SkyscrapersCell c : row) { - if (c.getData() > max) { - // System.out.print(c.getData()); - // System.out.println(cell.getData()); - max = c.getData(); - count++; + max = 0; + count = 0; + // from east border + Collections.reverse(row); + for (SkyscrapersCell c : row) { + if (c.getData() > max) { + // System.out.print(c.getData()); + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < east) { + return null; + } } - } - if (count < east) { - return null; - } - } - // check column - List col = skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); - if (col.size() == skyscrapersboard.getHeight()) { - // from north border - max = 0; - count = 0; - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // check column + List col = + skyscrapersboard.getRowCol(loc.x, SkyscrapersType.Number, false); + if (col.size() == skyscrapersboard.getHeight()) { + // from north border + max = 0; + count = 0; + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; - } - } - if (count < north) { - return null; - } + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < north) { + return null; + } - // from south border - max = 0; - count = 0; - Collections.reverse(col); - for (SkyscrapersCell c : col) { - // System.out.println(c.getData()); - if (c.getData() > max) { + // from south border + max = 0; + count = 0; + Collections.reverse(col); + for (SkyscrapersCell c : col) { + // System.out.println(c.getData()); + if (c.getData() > max) { - // System.out.println(cell.getData()); - max = c.getData(); - count++; + // System.out.println(cell.getData()); + max = c.getData(); + count++; + } + } + if (count < south) { + return null; + } } - } - if (count < south) { - return null; - } - } - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); - } + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } - /** - * Checks whether the Skyscraper cell has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the Skyscraper cell contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } + /** + * Checks whether the Skyscraper cell has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the Skyscraper cell contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; } - return "No instance of the contradiction " + this.ruleName + " here"; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java index 3d8649290..391448781 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularCellDirectRule.java @@ -12,115 +12,118 @@ public class LastSingularCellDirectRule extends DirectRule { - public LastSingularCellDirectRule() { - super( - "SKYS-BASC-0002", - "Last Cell for Number", - "There is only one cell on this row/col for this number that does not create a" - + " duplicate contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN - && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + public LastSingularCellDirectRule() { + super( + "SKYS-BASC-0002", + "Last Cell for Number", + "There is only one cell on this row/col for this number that does not create a" + + " duplicate contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastCell.png"); } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getWestClues().get(finalCell.getLocation().y), - (Integer) finalCell.getData()); - ArrayList YCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getNorthClues().get(finalCell.getLocation().x), - (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN + && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } - // System.out.println(XCandidates.size()); - // System.out.println(YCandidates.size()); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getWestClues().get(finalCell.getLocation().y), + (Integer) finalCell.getData()); + ArrayList YCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getNorthClues().get(finalCell.getLocation().x), + (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - // return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; - } + // System.out.println(XCandidates.size()); + // System.out.println(YCandidates.size()); - // helper to check if candidate list is valid - private String candidateCheck( - ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() - == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; + // return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; } - return ": This cell is not forced."; - } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + // helper to check if candidate list is valid + private String candidateCheck( + ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() + == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() + == finalCell.getData()) { + return null; + } + return ": Wrong number in the cell."; + } + return ": No case for this cell."; + } + return ": This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java index f95c1ace2..fceee0cd1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastSingularNumberDirectRule.java @@ -12,89 +12,92 @@ public class LastSingularNumberDirectRule extends DirectRule { - public LastSingularNumberDirectRule() { - super( - "SKYS-BASC-0003", - "Last Number for Cell", - "There is only one number for this cell that does not create a duplicate" - + " contradiction", - "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; + public LastSingularNumberDirectRule() { + super( + "SKYS-BASC-0003", + "Last Number for Cell", + "There is only one number for this cell that does not create a duplicate" + + " contradiction", + "edu/rpi/legup/images/skyscrapers/rules/LastNumber.png"); } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(true); - initialBoard.setViewFlag(false); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; - } + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(true); + initialBoard.setViewFlag(false); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + // check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() + == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; + } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java index 8658942e2..a853c657d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleCellDirectRule.java @@ -12,118 +12,121 @@ public class LastVisibleCellDirectRule extends DirectRule { - public LastVisibleCellDirectRule() { - super( - "SKYS-BASC-0001", - "Last Visible Cell", - "There is only one cell on this row/col for this number that does not create a" - + " visibility contradiction", - "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - // last cell for number based on preemptive visibility rules - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; + public LastVisibleCellDirectRule() { + super( + "SKYS-BASC-0001", + "Last Visible Cell", + "There is only one cell on this row/col for this number that does not create a" + + " visibility contradiction", + "edu/rpi/legup/images/skyscrapers/rules/FixedMax.png"); } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - ArrayList XCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getWestClues().get(finalCell.getLocation().y), - (Integer) finalCell.getData()); - ArrayList YCandidates = - caseRule.getCasesFor( - initialBoard, - initialBoard.getNorthClues().get(finalCell.getLocation().x), - (Integer) finalCell.getData()); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + // last cell for number based on preemptive visibility rules + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // System.out.println(XCandidates.size()); - // System.out.println(YCandidates.size()); + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + ArrayList XCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getWestClues().get(finalCell.getLocation().y), + (Integer) finalCell.getData()); + ArrayList YCandidates = + caseRule.getCasesFor( + initialBoard, + initialBoard.getNorthClues().get(finalCell.getLocation().x), + (Integer) finalCell.getData()); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - // return null if either pass, both messages otherwise - String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); - String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); - if (xCheck == null || yCheck == null) { - return null; - } - return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; - } + // System.out.println(XCandidates.size()); + // System.out.println(YCandidates.size()); - // helper to check if candidate list is valid - private String candidateCheck( - ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { - if (candidates.size() == 1) { - if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() - == SkyscrapersType.Number) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; + // return null if either pass, both messages otherwise + String xCheck = candidateCheck(XCandidates, puzzleElement, finalCell); + String yCheck = candidateCheck(YCandidates, puzzleElement, finalCell); + if (xCheck == null || yCheck == null) { + return null; } - return ": Wrong number in the cell."; - } - return ": No case for this cell."; + return super.getInvalidUseOfRuleMessage() + "\nRow" + xCheck + "\nCol" + yCheck; } - return ": This cell is not forced."; - } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + // helper to check if candidate list is valid + private String candidateCheck( + ArrayList candidates, PuzzleElement puzzleElement, SkyscrapersCell finalCell) { + if (candidates.size() == 1) { + if (((SkyscrapersCell) candidates.get(0).getPuzzleElement(puzzleElement)).getType() + == SkyscrapersType.Number) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() + == finalCell.getData()) { + return null; + } + return ": Wrong number in the cell."; + } + return ": No case for this cell."; + } + return ": This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(modBoard.getPuzzleElements().size()); - for (PuzzleElement element : modBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - modBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - // System.out.println(modBoard.getModifiedData().isEmpty()); - if (modBoard.getModifiedData().isEmpty()) { - return null; - } else { - return modBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard modBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(modBoard.getPuzzleElements().size()); + for (PuzzleElement element : modBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + modBoard.addModifiedData(cell); + } + } + // System.out.println(modBoard.getModifiedData().isEmpty()); + if (modBoard.getModifiedData().isEmpty()) { + return null; + } else { + return modBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java index 199c6f0f9..da1057b56 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/LastVisibleNumberDirectRule.java @@ -12,90 +12,93 @@ public class LastVisibleNumberDirectRule extends DirectRule { - public LastVisibleNumberDirectRule() { - super( - "SKYS-BASC-0005", - "Last Visible Number", - "There is only one number for this cell that does not create a visibility" - + " contradiction", - "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - // last number for cell based upon preemptive visibility rules - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (initCell.getType() != SkyscrapersType.UNKNOWN - || finalCell.getType() != SkyscrapersType.Number) { - return super.getInvalidUseOfRuleMessage() - + ": Modified cells must transition from unknown to number"; + public LastVisibleNumberDirectRule() { + super( + "SKYS-BASC-0005", + "Last Visible Number", + "There is only one number for this cell that does not create a visibility" + + " contradiction", + "edu/rpi/legup/images/skyscrapers/rules/OneEdge.png"); } - // set all rules used by case rule to false except for dupe, get all cases - boolean dupeTemp = initialBoard.getDupeFlag(); - boolean viewTemp = initialBoard.getViewFlag(); - initialBoard.setDupeFlag(false); - initialBoard.setViewFlag(true); - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); - initialBoard.setDupeFlag(dupeTemp); - initialBoard.setViewFlag(viewTemp); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + // last number for cell based upon preemptive visibility rules + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (initCell.getType() != SkyscrapersType.UNKNOWN + || finalCell.getType() != SkyscrapersType.Number) { + return super.getInvalidUseOfRuleMessage() + + ": Modified cells must transition from unknown to number"; + } - // check if given value is the only remaining value - if (candidates.size() == 1) { - if (candidates.get(0).getPuzzleElement(puzzleElement).getData() == finalCell.getData()) { - return null; - } - return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; - } - return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; - } + // set all rules used by case rule to false except for dupe, get all cases + boolean dupeTemp = initialBoard.getDupeFlag(); + boolean viewTemp = initialBoard.getViewFlag(); + initialBoard.setDupeFlag(false); + initialBoard.setViewFlag(true); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList candidates = caseRule.getCases(initialBoard, puzzleElement); + initialBoard.setDupeFlag(dupeTemp); + initialBoard.setViewFlag(viewTemp); - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + // check if given value is the only remaining value + if (candidates.size() == 1) { + if (candidates.get(0).getPuzzleElement(puzzleElement).getData() + == finalCell.getData()) { + return null; + } + return super.getInvalidUseOfRuleMessage() + ": Wrong number in the cell."; + } + return super.getInvalidUseOfRuleMessage() + ":This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java index 2ddb588cd..bbc202e72 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NEdgeDirectRule.java @@ -12,93 +12,95 @@ public class NEdgeDirectRule extends DirectRule { - public NEdgeDirectRule() { - super( - "SKYS-BASC-0004", - "N Edge", - "If the maximum number appears on an edge, the row or column's numbers appear in" - + " ascending order, starting at that edge.", - "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) transition.getParents().get(0).getBoard(); - SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); - SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == SkyscrapersType.UNKNOWN - && finalCell.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + public NEdgeDirectRule() { + super( + "SKYS-BASC-0004", + "N Edge", + "If the maximum number appears on an edge, the row or column's numbers appear in" + + " ascending order, starting at that edge.", + "edu/rpi/legup/images/skyscrapers/rules/NEdge.png"); } - SkyscrapersBoard emptyCase = initialBoard.copy(); - emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); - Point loc = finalCell.getLocation(); - int max = initialBoard.getHeight(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SkyscrapersBoard initialBoard = + (SkyscrapersBoard) transition.getParents().get(0).getBoard(); + SkyscrapersCell initCell = (SkyscrapersCell) initialBoard.getPuzzleElement(puzzleElement); + SkyscrapersBoard finalBoard = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell finalCell = (SkyscrapersCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == SkyscrapersType.UNKNOWN + && finalCell.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + ": Modified cells must be number"; + } - if (initialBoard.getWestClues().get(loc.y).getData() == max - && finalCell.getData() == loc.x + 1) { - return null; - } - if (initialBoard.getEastClues().get(loc.y).getData() == max - && finalCell.getData() == max - loc.x) { - return null; - } - if (initialBoard.getNorthClues().get(loc.x).getData() == max - && finalCell.getData() == loc.y + 1) { - return null; - } - if (initialBoard.getSouthClues().get(loc.x).getData() == max - && finalCell.getData() == max - loc.y) { - return null; - } + SkyscrapersBoard emptyCase = initialBoard.copy(); + emptyCase.getPuzzleElement(finalCell).setData(SkyscrapersType.UNKNOWN.value); + Point loc = finalCell.getLocation(); + int max = initialBoard.getHeight(); - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; - } + if (initialBoard.getWestClues().get(loc.y).getData() == max + && finalCell.getData() == loc.x + 1) { + return null; + } + if (initialBoard.getEastClues().get(loc.y).getData() == max + && finalCell.getData() == max - loc.x) { + return null; + } + if (initialBoard.getNorthClues().get(loc.x).getData() == max + && finalCell.getData() == loc.y + 1) { + return null; + } + if (initialBoard.getSouthClues().get(loc.x).getData() == max + && finalCell.getData() == max - loc.y) { + return null; + } - private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { - SkyscrapersBoard emptyCase = board.copy(); - emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); - DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); - if (duplicate.checkContradictionAt(emptyCase, cell) == null) { - System.out.println("no contradiction ln"); - return true; + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced."; } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); - // System.out.println(lightUpBoard.getPuzzleElements().size()); - for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { - SkyscrapersCell cell = (SkyscrapersCell) element; - if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { - // cell.setData(SkyscrapersType.BULB.value); - lightUpBoard.addModifiedData(cell); - } + private boolean isForced(SkyscrapersBoard board, SkyscrapersCell cell) { + SkyscrapersBoard emptyCase = board.copy(); + emptyCase.getPuzzleElement(cell).setData(SkyscrapersType.UNKNOWN.value); + DuplicateNumberContradictionRule duplicate = new DuplicateNumberContradictionRule(); + if (duplicate.checkContradictionAt(emptyCase, cell) == null) { + System.out.println("no contradiction ln"); + return true; + } + return false; } - if (lightUpBoard.getModifiedData().isEmpty()) { - return null; - } else { - return lightUpBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + SkyscrapersBoard initialBoard = (SkyscrapersBoard) node.getBoard(); + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) node.getBoard().copy(); + // System.out.println(lightUpBoard.getPuzzleElements().size()); + for (PuzzleElement element : lightUpBoard.getPuzzleElements()) { + SkyscrapersCell cell = (SkyscrapersCell) element; + if (cell.getType() == SkyscrapersType.UNKNOWN && isForced(initialBoard, cell)) { + // cell.setData(SkyscrapersType.BULB.value); + lightUpBoard.addModifiedData(cell); + } + } + if (lightUpBoard.getModifiedData().isEmpty()) { + return null; + } else { + return lightUpBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java index 9b6f67ca0..145dd6ee2 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/NumberForCellCaseRule.java @@ -16,158 +16,166 @@ public class NumberForCellCaseRule extends CaseRule { - public NumberForCellCaseRule() { - super( - "SKYS-CASE-0001", - "Number For Cell", - "A blank cell must have height of 1 to n.", - "edu/rpi/legup/images/skyscrapers/cases/NumberForCell.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) board.copy(); - lightUpBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); - for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { - if (((SkyscrapersCell) data).getType() == SkyscrapersType.UNKNOWN) { - caseBoard.addPickableElement(data); - } - } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement puzzleElement to determine the possible cases for - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; - Point loc = cell.getLocation(); - - Set candidates = new HashSet(); - for (int i = 1; i <= skyscrapersboard.getWidth(); i++) { - Board newCase = board.copy(); - PuzzleElement newCell = newCase.getPuzzleElement(puzzleElement); - newCell.setData(i); - newCase.addModifiedData(newCell); - - // if flags - boolean passed = true; - if (skyscrapersboard.getDupeFlag()) { - DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); - passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; - } - if (skyscrapersboard.getViewFlag()) { - PreemptiveVisibilityContradictionRule ViewRule = - new PreemptiveVisibilityContradictionRule(); - passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; - } - // how should unresolved be handled? should it be? - if (passed) { - cases.add(newCase); - } + public NumberForCellCaseRule() { + super( + "SKYS-CASE-0001", + "Number For Cell", + "A blank cell must have height of 1 to n.", + "edu/rpi/legup/images/skyscrapers/cases/NumberForCell.png"); } - return cases; - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() == 0) { - return "This case rule must have at least one child."; - } else { - if (childTransitions.size() - != getCases( - transition.getBoard(), - childTransitions.get(0).getBoard().getModifiedData().iterator().next()) - .size()) { - return "Wrong number of children."; - } + @Override + public CaseBoard getCaseBoard(Board board) { + SkyscrapersBoard lightUpBoard = (SkyscrapersBoard) board.copy(); + lightUpBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(lightUpBoard, this); + for (PuzzleElement data : lightUpBoard.getPuzzleElements()) { + if (((SkyscrapersCell) data).getType() == SkyscrapersType.UNKNOWN) { + caseBoard.addPickableElement(data); + } + } + return caseBoard; } - // TreeTransition case1 = childTransitions.get(0); - // TreeTransition case2 = childTransitions.get(1); - TreeTransition case1 = childTransitions.get(0); - SkyscrapersCell mod1 = (SkyscrapersCell) case1.getBoard().getModifiedData().iterator().next(); - for (int i = 0; i < childTransitions.size(); i++) { - TreeTransition case2 = childTransitions.get(i); - if (case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } - SkyscrapersCell mod2 = (SkyscrapersCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } - if (!(mod2.getType() == SkyscrapersType.Number)) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must assign a number."; - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement puzzleElement to determine the possible cases for + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + SkyscrapersBoard skyscrapersboard = (SkyscrapersBoard) board; + Point loc = cell.getLocation(); + + Set candidates = new HashSet(); + for (int i = 1; i <= skyscrapersboard.getWidth(); i++) { + Board newCase = board.copy(); + PuzzleElement newCell = newCase.getPuzzleElement(puzzleElement); + newCell.setData(i); + newCase.addModifiedData(newCell); + + // if flags + boolean passed = true; + if (skyscrapersboard.getDupeFlag()) { + DuplicateNumberContradictionRule DupeRule = new DuplicateNumberContradictionRule(); + passed = passed && DupeRule.checkContradictionAt(newCase, newCell) != null; + } + if (skyscrapersboard.getViewFlag()) { + PreemptiveVisibilityContradictionRule ViewRule = + new PreemptiveVisibilityContradictionRule(); + passed = passed && ViewRule.checkContradictionAt(newCase, newCell) != null; + } + // how should unresolved be handled? should it be? + if (passed) { + cases.add(newCase); + } + } + + return cases; } - // System.out.println("no contradiction"); - return null; - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement index of the puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; - SkyscrapersCell point = (SkyscrapersCell) puzzleBoard.getPuzzleElement(puzzleElement); - - List cells = new ArrayList<>(List.of(point)); - - // if dependent on row/col - if (puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) { - // add all cells in row/col intersecting given point - cells.addAll(puzzleBoard.getRowCol(point.getLocation().x, SkyscrapersType.ANY, false)); - cells.addAll(puzzleBoard.getRowCol(point.getLocation().y, SkyscrapersType.ANY, true)); + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() == 0) { + return "This case rule must have at least one child."; + } else { + if (childTransitions.size() + != getCases( + transition.getBoard(), + childTransitions + .get(0) + .getBoard() + .getModifiedData() + .iterator() + .next()) + .size()) { + return "Wrong number of children."; + } + } + + // TreeTransition case1 = childTransitions.get(0); + // TreeTransition case2 = childTransitions.get(1); + TreeTransition case1 = childTransitions.get(0); + SkyscrapersCell mod1 = + (SkyscrapersCell) case1.getBoard().getModifiedData().iterator().next(); + for (int i = 0; i < childTransitions.size(); i++) { + TreeTransition case2 = childTransitions.get(i); + if (case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } + SkyscrapersCell mod2 = + (SkyscrapersCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } + if (!(mod2.getType() == SkyscrapersType.Number)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must assign a number."; + } + } + // System.out.println("no contradiction"); + return null; } - for (SkyscrapersCell cell : cells) { - if (!elements.contains(board.getPuzzleElement(cell))) { - elements.add(board.getPuzzleElement(cell)); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement index of the puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); } - return elements; - } + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + SkyscrapersBoard puzzleBoard = (SkyscrapersBoard) board; + SkyscrapersCell point = (SkyscrapersCell) puzzleBoard.getPuzzleElement(puzzleElement); + + List cells = new ArrayList<>(List.of(point)); + + // if dependent on row/col + if (puzzleBoard.getDupeFlag() || puzzleBoard.getViewFlag()) { + // add all cells in row/col intersecting given point + cells.addAll(puzzleBoard.getRowCol(point.getLocation().x, SkyscrapersType.ANY, false)); + cells.addAll(puzzleBoard.getRowCol(point.getLocation().y, SkyscrapersType.ANY, true)); + } + + for (SkyscrapersCell cell : cells) { + if (!elements.contains(board.getPuzzleElement(cell))) { + elements.add(board.getPuzzleElement(cell)); + } + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java index 3b1537917..dc274eb15 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/PreemptiveVisibilityContradictionRule.java @@ -13,185 +13,191 @@ public class PreemptiveVisibilityContradictionRule extends ContradictionRule { - public PreemptiveVisibilityContradictionRule() { - super( - "SKYS-CONT-0006", - "Preemptive Visibility", - "Visibility constraints are not met given an incomplete row/col", - "edu/rpi/legup/images/skyscrapers/contradictions/PreemptiveVisibility.png"); - } - - /** - * Checks whether there is an instance of a visibility contradiction in every possible row/col - * based on the specific puzzleElement index using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the all possible rows/cols contain a contradiction at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); - - // Initialize instances of necessary contradiction and case rules - InsufficientVisibilityContradictionRule tooFew = new InsufficientVisibilityContradictionRule(); - ExceedingVisibilityContradictionRule tooMany = new ExceedingVisibilityContradictionRule(); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - - // Initialize skyscraperBoard queues for rows and cols - Queue rowQ = new LinkedList<>(); - rowQ.add(skyscrapersBoard); - Queue colQ = new LinkedList<>(); - colQ.add(skyscrapersBoard); - - // find all cases for the corresponding row and column for each possible skyscraper height - - // Add every possible case for all heights for each corresponding row and column - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - int num = i + 1; - - // check row west clue - List rows; - - int size = rowQ.size(); - for (int j = 0; j < size; j++) { - SkyscrapersBoard temp = rowQ.poll(); // get row from the top of the stack - - // don't do anything if already in row - boolean exists = false; - for (SkyscrapersCell c : temp.getRowCol(loc.y, SkyscrapersType.Number, true)) { - if (c.getData() == num) { - exists = true; - break; - } - } + public PreemptiveVisibilityContradictionRule() { + super( + "SKYS-CONT-0006", + "Preemptive Visibility", + "Visibility constraints are not met given an incomplete row/col", + "edu/rpi/legup/images/skyscrapers/contradictions/PreemptiveVisibility.png"); + } - if (exists) { - rowQ.add(temp); - } else { - // set flags - boolean dupeTemp = temp.getDupeFlag(); - boolean viewTemp = temp.getViewFlag(); - temp.setDupeFlag(false); - temp.setViewFlag(false); - - // get all cases for corresponding row based on west clue - rows = caseRule.getCasesFor(temp, skyscrapersBoard.getWestClues().get(loc.y), num); - - // reset flags - temp.setDupeFlag(dupeTemp); - temp.setViewFlag(viewTemp); - - // add all row cases to row queue - for (Board k : rows) { - rowQ.add((SkyscrapersBoard) k); - } - } - } - - // check col north clue - List cols; - - size = colQ.size(); - for (int j = 0; j < size; j++) { - SkyscrapersBoard temp = colQ.poll(); // get row from the top of the stack - - // don't do anything if already in col - boolean exists = false; - for (SkyscrapersCell c : temp.getRowCol(loc.x, SkyscrapersType.Number, false)) { - if (c.getData() == num) { - exists = true; - break; - } + /** + * Checks whether there is an instance of a visibility contradiction in every possible row/col + * based on the specific puzzleElement index using this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the all possible rows/cols contain a contradiction at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); + + // Initialize instances of necessary contradiction and case rules + InsufficientVisibilityContradictionRule tooFew = + new InsufficientVisibilityContradictionRule(); + ExceedingVisibilityContradictionRule tooMany = new ExceedingVisibilityContradictionRule(); + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + + // Initialize skyscraperBoard queues for rows and cols + Queue rowQ = new LinkedList<>(); + rowQ.add(skyscrapersBoard); + Queue colQ = new LinkedList<>(); + colQ.add(skyscrapersBoard); + + // find all cases for the corresponding row and column for each possible skyscraper height + + // Add every possible case for all heights for each corresponding row and column + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + int num = i + 1; + + // check row west clue + List rows; + + int size = rowQ.size(); + for (int j = 0; j < size; j++) { + SkyscrapersBoard temp = rowQ.poll(); // get row from the top of the stack + + // don't do anything if already in row + boolean exists = false; + for (SkyscrapersCell c : temp.getRowCol(loc.y, SkyscrapersType.Number, true)) { + if (c.getData() == num) { + exists = true; + break; + } + } + + if (exists) { + rowQ.add(temp); + } else { + // set flags + boolean dupeTemp = temp.getDupeFlag(); + boolean viewTemp = temp.getViewFlag(); + temp.setDupeFlag(false); + temp.setViewFlag(false); + + // get all cases for corresponding row based on west clue + rows = + caseRule.getCasesFor( + temp, skyscrapersBoard.getWestClues().get(loc.y), num); + + // reset flags + temp.setDupeFlag(dupeTemp); + temp.setViewFlag(viewTemp); + + // add all row cases to row queue + for (Board k : rows) { + rowQ.add((SkyscrapersBoard) k); + } + } + } + + // check col north clue + List cols; + + size = colQ.size(); + for (int j = 0; j < size; j++) { + SkyscrapersBoard temp = colQ.poll(); // get row from the top of the stack + + // don't do anything if already in col + boolean exists = false; + for (SkyscrapersCell c : temp.getRowCol(loc.x, SkyscrapersType.Number, false)) { + if (c.getData() == num) { + exists = true; + break; + } + } + + if (exists) { + colQ.add(temp); + } else { + // set flags + boolean dupeTemp = temp.getDupeFlag(); + boolean viewTemp = temp.getViewFlag(); + temp.setDupeFlag(false); + temp.setViewFlag(false); + + // get all cases for corresponding col based on north clue + cols = + caseRule.getCasesFor( + temp, skyscrapersBoard.getNorthClues().get(loc.x), num); + + // reset flags + temp.setDupeFlag(dupeTemp); + temp.setViewFlag(viewTemp); + + // add all row cases to row queue + for (Board k : cols) { + colQ.add((SkyscrapersBoard) k); + } + } + } } - if (exists) { - colQ.add(temp); - } else { - // set flags - boolean dupeTemp = temp.getDupeFlag(); - boolean viewTemp = temp.getViewFlag(); - temp.setDupeFlag(false); - temp.setViewFlag(false); - - // get all cases for corresponding col based on north clue - cols = caseRule.getCasesFor(temp, skyscrapersBoard.getNorthClues().get(loc.x), num); - - // reset flags - temp.setDupeFlag(dupeTemp); - temp.setViewFlag(viewTemp); - - // add all row cases to row queue - for (Board k : cols) { - colQ.add((SkyscrapersBoard) k); - } + String rowTooFew; + String rowTooMany; + boolean rowContradiction = true; + // check if each case board has a contradiction + while (rowQ.size() > 0) { + SkyscrapersBoard fullRow = rowQ.poll(); + + // checks if there is a contradiction given the row based on the west clue + rowTooFew = + tooFew.checkContradictionAt( + fullRow, cell); // is cell the correct puzzle element to check? + rowTooMany = tooMany.checkContradictionAt(fullRow, cell); + + // boolean that checks if there is a contradiction within all rows + rowContradiction = + rowContradiction + && (rowTooFew == null + || rowTooMany + == null); // !null means there isn't a contradiction, so + // there must be a valid + // permutation of the array } - } - } - String rowTooFew; - String rowTooMany; - boolean rowContradiction = true; - // check if each case board has a contradiction - while (rowQ.size() > 0) { - SkyscrapersBoard fullRow = rowQ.poll(); - - // checks if there is a contradiction given the row based on the west clue - rowTooFew = - tooFew.checkContradictionAt( - fullRow, cell); // is cell the correct puzzle element to check? - rowTooMany = tooMany.checkContradictionAt(fullRow, cell); - - // boolean that checks if there is a contradiction within all rows - rowContradiction = - rowContradiction - && (rowTooFew == null - || rowTooMany == null); // !null means there isn't a contradiction, so - // there must be a valid - // permutation of the array - } + String colTooFew; + String colTooMany; + boolean colContradiction = true; + while (colQ.size() > 0) { + SkyscrapersBoard fullCol = colQ.poll(); - String colTooFew; - String colTooMany; - boolean colContradiction = true; - while (colQ.size() > 0) { - SkyscrapersBoard fullCol = colQ.poll(); + // checks if there is a contradiction given the col baesd on the north clue + colTooFew = tooFew.checkContradictionAt(fullCol, cell); + colTooMany = tooMany.checkContradictionAt(fullCol, cell); - // checks if there is a contradiction given the col baesd on the north clue - colTooFew = tooFew.checkContradictionAt(fullCol, cell); - colTooMany = tooMany.checkContradictionAt(fullCol, cell); + // boolean that checks if there is a contradiction within all the cols + colContradiction = colContradiction && (colTooFew == null || colTooMany == null); + } - // boolean that checks if there is a contradiction within all the cols - colContradiction = colContradiction && (colTooFew == null || colTooMany == null); + // if every possible permutation results in contradictions return null, else no + // contradiction + if (rowContradiction || colContradiction) { + return null; + } + return super.getNoContradictionMessage(); } - // if every possible permutation results in contradictions return null, else no - // contradiction - if (rowContradiction || colContradiction) { - return null; - } - return super.getNoContradictionMessage(); - } - - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return checkStr; - } + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return checkStr; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; } - return "No instance of the contradiction " + this.ruleName + " here"; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java index a34fe0730..d4a3d0486 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedCellContradictionRule.java @@ -8,33 +8,33 @@ public class UnresolvedCellContradictionRule extends ContradictionRule { - public UnresolvedCellContradictionRule() { - super( - "SKYS-CONT-0004", - "Unresolved Cell", - "Elimination leaves no possible number for a cell.", - "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedCell.png"); - } + public UnresolvedCellContradictionRule() { + super( + "SKYS-CONT-0004", + "Unresolved Cell", + "Elimination leaves no possible number for a cell.", + "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedCell.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); - ArrayList cases = caseRule.getCases(board, puzzleElement); + NumberForCellCaseRule caseRule = new NumberForCellCaseRule(); + ArrayList cases = caseRule.getCases(board, puzzleElement); - if (cases.size() == 0) { - return null; - } + if (cases.size() == 0) { + return null; + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java index e4e1152e9..fed429988 100644 --- a/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/skyscrapers/rules/UnresolvedNumberContradictionRule.java @@ -10,90 +10,92 @@ public class UnresolvedNumberContradictionRule extends ContradictionRule { - public UnresolvedNumberContradictionRule() { - super( - "SKYS-CONT-0005", - "Unresolved Number", - "No possible cell for a number without a duplicate contradiction.", - // specify a number? defaulting to every number for now. expand to more than - // duplicate? - "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedNumber.png"); - } + public UnresolvedNumberContradictionRule() { + super( + "SKYS-CONT-0005", + "Unresolved Number", + "No possible cell for a number without a duplicate contradiction.", + // specify a number? defaulting to every number for now. expand to more than + // duplicate? + "edu/rpi/legup/images/skyscrapers/contradictions/UnresolvedNumber.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; - Point loc = cell.getLocation(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + SkyscrapersCell cell = (SkyscrapersCell) puzzleElement; + Point loc = cell.getLocation(); - CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - int num = i + 1; - // check row - // isn't already present - boolean exists = false; - for (SkyscrapersCell presentCell : - skyscrapersBoard.getRowCol(loc.y, SkyscrapersType.Number, true)) { - if (presentCell.getData() == num) { - exists = true; - break; - } - } - if (!exists) { - // and no possible cases - if (caseRule.getCasesFor(board, skyscrapersBoard.getWestClues().get(loc.y), num).size() - == 0) { - return null; - } - } + CellForNumberCaseRule caseRule = new CellForNumberCaseRule(); + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + int num = i + 1; + // check row + // isn't already present + boolean exists = false; + for (SkyscrapersCell presentCell : + skyscrapersBoard.getRowCol(loc.y, SkyscrapersType.Number, true)) { + if (presentCell.getData() == num) { + exists = true; + break; + } + } + if (!exists) { + // and no possible cases + if (caseRule.getCasesFor(board, skyscrapersBoard.getWestClues().get(loc.y), num) + .size() + == 0) { + return null; + } + } - // check col - // same process as for row - exists = false; - for (SkyscrapersCell presentCell : - skyscrapersBoard.getRowCol(loc.x, SkyscrapersType.Number, false)) { - if (presentCell.getData() == num) { - exists = true; - break; - } - } - if (!exists) { - if (caseRule.getCasesFor(board, skyscrapersBoard.getNorthClues().get(loc.x), num).size() - == 0) { - return null; + // check col + // same process as for row + exists = false; + for (SkyscrapersCell presentCell : + skyscrapersBoard.getRowCol(loc.x, SkyscrapersType.Number, false)) { + if (presentCell.getData() == num) { + exists = true; + break; + } + } + if (!exists) { + if (caseRule.getCasesFor(board, skyscrapersBoard.getNorthClues().get(loc.x), num) + .size() + == 0) { + return null; + } + } } - } - } - // System.out.print("Does not contain a contradiction at this index"); - return super.getNoContradictionMessage(); - } + // System.out.print("Does not contain a contradiction at this index"); + return super.getNoContradictionMessage(); + } - /** - * Checks whether the tree node has a contradiction using this rule - * - * @param board board to check contradiction - * @return null if the tree node contains a contradiction, otherwise error message - */ - @Override - public String checkContradiction(Board board) { - SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; - for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { - // checks the middle diagonal (checkContradictionAt checks row/col off each) - String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); - if (checkStr == null) { - return null; - } + /** + * Checks whether the tree node has a contradiction using this rule + * + * @param board board to check contradiction + * @return null if the tree node contains a contradiction, otherwise error message + */ + @Override + public String checkContradiction(Board board) { + SkyscrapersBoard skyscrapersBoard = (SkyscrapersBoard) board; + for (int i = 0; i < skyscrapersBoard.getWidth(); i++) { + // checks the middle diagonal (checkContradictionAt checks row/col off each) + String checkStr = checkContradictionAt(board, skyscrapersBoard.getCell(i, i)); + if (checkStr == null) { + return null; + } + } + return "No instance of the contradiction " + this.ruleName + " here"; } - return "No instance of the contradiction " + this.ruleName + " here"; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java index e0583a13b..a7cd9ac12 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/GroupType.java @@ -1,7 +1,7 @@ package edu.rpi.legup.puzzle.sudoku; public enum GroupType { - REGION, - ROW, - COLUMN + REGION, + ROW, + COLUMN } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java index e81bc909e..0b6971235 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/PossibleNumberCaseBoard.java @@ -9,76 +9,76 @@ public class PossibleNumberCaseBoard extends CaseBoard { - private SudokuCell cell; - private Set pickableRegions; - private Set pickableRows; - private Set pickableCols; + private SudokuCell cell; + private Set pickableRegions; + private Set pickableRows; + private Set pickableCols; - public PossibleNumberCaseBoard( - SudokuBoard baseBoard, PossibleNumberCaseRule caseRule, SudokuCell cell) { - super(baseBoard, caseRule); - this.cell = cell; - this.pickableRegions = new HashSet<>(); - this.pickableRows = new HashSet<>(); - this.pickableCols = new HashSet<>(); - } - - @Override - public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { - if (e == null) { - return false; + public PossibleNumberCaseBoard( + SudokuBoard baseBoard, PossibleNumberCaseRule caseRule, SudokuCell cell) { + super(baseBoard, caseRule); + this.cell = cell; + this.pickableRegions = new HashSet<>(); + this.pickableRows = new HashSet<>(); + this.pickableCols = new HashSet<>(); } - SudokuCell sudokuCell = (SudokuCell) puzzleElement; - if (e.isShiftDown()) { - for (int r : pickableRows) { - if (r == sudokuCell.getLocation().y) { - return true; - } - } - } else { - if (e.isControlDown()) { - for (int c : pickableCols) { - if (c == sudokuCell.getLocation().x) { - return true; - } + @Override + public boolean isPickable(PuzzleElement puzzleElement, MouseEvent e) { + if (e == null) { + return false; } - } else { - for (int r : pickableRegions) { - if (r == sudokuCell.getGroupIndex()) { - return true; - } + + SudokuCell sudokuCell = (SudokuCell) puzzleElement; + if (e.isShiftDown()) { + for (int r : pickableRows) { + if (r == sudokuCell.getLocation().y) { + return true; + } + } + } else { + if (e.isControlDown()) { + for (int c : pickableCols) { + if (c == sudokuCell.getLocation().x) { + return true; + } + } + } else { + for (int r : pickableRegions) { + if (r == sudokuCell.getGroupIndex()) { + return true; + } + } + } } - } + return false; } - return false; - } - public void addPickableRegion(int region) { - this.pickableRegions.add(region); - } + public void addPickableRegion(int region) { + this.pickableRegions.add(region); + } - public void addPickableRow(int row) { - this.pickableRows.add(row); - } + public void addPickableRow(int row) { + this.pickableRows.add(row); + } - public void addPickableCol(int col) { - this.pickableCols.add(col); - } + public void addPickableCol(int col) { + this.pickableCols.add(col); + } - public SudokuCell getCell() { - return cell; - } + public SudokuCell getCell() { + return cell; + } - public Set getPickableRegions() { - return pickableRegions; - } + public Set getPickableRegions() { + return pickableRegions; + } - public Set getPickableRows() { - return pickableRows; - } + public Set getPickableRows() { + return pickableRows; + } - public Set getPickableCols() { - return pickableCols; - } + public Set getPickableCols() { + return pickableCols; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java index 30aa78aac..877c92665 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/Sudoku.java @@ -7,102 +7,102 @@ import edu.rpi.legup.ui.boardview.BoardView; public class Sudoku extends Puzzle { - private SudokuView boardView; - - /** Sudoku Constructor */ - public Sudoku() { - super(); - - this.name = "Sudoku"; - - this.importer = new SudokuImporter(this); - this.exporter = new SudokuExporter(this); - - this.factory = new SudokuCellFactory(); - } - - public BoardView getBoardView() { - return boardView; - } - - /** Initializes the game board */ - @Override - public void initializeView() { - boardView = new SudokuView((SudokuBoard) currentBoard); - } - - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } - - @Override - /** - * Determines if the given dimensions are valid for Sudoku - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Sudoku, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // The number of rows and columns must be greater than 1 - if (rows <= 1 || columns <= 1) { - return false; + private SudokuView boardView; + + /** Sudoku Constructor */ + public Sudoku() { + super(); + + this.name = "Sudoku"; + + this.importer = new SudokuImporter(this); + this.exporter = new SudokuExporter(this); + + this.factory = new SudokuCellFactory(); } - // The number of rows and columns must be equal - if (rows != columns) { - return false; + public BoardView getBoardView() { + return boardView; } - // For Sudoku, the number of rows and columns must be a perfect square - // Note: we don't need to check the columns since by this point, we have verified that the - // number of rows - // equals the number of columns - double sqrtRows = Math.sqrt(rows); - if (sqrtRows - Math.floor(sqrtRows) != 0) { - return false; + /** Initializes the game board */ + @Override + public void initializeView() { + boardView = new SudokuView((SudokuBoard) currentBoard); } - return true; - } - - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - - for (ContradictionRule rule : contradictionRules) { - if (rule.checkContradiction(sudokuBoard) == null) { - return false; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; } - for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { - SudokuCell cell = (SudokuCell) puzzleElement; - if (cell.getData() == 0) { - return false; - } + @Override + /** + * Determines if the given dimensions are valid for Sudoku + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Sudoku, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // The number of rows and columns must be greater than 1 + if (rows <= 1 || columns <= 1) { + return false; + } + + // The number of rows and columns must be equal + if (rows != columns) { + return false; + } + + // For Sudoku, the number of rows and columns must be a perfect square + // Note: we don't need to check the columns since by this point, we have verified that the + // number of rows + // equals the number of columns + double sqrtRows = Math.sqrt(rows); + if (sqrtRows - Math.floor(sqrtRows) != 0) { + return false; + } + + return true; } - return true; - } - - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + + for (ContradictionRule rule : contradictionRules) { + if (rule.checkContradiction(sudokuBoard) == null) { + return false; + } + } + + for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { + SudokuCell cell = (SudokuCell) puzzleElement; + if (cell.getData() == 0) { + return false; + } + } + return true; + } + + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java index 095dbf64c..46e6020bb 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuBoard.java @@ -7,166 +7,166 @@ import java.util.Set; public class SudokuBoard extends GridBoard { - private int size; - private int groupSize; - - /** - * SudokuBoard Constructor - create a new Sudoku board - * - * @param size size of one side of the sudoku board, must be an integer square root - */ - public SudokuBoard(int size) { - super(size, size); - this.size = size; - this.groupSize = (int) Math.sqrt(dimension.width); - } - - /** - * Gets a SudokuCell from the board - * - * @param x x location of the cell - * @param y y location of the cell - * @return SudokuCell at location (x, y) - */ - @Override - public SudokuCell getCell(int x, int y) { - return (SudokuCell) super.getCell(x, y); - } - - /** - * Gets the SudokuCell in the specified group index at the x and y location given The group index - * must be by less than the width (or height) of the board and the x and y location is relative to - * the group. This means the x and y values must be less the square root of the width (or height) - * of the board. - * - * @param groupIndex group index of the cell - * @param x x location relative to the group - * @param y y location relative to the group - * @return cell in the specified group index at the given x and y location - */ - public SudokuCell getCell(int groupIndex, int x, int y) { - return getCell( - x + (groupIndex % groupSize) * groupSize, y + (groupIndex / groupSize) * groupSize); - } - - /** - * Gets the size of the sudoku board Standard board is 9x9 - * - * @return size of the board - */ - public int getSize() { - return size; - } - - /** - * Gets the minor group size of the sudoku board Standard board is 3x3x3x3 - * - * @return minor group size - */ - public int getGroupSize() { - return groupSize; - } - - /** - * Gets all the cells in the specified row - * - * @param rowNum row index - * @return list of all the cells in the row - */ - public Set getRow(int rowNum) { - Set row = new HashSet<>(); - for (int i = 0; i < size; i++) { - row.add(getCell(i, rowNum)); + private int size; + private int groupSize; + + /** + * SudokuBoard Constructor - create a new Sudoku board + * + * @param size size of one side of the sudoku board, must be an integer square root + */ + public SudokuBoard(int size) { + super(size, size); + this.size = size; + this.groupSize = (int) Math.sqrt(dimension.width); } - return row; - } - - /** - * Gets all the cells in the specified column - * - * @param colNum column index - * @return list of all the cells in the column - */ - public Set getCol(int colNum) { - Set col = new HashSet<>(); - for (int i = 0; i < size; i++) { - col.add(getCell(colNum, i)); + + /** + * Gets a SudokuCell from the board + * + * @param x x location of the cell + * @param y y location of the cell + * @return SudokuCell at location (x, y) + */ + @Override + public SudokuCell getCell(int x, int y) { + return (SudokuCell) super.getCell(x, y); } - return col; - } - - /** - * Gets all the cells in the specified region - * - * @param regionNum region index - * @return list of all the cells in the region - */ - public Set getRegion(int regionNum) { - Set region = new HashSet<>(); - for (int i = 0; i < size; i++) { - region.add(getCell(regionNum, i % groupSize, i / groupSize)); + + /** + * Gets the SudokuCell in the specified group index at the x and y location given The group + * index must be by less than the width (or height) of the board and the x and y location is + * relative to the group. This means the x and y values must be less the square root of the + * width (or height) of the board. + * + * @param groupIndex group index of the cell + * @param x x location relative to the group + * @param y y location relative to the group + * @return cell in the specified group index at the given x and y location + */ + public SudokuCell getCell(int groupIndex, int x, int y) { + return getCell( + x + (groupIndex % groupSize) * groupSize, y + (groupIndex / groupSize) * groupSize); } - return region; - } - - public Set getAffected(SudokuCell cell) { - Point loc = cell.getLocation(); - cell = getCell(loc.x, loc.y); - Set affected = new HashSet<>(); - affected.addAll(getRegion(cell.getGroupIndex())); - affected.addAll(getRow(loc.y)); - affected.addAll(getCol(loc.x)); - - return affected; - } - - public Set getPossibleValues(SudokuCell cell) { - Point loc = cell.getLocation(); - cell = getCell(loc.x, loc.y); - Set possible = getAffected(cell); - - Set possibleValues = new HashSet<>(); - for (int i = 0; i < size; i++) { - possibleValues.add(i); + + /** + * Gets the size of the sudoku board Standard board is 9x9 + * + * @return size of the board + */ + public int getSize() { + return size; } - for (SudokuCell c : possible) { - possibleValues.remove(c.getData()); + + /** + * Gets the minor group size of the sudoku board Standard board is 3x3x3x3 + * + * @return minor group size + */ + public int getGroupSize() { + return groupSize; } - return possibleValues; - } - - /** - * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent - * puzzle element with the new data. - * - * @param puzzleElement equivalent puzzle element with the new data. - */ - @Override - public void notifyChange(PuzzleElement puzzleElement) { - super.notifyChange(puzzleElement); - Set affected = getAffected((SudokuCell) puzzleElement); - for (SudokuCell c : affected) { - c.setAnnotations(getPossibleValues(c)); + /** + * Gets all the cells in the specified row + * + * @param rowNum row index + * @return list of all the cells in the row + */ + public Set getRow(int rowNum) { + Set row = new HashSet<>(); + for (int i = 0; i < size; i++) { + row.add(getCell(i, rowNum)); + } + return row; } - } - - /** - * Performs a deep copy of the Board - * - * @return a new copy of the board that is independent of this one - */ - @Override - public SudokuBoard copy() { - SudokuBoard copy = new SudokuBoard(size); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + + /** + * Gets all the cells in the specified column + * + * @param colNum column index + * @return list of all the cells in the column + */ + public Set getCol(int colNum) { + Set col = new HashSet<>(); + for (int i = 0; i < size; i++) { + col.add(getCell(colNum, i)); + } + return col; } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + /** + * Gets all the cells in the specified region + * + * @param regionNum region index + * @return list of all the cells in the region + */ + public Set getRegion(int regionNum) { + Set region = new HashSet<>(); + for (int i = 0; i < size; i++) { + region.add(getCell(regionNum, i % groupSize, i / groupSize)); + } + return region; + } + + public Set getAffected(SudokuCell cell) { + Point loc = cell.getLocation(); + cell = getCell(loc.x, loc.y); + Set affected = new HashSet<>(); + affected.addAll(getRegion(cell.getGroupIndex())); + affected.addAll(getRow(loc.y)); + affected.addAll(getCol(loc.x)); + + return affected; + } + + public Set getPossibleValues(SudokuCell cell) { + Point loc = cell.getLocation(); + cell = getCell(loc.x, loc.y); + Set possible = getAffected(cell); + + Set possibleValues = new HashSet<>(); + for (int i = 0; i < size; i++) { + possibleValues.add(i); + } + for (SudokuCell c : possible) { + possibleValues.remove(c.getData()); + } + + return possibleValues; + } + + /** + * Called when a {@link PuzzleElement} data on this has changed and passes in the equivalent + * puzzle element with the new data. + * + * @param puzzleElement equivalent puzzle element with the new data. + */ + @Override + public void notifyChange(PuzzleElement puzzleElement) { + super.notifyChange(puzzleElement); + Set affected = getAffected((SudokuCell) puzzleElement); + for (SudokuCell c : affected) { + c.setAnnotations(getPossibleValues(c)); + } + } + + /** + * Performs a deep copy of the Board + * + * @return a new copy of the board that is independent of this one + */ + @Override + public SudokuBoard copy() { + SudokuBoard copy = new SudokuBoard(size); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + return copy; } - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java index 4b9ea2b4c..006e6c0a5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCell.java @@ -6,57 +6,57 @@ import java.util.Set; public class SudokuCell extends GridCell { - private int groupIndex; - private Set annotations; - private int max; - - /** - * SudokuCell Constructor - creates a new Sudoku cell to hold the puzzleElement - * - * @param value value of the sudoku cell - * @param location location of the cell on the board - * @param groupIndex index of the group the cell is in on the board - * @param size size of the sudoku cell - */ - public SudokuCell(int value, Point location, int groupIndex, int size) { - super(value, location); - this.groupIndex = groupIndex; - this.annotations = new HashSet<>(); - this.max = size; - } - - /** - * Gets the group index of the cell - * - * @return group index of the cell - */ - public int getGroupIndex() { - return groupIndex; - } - - public int getMax() { - return max; - } - - public Set getAnnotations() { - return annotations; - } - - public void setAnnotations(Set annotations) { - this.annotations = annotations; - } - - /** - * Performs a deep copy on the SudokuCell - * - * @return a new copy of the SudokuCell that is independent of this one - */ - @Override - public SudokuCell copy() { - SudokuCell copy = new SudokuCell(data, (Point) location.clone(), groupIndex, max); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + private int groupIndex; + private Set annotations; + private int max; + + /** + * SudokuCell Constructor - creates a new Sudoku cell to hold the puzzleElement + * + * @param value value of the sudoku cell + * @param location location of the cell on the board + * @param groupIndex index of the group the cell is in on the board + * @param size size of the sudoku cell + */ + public SudokuCell(int value, Point location, int groupIndex, int size) { + super(value, location); + this.groupIndex = groupIndex; + this.annotations = new HashSet<>(); + this.max = size; + } + + /** + * Gets the group index of the cell + * + * @return group index of the cell + */ + public int getGroupIndex() { + return groupIndex; + } + + public int getMax() { + return max; + } + + public Set getAnnotations() { + return annotations; + } + + public void setAnnotations(Set annotations) { + this.annotations = annotations; + } + + /** + * Performs a deep copy on the SudokuCell + * + * @return a new copy of the SudokuCell that is independent of this one + */ + @Override + public SudokuCell copy() { + SudokuCell copy = new SudokuCell(data, (Point) location.clone(), groupIndex, max); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java index edb095519..9b24f13da 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellController.java @@ -5,33 +5,33 @@ import java.awt.event.MouseEvent; public class SudokuCellController extends ElementController { - @Override - public void changeCell(MouseEvent e, PuzzleElement data) { - SudokuCell cell = (SudokuCell) data; - System.out.print(111); - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown()) { - this.boardView - .getSelectionPopupMenu() - .show( - boardView, - this.boardView.getCanvas().getX() + e.getX(), - this.boardView.getCanvas().getY() + e.getY()); - } else { - if (cell.getData() < cell.getMax()) { - data.setData(cell.getData() + 1); + @Override + public void changeCell(MouseEvent e, PuzzleElement data) { + SudokuCell cell = (SudokuCell) data; + System.out.print(111); + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown()) { + this.boardView + .getSelectionPopupMenu() + .show( + boardView, + this.boardView.getCanvas().getX() + e.getX(), + this.boardView.getCanvas().getY() + e.getY()); + } else { + if (cell.getData() < cell.getMax()) { + data.setData(cell.getData() + 1); + } else { + data.setData(0); + } + } } else { - data.setData(0); + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() > 0) { + data.setData(cell.getData() - 1); + } else { + data.setData(cell.getMax()); + } + } } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() > 0) { - data.setData(cell.getData() - 1); - } else { - data.setData(cell.getMax()); - } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java index 7214193be..1ef24ea59 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuCellFactory.java @@ -10,63 +10,65 @@ import org.w3c.dom.Node; public class SudokuCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public SudokuCell importCell(Node node, Board board) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("cell")) { - throw new InvalidFileFormatException("Sudoku Factory: unknown puzzleElement puzzleElement"); - } + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public SudokuCell importCell(Node node, Board board) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("cell")) { + throw new InvalidFileFormatException( + "Sudoku Factory: unknown puzzleElement puzzleElement"); + } - SudokuBoard sudokuBoard = (SudokuBoard) board; - int size = sudokuBoard.getSize(); - int minorSize = (int) Math.sqrt(size); + SudokuBoard sudokuBoard = (SudokuBoard) board; + int size = sudokuBoard.getSize(); + int minorSize = (int) Math.sqrt(size); - NamedNodeMap attributeList = node.getAttributes(); - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= size || y >= size) { - throw new InvalidFileFormatException("Sudoku Factory: cell location out of bounds"); - } - if (value < 0 || value > 9) { - throw new InvalidFileFormatException("Sudoku Factory: cell unknown value"); - } - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(value, new Point(x, y), groupIndex, size); - cell.setIndex(y * size + x); - return cell; - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("Sudoku Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("Sudoku Factory: could not find attribute(s)"); + NamedNodeMap attributeList = node.getAttributes(); + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= size || y >= size) { + throw new InvalidFileFormatException("Sudoku Factory: cell location out of bounds"); + } + if (value < 0 || value > 9) { + throw new InvalidFileFormatException("Sudoku Factory: cell unknown value"); + } + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(value, new Point(x, y), groupIndex, size); + cell.setIndex(y * size + x); + return cell; + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Sudoku Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("Sudoku Factory: could not find attribute(s)"); + } } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - SudokuCell cell = (SudokuCell) puzzleElement; - Point loc = cell.getLocation(); + SudokuCell cell = (SudokuCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getData())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getData())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } + return cellElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java index 142cf8f88..c3d236b53 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuElementView.java @@ -6,65 +6,69 @@ import java.awt.*; public class SudokuElementView extends GridElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Font ANNOTATE_FONT = new Font("TimesRoman", Font.BOLD, 8); - private static final Color FONT_COLOR = new Color(0x212121); - private static final Color BORDER_COLOR = new Color(0x424242); - private static final Color GIVEN_COLOR = new Color(0x75, 0x75, 0x75, 0x80); - private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Font ANNOTATE_FONT = new Font("TimesRoman", Font.BOLD, 8); + private static final Color FONT_COLOR = new Color(0x212121); + private static final Color BORDER_COLOR = new Color(0x424242); + private static final Color GIVEN_COLOR = new Color(0x75, 0x75, 0x75, 0x80); + private static final Color BACKGROUND_COLOR = new Color(0xEEEEEE); - public SudokuElementView(GridCell cell) { - super(cell); - } + public SudokuElementView(GridCell cell) { + super(cell); + } - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public SudokuCell getPuzzleElement() { - return (SudokuCell) super.getPuzzleElement(); - } + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public SudokuCell getPuzzleElement() { + return (SudokuCell) super.getPuzzleElement(); + } - @Override - public void drawGiven(Graphics2D graphics2D) { - graphics2D.setColor(GIVEN_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - } + @Override + public void drawGiven(Graphics2D graphics2D) { + graphics2D.setColor(GIVEN_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + } - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(BACKGROUND_COLOR); - graphics2D.fillRect(location.x, location.y, size.width, size.height); - graphics2D.setColor(BORDER_COLOR); - graphics2D.drawRect(location.x, location.y, size.width, size.height); + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(BACKGROUND_COLOR); + graphics2D.fillRect(location.x, location.y, size.width, size.height); + graphics2D.setColor(BORDER_COLOR); + graphics2D.drawRect(location.x, location.y, size.width, size.height); - SudokuCell cell = (SudokuCell) puzzleElement; - int val = cell.getData(); - if (val != 0) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(val); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } else { - boolean annotate = - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.SHOW_ANNOTATIONS) - .equalsIgnoreCase(Boolean.toString(true)); - if (annotate) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(ANNOTATE_FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value = String.valueOf(cell.getAnnotations()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + SudokuCell cell = (SudokuCell) puzzleElement; + int val = cell.getData(); + if (val != 0) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(val); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } else { + boolean annotate = + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.SHOW_ANNOTATIONS) + .equalsIgnoreCase(Boolean.toString(true)); + if (annotate) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(ANNOTATE_FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value = String.valueOf(cell.getAnnotations()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = + location.y + + ((size.height - metrics.getHeight()) / 2) + + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java index 3bb78e9e9..f10aabae1 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuExporter.java @@ -6,33 +6,33 @@ public class SudokuExporter extends PuzzleExporter { - public SudokuExporter(Sudoku sudoku) { - super(sudoku); - } - - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - SudokuBoard board; - if (puzzle.getTree() != null) { - board = (SudokuBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (SudokuBoard) puzzle.getBoardView().getBoard(); + public SudokuExporter(Sudoku sudoku) { + super(sudoku); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("size", String.valueOf(board.getSize())); + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + SudokuBoard board; + if (puzzle.getTree() != null) { + board = (SudokuBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (SudokuBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - SudokuCell cell = (SudokuCell) puzzleElement; - if (cell.getData() != 0) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("size", String.valueOf(board.getSize())); - boardElement.appendChild(cellsElement); - return boardElement; - } + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + SudokuCell cell = (SudokuCell) puzzleElement; + if (cell.getData() != 0) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + + boardElement.appendChild(cellsElement); + return boardElement; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java index 5ad32efbc..68bf1e795 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuImporter.java @@ -8,122 +8,128 @@ import org.w3c.dom.NodeList; public class SudokuImporter extends PuzzleImporter { - public SudokuImporter(Sudoku sudoku) { - super(sudoku); - } + public SudokuImporter(Sudoku sudoku) { + super(sudoku); + } - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; + } - @Override - public boolean acceptsTextInput() { - return false; - } + @Override + public boolean acceptsTextInput() { + return false; + } - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - SudokuBoard sudokuBoard; - int minorSize = (int) Math.sqrt(rows); - sudokuBoard = new SudokuBoard(rows); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + SudokuBoard sudokuBoard; + int minorSize = (int) Math.sqrt(rows); + sudokuBoard = new SudokuBoard(rows); - for (int y = 0; y < columns; y++) { - for (int x = 0; x < rows; x++) { - if (sudokuBoard.getCell(x, y) == null) { - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, rows); - cell.setIndex(y * rows + x); - cell.setModifiable(true); - sudokuBoard.setCell(x, y, cell); + for (int y = 0; y < columns; y++) { + for (int x = 0; x < rows; x++) { + if (sudokuBoard.getCell(x, y) == null) { + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, rows); + cell.setIndex(y * rows + x); + cell.setModifiable(true); + sudokuBoard.setCell(x, y, cell); + } + } } - } + + puzzle.setCurrentBoard(sudokuBoard); } - puzzle.setCurrentBoard(sudokuBoard); - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "Sudoku Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "Sudoku Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("Sudoku Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("Sudoku Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); + SudokuBoard sudokuBoard; + int size; + int minorSize; + if (!boardElement.getAttribute("size").isEmpty()) { + size = Integer.valueOf(boardElement.getAttribute("size")); + minorSize = (int) Math.sqrt(size); + if (minorSize * minorSize != size) { + throw new InvalidFileFormatException( + "Sudoku Importer: invalid board dimensions"); + } + sudokuBoard = new SudokuBoard(size); + } else { + throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); + } - SudokuBoard sudokuBoard; - int size; - int minorSize; - if (!boardElement.getAttribute("size").isEmpty()) { - size = Integer.valueOf(boardElement.getAttribute("size")); - minorSize = (int) Math.sqrt(size); - if (minorSize * minorSize != size) { - throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); - } - sudokuBoard = new SudokuBoard(size); - } else { - throw new InvalidFileFormatException("Sudoku Importer: invalid board dimensions"); - } + for (int i = 0; i < elementDataList.getLength(); i++) { + SudokuCell cell = + (SudokuCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), sudokuBoard); + Point loc = cell.getLocation(); + if (cell.getData() != 0) { + cell.setModifiable(false); + cell.setGiven(true); + } + sudokuBoard.setCell(loc.x, loc.y, cell); + } - for (int i = 0; i < elementDataList.getLength(); i++) { - SudokuCell cell = - (SudokuCell) puzzle.getFactory().importCell(elementDataList.item(i), sudokuBoard); - Point loc = cell.getLocation(); - if (cell.getData() != 0) { - cell.setModifiable(false); - cell.setGiven(true); - } - sudokuBoard.setCell(loc.x, loc.y, cell); - } + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { + if (sudokuBoard.getCell(x, y) == null) { + int groupIndex = x / minorSize + y / minorSize * minorSize; + SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, size); + cell.setIndex(y * size + x); + cell.setModifiable(true); + sudokuBoard.setCell(x, y, cell); + } + } + } + // + // for(int y = 0; y < size; y++) + // { + // for(int x = 0; x < size; x++) + // { + // SudokuCell cell = sudokuBoard.getCell(x, y); + // System.err.println("(" + x + ", " + y + ") - " + + // cell.getGroupIndex()); + // } + // } - for (int y = 0; y < size; y++) { - for (int x = 0; x < size; x++) { - if (sudokuBoard.getCell(x, y) == null) { - int groupIndex = x / minorSize + y / minorSize * minorSize; - SudokuCell cell = new SudokuCell(0, new Point(x, y), groupIndex, size); - cell.setIndex(y * size + x); - cell.setModifiable(true); - sudokuBoard.setCell(x, y, cell); - } + puzzle.setCurrentBoard(sudokuBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "Sudoku Importer: unknown value where integer expected"); } - } - // - // for(int y = 0; y < size; y++) - // { - // for(int x = 0; x < size; x++) - // { - // SudokuCell cell = sudokuBoard.getCell(x, y); - // System.err.println("(" + x + ", " + y + ") - " + - // cell.getGroupIndex()); - // } - // } - - puzzle.setCurrentBoard(sudokuBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException("Sudoku Importer: unknown value where integer expected"); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Sudoku cannot accept text input"); - } + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Sudoku cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java index 43939bbd4..aa58f9a23 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/SudokuView.java @@ -10,160 +10,162 @@ import javax.swing.*; public class SudokuView extends GridBoardView { - private static final Color STROKE_COLOR = new Color(0, 0, 0); - private static final Stroke MINOR_STOKE = new BasicStroke(1); - private static final Stroke MAJOR_STOKE = new BasicStroke(4); - - public SudokuView(SudokuBoard board) { - super(new BoardController(), new SudokuCellController(), board.getDimension()); - - int minorSize = (int) Math.sqrt(gridSize.width); - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - Point location = - new Point( - k * elementSize.width + (k / minorSize) * 4 + 5, - i * elementSize.height + (i / minorSize) * 4 + 5); - SudokuElementView element = new SudokuElementView(board.getCell(k, i)); - element.setIndex(i * gridSize.width + k); - element.setSize(elementSize); - element.setLocation(location); - elementViews.add(element); - } + private static final Color STROKE_COLOR = new Color(0, 0, 0); + private static final Stroke MINOR_STOKE = new BasicStroke(1); + private static final Stroke MAJOR_STOKE = new BasicStroke(4); + + public SudokuView(SudokuBoard board) { + super(new BoardController(), new SudokuCellController(), board.getDimension()); + + int minorSize = (int) Math.sqrt(gridSize.width); + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + Point location = + new Point( + k * elementSize.width + (k / minorSize) * 4 + 5, + i * elementSize.height + (i / minorSize) * 4 + 5); + SudokuElementView element = new SudokuElementView(board.getCell(k, i)); + element.setIndex(i * gridSize.width + k); + element.setSize(elementSize); + element.setLocation(location); + elementViews.add(element); + } + } } - } - - /** - * Gets the SudokuElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return SudokuElementView at the specified index - */ - @Override - public SudokuElementView getElement(int index) { - return (SudokuElementView) super.getElement(index); - } - - public void drawGrid(Graphics2D graphics2D) { - int minorSize = (int) Math.sqrt(gridSize.width); - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MAJOR_STOKE); - graphics2D.drawRect( - 3, - 3, - gridSize.width * (elementSize.width + 1) + 3, - gridSize.height * (elementSize.height + 1) + 3); - - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MAJOR_STOKE); - for (int i = 1; i < minorSize; i++) { - int x = i * minorSize * elementSize.width + i * ((minorSize + 1)) + 3; - graphics2D.drawLine(x, 3, x, gridSize.height * (elementSize.height + 1) + 6); + + /** + * Gets the SudokuElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return SudokuElementView at the specified index + */ + @Override + public SudokuElementView getElement(int index) { + return (SudokuElementView) super.getElement(index); } - for (int i = 1; i < minorSize; i++) { - int y = i * minorSize * elementSize.height + i * ((minorSize + 1)) + 3; - graphics2D.drawLine(3, y, gridSize.width * (elementSize.width + 1) + 6, y); + + public void drawGrid(Graphics2D graphics2D) { + int minorSize = (int) Math.sqrt(gridSize.width); + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MAJOR_STOKE); + graphics2D.drawRect( + 3, + 3, + gridSize.width * (elementSize.width + 1) + 3, + gridSize.height * (elementSize.height + 1) + 3); + + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MAJOR_STOKE); + for (int i = 1; i < minorSize; i++) { + int x = i * minorSize * elementSize.width + i * ((minorSize + 1)) + 3; + graphics2D.drawLine(x, 3, x, gridSize.height * (elementSize.height + 1) + 6); + } + for (int i = 1; i < minorSize; i++) { + int y = i * minorSize * elementSize.height + i * ((minorSize + 1)) + 3; + graphics2D.drawLine(3, y, gridSize.width * (elementSize.width + 1) + 6, y); + } } - } - @Override - public void drawBoard(Graphics2D graphics2D) { - drawGrid(graphics2D); + @Override + public void drawBoard(Graphics2D graphics2D) { + drawGrid(graphics2D); - if (board instanceof PossibleNumberCaseBoard) { - drawCaseBoard(graphics2D); - return; - } - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MINOR_STOKE); - ElementView hover = null; - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - ElementView element = elementViews.get(i * gridSize.height + k); - if (!element.isHover()) { - element.draw(graphics2D); - } else { - hover = element; + if (board instanceof PossibleNumberCaseBoard) { + drawCaseBoard(graphics2D); + return; + } + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MINOR_STOKE); + ElementView hover = null; + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + ElementView element = elementViews.get(i * gridSize.height + k); + if (!element.isHover()) { + element.draw(graphics2D); + } else { + hover = element; + } + } } - } - } - if (hover != null) { - hover.draw(graphics2D); + if (hover != null) { + hover.draw(graphics2D); + } } - } - - public void drawCaseBoard(Graphics2D graphics2D) { - drawGrid(graphics2D); - - PossibleNumberCaseBoard caseBoard = (PossibleNumberCaseBoard) board; - SudokuBoard sudokuBoard = (SudokuBoard) caseBoard.getBaseBoard(); - - graphics2D.setColor(STROKE_COLOR); - graphics2D.setStroke(MINOR_STOKE); - ElementView hover = null; - for (int i = 0; i < gridSize.height; i++) { - for (int k = 0; k < gridSize.width; k++) { - ElementView element = elementViews.get(i * gridSize.height + k); - if (!element.isHover()) { - element.draw(graphics2D); - } else { - hover = element; + + public void drawCaseBoard(Graphics2D graphics2D) { + drawGrid(graphics2D); + + PossibleNumberCaseBoard caseBoard = (PossibleNumberCaseBoard) board; + SudokuBoard sudokuBoard = (SudokuBoard) caseBoard.getBaseBoard(); + + graphics2D.setColor(STROKE_COLOR); + graphics2D.setStroke(MINOR_STOKE); + ElementView hover = null; + for (int i = 0; i < gridSize.height; i++) { + for (int k = 0; k < gridSize.width; k++) { + ElementView element = elementViews.get(i * gridSize.height + k); + if (!element.isHover()) { + element.draw(graphics2D); + } else { + hover = element; + } + } } - } + + graphics2D.setColor(new Color(0x1A, 0x23, 0x7E, 200)); + for (int r : caseBoard.getPickableRegions()) { + Set region = sudokuBoard.getRegion(r); + int x = Integer.MAX_VALUE, + y = Integer.MAX_VALUE, + w = Integer.MIN_VALUE, + h = Integer.MIN_VALUE; + for (SudokuCell c : region) { + x = Math.min(x, c.getLocation().x); + y = Math.min(y, c.getLocation().y); + w = Math.max(w, c.getLocation().x); + h = Math.max(h, c.getLocation().y); + } + + SudokuElementView firstElement = getElement(y * gridSize.width + x); + SudokuElementView lastElement = getElement(h * gridSize.width + w); + x = firstElement.getLocation().x; + y = firstElement.getLocation().y; + w = (lastElement.getLocation().x + elementSize.width) - x; + h = (lastElement.getLocation().y + elementSize.height) - y; + graphics2D.fillRect(x + 4, y + 4, w - 8, h - 8); + } + + // if(hover != null) + // hover.draw(graphics2D); } - graphics2D.setColor(new Color(0x1A, 0x23, 0x7E, 200)); - for (int r : caseBoard.getPickableRegions()) { - Set region = sudokuBoard.getRegion(r); - int x = Integer.MAX_VALUE, - y = Integer.MAX_VALUE, - w = Integer.MIN_VALUE, - h = Integer.MIN_VALUE; - for (SudokuCell c : region) { - x = Math.min(x, c.getLocation().x); - y = Math.min(y, c.getLocation().y); - w = Math.max(w, c.getLocation().x); - h = Math.max(h, c.getLocation().y); - } - - SudokuElementView firstElement = getElement(y * gridSize.width + x); - SudokuElementView lastElement = getElement(h * gridSize.width + w); - x = firstElement.getLocation().x; - y = firstElement.getLocation().y; - w = (lastElement.getLocation().x + elementSize.width) - x; - h = (lastElement.getLocation().y + elementSize.height) - y; - graphics2D.fillRect(x + 4, y + 4, w - 8, h - 8); + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = gridSize.width * (elementSize.width + 1) + 9; + boardViewSize.height = gridSize.height * (elementSize.height + 1) + 9; + return boardViewSize; } - // if(hover != null) - // hover.draw(graphics2D); - } - - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = gridSize.width * (elementSize.width + 1) + 9; - boardViewSize.height = gridSize.height * (elementSize.height + 1) + 9; - return boardViewSize; - } - - public DataSelectionView getSelectionPopupMenu() { - DataSelectionView selectionView = new DataSelectionView(elementController); - GridLayout layout = new GridLayout(3, 3); - selectionView.setLayout(layout); - for (int r = 1; r <= 3; r++) { - for (int c = 1; c <= 3; c++) { - SudokuElementView element = - new SudokuElementView(new SudokuCell((r - 1) * 3 + c, null, 0, gridSize.width)); - element.setSize(new Dimension(32, 32)); - element.setLocation(new Point(0, 0)); - SelectionItemView item = - new SelectionItemView(element.getPuzzleElement(), new ImageIcon(element.getImage())); - item.addActionListener(elementController); - item.setHorizontalTextPosition(SwingConstants.CENTER); - selectionView.add(item); - } + public DataSelectionView getSelectionPopupMenu() { + DataSelectionView selectionView = new DataSelectionView(elementController); + GridLayout layout = new GridLayout(3, 3); + selectionView.setLayout(layout); + for (int r = 1; r <= 3; r++) { + for (int c = 1; c <= 3; c++) { + SudokuElementView element = + new SudokuElementView( + new SudokuCell((r - 1) * 3 + c, null, 0, gridSize.width)); + element.setSize(new Dimension(32, 32)); + element.setLocation(new Point(0, 0)); + SelectionItemView item = + new SelectionItemView( + element.getPuzzleElement(), new ImageIcon(element.getImage())); + item.addActionListener(elementController); + item.setHorizontalTextPosition(SwingConstants.CENTER); + selectionView.add(item); + } + } + return selectionView; } - return selectionView; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java index 4a122dbcf..12183d70d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/elements/NumberTile.java @@ -3,24 +3,24 @@ import edu.rpi.legup.model.elements.PlaceableElement; public class NumberTile extends PlaceableElement { - private int object_num; + private int object_num; - public NumberTile() { - super("SUDO-PLAC-0001", "Number Tile", "A numbered tile", null); - object_num = 0; - } + public NumberTile() { + super("SUDO-PLAC-0001", "Number Tile", "A numbered tile", null); + object_num = 0; + } - /** - * @return this object's tile number... - */ - public int getTileNumber() { - return object_num; - } + /** + * @return this object's tile number... + */ + public int getTileNumber() { + return object_num; + } - /** - * @param num Amount to set tile object to. - */ - public void setTileNumber(int num) { - object_num = num; - } + /** + * @param num Amount to set tile object to. + */ + public void setTileNumber(int num) { + object_num = num; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java index bde33119a..190679b41 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/AdvancedDeductionDirectRule.java @@ -10,89 +10,90 @@ public class AdvancedDeductionDirectRule extends DirectRule { - public AdvancedDeductionDirectRule() { - super( - "SUDO-BASC-0001", - "Advanced Deduction", - "Use of group logic deduces more answers by means of forced by Location and forced" - + " by Deduction", - "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); - } + public AdvancedDeductionDirectRule() { + super( + "SUDO-BASC-0001", + "Advanced Deduction", + "Use of group logic deduces more answers by means of forced by Location and forced" + + " by Deduction", + "edu/rpi/legup/images/sudoku/AdvancedDeduction.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - int index = cell.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int relX = rowIndex / groupDim; - int relY = colIndex % groupDim; - int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; - boolean[][] possible = new boolean[groupDim][groupDim]; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - SudokuCell c = initialBoard.getCell(groupNum, x, y); - if (c.getData() == cell.getData() && x != relX && y != relY) { - return super.getRuleName() + ": Duplicate value in sub-region"; + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + int index = cell.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int relX = rowIndex / groupDim; + int relY = colIndex % groupDim; + int groupNum = rowIndex / groupDim * groupDim + colIndex / groupDim; + boolean[][] possible = new boolean[groupDim][groupDim]; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + SudokuCell c = initialBoard.getCell(groupNum, x, y); + if (c.getData() == cell.getData() && x != relX && y != relY) { + return super.getRuleName() + ": Duplicate value in sub-region"; + } + possible[y][x] = c.getData() == 0; + } } - possible[y][x] = c.getData() == 0; - } - } - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupSize; x++) { - SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); - SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); - if (r.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[y][i] = false; - } + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupSize; x++) { + SudokuCell r = initialBoard.getCell(x, (groupNum / groupDim) * groupDim + y); + SudokuCell c = initialBoard.getCell((groupNum % groupDim) * groupDim + y, x); + if (r.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[y][i] = false; + } + } + if (c.getData() == cell.getData()) { + for (int i = 0; i < groupDim; i++) { + possible[i][y] = false; + } + } + } } - if (c.getData() == cell.getData()) { - for (int i = 0; i < groupDim; i++) { - possible[i][y] = false; - } + boolean isForced = false; + for (int y = 0; y < groupDim; y++) { + for (int x = 0; x < groupDim; x++) { + if (possible[y][x] && !isForced) { + isForced = true; + } else { + if (possible[y][x]) { + return super.getInvalidUseOfRuleMessage() + ": Not forced"; + } + } + } } - } - } - boolean isForced = false; - for (int y = 0; y < groupDim; y++) { - for (int x = 0; x < groupDim; x++) { - if (possible[y][x] && !isForced) { - isForced = true; - } else { - if (possible[y][x]) { + if (!isForced) { return super.getInvalidUseOfRuleMessage() + ": Not forced"; - } } - } + return null; } - if (!isForced) { - return super.getInvalidUseOfRuleMessage() + ": Not forced"; - } - return null; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java index fe32fc450..fd03ef36c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastCellForNumberDirectRule.java @@ -10,85 +10,86 @@ import java.util.Set; public class LastCellForNumberDirectRule extends DirectRule { - public LastCellForNumberDirectRule() { - super( - "SUDO-BASC-0002", - "Last Cell for Number", - "This is the only cell open in its group for some number.", - "edu/rpi/legup/images/sudoku/forcedByElimination.png"); - } + public LastCellForNumberDirectRule() { + super( + "SUDO-BASC-0002", + "Last Cell for Number", + "This is the only cell open in its group for some number.", + "edu/rpi/legup/images/sudoku/forcedByElimination.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; - } + SudokuCell cell = (SudokuCell) finalBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; + } - int size = initialBoard.getSize(); + int size = initialBoard.getSize(); - Set region = initialBoard.getRegion(cell.getGroupIndex()); - Set row = initialBoard.getRow(cell.getLocation().y); - Set col = initialBoard.getCol(cell.getLocation().x); + Set region = initialBoard.getRegion(cell.getGroupIndex()); + Set row = initialBoard.getRow(cell.getLocation().y); + Set col = initialBoard.getCol(cell.getLocation().x); - boolean contains = false; - if (region.size() == size - 1) { - for (SudokuCell c : region) { - if (cell.getData() == c.getData()) { - contains = true; - break; + boolean contains = false; + if (region.size() == size - 1) { + for (SudokuCell c : region) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } } - } - if (!contains) { - return null; - } - } - if (row.size() == size - 1) { - contains = false; - for (SudokuCell c : row) { - if (cell.getData() == c.getData()) { - contains = true; - break; + if (row.size() == size - 1) { + contains = false; + for (SudokuCell c : row) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } } - } - if (!contains) { - return null; - } - } - if (col.size() == size - 1) { - contains = false; - for (SudokuCell c : col) { - if (cell.getData() == c.getData()) { - contains = true; - break; + if (col.size() == size - 1) { + contains = false; + for (SudokuCell c : col) { + if (cell.getData() == c.getData()) { + contains = true; + break; + } + } + if (!contains) { + return null; + } } - } - if (!contains) { - return null; - } + return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; } - return super.getInvalidUseOfRuleMessage() + ": Cell is not forced at this index"; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java index 881df8455..ca0ac3023 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/LastNumberForCellDirectRule.java @@ -11,69 +11,71 @@ public class LastNumberForCellDirectRule extends DirectRule { - public LastNumberForCellDirectRule() { - super( - "SUDO-BASC-0003", - "Last Number for Cell", - "This is the only number left that can fit in the cell of a group.", - "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); - } + public LastNumberForCellDirectRule() { + super( + "SUDO-BASC-0003", + "Last Number for Cell", + "This is the only number left that can fit in the cell of a group.", + "edu/rpi/legup/images/sudoku/forcedByDeduction.png"); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); - SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + SudokuBoard initialBoard = (SudokuBoard) transition.getParents().get(0).getBoard(); + SudokuBoard finalBoard = (SudokuBoard) transition.getBoard(); - int index = puzzleElement.getIndex(); - int groupSize = initialBoard.getWidth(); - int groupDim = (int) Math.sqrt(groupSize); - int rowIndex = index / groupSize; - int colIndex = index % groupSize; - int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; - HashSet numbers = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - numbers.add(i); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); - numbers.remove(cell.getData()); - } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(i, colIndex); - numbers.remove(cell.getData()); + int index = puzzleElement.getIndex(); + int groupSize = initialBoard.getWidth(); + int groupDim = (int) Math.sqrt(groupSize); + int rowIndex = index / groupSize; + int colIndex = index % groupSize; + int groupNum = rowIndex / groupDim * groupDim + colIndex % groupDim; + HashSet numbers = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + numbers.add(i); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(groupNum, i % groupDim, i / groupDim); + numbers.remove(cell.getData()); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(i, colIndex); + numbers.remove(cell.getData()); + } + for (int i = 0; i < groupSize; i++) { + SudokuCell cell = initialBoard.getCell(rowIndex, i); + numbers.remove(cell.getData()); + } + if (numbers.size() > 1) { + return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; + } else { + if (numbers.size() == 1 + && numbers.iterator().next() + != finalBoard.getPuzzleElement(puzzleElement).getData()) { + return super.getInvalidUseOfRuleMessage() + + ": The number at the index is forced but not correct"; + } + } + return null; } - for (int i = 0; i < groupSize; i++) { - SudokuCell cell = initialBoard.getCell(rowIndex, i); - numbers.remove(cell.getData()); - } - if (numbers.size() > 1) { - return super.getInvalidUseOfRuleMessage() + ": The number at the index is not forced"; - } else { - if (numbers.size() == 1 - && numbers.iterator().next() != finalBoard.getPuzzleElement(puzzleElement).getData()) { - return super.getInvalidUseOfRuleMessage() - + ": The number at the index is forced but not correct"; - } - } - return null; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java index e87b77492..e44728d3e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/NoSolutionContradictionRule.java @@ -10,55 +10,55 @@ public class NoSolutionContradictionRule extends ContradictionRule { - public NoSolutionContradictionRule() { - super( - "SUDO-CONT-0001", - "No Solution for Cell", - "Process of elimination yields no valid numbers for an empty cell.", - "edu/rpi/legup/images/sudoku/NoSolution.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); - if (cell.getData() != 0) { - return super.getNoContradictionMessage(); + public NoSolutionContradictionRule() { + super( + "SUDO-CONT-0001", + "No Solution for Cell", + "Process of elimination yields no valid numbers for an empty cell.", + "edu/rpi/legup/images/sudoku/NoSolution.png"); } - int groupSize = sudokuBoard.getSize(); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); + if (cell.getData() != 0) { + return super.getNoContradictionMessage(); + } - Set region = sudokuBoard.getRegion(cell.getGroupIndex()); - Set row = sudokuBoard.getRow(cell.getLocation().y); - Set col = sudokuBoard.getCol(cell.getLocation().x); - Set solution = new HashSet<>(); - for (int i = 1; i <= groupSize; i++) { - solution.add(i); - } + int groupSize = sudokuBoard.getSize(); - for (SudokuCell c : region) { - solution.remove(c.getData()); - } - for (SudokuCell c : row) { - solution.remove(c.getData()); - } - for (SudokuCell c : col) { - solution.remove(c.getData()); - } + Set region = sudokuBoard.getRegion(cell.getGroupIndex()); + Set row = sudokuBoard.getRow(cell.getLocation().y); + Set col = sudokuBoard.getCol(cell.getLocation().x); + Set solution = new HashSet<>(); + for (int i = 1; i <= groupSize; i++) { + solution.add(i); + } - if (solution.isEmpty()) { - return null; - } + for (SudokuCell c : region) { + solution.remove(c.getData()); + } + for (SudokuCell c : row) { + solution.remove(c.getData()); + } + for (SudokuCell c : col) { + solution.remove(c.getData()); + } - return super.getNoContradictionMessage(); - } + if (solution.isEmpty()) { + return null; + } + + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java index be1875c90..fb6da62d4 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleCellCaseRule.java @@ -12,99 +12,99 @@ import java.util.Set; public class PossibleCellCaseRule extends CaseRule { - public PossibleCellCaseRule() { - super( - "SUDO-CASE-0001", - "Possible Cells for Number", - "A number has a limited set of cells in which it can be placed.", - "edu/rpi/legup/images/sudoku/possible_cells_number.png"); - } + public PossibleCellCaseRule() { + super( + "SUDO-CASE-0001", + "Possible Cells for Number", + "A number has a limited set of cells in which it can be placed.", + "edu/rpi/legup/images/sudoku/possible_cells_number.png"); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - @Override - public CaseBoard getCaseBoard(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board.copy(); - CaseBoard caseBoard = new CaseBoard(sudokuBoard, this); - for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { - if (((SudokuCell) puzzleElement).getData() == 0) { - caseBoard.addPickableElement(puzzleElement); - } + @Override + public CaseBoard getCaseBoard(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board.copy(); + CaseBoard caseBoard = new CaseBoard(sudokuBoard, this); + for (PuzzleElement puzzleElement : sudokuBoard.getPuzzleElements()) { + if (((SudokuCell) puzzleElement).getData() == 0) { + caseBoard.addPickableElement(puzzleElement); + } + } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) puzzleElement; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) puzzleElement; - Set possibleValue = new HashSet<>(); - for (int i = 1; i <= sudokuBoard.getSize(); i++) { - possibleValue.add(i); - } + Set possibleValue = new HashSet<>(); + for (int i = 1; i <= sudokuBoard.getSize(); i++) { + possibleValue.add(i); + } - int groupNum = cell.getGroupIndex(); - for (SudokuCell c : sudokuBoard.getRegion(groupNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int groupNum = cell.getGroupIndex(); + for (SudokuCell c : sudokuBoard.getRegion(groupNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - int rowNum = cell.getLocation().y; - for (SudokuCell c : sudokuBoard.getRegion(rowNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int rowNum = cell.getLocation().y; + for (SudokuCell c : sudokuBoard.getRegion(rowNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - int colNum = cell.getLocation().x; - for (SudokuCell c : sudokuBoard.getRegion(colNum)) { - if (c.getData().equals(c.getData())) { - possibleValue.remove(c.getData()); - } - } + int colNum = cell.getLocation().x; + for (SudokuCell c : sudokuBoard.getRegion(colNum)) { + if (c.getData().equals(c.getData())) { + possibleValue.remove(c.getData()); + } + } - for (Integer i : possibleValue) { - SudokuBoard newCase = sudokuBoard.copy(); + for (Integer i : possibleValue) { + SudokuBoard newCase = sudokuBoard.copy(); - PuzzleElement newCasePuzzleElement = newCase.getPuzzleElement(puzzleElement); - newCasePuzzleElement.setData(i); - newCase.addModifiedData(newCasePuzzleElement); - cases.add(newCase); - } + PuzzleElement newCasePuzzleElement = newCase.getPuzzleElement(puzzleElement); + newCasePuzzleElement.setData(i); + newCase.addModifiedData(newCasePuzzleElement); + cases.add(newCase); + } - return cases; - } + return cases; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java index f638fbbb6..e6ab0e64c 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/PossibleNumberCaseRule.java @@ -15,117 +15,117 @@ public class PossibleNumberCaseRule extends CaseRule { - public PossibleNumberCaseRule() { - super( - "SUDO-CASE-0002", - "Possible Numbers for Cell", - "An empty cell has a limited set of possible numbers that can fill it.", - "edu/rpi/legup/images/sudoku/PossibleValues.png"); - } + public PossibleNumberCaseRule() { + super( + "SUDO-CASE-0002", + "Possible Numbers for Cell", + "An empty cell has a limited set of possible numbers that can fill it.", + "edu/rpi/legup/images/sudoku/PossibleValues.png"); + } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } - @Override - public CaseBoard getCaseBoard(Board board) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - PossibleNumberCaseBoard caseBoard = new PossibleNumberCaseBoard(sudokuBoard, this, null); - for (int i = 0; i < sudokuBoard.getSize(); i++) { - caseBoard.addPickableRegion(i); - caseBoard.addPickableRow(i); - caseBoard.addPickableCol(i); + @Override + public CaseBoard getCaseBoard(Board board) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + PossibleNumberCaseBoard caseBoard = new PossibleNumberCaseBoard(sudokuBoard, this, null); + for (int i = 0; i < sudokuBoard.getSize(); i++) { + caseBoard.addPickableRegion(i); + caseBoard.addPickableRow(i); + caseBoard.addPickableCol(i); + } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - return getCases(board, puzzleElement, 1, GroupType.REGION); - } + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + return getCases(board, puzzleElement, 1, GroupType.REGION); + } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @param value value that the rule will be applied from - * @param groupType group type - * @return a list of elements the specified could be - */ - public ArrayList getCases( - Board board, PuzzleElement puzzleElement, int value, GroupType groupType) { - ArrayList cases = new ArrayList<>(); - SudokuBoard sudokuBoard = (SudokuBoard) board; - List caseCells = new ArrayList<>(); - SudokuCell cell = (SudokuCell) puzzleElement; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @param value value that the rule will be applied from + * @param groupType group type + * @return a list of elements the specified could be + */ + public ArrayList getCases( + Board board, PuzzleElement puzzleElement, int value, GroupType groupType) { + ArrayList cases = new ArrayList<>(); + SudokuBoard sudokuBoard = (SudokuBoard) board; + List caseCells = new ArrayList<>(); + SudokuCell cell = (SudokuCell) puzzleElement; - Set group; - if (groupType == GroupType.REGION) { - group = sudokuBoard.getRegion(cell.getGroupIndex()); - } else { - if (groupType == GroupType.ROW) { - group = sudokuBoard.getRow(cell.getLocation().y); - } else { - group = sudokuBoard.getCol(cell.getLocation().x); - } - } + Set group; + if (groupType == GroupType.REGION) { + group = sudokuBoard.getRegion(cell.getGroupIndex()); + } else { + if (groupType == GroupType.ROW) { + group = sudokuBoard.getRow(cell.getLocation().y); + } else { + group = sudokuBoard.getCol(cell.getLocation().x); + } + } - for (SudokuCell c : group) { - if (c.getData() == 0) { - Set blockableCells = sudokuBoard.getRegion(c.getGroupIndex()); - blockableCells.addAll(sudokuBoard.getRow(c.getLocation().y)); - blockableCells.addAll(sudokuBoard.getCol(c.getLocation().x)); + for (SudokuCell c : group) { + if (c.getData() == 0) { + Set blockableCells = sudokuBoard.getRegion(c.getGroupIndex()); + blockableCells.addAll(sudokuBoard.getRow(c.getLocation().y)); + blockableCells.addAll(sudokuBoard.getCol(c.getLocation().x)); - boolean repeat = false; - for (SudokuCell bc : blockableCells) { - if (bc.getData() == value) { - repeat = true; - break; - } + boolean repeat = false; + for (SudokuCell bc : blockableCells) { + if (bc.getData() == value) { + repeat = true; + break; + } + } + if (!repeat) { + caseCells.add(c); + } + } } - if (!repeat) { - caseCells.add(c); + + for (SudokuCell c : caseCells) { + Board newCase = sudokuBoard.copy(); + PuzzleElement element = newCase.getPuzzleElement(c); + element.setData(value); + newCase.addModifiedData(element); + cases.add(newCase); } - } - } - for (SudokuCell c : caseCells) { - Board newCase = sudokuBoard.copy(); - PuzzleElement element = newCase.getPuzzleElement(c); - element.setData(value); - newCase.addModifiedData(element); - cases.add(newCase); + return cases; } - - return cases; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java index cf0bfa600..955414e8e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/sudoku/rules/RepeatedNumberContradictionRule.java @@ -10,60 +10,60 @@ public class RepeatedNumberContradictionRule extends ContradictionRule { - public RepeatedNumberContradictionRule() { - super( - "SUDO-CONT-0002", - "Repeated Numbers", - "Two identical numbers are placed in the same group.", - "edu/rpi/legup/images/sudoku/RepeatedNumber.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - SudokuBoard sudokuBoard = (SudokuBoard) board; - SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); - if (cell.getData() == 0) { - return super.getNoContradictionMessage(); + public RepeatedNumberContradictionRule() { + super( + "SUDO-CONT-0002", + "Repeated Numbers", + "Two identical numbers are placed in the same group.", + "edu/rpi/legup/images/sudoku/RepeatedNumber.png"); } - Set region = sudokuBoard.getRegion(cell.getGroupIndex()); - Set row = sudokuBoard.getRow(cell.getLocation().y); - Set col = sudokuBoard.getCol(cell.getLocation().x); + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + SudokuBoard sudokuBoard = (SudokuBoard) board; + SudokuCell cell = (SudokuCell) sudokuBoard.getPuzzleElement(puzzleElement); + if (cell.getData() == 0) { + return super.getNoContradictionMessage(); + } - Set regionDup = new HashSet<>(); - Set rowDup = new HashSet<>(); - Set colDup = new HashSet<>(); + Set region = sudokuBoard.getRegion(cell.getGroupIndex()); + Set row = sudokuBoard.getRow(cell.getLocation().y); + Set col = sudokuBoard.getCol(cell.getLocation().x); - for (SudokuCell c : region) { - if (regionDup.contains(c.getData())) { - return null; - } - regionDup.add(c.getData()); - } + Set regionDup = new HashSet<>(); + Set rowDup = new HashSet<>(); + Set colDup = new HashSet<>(); - for (SudokuCell c : row) { - if (rowDup.contains(c.getData())) { - return null; - } - rowDup.add(c.getData()); - } + for (SudokuCell c : region) { + if (regionDup.contains(c.getData())) { + return null; + } + regionDup.add(c.getData()); + } - for (SudokuCell c : col) { - if (colDup.contains(c.getData())) { - return null; - } - colDup.add(c.getData()); - } + for (SudokuCell c : row) { + if (rowDup.contains(c.getData())) { + return null; + } + rowDup.add(c.getData()); + } + + for (SudokuCell c : col) { + if (colDup.contains(c.getData())) { + return null; + } + colDup.add(c.getData()); + } - return super.getNoContradictionMessage(); - } + return super.getNoContradictionMessage(); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java b/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java index fa66fcb1b..a11f5f05b 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/ClueCommand.java @@ -15,169 +15,170 @@ import java.util.Map; public class ClueCommand extends PuzzleCommand { - private TreeViewSelection selection; - private TreeTentClueView clueView; - private Map addTran; - private List> emptyCells; - - public ClueCommand(TreeViewSelection selection, TreeTentClueView clueView) { - this.selection = selection; - this.clueView = clueView; - this.addTran = new HashMap<>(); - this.emptyCells = new ArrayList<>(); - } - - /** Executes a command */ - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - - final TreeViewSelection newSelection = new TreeViewSelection(); - for (int i = 0; i < selection.getSelectedViews().size(); i++) { - TreeElementView selectedView = selection.getSelectedViews().get(i); - TreeElement treeElement = selectedView.getTreeElement(); - - final TreeTransition finalTran; - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - List tempList = emptyCells.get(i); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - TreeTransition transition = addTran.get(treeNode); - if (transition == null) { - transition = tree.addNewTransition(treeNode); - addTran.put(treeNode, transition); - } else { - treeNode.addChild(transition); - } - - finalTran = transition; - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); - - newSelection.addToSelection(treeView.getElementView(finalTran)); - board = (TreeTentBoard) finalTran.getBoard(); - } else { - finalTran = (TreeTransition) treeElement; - newSelection.addToSelection(treeView.getElementView(treeElement)); - } - - for (TreeTentCell cell : tempList) { - cell = (TreeTentCell) board.getPuzzleElement(cell); - cell.setData(TreeTentType.GRASS); - board.addModifiedData(cell); - finalTran.propagateChange(cell); - - final TreeTentCell finalCell = cell; - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); - } - if (i == 0) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); - } - } - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - if (selection.getSelectedViews().isEmpty()) { - return CommandError.NO_SELECTED_VIEWS.toString(); + private TreeViewSelection selection; + private TreeTentClueView clueView; + private Map addTran; + private List> emptyCells; + + public ClueCommand(TreeViewSelection selection, TreeTentClueView clueView) { + this.selection = selection; + this.clueView = clueView; + this.addTran = new HashMap<>(); + this.emptyCells = new ArrayList<>(); } - emptyCells.clear(); - for (TreeElementView view : selection.getSelectedViews()) { - TreeElement treeElement = view.getTreeElement(); - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) treeElement; - if (!node.getChildren().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); + /** Executes a command */ + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + + final TreeViewSelection newSelection = new TreeViewSelection(); + for (int i = 0; i < selection.getSelectedViews().size(); i++) { + TreeElementView selectedView = selection.getSelectedViews().get(i); + TreeElement treeElement = selectedView.getTreeElement(); + + final TreeTransition finalTran; + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + List tempList = emptyCells.get(i); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + TreeTransition transition = addTran.get(treeNode); + if (transition == null) { + transition = tree.addNewTransition(treeNode); + addTran.put(treeNode, transition); + } else { + treeNode.addChild(transition); + } + + finalTran = transition; + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(finalTran)); + + newSelection.addToSelection(treeView.getElementView(finalTran)); + board = (TreeTentBoard) finalTran.getBoard(); + } else { + finalTran = (TreeTransition) treeElement; + newSelection.addToSelection(treeView.getElementView(treeElement)); + } + + for (TreeTentCell cell : tempList) { + cell = (TreeTentCell) board.getPuzzleElement(cell); + cell.setData(TreeTentType.GRASS); + board.addModifiedData(cell); + finalTran.propagateChange(cell); + + final TreeTentCell finalCell = cell; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); + } + if (i == 0) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); + } } - } else { - if (!board.isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - - List tempList = new ArrayList<>(); - TreeTentClue clue = clueView.getPuzzleElement(); - if (clue.getType() == TreeTentType.CLUE_NORTH || clue.getType() == TreeTentType.CLUE_SOUTH) { - int col = - clue.getType() == TreeTentType.CLUE_NORTH - ? clue.getClueIndex() - : clue.getClueIndex() - 1; - for (int i = 0; i < board.getWidth(); i++) { - TreeTentCell cell = board.getCell(col, i); - if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { - tempList.add(cell); - } + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); + } + + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + if (selection.getSelectedViews().isEmpty()) { + return CommandError.NO_SELECTED_VIEWS.toString(); } - } else { - int row = - clue.getType() == TreeTentType.CLUE_WEST - ? clue.getClueIndex() - : clue.getClueIndex() - 1; - for (int i = 0; i < board.getWidth(); i++) { - TreeTentCell cell = board.getCell(i, row); - if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { - tempList.add(cell); - } + + emptyCells.clear(); + for (TreeElementView view : selection.getSelectedViews()) { + TreeElement treeElement = view.getTreeElement(); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) treeElement; + if (!node.getChildren().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } else { + if (!board.isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } + + List tempList = new ArrayList<>(); + TreeTentClue clue = clueView.getPuzzleElement(); + if (clue.getType() == TreeTentType.CLUE_NORTH + || clue.getType() == TreeTentType.CLUE_SOUTH) { + int col = + clue.getType() == TreeTentType.CLUE_NORTH + ? clue.getClueIndex() + : clue.getClueIndex() - 1; + for (int i = 0; i < board.getWidth(); i++) { + TreeTentCell cell = board.getCell(col, i); + if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { + tempList.add(cell); + } + } + } else { + int row = + clue.getType() == TreeTentType.CLUE_WEST + ? clue.getClueIndex() + : clue.getClueIndex() - 1; + for (int i = 0; i < board.getWidth(); i++) { + TreeTentCell cell = board.getCell(i, row); + if (cell.getType() == TreeTentType.UNKNOWN && cell.isModifiable()) { + tempList.add(cell); + } + } + } + if (tempList.isEmpty()) { + return "There are no modifiable unknown cells in every selected tree element."; + } + emptyCells.add(tempList); } - } - if (tempList.isEmpty()) { - return "There are no modifiable unknown cells in every selected tree element."; - } - emptyCells.add(tempList); + return null; } - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - - for (int i = 0; i < selection.getSelectedViews().size(); i++) { - TreeElementView selectedView = selection.getSelectedViews().get(i); - TreeElement treeElement = selectedView.getTreeElement(); - - final TreeTransition finalTran; - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - List tempList = emptyCells.get(i); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - finalTran = treeNode.getChildren().get(0); - tree.removeTreeElement(finalTran); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); - - board = (TreeTentBoard) finalTran.getBoard(); - } else { - finalTran = (TreeTransition) treeElement; - } - - for (TreeTentCell cell : tempList) { - cell = (TreeTentCell) board.getPuzzleElement(cell); - cell.setData(TreeTentType.UNKNOWN); - board.removeModifiedData(cell); - - final TreeTentCell finalCell = cell; - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); - } - - if (i == 0) { - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); - } + + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + + for (int i = 0; i < selection.getSelectedViews().size(); i++) { + TreeElementView selectedView = selection.getSelectedViews().get(i); + TreeElement treeElement = selectedView.getTreeElement(); + + final TreeTransition finalTran; + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + List tempList = emptyCells.get(i); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + + finalTran = treeNode.getChildren().get(0); + tree.removeTreeElement(finalTran); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(finalTran)); + + board = (TreeTentBoard) finalTran.getBoard(); + } else { + finalTran = (TreeTransition) treeElement; + } + + for (TreeTentCell cell : tempList) { + cell = (TreeTentCell) board.getPuzzleElement(cell); + cell.setData(TreeTentType.UNKNOWN); + board.removeModifiedData(cell); + + final TreeTentCell finalCell = cell; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(finalCell)); + } + + if (i == 0) { + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTran)); + } + } + final TreeViewSelection newSelection = selection; + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - final TreeViewSelection newSelection = selection; - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java b/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java index 4420d791e..feece58a9 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/EditLineCommand.java @@ -14,212 +14,214 @@ import java.util.List; public class EditLineCommand extends PuzzleCommand { - private TreeTentElementView start; - private TreeTentElementView end; - - private TreeViewSelection selection; - - public EditLineCommand( - TreeViewSelection selection, TreeTentElementView start, ElementView endDrag) { - this.selection = selection; - this.start = start; - this.end = getViewInDirection(endDrag); - } - - /** Executes a command */ - @Override - public void executeCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - TreeTentCell startCell; - TreeTentCell endCell; - - final TreeTransition transition; - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - - transition = tree.addNewTransition(treeNode); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - - board = (TreeTentBoard) transition.getBoard(); - } else { - transition = (TreeTransition) treeElement; + private TreeTentElementView start; + private TreeTentElementView end; + + private TreeViewSelection selection; + + public EditLineCommand( + TreeViewSelection selection, TreeTentElementView start, ElementView endDrag) { + this.selection = selection; + this.start = start; + this.end = getViewInDirection(endDrag); } - startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); - endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + /** Executes a command */ + @Override + public void executeCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeView treeView = getInstance().getLegupUI().getTreePanel().getTreeView(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); - TreeTentLine line = new TreeTentLine(startCell, endCell); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + TreeTentCell startCell; + TreeTentCell endCell; - TreeTentLine dupLine = null; - for (TreeTentLine l : board.getLines()) { - if (line.compare(l)) { - dupLine = l; - break; - } - } + final TreeTransition transition; + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; - final TreeTentLine notifyLine; - if (dupLine == null) { - board.addModifiedData(line); - board.getLines().add(line); - notifyLine = line; - transition.propagateAddition(notifyLine); - } else { - board.removeModifiedData(dupLine); - board.getLines().remove(dupLine); - notifyLine = dupLine; - transition.propagateDeletion(notifyLine); - } + transition = tree.addNewTransition(treeNode); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementAdded(transition)); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); - - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(transition)); - - final TreeViewSelection newSelection = - new TreeViewSelection(treeView.getElementView(transition)); - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); - } - - /** - * Gets the reason why the command cannot be executed - * - * @return if command cannot be executed, returns reason for why the command cannot be executed, - * otherwise null if command can be executed - */ - @Override - public String getErrorString() { - List selectedViews = selection.getSelectedViews(); - if (selectedViews.size() != 1) { - return CommandError.ONE_SELECTED_VIEW.toString(); - } + board = (TreeTentBoard) transition.getBoard(); + } else { + transition = (TreeTransition) treeElement; + } - if (start == null || end == null) { - return "The line must connect a tree to a tent."; - } + startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); + endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); - TreeElementView view = selection.getFirstSelection(); - TreeElement treeElement = view.getTreeElement(); - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode node = (TreeNode) treeElement; - if (!node.getChildren().isEmpty()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } else { - if (!board.isModifiable()) { - return CommandError.UNMODIFIABLE_BOARD.toString(); - } - } - TreeTentLine line = - new TreeTentLine( - (TreeTentCell) start.getPuzzleElement(), (TreeTentCell) end.getPuzzleElement()); - for (TreeTentLine l : board.getLines()) { - if (line.compare(l) && !l.isModifiable()) { - return CommandError.UNMODIFIABLE_DATA.toString(); - } - } + TreeTentLine line = new TreeTentLine(startCell, endCell); - TreeTentCell startCell = (TreeTentCell) start.getPuzzleElement(); - TreeTentCell endCell = (TreeTentCell) end.getPuzzleElement(); - if (!((startCell.getType() == TreeTentType.TENT && endCell.getType() == TreeTentType.TREE) - || (endCell.getType() == TreeTentType.TENT && startCell.getType() == TreeTentType.TREE))) { - return "The line must connect a tree to a tent."; - } + TreeTentLine dupLine = null; + for (TreeTentLine l : board.getLines()) { + if (line.compare(l)) { + dupLine = l; + break; + } + } + + final TreeTentLine notifyLine; + if (dupLine == null) { + board.addModifiedData(line); + board.getLines().add(line); + notifyLine = line; + transition.propagateAddition(notifyLine); + } else { + board.removeModifiedData(dupLine); + board.getLines().remove(dupLine); + notifyLine = dupLine; + transition.propagateDeletion(notifyLine); + } - return null; - } - - /** Undoes an command */ - @Override - public void undoCommand() { - Puzzle puzzle = getInstance().getPuzzleModule(); - Tree tree = puzzle.getTree(); - TreeElementView selectedView = selection.getFirstSelection(); - TreeElement treeElement = selectedView.getTreeElement(); - - TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); - TreeTentCell startCell; - TreeTentCell endCell; - TreeTransition transition; - if (treeElement.getType() == TreeElementType.NODE) { - TreeNode treeNode = (TreeNode) treeElement; - transition = treeNode.getChildren().get(0); - - tree.removeTreeElement(transition); - puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); - - board = (TreeTentBoard) transition.getBoard(); - } else { - transition = (TreeTransition) treeElement; + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(transition)); + + final TreeViewSelection newSelection = + new TreeViewSelection(treeView.getElementView(transition)); + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(newSelection)); } - startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); - endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + /** + * Gets the reason why the command cannot be executed + * + * @return if command cannot be executed, returns reason for why the command cannot be executed, + * otherwise null if command can be executed + */ + @Override + public String getErrorString() { + List selectedViews = selection.getSelectedViews(); + if (selectedViews.size() != 1) { + return CommandError.ONE_SELECTED_VIEW.toString(); + } - TreeTentLine line = new TreeTentLine(startCell, endCell); + if (start == null || end == null) { + return "The line must connect a tree to a tent."; + } - TreeTentLine dupLine = null; - for (TreeTentLine l : board.getLines()) { - if (line.compare(l)) { - dupLine = l; - break; - } + TreeElementView view = selection.getFirstSelection(); + TreeElement treeElement = view.getTreeElement(); + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode node = (TreeNode) treeElement; + if (!node.getChildren().isEmpty()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } else { + if (!board.isModifiable()) { + return CommandError.UNMODIFIABLE_BOARD.toString(); + } + } + TreeTentLine line = + new TreeTentLine( + (TreeTentCell) start.getPuzzleElement(), + (TreeTentCell) end.getPuzzleElement()); + for (TreeTentLine l : board.getLines()) { + if (line.compare(l) && !l.isModifiable()) { + return CommandError.UNMODIFIABLE_DATA.toString(); + } + } + + TreeTentCell startCell = (TreeTentCell) start.getPuzzleElement(); + TreeTentCell endCell = (TreeTentCell) end.getPuzzleElement(); + if (!((startCell.getType() == TreeTentType.TENT && endCell.getType() == TreeTentType.TREE) + || (endCell.getType() == TreeTentType.TENT + && startCell.getType() == TreeTentType.TREE))) { + return "The line must connect a tree to a tent."; + } + + return null; } - final TreeTentLine notifyLine; - if (dupLine == null) { - board.addModifiedData(line); - board.getLines().add(line); - notifyLine = line; - } else { - board.removeModifiedData(dupLine); - board.getLines().remove(dupLine); - notifyLine = dupLine; + /** Undoes an command */ + @Override + public void undoCommand() { + Puzzle puzzle = getInstance().getPuzzleModule(); + Tree tree = puzzle.getTree(); + TreeElementView selectedView = selection.getFirstSelection(); + TreeElement treeElement = selectedView.getTreeElement(); + + TreeTentBoard board = (TreeTentBoard) treeElement.getBoard(); + TreeTentCell startCell; + TreeTentCell endCell; + TreeTransition transition; + if (treeElement.getType() == TreeElementType.NODE) { + TreeNode treeNode = (TreeNode) treeElement; + transition = treeNode.getChildren().get(0); + + tree.removeTreeElement(transition); + puzzle.notifyTreeListeners(listener -> listener.onTreeElementRemoved(transition)); + + board = (TreeTentBoard) transition.getBoard(); + } else { + transition = (TreeTransition) treeElement; + } + + startCell = (TreeTentCell) board.getPuzzleElement(start.getPuzzleElement()); + endCell = (TreeTentCell) board.getPuzzleElement(end.getPuzzleElement()); + + TreeTentLine line = new TreeTentLine(startCell, endCell); + + TreeTentLine dupLine = null; + for (TreeTentLine l : board.getLines()) { + if (line.compare(l)) { + dupLine = l; + break; + } + } + + final TreeTentLine notifyLine; + if (dupLine == null) { + board.addModifiedData(line); + board.getLines().add(line); + notifyLine = line; + } else { + board.removeModifiedData(dupLine); + board.getLines().remove(dupLine); + notifyLine = dupLine; + } + transition.propagateChange(notifyLine); + puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); + + final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); + puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); + + puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); } - transition.propagateChange(notifyLine); - puzzle.notifyBoardListeners(listener -> listener.onBoardDataChanged(notifyLine)); - - final TreeElement finalTreeElement = selection.getFirstSelection().getTreeElement(); - puzzle.notifyBoardListeners(listener -> listener.onTreeElementChanged(finalTreeElement)); - - puzzle.notifyTreeListeners(listener -> listener.onTreeSelectionChanged(selection)); - } - - private TreeTentElementView getViewInDirection(ElementView endDrag) { - TreeTentView boardView = (TreeTentView) getInstance().getLegupUI().getBoardView(); - Dimension size = boardView.getElementSize(); - int xIndex, yIndex; - - Point startLoc = start.getLocation(); - Point endLoc = endDrag.getLocation(); - double radians = Math.atan2(startLoc.y - endLoc.y, endLoc.x - startLoc.x); - if (radians >= Math.PI / 4 && radians < 3 * Math.PI / 4) { - // up - xIndex = startLoc.x / size.width; - yIndex = (startLoc.y / size.height) - 1; - } else { - if (radians >= -Math.PI / 4 && radians < Math.PI / 4) { - // right - xIndex = (startLoc.x / size.width) + 1; - yIndex = startLoc.y / size.height; - } else { - if (radians >= -3 * Math.PI / 4 && radians < -Math.PI / 4) { - // down - xIndex = startLoc.x / size.width; - yIndex = (startLoc.y / size.height) + 1; + + private TreeTentElementView getViewInDirection(ElementView endDrag) { + TreeTentView boardView = (TreeTentView) getInstance().getLegupUI().getBoardView(); + Dimension size = boardView.getElementSize(); + int xIndex, yIndex; + + Point startLoc = start.getLocation(); + Point endLoc = endDrag.getLocation(); + double radians = Math.atan2(startLoc.y - endLoc.y, endLoc.x - startLoc.x); + if (radians >= Math.PI / 4 && radians < 3 * Math.PI / 4) { + // up + xIndex = startLoc.x / size.width; + yIndex = (startLoc.y / size.height) - 1; } else { - // left - xIndex = (startLoc.x / size.width) - 1; - yIndex = startLoc.y / size.height; + if (radians >= -Math.PI / 4 && radians < Math.PI / 4) { + // right + xIndex = (startLoc.x / size.width) + 1; + yIndex = startLoc.y / size.height; + } else { + if (radians >= -3 * Math.PI / 4 && radians < -Math.PI / 4) { + // down + xIndex = startLoc.x / size.width; + yIndex = (startLoc.y / size.height) + 1; + } else { + // left + xIndex = (startLoc.x / size.width) - 1; + yIndex = startLoc.y / size.height; + } + } } - } + return (TreeTentElementView) boardView.getElement(xIndex - 1, yIndex - 1); } - return (TreeTentElementView) boardView.getElement(xIndex - 1, yIndex - 1); - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java index 94381b031..68c97865d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTent.java @@ -7,82 +7,82 @@ public class TreeTent extends Puzzle { - public TreeTent() { - super(); + public TreeTent() { + super(); - this.name = "TreeTent"; + this.name = "TreeTent"; - this.importer = new TreeTentImporter(this); - this.exporter = new TreeTentExporter(this); + this.importer = new TreeTentImporter(this); + this.exporter = new TreeTentExporter(this); - this.factory = new TreeTentCellFactory(); - } + this.factory = new TreeTentCellFactory(); + } - /** Initializes the game board. Called by the invoker of the class */ - @Override - public void initializeView() { - TreeTentBoard board = (TreeTentBoard) currentBoard; - boardView = new TreeTentView((TreeTentBoard) currentBoard); - boardView.setBoard(board); - } + /** Initializes the game board. Called by the invoker of the class */ + @Override + public void initializeView() { + TreeTentBoard board = (TreeTentBoard) currentBoard; + boardView = new TreeTentView((TreeTentBoard) currentBoard); + boardView.setBoard(board); + } - /** - * Generates a random edu.rpi.legup.puzzle based on the difficulty - * - * @param difficulty level of difficulty (1-10) - * @return board of the random edu.rpi.legup.puzzle - */ - @Override - public Board generatePuzzle(int difficulty) { - return null; - } + /** + * Generates a random edu.rpi.legup.puzzle based on the difficulty + * + * @param difficulty level of difficulty (1-10) + * @return board of the random edu.rpi.legup.puzzle + */ + @Override + public Board generatePuzzle(int difficulty) { + return null; + } - @Override - /** - * Determines if the given dimensions are valid for Tree Tent - * - * @param rows the number of rows - * @param columns the number of columns - * @return true if the given dimensions are valid for Tree Tent, false otherwise - */ - public boolean isValidDimensions(int rows, int columns) { - // This is a placeholder, this method needs to be implemented - return rows > 0 && columns > 0; - } + @Override + /** + * Determines if the given dimensions are valid for Tree Tent + * + * @param rows the number of rows + * @param columns the number of columns + * @return true if the given dimensions are valid for Tree Tent, false otherwise + */ + public boolean isValidDimensions(int rows, int columns) { + // This is a placeholder, this method needs to be implemented + return rows > 0 && columns > 0; + } - /** - * Determines if the current board is a valid state - * - * @param board board to check for validity - * @return true if board is valid, false otherwise - */ - @Override - public boolean isBoardComplete(Board board) { - return false; - } + /** + * Determines if the current board is a valid state + * + * @param board board to check for validity + * @return true if board is valid, false otherwise + */ + @Override + public boolean isBoardComplete(Board board) { + return false; + } - /** - * Callback for when the board puzzleElement changes - * - * @param board the board that has changed - */ - @Override - public void onBoardChange(Board board) {} + /** + * Callback for when the board puzzleElement changes + * + * @param board the board that has changed + */ + @Override + public void onBoardChange(Board board) {} - /** - * @return if it is valid TreeTent puzzle must have same number of clues as the dimension size - */ - @Override - public boolean checkValidity() { - TreeTentBoard b = (TreeTentBoard) this.getBoardView().getBoard(); - List elements = b.getPuzzleElements(); - int treeCount = 0; - for (PuzzleElement element : elements) { - TreeTentCell c = (TreeTentCell) element; - if (c.getType() == TreeTentType.TREE) { - treeCount++; - } + /** + * @return if it is valid TreeTent puzzle must have same number of clues as the dimension size + */ + @Override + public boolean checkValidity() { + TreeTentBoard b = (TreeTentBoard) this.getBoardView().getBoard(); + List elements = b.getPuzzleElements(); + int treeCount = 0; + for (PuzzleElement element : elements) { + TreeTentCell c = (TreeTentCell) element; + if (c.getType() == TreeTentType.TREE) { + treeCount++; + } + } + return treeCount != 0; } - return treeCount != 0; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java index ac1dcca38..09706f92a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentBoard.java @@ -9,234 +9,234 @@ public class TreeTentBoard extends GridBoard { - private ArrayList lines; + private ArrayList lines; - private ArrayList rowClues; - private ArrayList colClues; + private ArrayList rowClues; + private ArrayList colClues; - public TreeTentBoard(int width, int height) { - super(width, height); + public TreeTentBoard(int width, int height) { + super(width, height); - this.lines = new ArrayList<>(); + this.lines = new ArrayList<>(); - this.rowClues = new ArrayList<>(); - this.colClues = new ArrayList<>(); + this.rowClues = new ArrayList<>(); + this.colClues = new ArrayList<>(); - for (int i = 0; i < height; i++) { - rowClues.add(null); - } - for (int i = 0; i < width; i++) { - colClues.add(null); - } - } - - public TreeTentBoard(int size) { - this(size, size); - } - - public ArrayList getLines() { - return lines; - } - - public ArrayList getRowClues() { - return rowClues; - } - - public ArrayList getColClues() { - return colClues; - } - - @Override - public TreeTentCell getCell(int x, int y) { - return (TreeTentCell) super.getCell(x, y); - } - - @Override - public PuzzleElement getPuzzleElement(PuzzleElement element) { - switch (element.getIndex()) { - case -2: - return element; - case -1: - TreeTentLine line = (TreeTentLine) element; - TreeTentLine thisLine = null; - for (TreeTentLine l : lines) { - if (line.compare(l)) { - thisLine = l; - break; - } - } - return thisLine; - default: - return super.getPuzzleElement(element); - } - } - - public TreeTentClue getClue(int x, int y) { - if (x == getWidth() && 0 <= y && y < getHeight()) { - return rowClues.get(y); - } else { - if (y == getHeight() && 0 <= x && x < getWidth()) { - return colClues.get(x); - } - } - return null; - } - - /** - * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle element - * with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - @Override - public void notifyAddition(PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - lines.add((TreeTentLine) puzzleElement); - } - } - - /** - * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle - * element with the data. - * - * @param puzzleElement equivalent puzzle element with the data. - */ - @Override - public void notifyDeletion(PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - for (TreeTentLine line : lines) { - if (line.compare((TreeTentLine) puzzleElement)) { - lines.remove(line); - break; - } - } - } - } - - /** - * Get a list of all orthogonally adjacent cells. - * - * @param cell The cell to get adjacent cells from. - * @param type The cell types to get. - * @return List of adjacent cells in the form { up, right, down, left }. If an adjacent cell is - * null, it will not be added to the list. - */ - public List getAdjacent(TreeTentCell cell, TreeTentType type) { - List adj = new ArrayList<>(); - Point loc = cell.getLocation(); - for (int i = -2; i < 2; i++) { - TreeTentCell adjCell = getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); - if (adjCell != null && adjCell.getType() == type) { - adj.add(adjCell); - } + for (int i = 0; i < height; i++) { + rowClues.add(null); + } + for (int i = 0; i < width; i++) { + colClues.add(null); + } } - return adj; - } - - /** - * Gets all cells of a specified type that are diagonals of a specified cell - * - * @param cell the base cell - * @param type the type to look for - * @return a list of TreeTentCells that are diagonals of the given TreeTentCell and are of the - * given TreeTentType - */ - public List getDiagonals(TreeTentCell cell, TreeTentType type) { - List dia = new ArrayList<>(); - Point loc = cell.getLocation(); - TreeTentCell upRight = getCell(loc.x + 1, loc.y - 1); - TreeTentCell downRight = getCell(loc.x + 1, loc.y + 1); - TreeTentCell downLeft = getCell(loc.x - 1, loc.y + 1); - TreeTentCell upLeft = getCell(loc.x - 1, loc.y - 1); - if (upRight != null && upRight.getType() == type) { - dia.add(upRight); + + public TreeTentBoard(int size) { + this(size, size); } - if (downLeft != null && downLeft.getType() == type) { - dia.add(downLeft); + + public ArrayList getLines() { + return lines; } - if (downRight != null && downRight.getType() == type) { - dia.add(downRight); + + public ArrayList getRowClues() { + return rowClues; } - if (upLeft != null && upLeft.getType() == type) { - dia.add(upLeft); + + public ArrayList getColClues() { + return colClues; } - return dia; - } - - /** - * Creates and returns a list of TreeTentCells that match the given TreeTentType - * - * @param index the row or column number - * @param type type of TreeTent element - * @param isRow boolean value beased on whether a row of column is being checked - * @return List of TreeTentCells that match the given TreeTentType - */ - public List getRowCol(int index, TreeTentType type, boolean isRow) { - List list = new ArrayList<>(); - if (isRow) { - for (int i = 0; i < dimension.height; i++) { - TreeTentCell cell = getCell(i, index); - if (cell.getType() == type) { - list.add(cell); - } - } - } else { - for (int i = 0; i < dimension.width; i++) { - TreeTentCell cell = getCell(index, i); - if (cell.getType() == type) { - list.add(cell); - } - } + + @Override + public TreeTentCell getCell(int x, int y) { + return (TreeTentCell) super.getCell(x, y); } - return list; - } - - /** - * Determines if this board contains the equivalent puzzle elements as the one specified - * - * @param board board to check equivalence - * @return true if the boards are equivalent, false otherwise - */ - @Override - public boolean equalsBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - for (TreeTentLine l1 : lines) { - boolean hasLine = false; - for (TreeTentLine l2 : treeTentBoard.lines) { - if (l1.compare(l2)) { - hasLine = true; - } - } - if (!hasLine) { - return false; - } + + @Override + public PuzzleElement getPuzzleElement(PuzzleElement element) { + switch (element.getIndex()) { + case -2: + return element; + case -1: + TreeTentLine line = (TreeTentLine) element; + TreeTentLine thisLine = null; + for (TreeTentLine l : lines) { + if (line.compare(l)) { + thisLine = l; + break; + } + } + return thisLine; + default: + return super.getPuzzleElement(element); + } } - return super.equalsBoard(treeTentBoard); - } - - /** - * Performs a deep copy of the TreeTentBoard - * - * @return a TreeTentBoard object that is a deep copy of the current TreeTentBoard - */ - @Override - public TreeTentBoard copy() { - TreeTentBoard copy = new TreeTentBoard(dimension.width, dimension.height); - for (int x = 0; x < this.dimension.width; x++) { - for (int y = 0; y < this.dimension.height; y++) { - copy.setCell(x, y, getCell(x, y).copy()); - } + + public TreeTentClue getClue(int x, int y) { + if (x == getWidth() && 0 <= y && y < getHeight()) { + return rowClues.get(y); + } else { + if (y == getHeight() && 0 <= x && x < getWidth()) { + return colClues.get(x); + } + } + return null; + } + + /** + * Called when a {@link PuzzleElement} has been added and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + @Override + public void notifyAddition(PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + lines.add((TreeTentLine) puzzleElement); + } } - for (TreeTentLine line : lines) { - TreeTentLine lineCpy = line.copy(); - lineCpy.setModifiable(false); - copy.getLines().add(lineCpy); + + /** + * Called when a {@link PuzzleElement} has been deleted and passes in the equivalent puzzle + * element with the data. + * + * @param puzzleElement equivalent puzzle element with the data. + */ + @Override + public void notifyDeletion(PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + for (TreeTentLine line : lines) { + if (line.compare((TreeTentLine) puzzleElement)) { + lines.remove(line); + break; + } + } + } } - for (PuzzleElement e : modifiedData) { - copy.getPuzzleElement(e).setModifiable(false); + + /** + * Get a list of all orthogonally adjacent cells. + * + * @param cell The cell to get adjacent cells from. + * @param type The cell types to get. + * @return List of adjacent cells in the form { up, right, down, left }. If an adjacent cell is + * null, it will not be added to the list. + */ + public List getAdjacent(TreeTentCell cell, TreeTentType type) { + List adj = new ArrayList<>(); + Point loc = cell.getLocation(); + for (int i = -2; i < 2; i++) { + TreeTentCell adjCell = getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); + if (adjCell != null && adjCell.getType() == type) { + adj.add(adjCell); + } + } + return adj; + } + + /** + * Gets all cells of a specified type that are diagonals of a specified cell + * + * @param cell the base cell + * @param type the type to look for + * @return a list of TreeTentCells that are diagonals of the given TreeTentCell and are of the + * given TreeTentType + */ + public List getDiagonals(TreeTentCell cell, TreeTentType type) { + List dia = new ArrayList<>(); + Point loc = cell.getLocation(); + TreeTentCell upRight = getCell(loc.x + 1, loc.y - 1); + TreeTentCell downRight = getCell(loc.x + 1, loc.y + 1); + TreeTentCell downLeft = getCell(loc.x - 1, loc.y + 1); + TreeTentCell upLeft = getCell(loc.x - 1, loc.y - 1); + if (upRight != null && upRight.getType() == type) { + dia.add(upRight); + } + if (downLeft != null && downLeft.getType() == type) { + dia.add(downLeft); + } + if (downRight != null && downRight.getType() == type) { + dia.add(downRight); + } + if (upLeft != null && upLeft.getType() == type) { + dia.add(upLeft); + } + return dia; + } + + /** + * Creates and returns a list of TreeTentCells that match the given TreeTentType + * + * @param index the row or column number + * @param type type of TreeTent element + * @param isRow boolean value beased on whether a row of column is being checked + * @return List of TreeTentCells that match the given TreeTentType + */ + public List getRowCol(int index, TreeTentType type, boolean isRow) { + List list = new ArrayList<>(); + if (isRow) { + for (int i = 0; i < dimension.height; i++) { + TreeTentCell cell = getCell(i, index); + if (cell.getType() == type) { + list.add(cell); + } + } + } else { + for (int i = 0; i < dimension.width; i++) { + TreeTentCell cell = getCell(index, i); + if (cell.getType() == type) { + list.add(cell); + } + } + } + return list; + } + + /** + * Determines if this board contains the equivalent puzzle elements as the one specified + * + * @param board board to check equivalence + * @return true if the boards are equivalent, false otherwise + */ + @Override + public boolean equalsBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + for (TreeTentLine l1 : lines) { + boolean hasLine = false; + for (TreeTentLine l2 : treeTentBoard.lines) { + if (l1.compare(l2)) { + hasLine = true; + } + } + if (!hasLine) { + return false; + } + } + return super.equalsBoard(treeTentBoard); + } + + /** + * Performs a deep copy of the TreeTentBoard + * + * @return a TreeTentBoard object that is a deep copy of the current TreeTentBoard + */ + @Override + public TreeTentBoard copy() { + TreeTentBoard copy = new TreeTentBoard(dimension.width, dimension.height); + for (int x = 0; x < this.dimension.width; x++) { + for (int y = 0; y < this.dimension.height; y++) { + copy.setCell(x, y, getCell(x, y).copy()); + } + } + for (TreeTentLine line : lines) { + TreeTentLine lineCpy = line.copy(); + lineCpy.setModifiable(false); + copy.getLines().add(lineCpy); + } + for (PuzzleElement e : modifiedData) { + copy.getPuzzleElement(e).setModifiable(false); + } + copy.rowClues = rowClues; + copy.colClues = colClues; + return copy; } - copy.rowClues = rowClues; - copy.colClues = colClues; - return copy; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java index e19c8b3a2..c7c9f0d21 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCell.java @@ -7,50 +7,50 @@ public class TreeTentCell extends GridCell { - public TreeTentCell(TreeTentType value, Point location) { - super(value, location); - } + public TreeTentCell(TreeTentType value, Point location) { + super(value, location); + } - public TreeTentType getType() { - return data; - } + public TreeTentType getType() { + return data; + } - public int getValue() { - switch (data) { - case TREE: - return 1; - case GRASS: - return 2; - case TENT: - return 3; - default: - return 0; + public int getValue() { + switch (data) { + case TREE: + return 1; + case GRASS: + return 2; + case TENT: + return 3; + default: + return 0; + } } - } - @Override - public void setType(Element e, MouseEvent m) { - switch (e.getElementName()) { - case "Unknown Tile": - this.data = TreeTentType.UNKNOWN; - break; - case "Tree Tile": - this.data = TreeTentType.TREE; - break; - case "Grass Tile": - this.data = TreeTentType.GRASS; - break; - case "Tent Tile": - this.data = TreeTentType.TENT; + @Override + public void setType(Element e, MouseEvent m) { + switch (e.getElementName()) { + case "Unknown Tile": + this.data = TreeTentType.UNKNOWN; + break; + case "Tree Tile": + this.data = TreeTentType.TREE; + break; + case "Grass Tile": + this.data = TreeTentType.GRASS; + break; + case "Tent Tile": + this.data = TreeTentType.TENT; + } } - } - @Override - public TreeTentCell copy() { - TreeTentCell copy = new TreeTentCell(data, (Point) location.clone()); - copy.setIndex(index); - copy.setModifiable(isModifiable); - copy.setGiven(isGiven); - return copy; - } + @Override + public TreeTentCell copy() { + TreeTentCell copy = new TreeTentCell(data, (Point) location.clone()); + copy.setIndex(index); + copy.setModifiable(isModifiable); + copy.setGiven(isGiven); + return copy; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java index 10bcf77c7..1697b8bd5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentCellFactory.java @@ -10,92 +10,94 @@ import org.w3c.dom.Node; public class TreeTentCellFactory extends ElementFactory { - /** - * Creates a puzzleElement based on the xml document Node and adds it to the board - * - * @param node node that represents the puzzleElement - * @param board board to add the newly created cell - * @return newly created cell from the xml document Node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { - try { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - int width = treeTentBoard.getWidth(); - int height = treeTentBoard.getHeight(); - NamedNodeMap attributeList = node.getAttributes(); - if (node.getNodeName().equalsIgnoreCase("cell")) { + /** + * Creates a puzzleElement based on the xml document Node and adds it to the board + * + * @param node node that represents the puzzleElement + * @param board board to add the newly created cell + * @return newly created cell from the xml document Node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public PuzzleElement importCell(Node node, Board board) throws InvalidFileFormatException { + try { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + int width = treeTentBoard.getWidth(); + int height = treeTentBoard.getHeight(); + NamedNodeMap attributeList = node.getAttributes(); + if (node.getNodeName().equalsIgnoreCase("cell")) { - int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); - int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); - int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); - if (x >= width || y >= height) { - throw new InvalidFileFormatException("TreeTent Factory: cell location out of bounds"); - } - if (value < 0 || value > 3) { - throw new InvalidFileFormatException("TreeTent Factory: cell unknown value"); - } + int value = Integer.valueOf(attributeList.getNamedItem("value").getNodeValue()); + int x = Integer.valueOf(attributeList.getNamedItem("x").getNodeValue()); + int y = Integer.valueOf(attributeList.getNamedItem("y").getNodeValue()); + if (x >= width || y >= height) { + throw new InvalidFileFormatException( + "TreeTent Factory: cell location out of bounds"); + } + if (value < 0 || value > 3) { + throw new InvalidFileFormatException("TreeTent Factory: cell unknown value"); + } - TreeTentCell cell = new TreeTentCell(TreeTentType.valueOf(value), new Point(x, y)); - cell.setIndex(y * height + x); - return cell; - } else { - if (node.getNodeName().equalsIgnoreCase("line")) { - int x1 = Integer.valueOf(attributeList.getNamedItem("x1").getNodeValue()); - int y1 = Integer.valueOf(attributeList.getNamedItem("y1").getNodeValue()); - int x2 = Integer.valueOf(attributeList.getNamedItem("x2").getNodeValue()); - int y2 = Integer.valueOf(attributeList.getNamedItem("y2").getNodeValue()); - if (x1 >= width || y1 >= height || x2 >= width || y2 >= height) { - throw new InvalidFileFormatException("TreeTent Factory: line location out of bounds"); - } + TreeTentCell cell = new TreeTentCell(TreeTentType.valueOf(value), new Point(x, y)); + cell.setIndex(y * height + x); + return cell; + } else { + if (node.getNodeName().equalsIgnoreCase("line")) { + int x1 = Integer.valueOf(attributeList.getNamedItem("x1").getNodeValue()); + int y1 = Integer.valueOf(attributeList.getNamedItem("y1").getNodeValue()); + int x2 = Integer.valueOf(attributeList.getNamedItem("x2").getNodeValue()); + int y2 = Integer.valueOf(attributeList.getNamedItem("y2").getNodeValue()); + if (x1 >= width || y1 >= height || x2 >= width || y2 >= height) { + throw new InvalidFileFormatException( + "TreeTent Factory: line location out of bounds"); + } - TreeTentCell c1 = treeTentBoard.getCell(x1, y1); - TreeTentCell c2 = treeTentBoard.getCell(x2, y2); - return new TreeTentLine(c1, c2); - } else { - throw new InvalidFileFormatException( - "TreeTent Factory: unknown puzzleElement puzzleElement"); + TreeTentCell c1 = treeTentBoard.getCell(x1, y1); + TreeTentCell c2 = treeTentBoard.getCell(x2, y2); + return new TreeTentLine(c1, c2); + } else { + throw new InvalidFileFormatException( + "TreeTent Factory: unknown puzzleElement puzzleElement"); + } + } + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "TreeTent Factory: unknown value where integer expected"); + } catch (NullPointerException e) { + throw new InvalidFileFormatException("TreeTent Factory: could not find attribute(s)"); } - } - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "TreeTent Factory: unknown value where integer expected"); - } catch (NullPointerException e) { - throw new InvalidFileFormatException("TreeTent Factory: could not find attribute(s)"); } - } - /** - * Creates a xml document puzzleElement from a cell for exporting - * - * @param document xml document - * @param puzzleElement PuzzleElement cell - * @return xml PuzzleElement - */ - public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentCell) { - org.w3c.dom.Element cellElement = document.createElement("cell"); + /** + * Creates a xml document puzzleElement from a cell for exporting + * + * @param document xml document + * @param puzzleElement PuzzleElement cell + * @return xml PuzzleElement + */ + public org.w3c.dom.Element exportCell(Document document, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentCell) { + org.w3c.dom.Element cellElement = document.createElement("cell"); - TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); + TreeTentCell cell = (TreeTentCell) puzzleElement; + Point loc = cell.getLocation(); - cellElement.setAttribute("value", String.valueOf(cell.getValue())); - cellElement.setAttribute("x", String.valueOf(loc.x)); - cellElement.setAttribute("y", String.valueOf(loc.y)); + cellElement.setAttribute("value", String.valueOf(cell.getValue())); + cellElement.setAttribute("x", String.valueOf(loc.x)); + cellElement.setAttribute("y", String.valueOf(loc.y)); - return cellElement; - } else { - org.w3c.dom.Element lineElement = document.createElement("line"); + return cellElement; + } else { + org.w3c.dom.Element lineElement = document.createElement("line"); - TreeTentLine line = (TreeTentLine) puzzleElement; + TreeTentLine line = (TreeTentLine) puzzleElement; - lineElement.setAttribute("x1", String.valueOf(line.getC1().getLocation().x)); - lineElement.setAttribute("y1", String.valueOf(line.getC1().getLocation().y)); - lineElement.setAttribute("x2", String.valueOf(line.getC2().getLocation().x)); - lineElement.setAttribute("y2", String.valueOf(line.getC2().getLocation().y)); + lineElement.setAttribute("x1", String.valueOf(line.getC1().getLocation().x)); + lineElement.setAttribute("y1", String.valueOf(line.getC1().getLocation().y)); + lineElement.setAttribute("x2", String.valueOf(line.getC2().getLocation().x)); + lineElement.setAttribute("y2", String.valueOf(line.getC2().getLocation().y)); - return lineElement; + return lineElement; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java index df9e7eed2..bcba7dc94 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClue.java @@ -3,53 +3,53 @@ import edu.rpi.legup.model.gameboard.PuzzleElement; public class TreeTentClue extends PuzzleElement { - private TreeTentType type; - private int clueIndex; - - public TreeTentClue(int value, int clueIndex, TreeTentType type) { - super(value); - this.index = -2; - this.clueIndex = clueIndex; - this.type = type; - } - - public static String colNumToString(int col) { - final StringBuilder sb = new StringBuilder(); - col--; - while (col >= 0) { - int numChar = (col % 26) + 65; - sb.append((char) numChar); - col = (col / 26) - 1; - } - return sb.reverse().toString(); - } - - public static int colStringToColNum(String col) { - int result = 0; - for (int i = 0; i < col.length(); i++) { - result *= 26; - result += col.charAt(i) - 'A' + 1; - } - return result; - } - - public int getClueIndex() { - return clueIndex; - } - - public void setClueIndex(int clueIndex) { - this.clueIndex = clueIndex; - } - - public TreeTentType getType() { - return type; - } - - public void setType(TreeTentType type) { - this.type = type; - } - - public TreeTentClue copy() { - return null; - } + private TreeTentType type; + private int clueIndex; + + public TreeTentClue(int value, int clueIndex, TreeTentType type) { + super(value); + this.index = -2; + this.clueIndex = clueIndex; + this.type = type; + } + + public static String colNumToString(int col) { + final StringBuilder sb = new StringBuilder(); + col--; + while (col >= 0) { + int numChar = (col % 26) + 65; + sb.append((char) numChar); + col = (col / 26) - 1; + } + return sb.reverse().toString(); + } + + public static int colStringToColNum(String col) { + int result = 0; + for (int i = 0; i < col.length(); i++) { + result *= 26; + result += col.charAt(i) - 'A' + 1; + } + return result; + } + + public int getClueIndex() { + return clueIndex; + } + + public void setClueIndex(int clueIndex) { + this.clueIndex = clueIndex; + } + + public TreeTentType getType() { + return type; + } + + public void setType(TreeTentType type) { + this.type = type; + } + + public TreeTentClue copy() { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java index e59c86f62..d1b230d20 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentClueView.java @@ -5,50 +5,50 @@ public class TreeTentClueView extends ElementView { - private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); - private static final Color FONT_COLOR = Color.BLACK; - - public TreeTentClueView(TreeTentClue clue) { - super(clue); - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - @Override - public TreeTentClue getPuzzleElement() { - return (TreeTentClue) super.getPuzzleElement(); - } - - @Override - public void drawElement(Graphics2D graphics2D) { - graphics2D.setColor(FONT_COLOR); - graphics2D.setFont(FONT); - FontMetrics metrics = graphics2D.getFontMetrics(FONT); - String value; - - TreeTentClue clue = getPuzzleElement(); - switch (clue.getType()) { - case CLUE_NORTH: - value = String.valueOf(clue.getData() + 1); - break; - case CLUE_EAST: - value = String.valueOf(clue.getData()); - break; - case CLUE_SOUTH: - value = String.valueOf(clue.getData()); - break; - case CLUE_WEST: - value = TreeTentClue.colNumToString(clue.getData() + 1); - break; - default: - value = ""; + private static final Font FONT = new Font("TimesRoman", Font.BOLD, 16); + private static final Color FONT_COLOR = Color.BLACK; + + public TreeTentClueView(TreeTentClue clue) { + super(clue); + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + @Override + public TreeTentClue getPuzzleElement() { + return (TreeTentClue) super.getPuzzleElement(); } - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(value, xText, yText); - } + @Override + public void drawElement(Graphics2D graphics2D) { + graphics2D.setColor(FONT_COLOR); + graphics2D.setFont(FONT); + FontMetrics metrics = graphics2D.getFontMetrics(FONT); + String value; + + TreeTentClue clue = getPuzzleElement(); + switch (clue.getType()) { + case CLUE_NORTH: + value = String.valueOf(clue.getData() + 1); + break; + case CLUE_EAST: + value = String.valueOf(clue.getData()); + break; + case CLUE_SOUTH: + value = String.valueOf(clue.getData()); + break; + case CLUE_WEST: + value = TreeTentClue.colNumToString(clue.getData() + 1); + break; + default: + value = ""; + } + + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(value, xText, yText); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java index d3a4b3d26..79e074657 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentController.java @@ -19,115 +19,120 @@ public class TreeTentController extends ElementController { - private ElementView lastCellPressed; - private ElementView dragStart; + private ElementView lastCellPressed; + private ElementView dragStart; - public TreeTentController() { - super(); - this.dragStart = null; - this.lastCellPressed = null; - } + public TreeTentController() { + super(); + this.dragStart = null; + this.lastCellPressed = null; + } - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() != MouseEvent.BUTTON2) { - BoardView boardView = getInstance().getLegupUI().getBoardView(); - dragStart = boardView.getElement(e.getPoint()); - lastCellPressed = boardView.getElement(e.getPoint()); + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() != MouseEvent.BUTTON2) { + BoardView boardView = getInstance().getLegupUI().getBoardView(); + dragStart = boardView.getElement(e.getPoint()); + lastCellPressed = boardView.getElement(e.getPoint()); + } } - } - @Override - public void mouseReleased(MouseEvent e) { - if (GameBoardFacade.getInstance().getLegupUI().getTreePanel() != null - && e.getButton() != MouseEvent.BUTTON2) { - TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); - TreeView treeView = GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); - BoardView boardView = getInstance().getLegupUI().getBoardView(); - lastCellPressed = boardView.getElement(e.getPoint()); - Board board = boardView.getBoard(); - TreeViewSelection selection = treeView.getSelection(); + @Override + public void mouseReleased(MouseEvent e) { + if (GameBoardFacade.getInstance().getLegupUI().getTreePanel() != null + && e.getButton() != MouseEvent.BUTTON2) { + TreePanel treePanel = GameBoardFacade.getInstance().getLegupUI().getTreePanel(); + TreeView treeView = + GameBoardFacade.getInstance().getLegupUI().getTreePanel().getTreeView(); + BoardView boardView = getInstance().getLegupUI().getBoardView(); + lastCellPressed = boardView.getElement(e.getPoint()); + Board board = boardView.getBoard(); + TreeViewSelection selection = treeView.getSelection(); - if (dragStart != null) { - if (board instanceof CaseBoard) { - CaseBoard caseBoard = (CaseBoard) board; - AutoCaseRuleCommand autoCaseRuleCommand = - new AutoCaseRuleCommand(dragStart, selection, caseBoard.getCaseRule(), caseBoard, e); - if (autoCaseRuleCommand.canExecute()) { - autoCaseRuleCommand.execute(); - getInstance().getHistory().pushChange(autoCaseRuleCommand); - treePanel.updateError(""); - } else { - treePanel.updateError(autoCaseRuleCommand.getError()); - } - } else { - if (dragStart == lastCellPressed) { - if (dragStart.getPuzzleElement().getIndex() >= 0) { - ICommand edit = new EditDataCommand(lastCellPressed, selection, e); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - treePanel.updateError(""); - } else { - treePanel.updateError(edit.getError()); - } - } else { - ClueCommand edit = new ClueCommand(selection, (TreeTentClueView) dragStart); - if (edit.canExecute()) { - edit.execute(); - getInstance().getHistory().pushChange(edit); - treePanel.updateError(""); - } else { - treePanel.updateError(edit.getError()); - } - } - } else { - if (lastCellPressed != null) { - if (dragStart instanceof TreeTentElementView) { - ICommand editLine = - new EditLineCommand( - selection, (TreeTentElementView) dragStart, lastCellPressed); - if (editLine.canExecute()) { - editLine.execute(); - getInstance().getHistory().pushChange(editLine); + if (dragStart != null) { + if (board instanceof CaseBoard) { + CaseBoard caseBoard = (CaseBoard) board; + AutoCaseRuleCommand autoCaseRuleCommand = + new AutoCaseRuleCommand( + dragStart, selection, caseBoard.getCaseRule(), caseBoard, e); + if (autoCaseRuleCommand.canExecute()) { + autoCaseRuleCommand.execute(); + getInstance().getHistory().pushChange(autoCaseRuleCommand); + treePanel.updateError(""); + } else { + treePanel.updateError(autoCaseRuleCommand.getError()); + } } else { - treePanel.updateError(editLine.getError()); + if (dragStart == lastCellPressed) { + if (dragStart.getPuzzleElement().getIndex() >= 0) { + ICommand edit = new EditDataCommand(lastCellPressed, selection, e); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + treePanel.updateError(""); + } else { + treePanel.updateError(edit.getError()); + } + } else { + ClueCommand edit = + new ClueCommand(selection, (TreeTentClueView) dragStart); + if (edit.canExecute()) { + edit.execute(); + getInstance().getHistory().pushChange(edit); + treePanel.updateError(""); + } else { + treePanel.updateError(edit.getError()); + } + } + } else { + if (lastCellPressed != null) { + if (dragStart instanceof TreeTentElementView) { + ICommand editLine = + new EditLineCommand( + selection, + (TreeTentElementView) dragStart, + lastCellPressed); + if (editLine.canExecute()) { + editLine.execute(); + getInstance().getHistory().pushChange(editLine); + } else { + treePanel.updateError(editLine.getError()); + } + } + } + } } - } } - } + dragStart = null; + lastCellPressed = null; } - } - dragStart = null; - lastCellPressed = null; } - } - @Override - public void changeCell(MouseEvent e, PuzzleElement element) { - TreeTentCell cell = (TreeTentCell) element; - if (e.getButton() == MouseEvent.BUTTON1) { - if (cell.getData() == TreeTentType.UNKNOWN) { - element.setData(TreeTentType.GRASS); - } else { - if (cell.getData() == TreeTentType.GRASS) { - element.setData(TreeTentType.TENT); - } else { - element.setData(TreeTentType.UNKNOWN); - } - } - } else { - if (e.getButton() == MouseEvent.BUTTON3) { - if (cell.getData() == TreeTentType.UNKNOWN) { - element.setData(TreeTentType.TENT); + @Override + public void changeCell(MouseEvent e, PuzzleElement element) { + TreeTentCell cell = (TreeTentCell) element; + if (e.getButton() == MouseEvent.BUTTON1) { + if (cell.getData() == TreeTentType.UNKNOWN) { + element.setData(TreeTentType.GRASS); + } else { + if (cell.getData() == TreeTentType.GRASS) { + element.setData(TreeTentType.TENT); + } else { + element.setData(TreeTentType.UNKNOWN); + } + } } else { - if (cell.getData() == TreeTentType.GRASS) { - element.setData(TreeTentType.UNKNOWN); - } else { - element.setData(TreeTentType.GRASS); - } + if (e.getButton() == MouseEvent.BUTTON3) { + if (cell.getData() == TreeTentType.UNKNOWN) { + element.setData(TreeTentType.TENT); + } else { + if (cell.getData() == TreeTentType.GRASS) { + element.setData(TreeTentType.UNKNOWN); + } else { + element.setData(TreeTentType.GRASS); + } + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java index 740ea5ea8..1196ab075 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentElementView.java @@ -5,51 +5,69 @@ import java.awt.geom.Rectangle2D; public class TreeTentElementView extends GridElementView { - public TreeTentElementView(TreeTentCell cell) { - super(cell); - } + public TreeTentElementView(TreeTentCell cell) { + super(cell); + } - /** - * Draws on the given frame based on the type of the cell of the current puzzleElement - * - * @param graphics2D the frame to be drawn on - */ - @Override - public void drawElement(Graphics2D graphics2D) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - TreeTentType type = cell.getType(); - graphics2D.setStroke(new BasicStroke(0)); - if (type == TreeTentType.UNKNOWN) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.setColor(Color.LIGHT_GRAY); - graphics2D.fill( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); - graphics2D.setColor(Color.BLACK); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); - } else { - if (type == TreeTentType.TREE) { - graphics2D.drawImage( - TreeTentView.TREE, location.x, location.y, size.width, size.height, null, null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == TreeTentType.GRASS) { - graphics2D.drawImage( - TreeTentView.GRASS, location.x, location.y, size.width, size.height, null, null); - graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } else { - if (type == TreeTentType.TENT) { - graphics2D.drawImage( - TreeTentView.TENT, location.x, location.y, size.width, size.height, null, null); + /** + * Draws on the given frame based on the type of the cell of the current puzzleElement + * + * @param graphics2D the frame to be drawn on + */ + @Override + public void drawElement(Graphics2D graphics2D) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + TreeTentType type = cell.getType(); + graphics2D.setStroke(new BasicStroke(0)); + if (type == TreeTentType.UNKNOWN) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.setColor(Color.LIGHT_GRAY); + graphics2D.fill( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); graphics2D.setColor(Color.BLACK); - graphics2D.drawRect(location.x, location.y, size.width, size.height); - } + graphics2D.draw( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 1, size.height - 1)); + } else { + if (type == TreeTentType.TREE) { + graphics2D.drawImage( + TreeTentView.TREE, + location.x, + location.y, + size.width, + size.height, + null, + null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == TreeTentType.GRASS) { + graphics2D.drawImage( + TreeTentView.GRASS, + location.x, + location.y, + size.width, + size.height, + null, + null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } else { + if (type == TreeTentType.TENT) { + graphics2D.drawImage( + TreeTentView.TENT, + location.x, + location.y, + size.width, + size.height, + null, + null); + graphics2D.setColor(Color.BLACK); + graphics2D.drawRect(location.x, location.y, size.width, size.height); + } + } + } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java index 621ea0a38..475aaab1e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentExporter.java @@ -6,68 +6,68 @@ public class TreeTentExporter extends PuzzleExporter { - public TreeTentExporter(TreeTent treeTent) { - super(treeTent); - } - - /** - * Creates and returns a new board element in the XML document specified - * - * @param newDocument the XML document to append to - * @return the new board element - */ - @Override - protected org.w3c.dom.Element createBoardElement(Document newDocument) { - TreeTentBoard board; - if (puzzle.getTree() != null) { - board = (TreeTentBoard) puzzle.getTree().getRootNode().getBoard(); - } else { - board = (TreeTentBoard) puzzle.getBoardView().getBoard(); + public TreeTentExporter(TreeTent treeTent) { + super(treeTent); } - org.w3c.dom.Element boardElement = newDocument.createElement("board"); - boardElement.setAttribute("width", String.valueOf(board.getWidth())); - boardElement.setAttribute("height", String.valueOf(board.getHeight())); + /** + * Creates and returns a new board element in the XML document specified + * + * @param newDocument the XML document to append to + * @return the new board element + */ + @Override + protected org.w3c.dom.Element createBoardElement(Document newDocument) { + TreeTentBoard board; + if (puzzle.getTree() != null) { + board = (TreeTentBoard) puzzle.getTree().getRootNode().getBoard(); + } else { + board = (TreeTentBoard) puzzle.getBoardView().getBoard(); + } - org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getData() != TreeTentType.UNKNOWN) { - org.w3c.dom.Element cellElement = - puzzle.getFactory().exportCell(newDocument, puzzleElement); - cellsElement.appendChild(cellElement); - } - } - boardElement.appendChild(cellsElement); + org.w3c.dom.Element boardElement = newDocument.createElement("board"); + boardElement.setAttribute("width", String.valueOf(board.getWidth())); + boardElement.setAttribute("height", String.valueOf(board.getHeight())); - org.w3c.dom.Element axisEast = newDocument.createElement("axis"); - axisEast.setAttribute("side", "east"); - for (TreeTentClue clue : board.getRowClues()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", TreeTentClue.colNumToString(clue.getClueIndex())); - axisEast.appendChild(clueElement); - } - boardElement.appendChild(axisEast); + org.w3c.dom.Element cellsElement = newDocument.createElement("cells"); + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getData() != TreeTentType.UNKNOWN) { + org.w3c.dom.Element cellElement = + puzzle.getFactory().exportCell(newDocument, puzzleElement); + cellsElement.appendChild(cellElement); + } + } + boardElement.appendChild(cellsElement); - org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); - axisSouth.setAttribute("side", "south"); - for (TreeTentClue clue : board.getRowClues()) { - org.w3c.dom.Element clueElement = newDocument.createElement("clue"); - clueElement.setAttribute("value", String.valueOf(clue.getData())); - clueElement.setAttribute("index", String.valueOf(clue.getClueIndex())); - axisSouth.appendChild(clueElement); - } - boardElement.appendChild(axisSouth); + org.w3c.dom.Element axisEast = newDocument.createElement("axis"); + axisEast.setAttribute("side", "east"); + for (TreeTentClue clue : board.getRowClues()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", TreeTentClue.colNumToString(clue.getClueIndex())); + axisEast.appendChild(clueElement); + } + boardElement.appendChild(axisEast); + + org.w3c.dom.Element axisSouth = newDocument.createElement("axis"); + axisSouth.setAttribute("side", "south"); + for (TreeTentClue clue : board.getRowClues()) { + org.w3c.dom.Element clueElement = newDocument.createElement("clue"); + clueElement.setAttribute("value", String.valueOf(clue.getData())); + clueElement.setAttribute("index", String.valueOf(clue.getClueIndex())); + axisSouth.appendChild(clueElement); + } + boardElement.appendChild(axisSouth); - if (!board.getLines().isEmpty()) { - org.w3c.dom.Element linesElement = newDocument.createElement("lines"); - for (PuzzleElement data : board.getLines()) { - org.w3c.dom.Element lineElement = puzzle.getFactory().exportCell(newDocument, data); - linesElement.appendChild(lineElement); - } - boardElement.appendChild(linesElement); + if (!board.getLines().isEmpty()) { + org.w3c.dom.Element linesElement = newDocument.createElement("lines"); + for (PuzzleElement data : board.getLines()) { + org.w3c.dom.Element lineElement = puzzle.getFactory().exportCell(newDocument, data); + linesElement.appendChild(lineElement); + } + boardElement.appendChild(linesElement); + } + return boardElement; } - return boardElement; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java index ecb8eb664..0117f41ce 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentImporter.java @@ -8,203 +8,212 @@ import org.w3c.dom.NodeList; public class TreeTentImporter extends PuzzleImporter { - public TreeTentImporter(TreeTent treeTent) { - super(treeTent); - } - - @Override - public boolean acceptsRowsAndColumnsInput() { - return true; - } - - @Override - public boolean acceptsTextInput() { - return false; - } - - /** - * Creates an empty board for building - * - * @param rows the number of rows on the board - * @param columns the number of columns on the board - * @throws RuntimeException if board can not be created - */ - @Override - public void initializeBoard(int rows, int columns) { - TreeTentBoard treeTentBoard = new TreeTentBoard(columns, rows); - - for (int y = 0; y < rows; y++) { - for (int x = 0; x < columns; x++) { - if (treeTentBoard.getCell(x, y) == null) { - TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * columns + x); - cell.setModifiable(true); - treeTentBoard.setCell(x, y, cell); - } - } + public TreeTentImporter(TreeTent treeTent) { + super(treeTent); } - for (int i = 0; i < rows; i++) { - treeTentBoard.getRowClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_EAST)); + @Override + public boolean acceptsRowsAndColumnsInput() { + return true; } - for (int i = 0; i < columns; i++) { - treeTentBoard.getColClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_SOUTH)); + @Override + public boolean acceptsTextInput() { + return false; } - puzzle.setCurrentBoard(treeTentBoard); - } - - /** - * Creates the board for building - * - * @param node xml document node - * @throws InvalidFileFormatException if file is invalid - */ - @Override - public void initializeBoard(Node node) throws InvalidFileFormatException { - try { - if (!node.getNodeName().equalsIgnoreCase("board")) { - throw new InvalidFileFormatException("TreeTent Importer: cannot find board puzzleElement"); - } - Element boardElement = (Element) node; - if (boardElement.getElementsByTagName("cells").getLength() == 0) { - throw new InvalidFileFormatException("TreeTent Importer: no puzzleElement found for board"); - } - Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); - NodeList elementDataList = dataElement.getElementsByTagName("cell"); - - TreeTentBoard treeTentBoard = null; - if (!boardElement.getAttribute("size").isEmpty()) { - int size = Integer.valueOf(boardElement.getAttribute("size")); - treeTentBoard = new TreeTentBoard(size); - } else { - if (!boardElement.getAttribute("width").isEmpty() - && !boardElement.getAttribute("height").isEmpty()) { - int width = Integer.valueOf(boardElement.getAttribute("width")); - int height = Integer.valueOf(boardElement.getAttribute("height")); - treeTentBoard = new TreeTentBoard(width, height); - } - } - - if (treeTentBoard == null) { - throw new InvalidFileFormatException("TreeTent Importer: invalid board dimensions"); - } - - int width = treeTentBoard.getWidth(); - int height = treeTentBoard.getHeight(); - - for (int i = 0; i < elementDataList.getLength(); i++) { - TreeTentCell cell = - (TreeTentCell) puzzle.getFactory().importCell(elementDataList.item(i), treeTentBoard); - Point loc = cell.getLocation(); - if (cell.getData() != TreeTentType.UNKNOWN) { - cell.setModifiable(false); - cell.setGiven(true); - } - treeTentBoard.setCell(loc.x, loc.y, cell); - } - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (treeTentBoard.getCell(x, y) == null) { - TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); - cell.setIndex(y * height + x); - cell.setModifiable(true); - treeTentBoard.setCell(x, y, cell); - } - } - } - - NodeList axes = boardElement.getElementsByTagName("axis"); - if (axes.getLength() != 2) { - throw new InvalidFileFormatException("TreeTent Importer: cannot find axes"); - } - - Element axis1 = (Element) axes.item(0); - Element axis2 = (Element) axes.item(1); - - if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { - throw new InvalidFileFormatException( - "TreeTent Importer: side attribute of axis not specified"); - } - String side1 = axis1.getAttribute("side"); - String side2 = axis2.getAttribute("side"); - if (side1.equalsIgnoreCase(side2) - || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) - || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { - throw new InvalidFileFormatException( - "TreeTent Importer: axes must be different and be {east | south}"); - } - NodeList eastClues = - side1.equalsIgnoreCase("east") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - NodeList southClues = - side1.equalsIgnoreCase("south") - ? axis1.getElementsByTagName("clue") - : axis2.getElementsByTagName("clue"); - - if (eastClues.getLength() != treeTentBoard.getHeight() - || southClues.getLength() != treeTentBoard.getWidth()) { - throw new InvalidFileFormatException( - "TreeTent Importer: there must be same number of clues as the dimension of" - + " the board"); - } - - for (int i = 0; i < eastClues.getLength(); i++) { - Element clue = (Element) eastClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = TreeTentClue.colStringToColNum(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > treeTentBoard.getHeight()) { - throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); + /** + * Creates an empty board for building + * + * @param rows the number of rows on the board + * @param columns the number of columns on the board + * @throws RuntimeException if board can not be created + */ + @Override + public void initializeBoard(int rows, int columns) { + TreeTentBoard treeTentBoard = new TreeTentBoard(columns, rows); + + for (int y = 0; y < rows; y++) { + for (int x = 0; x < columns; x++) { + if (treeTentBoard.getCell(x, y) == null) { + TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * columns + x); + cell.setModifiable(true); + treeTentBoard.setCell(x, y, cell); + } + } } - if (treeTentBoard.getRowClues().get(index - 1) != null) { - throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); - } - treeTentBoard - .getRowClues() - .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_EAST)); - } - - for (int i = 0; i < southClues.getLength(); i++) { - Element clue = (Element) southClues.item(i); - int value = Integer.valueOf(clue.getAttribute("value")); - int index = Integer.valueOf(clue.getAttribute("index")); - - if (index - 1 < 0 || index - 1 > treeTentBoard.getWidth()) { - throw new InvalidFileFormatException("TreeTent Importer: clue index out of bounds"); + for (int i = 0; i < rows; i++) { + treeTentBoard.getRowClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_EAST)); } - if (treeTentBoard.getColClues().get(index - 1) != null) { - throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); + for (int i = 0; i < columns; i++) { + treeTentBoard.getColClues().set(i, new TreeTentClue(0, i + 1, TreeTentType.CLUE_SOUTH)); } - treeTentBoard - .getColClues() - .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_SOUTH)); - } - - if (boardElement.getElementsByTagName("lines").getLength() == 1) { - Element linesElement = (Element) boardElement.getElementsByTagName("lines").item(0); - NodeList linesList = linesElement.getElementsByTagName("line"); - for (int i = 0; i < linesList.getLength(); i++) { - treeTentBoard - .getLines() - .add((TreeTentLine) puzzle.getFactory().importCell(linesList.item(i), treeTentBoard)); - } - } - puzzle.setCurrentBoard(treeTentBoard); - } catch (NumberFormatException e) { - throw new InvalidFileFormatException( - "TreeTent Importer: unknown value where integer expected"); + puzzle.setCurrentBoard(treeTentBoard); } - } - @Override - public void initializeBoard(String[] statements) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Tree Tent cannot accept text input"); - } + /** + * Creates the board for building + * + * @param node xml document node + * @throws InvalidFileFormatException if file is invalid + */ + @Override + public void initializeBoard(Node node) throws InvalidFileFormatException { + try { + if (!node.getNodeName().equalsIgnoreCase("board")) { + throw new InvalidFileFormatException( + "TreeTent Importer: cannot find board puzzleElement"); + } + Element boardElement = (Element) node; + if (boardElement.getElementsByTagName("cells").getLength() == 0) { + throw new InvalidFileFormatException( + "TreeTent Importer: no puzzleElement found for board"); + } + Element dataElement = (Element) boardElement.getElementsByTagName("cells").item(0); + NodeList elementDataList = dataElement.getElementsByTagName("cell"); + + TreeTentBoard treeTentBoard = null; + if (!boardElement.getAttribute("size").isEmpty()) { + int size = Integer.valueOf(boardElement.getAttribute("size")); + treeTentBoard = new TreeTentBoard(size); + } else { + if (!boardElement.getAttribute("width").isEmpty() + && !boardElement.getAttribute("height").isEmpty()) { + int width = Integer.valueOf(boardElement.getAttribute("width")); + int height = Integer.valueOf(boardElement.getAttribute("height")); + treeTentBoard = new TreeTentBoard(width, height); + } + } + + if (treeTentBoard == null) { + throw new InvalidFileFormatException("TreeTent Importer: invalid board dimensions"); + } + + int width = treeTentBoard.getWidth(); + int height = treeTentBoard.getHeight(); + + for (int i = 0; i < elementDataList.getLength(); i++) { + TreeTentCell cell = + (TreeTentCell) + puzzle.getFactory() + .importCell(elementDataList.item(i), treeTentBoard); + Point loc = cell.getLocation(); + if (cell.getData() != TreeTentType.UNKNOWN) { + cell.setModifiable(false); + cell.setGiven(true); + } + treeTentBoard.setCell(loc.x, loc.y, cell); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + if (treeTentBoard.getCell(x, y) == null) { + TreeTentCell cell = new TreeTentCell(TreeTentType.UNKNOWN, new Point(x, y)); + cell.setIndex(y * height + x); + cell.setModifiable(true); + treeTentBoard.setCell(x, y, cell); + } + } + } + + NodeList axes = boardElement.getElementsByTagName("axis"); + if (axes.getLength() != 2) { + throw new InvalidFileFormatException("TreeTent Importer: cannot find axes"); + } + + Element axis1 = (Element) axes.item(0); + Element axis2 = (Element) axes.item(1); + + if (!axis1.hasAttribute("side") || !axis1.hasAttribute("side")) { + throw new InvalidFileFormatException( + "TreeTent Importer: side attribute of axis not specified"); + } + String side1 = axis1.getAttribute("side"); + String side2 = axis2.getAttribute("side"); + if (side1.equalsIgnoreCase(side2) + || !(side1.equalsIgnoreCase("east") || side1.equalsIgnoreCase("south")) + || !(side2.equalsIgnoreCase("east") || side2.equalsIgnoreCase("south"))) { + throw new InvalidFileFormatException( + "TreeTent Importer: axes must be different and be {east | south}"); + } + NodeList eastClues = + side1.equalsIgnoreCase("east") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + NodeList southClues = + side1.equalsIgnoreCase("south") + ? axis1.getElementsByTagName("clue") + : axis2.getElementsByTagName("clue"); + + if (eastClues.getLength() != treeTentBoard.getHeight() + || southClues.getLength() != treeTentBoard.getWidth()) { + throw new InvalidFileFormatException( + "TreeTent Importer: there must be same number of clues as the dimension of" + + " the board"); + } + + for (int i = 0; i < eastClues.getLength(); i++) { + Element clue = (Element) eastClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = TreeTentClue.colStringToColNum(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > treeTentBoard.getHeight()) { + throw new InvalidFileFormatException( + "TreeTent Importer: clue index out of bounds"); + } + + if (treeTentBoard.getRowClues().get(index - 1) != null) { + throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); + } + treeTentBoard + .getRowClues() + .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_EAST)); + } + + for (int i = 0; i < southClues.getLength(); i++) { + Element clue = (Element) southClues.item(i); + int value = Integer.valueOf(clue.getAttribute("value")); + int index = Integer.valueOf(clue.getAttribute("index")); + + if (index - 1 < 0 || index - 1 > treeTentBoard.getWidth()) { + throw new InvalidFileFormatException( + "TreeTent Importer: clue index out of bounds"); + } + + if (treeTentBoard.getColClues().get(index - 1) != null) { + throw new InvalidFileFormatException("TreeTent Importer: duplicate clue index"); + } + treeTentBoard + .getColClues() + .set(index - 1, new TreeTentClue(value, index, TreeTentType.CLUE_SOUTH)); + } + + if (boardElement.getElementsByTagName("lines").getLength() == 1) { + Element linesElement = (Element) boardElement.getElementsByTagName("lines").item(0); + NodeList linesList = linesElement.getElementsByTagName("line"); + for (int i = 0; i < linesList.getLength(); i++) { + treeTentBoard + .getLines() + .add( + (TreeTentLine) + puzzle.getFactory() + .importCell(linesList.item(i), treeTentBoard)); + } + } + + puzzle.setCurrentBoard(treeTentBoard); + } catch (NumberFormatException e) { + throw new InvalidFileFormatException( + "TreeTent Importer: unknown value where integer expected"); + } + } + + @Override + public void initializeBoard(String[] statements) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Tree Tent cannot accept text input"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java index bc252b0ba..dae10a1ae 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLine.java @@ -5,40 +5,40 @@ public class TreeTentLine extends PuzzleElement> { - public TreeTentLine(TreeTentCell c1, TreeTentCell c2) { - this.data = new Entry<>(c1, c2); - } - - public TreeTentCell getC1() { - return data.getKey(); - } - - public void setC1(TreeTentCell c1) { - this.data.setKey(c1); - } - - public TreeTentCell getC2() { - return data.getValue(); - } - - public void setC2(TreeTentCell c2) { - this.data.setValue(c2); - } - - public boolean compare(TreeTentLine line) { - return ((line.getC1().getLocation().equals(data.getKey().getLocation()) - && line.getC2().getLocation().equals(data.getValue().getLocation())) - || (line.getC1().getLocation().equals(data.getValue().getLocation()) - && line.getC2().getLocation().equals(data.getKey().getLocation()))); - } - - /** - * Copies this elements puzzleElement to a new PuzzleElement object - * - * @return copied PuzzleElement object - */ - @Override - public TreeTentLine copy() { - return new TreeTentLine(data.getKey().copy(), data.getValue().copy()); - } + public TreeTentLine(TreeTentCell c1, TreeTentCell c2) { + this.data = new Entry<>(c1, c2); + } + + public TreeTentCell getC1() { + return data.getKey(); + } + + public void setC1(TreeTentCell c1) { + this.data.setKey(c1); + } + + public TreeTentCell getC2() { + return data.getValue(); + } + + public void setC2(TreeTentCell c2) { + this.data.setValue(c2); + } + + public boolean compare(TreeTentLine line) { + return ((line.getC1().getLocation().equals(data.getKey().getLocation()) + && line.getC2().getLocation().equals(data.getValue().getLocation())) + || (line.getC1().getLocation().equals(data.getValue().getLocation()) + && line.getC2().getLocation().equals(data.getKey().getLocation()))); + } + + /** + * Copies this elements puzzleElement to a new PuzzleElement object + * + * @return copied PuzzleElement object + */ + @Override + public TreeTentLine copy() { + return new TreeTentLine(data.getKey().copy(), data.getValue().copy()); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java index b2e6ed7b5..6d478cff8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentLineView.java @@ -4,28 +4,28 @@ import java.awt.*; public class TreeTentLineView extends ElementView { - private final Color LINE_COLOR = Color.GREEN; + private final Color LINE_COLOR = Color.GREEN; - private final Stroke LINE_STROKE = new BasicStroke(2); + private final Stroke LINE_STROKE = new BasicStroke(2); - public TreeTentLineView(TreeTentLine line) { - super(line); - } + public TreeTentLineView(TreeTentLine line) { + super(line); + } - @Override - public void draw(Graphics2D graphics2D) { + @Override + public void draw(Graphics2D graphics2D) { - TreeTentLine line = (TreeTentLine) puzzleElement; - Point p1 = line.getC1().getLocation(); - Point p2 = line.getC2().getLocation(); - int x1 = (p1.x + 1) * size.width + size.width / 2; - int y1 = (p1.y + 1) * size.height + size.height / 2; + TreeTentLine line = (TreeTentLine) puzzleElement; + Point p1 = line.getC1().getLocation(); + Point p2 = line.getC2().getLocation(); + int x1 = (p1.x + 1) * size.width + size.width / 2; + int y1 = (p1.y + 1) * size.height + size.height / 2; - int x2 = (p2.x + 1) * size.width + size.width / 2; - int y2 = (p2.y + 1) * size.height + size.height / 2; - // graphics2D.setColor(LINE_COLOR); - graphics2D.setColor(line.isModified() ? Color.GREEN : Color.WHITE); - graphics2D.setStroke(LINE_STROKE); - graphics2D.drawLine(x1, y1, x2, y2); - } + int x2 = (p2.x + 1) * size.width + size.width / 2; + int y2 = (p2.y + 1) * size.height + size.height / 2; + // graphics2D.setColor(LINE_COLOR); + graphics2D.setColor(line.isModified() ? Color.GREEN : Color.WHITE); + graphics2D.setStroke(LINE_STROKE); + graphics2D.drawLine(x1, y1, x2, y2); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java index b1e480335..230283418 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentType.java @@ -1,25 +1,25 @@ package edu.rpi.legup.puzzle.treetent; public enum TreeTentType { - UNKNOWN, - TREE, - GRASS, - TENT, - CLUE_NORTH, - CLUE_EAST, - CLUE_SOUTH, - CLUE_WEST; + UNKNOWN, + TREE, + GRASS, + TENT, + CLUE_NORTH, + CLUE_EAST, + CLUE_SOUTH, + CLUE_WEST; - public static TreeTentType valueOf(int num) { - switch (num) { - case 1: - return TREE; - case 2: - return GRASS; - case 3: - return TENT; - default: - return UNKNOWN; + public static TreeTentType valueOf(int num) { + switch (num) { + case 1: + return TREE; + case 2: + return GRASS; + case 3: + return TENT; + default: + return UNKNOWN; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java index 0973f9452..3b8cadad6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/TreeTentView.java @@ -14,201 +14,212 @@ import org.apache.logging.log4j.Logger; public class TreeTentView extends GridBoardView { - private static final Logger LOGGER = LogManager.getLogger(TreeTentView.class.getName()); - - static Image TREE, GRASS, TENT; - - static { - try { - TREE = - ImageIO.read( - ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tree.png")); - GRASS = - ImageIO.read( - ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/grass.png")); - TENT = - ImageIO.read( - ClassLoader.getSystemResourceAsStream("edu/rpi/legup/images/treetent/tent.png")); - } catch (IOException e) { - LOGGER.error("Failed to open TreeTent images"); + private static final Logger LOGGER = LogManager.getLogger(TreeTentView.class.getName()); + + static Image TREE, GRASS, TENT; + + static { + try { + TREE = + ImageIO.read( + ClassLoader.getSystemResourceAsStream( + "edu/rpi/legup/images/treetent/tree.png")); + GRASS = + ImageIO.read( + ClassLoader.getSystemResourceAsStream( + "edu/rpi/legup/images/treetent/grass.png")); + TENT = + ImageIO.read( + ClassLoader.getSystemResourceAsStream( + "edu/rpi/legup/images/treetent/tent.png")); + } catch (IOException e) { + LOGGER.error("Failed to open TreeTent images"); + } + } + + private ArrayList lineViews; + + private ArrayList northClues; + private ArrayList eastClues; + private ArrayList southClues; + private ArrayList westClues; + + public TreeTentView(TreeTentBoard board) { + super(new BoardController(), new TreeTentController(), board.getDimension()); + + this.lineViews = new ArrayList<>(); + + this.northClues = new ArrayList<>(); + this.eastClues = new ArrayList<>(); + this.southClues = new ArrayList<>(); + this.westClues = new ArrayList<>(); + + for (PuzzleElement puzzleElement : board.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) puzzleElement; + Point loc = cell.getLocation(); + TreeTentElementView elementView = new TreeTentElementView(cell); + elementView.setIndex(cell.getIndex()); + elementView.setSize(elementSize); + elementView.setLocation( + new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); + elementViews.add(elementView); + } + + for (TreeTentLine line : board.getLines()) { + TreeTentLineView lineView = new TreeTentLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + + for (int i = 0; i < gridSize.height; i++) { + TreeTentClueView row = + new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_WEST)); + row.setLocation(new Point(0, (i + 1) * elementSize.height)); + row.setSize(elementSize); + + TreeTentClueView clue = new TreeTentClueView(board.getRowClues().get(i)); + clue.setLocation( + new Point( + (gridSize.width + 1) * elementSize.width, + (i + 1) * elementSize.height)); + clue.setSize(elementSize); + + westClues.add(row); + eastClues.add(clue); + } + + for (int i = 0; i < gridSize.width; i++) { + TreeTentClueView col = + new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_NORTH)); + col.setLocation(new Point((i + 1) * elementSize.width, 0)); + col.setSize(elementSize); + + TreeTentClueView clue = new TreeTentClueView(board.getColClues().get(i)); + clue.setLocation( + new Point( + (i + 1) * elementSize.width, + (gridSize.height + 1) * elementSize.height)); + clue.setSize(elementSize); + + northClues.add(col); + southClues.add(clue); + } + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + @Override + public ElementView getElement(Point point) { + Point scaledPoint = + new Point( + (int) Math.round(point.x / getScale()), + (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + for (TreeTentClueView clueView : northClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : eastClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : southClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + for (TreeTentClueView clueView : westClues) { + if (clueView.isWithinBounds(scaledPoint)) { + return clueView; + } + } + return null; + } + + public ArrayList getLineViews() { + return lineViews; + } + + public ArrayList getNorthClues() { + return northClues; + } + + public ArrayList getEastClues() { + return eastClues; + } + + public ArrayList getSouthClues() { + return southClues; + } + + public ArrayList getWestClues() { + return westClues; + } + + @Override + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = (gridSize.width + 2) * elementSize.width; + boardViewSize.height = (gridSize.height + 2) * elementSize.height; + return boardViewSize; + } + + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + super.onTreeElementChanged(treeElement); + TreeTentBoard treeTentBoard; + if (board instanceof CaseBoard) { + treeTentBoard = (TreeTentBoard) ((CaseBoard) board).getBaseBoard(); + } else { + treeTentBoard = (TreeTentBoard) board; + } + + lineViews.clear(); + for (TreeTentLine line : treeTentBoard.getLines()) { + TreeTentLineView lineView = new TreeTentLineView(line); + lineView.setSize(elementSize); + lineViews.add(lineView); + } + } + + @Override + public void drawBoard(Graphics2D graphics2D) { + super.drawBoard(graphics2D); + + for (TreeTentLineView view : lineViews) { + view.draw(graphics2D); + } + + for (TreeTentClueView clueView : northClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : eastClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : southClues) { + clueView.draw(graphics2D); + } + + for (TreeTentClueView clueView : westClues) { + clueView.draw(graphics2D); + } } - } - - private ArrayList lineViews; - - private ArrayList northClues; - private ArrayList eastClues; - private ArrayList southClues; - private ArrayList westClues; - - public TreeTentView(TreeTentBoard board) { - super(new BoardController(), new TreeTentController(), board.getDimension()); - - this.lineViews = new ArrayList<>(); - - this.northClues = new ArrayList<>(); - this.eastClues = new ArrayList<>(); - this.southClues = new ArrayList<>(); - this.westClues = new ArrayList<>(); - - for (PuzzleElement puzzleElement : board.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - TreeTentElementView elementView = new TreeTentElementView(cell); - elementView.setIndex(cell.getIndex()); - elementView.setSize(elementSize); - elementView.setLocation( - new Point((loc.x + 1) * elementSize.width, (loc.y + 1) * elementSize.height)); - elementViews.add(elementView); - } - - for (TreeTentLine line : board.getLines()) { - TreeTentLineView lineView = new TreeTentLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - - for (int i = 0; i < gridSize.height; i++) { - TreeTentClueView row = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_WEST)); - row.setLocation(new Point(0, (i + 1) * elementSize.height)); - row.setSize(elementSize); - - TreeTentClueView clue = new TreeTentClueView(board.getRowClues().get(i)); - clue.setLocation( - new Point((gridSize.width + 1) * elementSize.width, (i + 1) * elementSize.height)); - clue.setSize(elementSize); - - westClues.add(row); - eastClues.add(clue); - } - - for (int i = 0; i < gridSize.width; i++) { - TreeTentClueView col = new TreeTentClueView(new TreeTentClue(i, i, TreeTentType.CLUE_NORTH)); - col.setLocation(new Point((i + 1) * elementSize.width, 0)); - col.setSize(elementSize); - - TreeTentClueView clue = new TreeTentClueView(board.getColClues().get(i)); - clue.setLocation( - new Point((i + 1) * elementSize.width, (gridSize.height + 1) * elementSize.height)); - clue.setSize(elementSize); - - northClues.add(col); - southClues.add(clue); - } - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - @Override - public ElementView getElement(Point point) { - Point scaledPoint = - new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - for (TreeTentClueView clueView : northClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : eastClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : southClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - for (TreeTentClueView clueView : westClues) { - if (clueView.isWithinBounds(scaledPoint)) { - return clueView; - } - } - return null; - } - - public ArrayList getLineViews() { - return lineViews; - } - - public ArrayList getNorthClues() { - return northClues; - } - - public ArrayList getEastClues() { - return eastClues; - } - - public ArrayList getSouthClues() { - return southClues; - } - - public ArrayList getWestClues() { - return westClues; - } - - @Override - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = (gridSize.width + 2) * elementSize.width; - boardViewSize.height = (gridSize.height + 2) * elementSize.height; - return boardViewSize; - } - - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - super.onTreeElementChanged(treeElement); - TreeTentBoard treeTentBoard; - if (board instanceof CaseBoard) { - treeTentBoard = (TreeTentBoard) ((CaseBoard) board).getBaseBoard(); - } else { - treeTentBoard = (TreeTentBoard) board; - } - - lineViews.clear(); - for (TreeTentLine line : treeTentBoard.getLines()) { - TreeTentLineView lineView = new TreeTentLineView(line); - lineView.setSize(elementSize); - lineViews.add(lineView); - } - } - - @Override - public void drawBoard(Graphics2D graphics2D) { - super.drawBoard(graphics2D); - - for (TreeTentLineView view : lineViews) { - view.draw(graphics2D); - } - - for (TreeTentClueView clueView : northClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : eastClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : southClues) { - clueView.draw(graphics2D); - } - - for (TreeTentClueView clueView : westClues) { - clueView.draw(graphics2D); - } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java index 4d452f48d..5356120a8 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/GrassTile.java @@ -4,11 +4,11 @@ public class GrassTile extends PlaceableElement { - public GrassTile() { - super( - "TREE-PlAC-0002", - "Grass Tile", - "The grass crest tile", - "edu/rpi/legup/images/treetent/grass.png"); - } + public GrassTile() { + super( + "TREE-PlAC-0002", + "Grass Tile", + "The grass crest tile", + "edu/rpi/legup/images/treetent/grass.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java index 249b22b04..950aebfa7 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TentTile.java @@ -4,7 +4,11 @@ public class TentTile extends PlaceableElement { - public TentTile() { - super("TREE-PLAC-0001", "Tent Tile", "The tent tile", "edu/rpi/legup/images/treetent/tent.png"); - } + public TentTile() { + super( + "TREE-PLAC-0001", + "Tent Tile", + "The tent tile", + "edu/rpi/legup/images/treetent/tent.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java index eab34e0b2..d04886ed5 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/TreeTile.java @@ -4,7 +4,11 @@ public class TreeTile extends NonPlaceableElement { - public TreeTile() { - super("TREE-UNPL-0001", "Tree Tile", "The tree tile", "edu/rpi/legup/images/treetent/tree.png"); - } + public TreeTile() { + super( + "TREE-UNPL-0001", + "Tree Tile", + "The tree tile", + "edu/rpi/legup/images/treetent/tree.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java index 589053d5a..a54240efd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/elements/UnknownTile.java @@ -3,11 +3,11 @@ import edu.rpi.legup.model.elements.NonPlaceableElement; public class UnknownTile extends NonPlaceableElement { - public UnknownTile() { - super( - "TREE-UNPL-0002", - "Unknown Tile", - "The blank tile", - "edu/rpi/legup/images/treetent/UnknownTile.png"); - } + public UnknownTile() { + super( + "TREE-UNPL-0002", + "Unknown Tile", + "The blank tile", + "edu/rpi/legup/images/treetent/UnknownTile.png"); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java index 2e7b7a031..c91a60b1a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/EmptyFieldDirectRule.java @@ -12,77 +12,78 @@ import java.util.List; public class EmptyFieldDirectRule extends DirectRule { - public EmptyFieldDirectRule() { - super( - "TREE-BASC-0001", - "Empty Field", - "Blank cells not adjacent to an unlinked tree are grass.", - "edu/rpi/legup/images/treetent/noTreesAround.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS - && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; + public EmptyFieldDirectRule() { + super( + "TREE-BASC-0001", + "Empty Field", + "Blank cells not adjacent to an unlinked tree are grass.", + "edu/rpi/legup/images/treetent/noTreesAround.png"); } - if (isForced(finalBoard, finalCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS + && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass"; + } - /** - * Returns a boolean value based on whether the specified cell has adjacent cells (true - no - * adjacent, false - has adjacent) - * - * @param board the TreeTent board - * @param cell the specified TreeTent cell - * @return true - no adjacent, false - has adjacent - */ - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjCells = board.getAdjacent(cell, TreeTentType.TREE); - return adjCells.isEmpty(); - } + if (isForced(finalBoard, finalCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be empty."; + } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } + /** + * Returns a boolean value based on whether the specified cell has adjacent cells (true - no + * adjacent, false - has adjacent) + * + * @param board the TreeTent board + * @param cell the specified TreeTent cell + * @return true - no adjacent, false - has adjacent + */ + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjCells = board.getAdjacent(cell, TreeTentType.TREE); + return adjCells.isEmpty(); } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java index 20b6628f0..0116c0dcd 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FillinRowCaseRule.java @@ -15,192 +15,198 @@ public class FillinRowCaseRule extends CaseRule { - public FillinRowCaseRule() { - super( - "TREE-CASE-0001", - "Fill In row", - "A row must have the number of tents of its clue.", - "edu/rpi/legup/images/treetent/case_rowcount.png"); - } - - /** - * Gets the case board that indicates where this case rule can be applied on the given Board. - * - * @param board the given board - * @return the case board object - */ - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - ArrayList clues = treeTentBoard.getRowClues(); - clues.addAll(treeTentBoard.getColClues()); - for (PuzzleElement element : clues) { - // if ((((TreeTentCell) element).getType() == TreeTentType.CLUE_SOUTH && - // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().y, - // TreeTentType.UNKNOWN, - // true).size() != 0) || - // (((TreeTentCell) element).getType() == TreeTentType.CLUE_EAST && - // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().x, - // TreeTentType.UNKNOWN, - // false).size() != 0)) { - // caseBoard.addPickableElement(element); - // } - caseBoard.addPickableElement(element); - } - return caseBoard; - } - - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - List group; - int tentsLeft; - TreeTentClue clue = ((TreeTentClue) puzzleElement); - int clueIndex = clue.getClueIndex() - 1; - TreeTentBoard tBoard = (TreeTentBoard) board; - if (clue.getType() == TreeTentType.CLUE_SOUTH) { - group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, false); - tentsLeft = - tBoard.getRowClues().get(clueIndex).getData() - - tBoard.getRowCol(clueIndex, TreeTentType.TENT, false).size(); - cases = genCombinations(tBoard, group, tentsLeft, clueIndex, false); - } else { - group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, true); - tentsLeft = - tBoard.getRowClues().get(clueIndex).getData() - - tBoard.getRowCol(clueIndex, TreeTentType.TENT, true).size(); - cases = genCombinations(tBoard, group, tentsLeft, clueIndex, true); + public FillinRowCaseRule() { + super( + "TREE-CASE-0001", + "Fill In row", + "A row must have the number of tents of its clue.", + "edu/rpi/legup/images/treetent/case_rowcount.png"); } - // generate every combination (nCr) - // call goodBoard for each generated combination - // alternitive would be to implement collision avoidance while generating instead of after - if (cases.size() > 0) { - return cases; + /** + * Gets the case board that indicates where this case rule can be applied on the given Board. + * + * @param board the given board + * @return the case board object + */ + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + ArrayList clues = treeTentBoard.getRowClues(); + clues.addAll(treeTentBoard.getColClues()); + for (PuzzleElement element : clues) { + // if ((((TreeTentCell) element).getType() == TreeTentType.CLUE_SOUTH && + // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().y, + // TreeTentType.UNKNOWN, + // true).size() != 0) || + // (((TreeTentCell) element).getType() == TreeTentType.CLUE_EAST && + // treeTentBoard.getRowCol(((TreeTentCell)element).getLocation().x, + // TreeTentType.UNKNOWN, + // false).size() != 0)) { + // caseBoard.addPickableElement(element); + // } + caseBoard.addPickableElement(element); + } + return caseBoard; } - return null; - } - - private ArrayList genCombinations( - TreeTentBoard iBoard, List tiles, int target, Integer index, boolean isRow) { - return genCombRecursive( - iBoard, tiles, tiles, target, 0, new ArrayList(), index, isRow); - } - - private ArrayList genCombRecursive( - TreeTentBoard iBoard, - List original, - List tiles, - int target, - int current, - List selected, - Integer index, - boolean isRow) { - ArrayList b = new ArrayList<>(); - if (target == current) { - TreeTentBoard temp = iBoard.copy(); - for (TreeTentCell c : original) { - if (selected.contains(c)) { - PuzzleElement change = temp.getPuzzleElement(c); - change.setData(TreeTentType.TENT); - temp.addModifiedData(change); + + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + List group; + int tentsLeft; + TreeTentClue clue = ((TreeTentClue) puzzleElement); + int clueIndex = clue.getClueIndex() - 1; + TreeTentBoard tBoard = (TreeTentBoard) board; + if (clue.getType() == TreeTentType.CLUE_SOUTH) { + group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, false); + tentsLeft = + tBoard.getRowClues().get(clueIndex).getData() + - tBoard.getRowCol(clueIndex, TreeTentType.TENT, false).size(); + cases = genCombinations(tBoard, group, tentsLeft, clueIndex, false); } else { - PuzzleElement change = temp.getPuzzleElement(c); - change.setData(TreeTentType.GRASS); - temp.addModifiedData(change); + group = tBoard.getRowCol(clueIndex, TreeTentType.UNKNOWN, true); + tentsLeft = + tBoard.getRowClues().get(clueIndex).getData() + - tBoard.getRowCol(clueIndex, TreeTentType.TENT, true).size(); + cases = genCombinations(tBoard, group, tentsLeft, clueIndex, true); + } + + // generate every combination (nCr) + // call goodBoard for each generated combination + // alternitive would be to implement collision avoidance while generating instead of after + if (cases.size() > 0) { + return cases; } - } - if (goodBoard(temp, index, isRow)) { - b.add(temp); - } - return b; + return null; } - for (int i = 0; i < tiles.size(); ++i) { - List sub = tiles.subList(i + 1, tiles.size()); - List next = new ArrayList(selected); - next.add(tiles.get(i)); - b.addAll(genCombRecursive(iBoard, original, sub, target, current + 1, next, index, isRow)); + + private ArrayList genCombinations( + TreeTentBoard iBoard, + List tiles, + int target, + Integer index, + boolean isRow) { + return genCombRecursive( + iBoard, tiles, tiles, target, 0, new ArrayList(), index, isRow); } - return b; - } - - // Effectively runs TouchingTents check on all the added tents to make sure that the proposed - // board is valid. - // Could check more or less in the future depending on how "smart" this case rule should be. - private boolean goodBoard(TreeTentBoard board, Integer index, boolean isRow) { - List tents; - if (isRow) { - tents = board.getRowCol(index, TreeTentType.TENT, true); - } else { - tents = board.getRowCol(index, TreeTentType.TENT, false); + + private ArrayList genCombRecursive( + TreeTentBoard iBoard, + List original, + List tiles, + int target, + int current, + List selected, + Integer index, + boolean isRow) { + ArrayList b = new ArrayList<>(); + if (target == current) { + TreeTentBoard temp = iBoard.copy(); + for (TreeTentCell c : original) { + if (selected.contains(c)) { + PuzzleElement change = temp.getPuzzleElement(c); + change.setData(TreeTentType.TENT); + temp.addModifiedData(change); + } else { + PuzzleElement change = temp.getPuzzleElement(c); + change.setData(TreeTentType.GRASS); + temp.addModifiedData(change); + } + } + if (goodBoard(temp, index, isRow)) { + b.add(temp); + } + return b; + } + for (int i = 0; i < tiles.size(); ++i) { + List sub = tiles.subList(i + 1, tiles.size()); + List next = new ArrayList(selected); + next.add(tiles.get(i)); + b.addAll( + genCombRecursive( + iBoard, original, sub, target, current + 1, next, index, isRow)); + } + return b; } - for (TreeTentCell t : tents) { - List adj = board.getAdjacent(t, TreeTentType.TENT); - List diag = board.getDiagonals(t, TreeTentType.TENT); - if (adj.size() > 0 || diag.size() > 0) { - return false; - } + // Effectively runs TouchingTents check on all the added tents to make sure that the proposed + // board is valid. + // Could check more or less in the future depending on how "smart" this case rule should be. + private boolean goodBoard(TreeTentBoard board, Integer index, boolean isRow) { + List tents; + if (isRow) { + tents = board.getRowCol(index, TreeTentType.TENT, true); + } else { + tents = board.getRowCol(index, TreeTentType.TENT, false); + } + + for (TreeTentCell t : tents) { + List adj = board.getAdjacent(t, TreeTentType.TENT); + List diag = board.getDiagonals(t, TreeTentType.TENT); + if (adj.size() > 0 || diag.size() > 0) { + return false; + } + } + return true; } - return true; - } - - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - return null; - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return null; - } - - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(); - - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentClue clue = (TreeTentClue) puzzleElement; - - // add all elements of filled row - for (int i = 0; i < treeTentBoard.getWidth(); i++) { - TreeTentCell cell = treeTentBoard.getCell(i, clue.getClueIndex() - 1); - elements.add(board.getPuzzleElement((cell))); + + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + return null; } - return elements; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return null; + } + + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = new ArrayList<>(); + + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentClue clue = (TreeTentClue) puzzleElement; + + // add all elements of filled row + for (int i = 0; i < treeTentBoard.getWidth(); i++) { + TreeTentCell cell = treeTentBoard.getCell(i, clue.getClueIndex() - 1); + elements.add(board.getPuzzleElement((cell))); + } + + return elements; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java index bb371c52b..838a3ca24 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithGrassDirectRule.java @@ -14,73 +14,74 @@ public class FinishWithGrassDirectRule extends DirectRule { - public FinishWithGrassDirectRule() { - super( - "TREE-BASC-0002", - "Finish with Grass", - "Grass can be added to finish a row or column that has reached its tent limit.", - "edu/rpi/legup/images/treetent/finishGrass.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(finalCell.getType() == TreeTentType.GRASS - && initCell.getType() == TreeTentType.UNKNOWN)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; + public FinishWithGrassDirectRule() { + super( + "TREE-BASC-0002", + "Finish with Grass", + "Grass can be added to finish a row or column that has reached its tent limit.", + "edu/rpi/legup/images/treetent/finishGrass.png"); } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule"; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(finalCell.getType() == TreeTentType.GRASS + && initCell.getType() == TreeTentType.UNKNOWN)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be grass."; + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be grass."; + } + } - return tentsRow.size() >= board.getRowClues().get(loc.y).getData() - || tentsCol.size() >= board.getColClues().get(loc.x).getData(); - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } + return tentsRow.size() >= board.getRowClues().get(loc.y).getData() + || tentsCol.size() >= board.getColClues().get(loc.x).getData(); } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java index 1d1584353..ae1a72e9d 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/FinishWithTentsDirectRule.java @@ -14,75 +14,77 @@ public class FinishWithTentsDirectRule extends DirectRule { - public FinishWithTentsDirectRule() { - super( - "TREE-BASC-0003", - "Finish with Tents", - "Tents can be added to finish a row or column that has one open spot per required" - + " tent.", - "edu/rpi/legup/images/treetent/finishTent.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + public FinishWithTentsDirectRule() { + super( + "TREE-BASC-0003", + "Finish with Tents", + "Tents can be added to finish a row or column that has one open spot per required" + + " tent.", + "edu/rpi/legup/images/treetent/finishTent.png"); } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN + && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - Point loc = cell.getLocation(); - List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); - List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); - List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); - List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; + } + } - return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() - || unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + Point loc = cell.getLocation(); + List tentsRow = board.getRowCol(loc.y, TreeTentType.TENT, true); + List unknownsRow = board.getRowCol(loc.y, TreeTentType.UNKNOWN, true); + List tentsCol = board.getRowCol(loc.x, TreeTentType.TENT, false); + List unknownsCol = board.getRowCol(loc.x, TreeTentType.UNKNOWN, false); - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } + return unknownsRow.size() <= board.getRowClues().get(loc.y).getData() - tentsRow.size() + || unknownsCol.size() <= board.getColClues().get(loc.x).getData() - tentsCol.size(); } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java index 5d0ae5cd6..53f7b9831 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LastCampingSpotDirectRule.java @@ -13,89 +13,92 @@ public class LastCampingSpotDirectRule extends DirectRule { - public LastCampingSpotDirectRule() { - super( - "TREE-BASC-0004", - "Last Camping Spot", - "If an unlinked tree is adjacent to only one blank cell and not adjacent to any" - + " unlinked tents, the blank cell must be a tent.", - "edu/rpi/legup/images/treetent/oneTentPosition.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN && finalCell.getType() == TreeTentType.TENT)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + public LastCampingSpotDirectRule() { + super( + "TREE-BASC-0004", + "Last Camping Spot", + "If an unlinked tree is adjacent to only one blank cell and not adjacent to any" + + " unlinked tents, the blank cell must be a tent.", + "edu/rpi/legup/images/treetent/oneTentPosition.png"); } - if (isForced(finalBoard, finalCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN + && finalCell.getType() == TreeTentType.TENT)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); - for (TreeTentCell c : adjTrees) { - List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); - List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); - if (unkAroundTree.size() == 0) { - if (tntAroundTree.size() == 1) { - return true; + if (isForced(finalBoard, finalCell)) { + return null; } else { - for (TreeTentCell t : tntAroundTree) { - if (t == cell) { - continue; - } - List treesAroundTents = board.getAdjacent(t, TreeTentType.TREE); - if (treesAroundTents.size() == 1) { - return false; - } - } - return true; + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; } - } } - return false; - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.TENT); - treeTentBoard.addModifiedData(cell); - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List adjTrees = board.getAdjacent(cell, TreeTentType.TREE); + for (TreeTentCell c : adjTrees) { + List unkAroundTree = board.getAdjacent(c, TreeTentType.UNKNOWN); + List tntAroundTree = board.getAdjacent(c, TreeTentType.TENT); + if (unkAroundTree.size() == 0) { + if (tntAroundTree.size() == 1) { + return true; + } else { + for (TreeTentCell t : tntAroundTree) { + if (t == cell) { + continue; + } + List treesAroundTents = + board.getAdjacent(t, TreeTentType.TREE); + if (treesAroundTents.size() == 1) { + return false; + } + } + return true; + } + } + } + return false; } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.TENT); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java index fec820260..bd303174a 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTentCaseRule.java @@ -15,163 +15,165 @@ public class LinkTentCaseRule extends CaseRule { - public LinkTentCaseRule() { - super( - "TREE-CASE-0002", - "Links from tent", - "A tent must link to exactly one adjacent tree.", - "edu/rpi/legup/images/treetent/caseLinkTent.png"); - } + public LinkTentCaseRule() { + super( + "TREE-CASE-0002", + "Links from tent", + "A tent must link to exactly one adjacent tree.", + "edu/rpi/legup/images/treetent/caseLinkTent.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.TENT - && !getCases(board, element).isEmpty()) { - Boolean canAdd = true; - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) - || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { - canAdd = false; - break; - } - } - if (canAdd) { - caseBoard.addPickableElement(element); + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.TENT + && !getCases(board, element).isEmpty()) { + Boolean canAdd = true; + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) + || l.getC2() + .getLocation() + .equals(((TreeTentCell) element).getLocation())) { + canAdd = false; + break; + } + } + if (canAdd) { + caseBoard.addPickableElement(element); + } + } } - } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList(); - TreeTentCell cell = (TreeTentCell) puzzleElement; - List adj = ((TreeTentBoard) board).getAdjacent(cell, TreeTentType.TREE); - List lines = ((TreeTentBoard) board).getLines(); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList(); + TreeTentCell cell = (TreeTentCell) puzzleElement; + List adj = ((TreeTentBoard) board).getAdjacent(cell, TreeTentType.TREE); + List lines = ((TreeTentBoard) board).getLines(); - for (TreeTentCell tree : adj) { - Boolean makeline = true; - for (TreeTentLine l : ((TreeTentBoard) board).getLines()) { - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - makeline = false; + for (TreeTentCell tree : adj) { + Boolean makeline = true; + for (TreeTentLine l : ((TreeTentBoard) board).getLines()) { + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + makeline = false; + } + } + if (makeline) { + TreeTentBoard temp = ((TreeTentBoard) board).copy(); + TreeTentLine l = + new TreeTentLine( + (TreeTentCell) temp.getPuzzleElement(cell), + (TreeTentCell) temp.getPuzzleElement(tree)); + temp.getLines().add(l); + temp.addModifiedData(l); + cases.add(temp); + } } - } - if (makeline) { - TreeTentBoard temp = ((TreeTentBoard) board).copy(); - TreeTentLine l = - new TreeTentLine( - (TreeTentCell) temp.getPuzzleElement(cell), - (TreeTentCell) temp.getPuzzleElement(tree)); - temp.getLines().add(l); - temp.addModifiedData(l); - cases.add(temp); - } + return cases; } - return cases; - } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } - PuzzleElement mod = modCells.iterator().next(); - TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; - if (line == null) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; - } - TreeTentCell tent = null; - if (line.getC1().getType() == TreeTentType.TENT) { - tent = line.getC1(); - } - if (line.getC2().getType() == TreeTentType.TENT) { - tent = line.getC2(); - } - if (tent == null) { - return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; - } - - TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - ArrayList cases = getCases(parentBoard, tent); - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != cases.size()) { - return super.getInvalidUseOfRuleMessage(); - } - for (Board caseBoard : cases) { - TreeTentBoard cBoard = (TreeTentBoard) caseBoard; - TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); - boolean hasLine = false; - for (TreeTransition tran : childTransitions) { - TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); - if (tBoard.getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage(); + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; } - PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); - if (!(tElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; + PuzzleElement mod = modCells.iterator().next(); + TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; + if (line == null) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; } - if (cLine.compare((TreeTentLine) tElement)) { - hasLine = true; - break; + TreeTentCell tent = null; + if (line.getC1().getType() == TreeTentType.TENT) { + tent = line.getC1(); + } + if (line.getC2().getType() == TreeTentType.TENT) { + tent = line.getC2(); + } + if (tent == null) { + return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; } - } - if (!hasLine) { - return super.getInvalidUseOfRuleMessage(); - } - } - return null; - } + TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + ArrayList cases = getCases(parentBoard, tent); + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != cases.size()) { + return super.getInvalidUseOfRuleMessage(); + } + for (Board caseBoard : cases) { + TreeTentBoard cBoard = (TreeTentBoard) caseBoard; + TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); + boolean hasLine = false; + for (TreeTransition tran : childTransitions) { + TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); + if (tBoard.getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage(); + } + PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); + if (!(tElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; + } + if (cLine.compare((TreeTentLine) tElement)) { + hasLine = true; + break; + } + } + if (!hasLine) { + return super.getInvalidUseOfRuleMessage(); + } + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + return null; + } + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - return List.of(board.getPuzzleElement(puzzleElement)); - } + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + return List.of(board.getPuzzleElement(puzzleElement)); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java index 65bc52723..03d039898 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/LinkTreeCaseRule.java @@ -16,174 +16,177 @@ public class LinkTreeCaseRule extends CaseRule { - public LinkTreeCaseRule() { - super( - "TREE-CASE-0003", - "Links from tree", - "A tree must link to exactly one adjacent tent.", - "edu/rpi/legup/images/treetent/caseLinkTree.png"); - } + public LinkTreeCaseRule() { + super( + "TREE-CASE-0003", + "Links from tree", + "A tree must link to exactly one adjacent tent.", + "edu/rpi/legup/images/treetent/caseLinkTree.png"); + } - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.TREE - && !getCases(treeTentBoard, element).isEmpty()) { + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.TREE + && !getCases(treeTentBoard, element).isEmpty()) { - Boolean canAdd = true; - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) - || l.getC2().getLocation().equals(((TreeTentCell) element).getLocation())) { - canAdd = false; - break; - } - } - if (canAdd) { - caseBoard.addPickableElement(element); + Boolean canAdd = true; + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + if (l.getC1().getLocation().equals(((TreeTentCell) element).getLocation()) + || l.getC2() + .getLocation() + .equals(((TreeTentCell) element).getLocation())) { + canAdd = false; + break; + } + } + if (canAdd) { + caseBoard.addPickableElement(element); + } + } } - } + return caseBoard; } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - List adjCells = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); - for (TreeTentCell c : adjCells) { - Boolean makeline = true; - for (TreeTentLine l : treeTentBoard.getLines()) { - if (l.getC1().getLocation().equals(c.getLocation()) - || l.getC2().getLocation().equals(c.getLocation())) { - makeline = false; + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + List adjCells = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); + for (TreeTentCell c : adjCells) { + Boolean makeline = true; + for (TreeTentLine l : treeTentBoard.getLines()) { + if (l.getC1().getLocation().equals(c.getLocation()) + || l.getC2().getLocation().equals(c.getLocation())) { + makeline = false; + } + } + if (makeline) { + TreeTentBoard caseBoard = (TreeTentBoard) board.copy(); + TreeTentLine line = new TreeTentLine(cell, c); + caseBoard.getLines().add(line); + caseBoard.addModifiedData(line); + cases.add(caseBoard); + } } - } - if (makeline) { - TreeTentBoard caseBoard = (TreeTentBoard) board.copy(); - TreeTentLine line = new TreeTentLine(cell, c); - caseBoard.getLines().add(line); - caseBoard.addModifiedData(line); - cases.add(caseBoard); - } + return cases; } - return cases; - } - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - Set modCells = transition.getBoard().getModifiedData(); - if (modCells.size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case"; - } - PuzzleElement mod = modCells.iterator().next(); - TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; - if (line == null) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; - } - TreeTentCell tree = null; - if (line.getC1().getType() == TreeTentType.TREE) { - tree = line.getC1(); - } - if (line.getC2().getType() == TreeTentType.TREE) { - tree = line.getC2(); - } - if (tree == null) { - return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; - } - - TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - ArrayList cases = getCases(parentBoard, tree); - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != cases.size()) { - return super.getInvalidUseOfRuleMessage(); - } - for (Board caseBoard : cases) { - TreeTentBoard cBoard = (TreeTentBoard) caseBoard; - TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); - boolean hasLine = false; - for (TreeTransition tran : childTransitions) { - TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); - if (tBoard.getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage(); + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + Set modCells = transition.getBoard().getModifiedData(); + if (modCells.size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case"; } - PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); - if (!(tElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule only involves tree and tent connection lines"; + PuzzleElement mod = modCells.iterator().next(); + TreeTentLine line = mod instanceof TreeTentLine ? (TreeTentLine) mod : null; + if (line == null) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; } - if (cLine.compare((TreeTentLine) tElement)) { - hasLine = true; - break; + TreeTentCell tree = null; + if (line.getC1().getType() == TreeTentType.TREE) { + tree = line.getC1(); } - } - if (!hasLine) { - return super.getInvalidUseOfRuleMessage(); - } + if (line.getC2().getType() == TreeTentType.TREE) { + tree = line.getC2(); + } + if (tree == null) { + return super.getInvalidUseOfRuleMessage() + "This case rule must have a tent cell"; + } + + TreeTentBoard parentBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + ArrayList cases = getCases(parentBoard, tree); + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != cases.size()) { + return super.getInvalidUseOfRuleMessage(); + } + for (Board caseBoard : cases) { + TreeTentBoard cBoard = (TreeTentBoard) caseBoard; + TreeTentLine cLine = (TreeTentLine) cBoard.getModifiedData().iterator().next(); + boolean hasLine = false; + for (TreeTransition tran : childTransitions) { + TreeTentBoard tBoard = (TreeTentBoard) tran.getBoard(); + if (tBoard.getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage(); + } + PuzzleElement tElement = tBoard.getModifiedData().iterator().next(); + if (!(tElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule only involves tree and tent connection lines"; + } + if (cLine.compare((TreeTentLine) tElement)) { + hasLine = true; + break; + } + } + if (!hasLine) { + return super.getInvalidUseOfRuleMessage(); + } + } + + return null; } - return null; - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + /** + * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be + * valid Overridden by case rules dependent on more than just the modified data + * + * @param board board state at application + * @param puzzleElement selected puzzleElement + * @return List of puzzle elements (typically cells) this application of the case rule depends + * upon. Defaults to any element modified by any case + */ + @Override + public List dependentElements(Board board, PuzzleElement puzzleElement) { + List elements = + new ArrayList<>(List.of(board.getPuzzleElement(puzzleElement))); - /** - * Returns the elements necessary for the cases returned by getCases(board,puzzleElement) to be - * valid Overridden by case rules dependent on more than just the modified data - * - * @param board board state at application - * @param puzzleElement selected puzzleElement - * @return List of puzzle elements (typically cells) this application of the case rule depends - * upon. Defaults to any element modified by any case - */ - @Override - public List dependentElements(Board board, PuzzleElement puzzleElement) { - List elements = new ArrayList<>(List.of(board.getPuzzleElement(puzzleElement))); + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell point = (TreeTentCell) puzzleElement; - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell point = (TreeTentCell) puzzleElement; + // get all adjacent cells + Point loc = point.getLocation(); + for (int i = -2; i < 2; i++) { + TreeTentCell cell = treeTentBoard.getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); + if (cell != null) { + elements.add(board.getPuzzleElement(cell)); + } + } - // get all adjacent cells - Point loc = point.getLocation(); - for (int i = -2; i < 2; i++) { - TreeTentCell cell = treeTentBoard.getCell(loc.x + (i % 2), loc.y + ((i + 1) % 2)); - if (cell != null) { - elements.add(board.getPuzzleElement(cell)); - } + return elements; } - - return elements; - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java index 900c37d92..912fa6d20 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTentForTreeContradictionRule.java @@ -12,57 +12,57 @@ public class NoTentForTreeContradictionRule extends ContradictionRule { - public NoTentForTreeContradictionRule() { - super( - "TREE-CONT-0001", - "No Tent For Tree", - "Each tree must link to a tent.", - "edu/rpi/legup/images/treetent/contra_NoTentForTree.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TREE) { - return super.getNoContradictionMessage(); + public NoTentForTreeContradictionRule() { + super( + "TREE-CONT-0001", + "No Tent For Tree", + "Each tree must link to a tent.", + "edu/rpi/legup/images/treetent/contra_NoTentForTree.png"); } - int adjTent = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); - int adjUnknown = treeTentBoard.getAdjacent(cell, TreeTentType.UNKNOWN).size(); - if (adjTent == 0 && adjUnknown == 0) { - return null; - } else { - if (adjTent != 0) { - List lines = treeTentBoard.getLines(); - List adjTents = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); - for (TreeTentLine l : lines) { - Iterator i = adjTents.iterator(); - while (i.hasNext()) { - TreeTentCell t = i.next(); - if (t.getLocation().equals(l.getC1().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - if (t.getLocation().equals(l.getC2().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); - } - } + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TREE) { + return super.getNoContradictionMessage(); } - if (adjTents.size() == 0 && adjUnknown == 0) { - return null; + int adjTent = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); + int adjUnknown = treeTentBoard.getAdjacent(cell, TreeTentType.UNKNOWN).size(); + if (adjTent == 0 && adjUnknown == 0) { + return null; + } else { + if (adjTent != 0) { + List lines = treeTentBoard.getLines(); + List adjTents = treeTentBoard.getAdjacent(cell, TreeTentType.TENT); + for (TreeTentLine l : lines) { + Iterator i = adjTents.iterator(); + while (i.hasNext()) { + TreeTentCell t = i.next(); + if (t.getLocation().equals(l.getC1().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + if (t.getLocation().equals(l.getC2().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + } + } + if (adjTents.size() == 0 && adjUnknown == 0) { + return null; + } + } + return super.getNoContradictionMessage(); } - } - return super.getNoContradictionMessage(); } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java index c6cf2fc35..9bc3fddea 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/NoTreeForTentContradictionRule.java @@ -12,51 +12,51 @@ public class NoTreeForTentContradictionRule extends ContradictionRule { - public NoTreeForTentContradictionRule() { - super( - "TREE-CONT-0002", - "No Tree For Tent", - "Each tent must link to a tree.", - "edu/rpi/legup/images/treetent/contra_NoTreeForTent.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TENT) { - return super.getNoContradictionMessage(); + public NoTreeForTentContradictionRule() { + super( + "TREE-CONT-0002", + "No Tree For Tent", + "Each tent must link to a tree.", + "edu/rpi/legup/images/treetent/contra_NoTreeForTent.png"); } - List adjTrees = treeTentBoard.getAdjacent(cell, TreeTentType.TREE); - List lines = treeTentBoard.getLines(); - for (TreeTentLine l : lines) { - Iterator i = adjTrees.iterator(); - while (i.hasNext()) { - TreeTentCell t = i.next(); - if (t.getLocation().equals(l.getC1().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); + + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TENT) { + return super.getNoContradictionMessage(); } - if (t.getLocation().equals(l.getC2().getLocation()) - && !(cell.getLocation().equals(l.getC2().getLocation()))) { - i.remove(); + List adjTrees = treeTentBoard.getAdjacent(cell, TreeTentType.TREE); + List lines = treeTentBoard.getLines(); + for (TreeTentLine l : lines) { + Iterator i = adjTrees.iterator(); + while (i.hasNext()) { + TreeTentCell t = i.next(); + if (t.getLocation().equals(l.getC1().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + if (t.getLocation().equals(l.getC2().getLocation()) + && !(cell.getLocation().equals(l.getC2().getLocation()))) { + i.remove(); + } + } + } + int adjTree = adjTrees.size(); + if (adjTree == 0) { + return null; + } else { + return super.getNoContradictionMessage(); } - } - } - int adjTree = adjTrees.size(); - if (adjTree == 0) { - return null; - } else { - return super.getNoContradictionMessage(); } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java index 447bbcde0..e800dc416 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/SurroundTentWithGrassDirectRule.java @@ -13,73 +13,74 @@ public class SurroundTentWithGrassDirectRule extends DirectRule { - public SurroundTentWithGrassDirectRule() { - super( - "TREE-BASC-0005", - "Surround Tent with Grass", - "Blank cells adjacent or diagonal to a tent are grass.", - "edu/rpi/legup/images/treetent/aroundTent.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (puzzleElement == null) { - return null; - } - if (puzzleElement instanceof TreeTentLine) { - return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; - } - TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); - TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); - TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); - TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); - if (!(initCell.getType() == TreeTentType.UNKNOWN - && finalCell.getType() == TreeTentType.GRASS)) { - return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + public SurroundTentWithGrassDirectRule() { + super( + "TREE-BASC-0005", + "Surround Tent with Grass", + "Blank cells adjacent or diagonal to a tent are grass.", + "edu/rpi/legup/images/treetent/aroundTent.png"); } - if (isForced(initialBoard, initCell)) { - return null; - } else { - return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; - } - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (puzzleElement == null) { + return null; + } + if (puzzleElement instanceof TreeTentLine) { + return super.getInvalidUseOfRuleMessage() + ": Line is not valid for this rule."; + } + TreeTentBoard initialBoard = (TreeTentBoard) transition.getParents().get(0).getBoard(); + TreeTentCell initCell = (TreeTentCell) initialBoard.getPuzzleElement(puzzleElement); + TreeTentBoard finalBoard = (TreeTentBoard) transition.getBoard(); + TreeTentCell finalCell = (TreeTentCell) finalBoard.getPuzzleElement(puzzleElement); + if (!(initCell.getType() == TreeTentType.UNKNOWN + && finalCell.getType() == TreeTentType.GRASS)) { + return super.getInvalidUseOfRuleMessage() + ": This cell must be a tent."; + } - private boolean isForced(TreeTentBoard board, TreeTentCell cell) { - List tents = board.getAdjacent(cell, TreeTentType.TENT); - tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); - return !tents.isEmpty(); - } + if (isForced(initialBoard, initCell)) { + return null; + } else { + return super.getInvalidUseOfRuleMessage() + ": This cell is not forced to be tent."; + } + } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - TreeTentCell cell = (TreeTentCell) element; - if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { - cell.setData(TreeTentType.GRASS); - treeTentBoard.addModifiedData(cell); - } + private boolean isForced(TreeTentBoard board, TreeTentCell cell) { + List tents = board.getAdjacent(cell, TreeTentType.TENT); + tents.addAll(board.getDiagonals(cell, TreeTentType.TENT)); + return !tents.isEmpty(); } - if (treeTentBoard.getModifiedData().isEmpty()) { - return null; - } else { - return treeTentBoard; + + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + TreeTentBoard treeTentBoard = (TreeTentBoard) node.getBoard().copy(); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + TreeTentCell cell = (TreeTentCell) element; + if (cell.getType() == TreeTentType.UNKNOWN && isForced(treeTentBoard, cell)) { + cell.setData(TreeTentType.GRASS); + treeTentBoard.addModifiedData(cell); + } + } + if (treeTentBoard.getModifiedData().isEmpty()) { + return null; + } else { + return treeTentBoard; + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java index af44359fb..8044faa0e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentForTreeDirectRule.java @@ -14,110 +14,112 @@ public class TentForTreeDirectRule extends DirectRule { - public TentForTreeDirectRule() { - super( - "TREE-BASC-0006", - "Tent for Tree", - "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the" - + " unlinked tree must link to the unlinked tent.", - "edu/rpi/legup/images/treetent/NewTreeLink.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE - && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } else { - if (line.getC2().getType() == TreeTentType.TREE - && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } else { - return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; - } + public TentForTreeDirectRule() { + super( + "TREE-BASC-0006", + "Tent for Tree", + "If only one unlinked tent and no blank cells are adjacent to an unlinked tree, the" + + " unlinked tree must link to the unlinked tent.", + "edu/rpi/legup/images/treetent/NewTreeLink.png"); } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; - } else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; - } else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE + && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); } else { - return super.getInvalidUseOfRuleMessage() - + ": This tree and tent don't need to be linked."; + if (line.getC2().getType() == TreeTentType.TREE + && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } else { + return super.getInvalidUseOfRuleMessage() + + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This tree and tent don't need to be linked."; + } + } } - } } - } - private Integer isForced( - TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTents = board.getAdjacent(tree, TreeTentType.TENT); - adjTents.remove(tent); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTents) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tree.getLocation())) { - return -1; - } - toRemove.add(c); + private Integer isForced( + TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTents = board.getAdjacent(tree, TreeTentType.TENT); + adjTents.remove(tent); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTents) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); - } else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tree.getLocation())) { - return -1; + } else { + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tree.getLocation())) { + return -1; + } + toRemove.add(c); + } + } } - toRemove.add(c); - } + for (TreeTentCell c : toRemove) { + adjTents.remove(c); + } + toRemove.clear(); + } + if (adjTents.size() == 0) { + return 1; + } else { + return 0; } - } - for (TreeTentCell c : toRemove) { - adjTents.remove(c); - } - toRemove.clear(); - } - if (adjTents.size() == 0) { - return 1; - } else { - return 0; } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java index 2b6afd5d0..63478f83e 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TentOrGrassCaseRule.java @@ -13,101 +13,101 @@ public class TentOrGrassCaseRule extends CaseRule { - public TentOrGrassCaseRule() { - super( - "TREE-CASE-0004", - "Tent or Grass", - "Each blank cell is either a tent or grass.", - "edu/rpi/legup/images/treetent/caseTentOrGrass.png"); - } - - @Override - public CaseBoard getCaseBoard(Board board) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); - treeTentBoard.setModifiable(false); - CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); - for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { - if (((TreeTentCell) element).getType() == TreeTentType.UNKNOWN) { - caseBoard.addPickableElement(element); - } + public TentOrGrassCaseRule() { + super( + "TREE-CASE-0004", + "Tent or Grass", + "Each blank cell is either a tent or grass.", + "edu/rpi/legup/images/treetent/caseTentOrGrass.png"); } - return caseBoard; - } - /** - * Gets the possible cases at a specific location based on this case rule - * - * @param board the current board state - * @param puzzleElement equivalent puzzleElement - * @return a list of elements the specified could be - */ - @SuppressWarnings("unchecked") - @Override - public ArrayList getCases(Board board, PuzzleElement puzzleElement) { - ArrayList cases = new ArrayList<>(); - Board case1 = board.copy(); - PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); - data1.setData(TreeTentType.TENT); - case1.addModifiedData(data1); - cases.add(case1); + @Override + public CaseBoard getCaseBoard(Board board) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board.copy(); + treeTentBoard.setModifiable(false); + CaseBoard caseBoard = new CaseBoard(treeTentBoard, this); + for (PuzzleElement element : treeTentBoard.getPuzzleElements()) { + if (((TreeTentCell) element).getType() == TreeTentType.UNKNOWN) { + caseBoard.addPickableElement(element); + } + } + return caseBoard; + } - Board case2 = board.copy(); - PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); - data2.setData(TreeTentType.GRASS); - case2.addModifiedData(data2); - cases.add(case2); + /** + * Gets the possible cases at a specific location based on this case rule + * + * @param board the current board state + * @param puzzleElement equivalent puzzleElement + * @return a list of elements the specified could be + */ + @SuppressWarnings("unchecked") + @Override + public ArrayList getCases(Board board, PuzzleElement puzzleElement) { + ArrayList cases = new ArrayList<>(); + Board case1 = board.copy(); + PuzzleElement data1 = case1.getPuzzleElement(puzzleElement); + data1.setData(TreeTentType.TENT); + case1.addModifiedData(data1); + cases.add(case1); - return cases; - } + Board case2 = board.copy(); + PuzzleElement data2 = case2.getPuzzleElement(puzzleElement); + data2.setData(TreeTentType.GRASS); + case2.addModifiedData(data2); + cases.add(case2); - /** - * Checks whether the transition logically follows from the parent node using this rule - * - * @param transition transition to check - * @return null if the child node logically follow from the parent node, otherwise error message - */ - @Override - public String checkRuleRaw(TreeTransition transition) { - List childTransitions = transition.getParents().get(0).getChildren(); - if (childTransitions.size() != 2) { - return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + return cases; } - TreeTransition case1 = childTransitions.get(0); - TreeTransition case2 = childTransitions.get(1); - if (case1.getBoard().getModifiedData().size() != 1 - || case2.getBoard().getModifiedData().size() != 1) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have 1 modified cell for each case."; - } + /** + * Checks whether the transition logically follows from the parent node using this rule + * + * @param transition transition to check + * @return null if the child node logically follow from the parent node, otherwise error message + */ + @Override + public String checkRuleRaw(TreeTransition transition) { + List childTransitions = transition.getParents().get(0).getChildren(); + if (childTransitions.size() != 2) { + return super.getInvalidUseOfRuleMessage() + ": This case rule must have 2 children."; + } - TreeTentCell mod1 = (TreeTentCell) case1.getBoard().getModifiedData().iterator().next(); - TreeTentCell mod2 = (TreeTentCell) case2.getBoard().getModifiedData().iterator().next(); - if (!mod1.getLocation().equals(mod2.getLocation())) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must modify the same cell for each case."; - } + TreeTransition case1 = childTransitions.get(0); + TreeTransition case2 = childTransitions.get(1); + if (case1.getBoard().getModifiedData().size() != 1 + || case2.getBoard().getModifiedData().size() != 1) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have 1 modified cell for each case."; + } - if (!((mod1.getType() == TreeTentType.TENT && mod2.getType() == TreeTentType.GRASS) - || (mod2.getType() == TreeTentType.TENT && mod1.getType() == TreeTentType.GRASS))) { - return super.getInvalidUseOfRuleMessage() - + ": This case rule must have a tent and a grass cell."; - } + TreeTentCell mod1 = (TreeTentCell) case1.getBoard().getModifiedData().iterator().next(); + TreeTentCell mod2 = (TreeTentCell) case2.getBoard().getModifiedData().iterator().next(); + if (!mod1.getLocation().equals(mod2.getLocation())) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must modify the same cell for each case."; + } + + if (!((mod1.getType() == TreeTentType.TENT && mod2.getType() == TreeTentType.GRASS) + || (mod2.getType() == TreeTentType.TENT && mod1.getType() == TreeTentType.GRASS))) { + return super.getInvalidUseOfRuleMessage() + + ": This case rule must have a tent and a grass cell."; + } - return null; - } + return null; + } - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - return checkRuleRaw(transition); - } + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + return checkRuleRaw(transition); + } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java index 220a9aeb0..7b3f43dbe 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooFewTentsContradictionRule.java @@ -10,39 +10,39 @@ public class TooFewTentsContradictionRule extends ContradictionRule { - public TooFewTentsContradictionRule() { - super( - "TREE-CONT-0003", - "Too Few Tents", - "Rows and columns cannot have fewer tents than their clue.", - "edu/rpi/legup/images/treetent/too_few_tents.png"); - } + public TooFewTentsContradictionRule() { + super( + "TREE-CONT-0003", + "Too Few Tents", + "Rows and columns cannot have fewer tents than their clue.", + "edu/rpi/legup/images/treetent/too_few_tents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); - int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); - int rowUnknowns = treeTentBoard.getRowCol(loc.y, TreeTentType.UNKNOWN, true).size(); - int colUnknowns = treeTentBoard.getRowCol(loc.x, TreeTentType.UNKNOWN, false).size(); + Point loc = cell.getLocation(); + int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); + int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); + int rowUnknowns = treeTentBoard.getRowCol(loc.y, TreeTentType.UNKNOWN, true).size(); + int colUnknowns = treeTentBoard.getRowCol(loc.x, TreeTentType.UNKNOWN, false).size(); - if (rowTents + rowUnknowns < treeTentBoard.getRowClues().get(loc.y).getData() - || colTents + colUnknowns < treeTentBoard.getColClues().get(loc.x).getData()) { - return null; - } else { - return super.getNoContradictionMessage(); + if (rowTents + rowUnknowns < treeTentBoard.getRowClues().get(loc.y).getData() + || colTents + colUnknowns < treeTentBoard.getColClues().get(loc.x).getData()) { + return null; + } else { + return super.getNoContradictionMessage(); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java index da2a3964d..dcc65feb6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TooManyTentsContradictionRule.java @@ -10,37 +10,37 @@ public class TooManyTentsContradictionRule extends ContradictionRule { - public TooManyTentsContradictionRule() { - super( - "TREE-CONT-0004", - "Too Many Tents", - "Rows and columns cannot have more tents than their clue.", - "edu/rpi/legup/images/treetent/too_many_tents.png"); - } + public TooManyTentsContradictionRule() { + super( + "TREE-CONT-0004", + "Too Many Tents", + "Rows and columns cannot have more tents than their clue.", + "edu/rpi/legup/images/treetent/too_many_tents.png"); + } - /** - * Checks whether the transition has a contradiction at the specific puzzleElement index using - * this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent puzzleElement - * @return null if the transition contains a contradiction at the specified puzzleElement, - * otherwise error message - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; + /** + * Checks whether the transition has a contradiction at the specific puzzleElement index using + * this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent puzzleElement + * @return null if the transition contains a contradiction at the specified puzzleElement, + * otherwise error message + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; - Point loc = cell.getLocation(); - int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); - int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); + Point loc = cell.getLocation(); + int rowTents = treeTentBoard.getRowCol(loc.y, TreeTentType.TENT, true).size(); + int colTents = treeTentBoard.getRowCol(loc.x, TreeTentType.TENT, false).size(); - if (rowTents > treeTentBoard.getRowClues().get(loc.y).getData() - || colTents > treeTentBoard.getColClues().get(loc.x).getData()) { - return null; - } else { - return super.getNoContradictionMessage(); + if (rowTents > treeTentBoard.getRowClues().get(loc.y).getData() + || colTents > treeTentBoard.getColClues().get(loc.x).getData()) { + return null; + } else { + return super.getNoContradictionMessage(); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java index 075003130..d9dd36e12 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TouchingTentsContradictionRule.java @@ -9,36 +9,36 @@ public class TouchingTentsContradictionRule extends ContradictionRule { - public TouchingTentsContradictionRule() { - super( - "TREE-CONT-0005", - "Touching Tents", - "Tents cannot touch other tents.", - "edu/rpi/legup/images/treetent/contra_adjacentTents.png"); - } - - /** - * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index - * using this rule - * - * @param board board to check contradiction - * @param puzzleElement equivalent {@link PuzzleElement} - * @return null if the transition contains a contradiction at the specified - * puzzleElement, otherwise error message. - */ - @Override - public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { - TreeTentBoard treeTentBoard = (TreeTentBoard) board; - TreeTentCell cell = (TreeTentCell) puzzleElement; - if (cell.getType() != TreeTentType.TENT) { - return super.getNoContradictionMessage(); + public TouchingTentsContradictionRule() { + super( + "TREE-CONT-0005", + "Touching Tents", + "Tents cannot touch other tents.", + "edu/rpi/legup/images/treetent/contra_adjacentTents.png"); } - int adjTree = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); - int diagTree = treeTentBoard.getDiagonals(cell, TreeTentType.TENT).size(); - if (adjTree > 0 || diagTree > 0) { - return null; - } else { - return super.getNoContradictionMessage(); + + /** + * Checks whether the transition has a contradiction at the specific {@link PuzzleElement} index + * using this rule + * + * @param board board to check contradiction + * @param puzzleElement equivalent {@link PuzzleElement} + * @return null if the transition contains a contradiction at the specified + * puzzleElement, otherwise error message. + */ + @Override + public String checkContradictionAt(Board board, PuzzleElement puzzleElement) { + TreeTentBoard treeTentBoard = (TreeTentBoard) board; + TreeTentCell cell = (TreeTentCell) puzzleElement; + if (cell.getType() != TreeTentType.TENT) { + return super.getNoContradictionMessage(); + } + int adjTree = treeTentBoard.getAdjacent(cell, TreeTentType.TENT).size(); + int diagTree = treeTentBoard.getDiagonals(cell, TreeTentType.TENT).size(); + if (adjTree > 0 || diagTree > 0) { + return null; + } else { + return super.getNoContradictionMessage(); + } } - } } diff --git a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java index 1fd15dbc9..d4360c7f6 100644 --- a/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java +++ b/src/main/java/edu/rpi/legup/puzzle/treetent/rules/TreeForTentDirectRule.java @@ -13,110 +13,112 @@ import java.util.List; public class TreeForTentDirectRule extends DirectRule { - public TreeForTentDirectRule() { - super( - "TREE-BASC-0007", - "Tree for Tent", - "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must" - + " link to the unlinked tree.", - "edu/rpi/legup/images/treetent/NewTentLink.png"); - } - - /** - * Checks whether the child node logically follows from the parent node at the specific - * puzzleElement index using this rule - * - * @param transition transition to check - * @param puzzleElement equivalent puzzleElement - * @return null if the child node logically follow from the parent node at the specified - * puzzleElement, otherwise error message - */ - @Override - public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { - if (!(puzzleElement instanceof TreeTentLine)) { - return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; - } - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); - TreeTentCell tree, tent; - if (line.getC1().getType() == TreeTentType.TREE - && line.getC2().getType() == TreeTentType.TENT) { - tree = line.getC1(); - tent = line.getC2(); - } else { - if (line.getC2().getType() == TreeTentType.TREE - && line.getC1().getType() == TreeTentType.TENT) { - tree = line.getC2(); - tent = line.getC1(); - } else { - return super.getInvalidUseOfRuleMessage() + ": This line must connect a tree to a tent."; - } + public TreeForTentDirectRule() { + super( + "TREE-BASC-0007", + "Tree for Tent", + "If only one unlinked tree is adjacent to an unlinked tent, the unlinked tent must" + + " link to the unlinked tree.", + "edu/rpi/legup/images/treetent/NewTentLink.png"); } - int forced = isForced(board, tree, tent, line); - if (forced == 1) { - return null; - } else { - if (forced == -1) { - return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; - } else { - if (forced == -2) { - return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + + /** + * Checks whether the child node logically follows from the parent node at the specific + * puzzleElement index using this rule + * + * @param transition transition to check + * @param puzzleElement equivalent puzzleElement + * @return null if the child node logically follow from the parent node at the specified + * puzzleElement, otherwise error message + */ + @Override + public String checkRuleRawAt(TreeTransition transition, PuzzleElement puzzleElement) { + if (!(puzzleElement instanceof TreeTentLine)) { + return super.getInvalidUseOfRuleMessage() + ": Lines must be created for this rule."; + } + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentLine line = (TreeTentLine) board.getPuzzleElement(puzzleElement); + TreeTentCell tree, tent; + if (line.getC1().getType() == TreeTentType.TREE + && line.getC2().getType() == TreeTentType.TENT) { + tree = line.getC1(); + tent = line.getC2(); } else { - return super.getInvalidUseOfRuleMessage() - + ": This tree and tent don't need to be linked."; + if (line.getC2().getType() == TreeTentType.TREE + && line.getC1().getType() == TreeTentType.TENT) { + tree = line.getC2(); + tent = line.getC1(); + } else { + return super.getInvalidUseOfRuleMessage() + + ": This line must connect a tree to a tent."; + } + } + int forced = isForced(board, tree, tent, line); + if (forced == 1) { + return null; + } else { + if (forced == -1) { + return super.getInvalidUseOfRuleMessage() + ": This tent already has a link"; + } else { + if (forced == -2) { + return super.getInvalidUseOfRuleMessage() + ": This tree already has a link"; + } else { + return super.getInvalidUseOfRuleMessage() + + ": This tree and tent don't need to be linked."; + } + } } - } } - } - private Integer isForced( - TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { - List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); - adjTrees.remove(tree); - List lines = board.getLines(); - lines.remove(line); - for (TreeTentLine l : lines) { - ArrayList toRemove = new ArrayList<>(); - if (l.getC1().getLocation().equals(tree.getLocation()) - || l.getC2().getLocation().equals(tree.getLocation())) { - return -2; - } - for (TreeTentCell c : adjTrees) { - if (l.getC1().getLocation().equals(c.getLocation())) { - if (l.getC2().getLocation().equals(tent.getLocation())) { - return -1; - } - toRemove.add(c); + private Integer isForced( + TreeTentBoard board, TreeTentCell tree, TreeTentCell tent, TreeTentLine line) { + List adjTrees = board.getAdjacent(tent, TreeTentType.TREE); + adjTrees.remove(tree); + List lines = board.getLines(); + lines.remove(line); + for (TreeTentLine l : lines) { + ArrayList toRemove = new ArrayList<>(); + if (l.getC1().getLocation().equals(tree.getLocation()) + || l.getC2().getLocation().equals(tree.getLocation())) { + return -2; + } + for (TreeTentCell c : adjTrees) { + if (l.getC1().getLocation().equals(c.getLocation())) { + if (l.getC2().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); - } else { - if (l.getC2().getLocation().equals(c.getLocation())) { - if (l.getC1().getLocation().equals(tent.getLocation())) { - return -1; + } else { + if (l.getC2().getLocation().equals(c.getLocation())) { + if (l.getC1().getLocation().equals(tent.getLocation())) { + return -1; + } + toRemove.add(c); + } + } } - toRemove.add(c); - } + for (TreeTentCell c : toRemove) { + adjTrees.remove(c); + } + toRemove.clear(); + } + if (adjTrees.size() == 0) { + return 1; + } else { + return 0; } - } - for (TreeTentCell c : toRemove) { - adjTrees.remove(c); - } - toRemove.clear(); - } - if (adjTrees.size() == 0) { - return 1; - } else { - return 0; } - } - /** - * Creates a transition {@link Board} that has this rule applied to it using the {@link TreeNode}. - * - * @param node tree node used to create default transition board - * @return default board or null if this rule cannot be applied to this tree node - */ - @Override - public Board getDefaultBoard(TreeNode node) { - return null; - } + /** + * Creates a transition {@link Board} that has this rule applied to it using the {@link + * TreeNode}. + * + * @param node tree node used to create default transition board + * @return default board or null if this rule cannot be applied to this tree node + */ + @Override + public Board getDefaultBoard(TreeNode node) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/save/ExportFileException.java b/src/main/java/edu/rpi/legup/save/ExportFileException.java index 70eec7868..9def1f392 100644 --- a/src/main/java/edu/rpi/legup/save/ExportFileException.java +++ b/src/main/java/edu/rpi/legup/save/ExportFileException.java @@ -2,7 +2,7 @@ public class ExportFileException extends Exception { - public ExportFileException(String message) { - super("Export File Exception: " + message); - } + public ExportFileException(String message) { + super("Export File Exception: " + message); + } } diff --git a/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java b/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java index 9207aeaa6..1e24c5762 100644 --- a/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java +++ b/src/main/java/edu/rpi/legup/save/InvalidFileFormatException.java @@ -2,7 +2,7 @@ public class InvalidFileFormatException extends Exception { - public InvalidFileFormatException(String message) { - super("InvalidFileFormatException: " + message); - } + public InvalidFileFormatException(String message) { + super("InvalidFileFormatException: " + message); + } } diff --git a/src/main/java/edu/rpi/legup/save/SavableBoard.java b/src/main/java/edu/rpi/legup/save/SavableBoard.java index a0d141dea..bd246303b 100644 --- a/src/main/java/edu/rpi/legup/save/SavableBoard.java +++ b/src/main/java/edu/rpi/legup/save/SavableBoard.java @@ -4,13 +4,13 @@ import java.io.InputStream; public class SavableBoard { - private static final String LEGUP_HEADER = "edu.rpi.legup.Legup"; + private static final String LEGUP_HEADER = "edu.rpi.legup.Legup"; - private String filePath; - private InputStream inputStream; + private String filePath; + private InputStream inputStream; - public SavableBoard(String filePath) throws Exception { - this.filePath = filePath; - this.inputStream = new FileInputStream(filePath); - } + public SavableBoard(String filePath) throws Exception { + this.filePath = filePath; + this.inputStream = new FileInputStream(filePath); + } } diff --git a/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java b/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java index dd56a3a72..70fbea033 100644 --- a/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java +++ b/src/main/java/edu/rpi/legup/ui/CreatePuzzleDialog.java @@ -11,206 +11,216 @@ import javax.swing.*; public class CreatePuzzleDialog extends JDialog { - private HomePanel homePanel; - - private String[] games; - private JComboBox gameBox; - private ActionListener gameBoxListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JComboBox comboBox = (JComboBox) e.getSource(); - String puzzleName = (String) comboBox.getSelectedItem(); - if (puzzleName.equals("ShortTruthTable")) { + private HomePanel homePanel; + + private String[] games; + private JComboBox gameBox; + private ActionListener gameBoxListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JComboBox comboBox = (JComboBox) e.getSource(); + String puzzleName = (String) comboBox.getSelectedItem(); + if (puzzleName.equals("ShortTruthTable")) { + textInputScrollPane.setVisible(true); + rowsLabel.setVisible(false); + rows.setVisible(false); + columnsLabel.setVisible(false); + columns.setVisible(false); + } else { + textInputScrollPane.setVisible(false); + rowsLabel.setVisible(true); + rows.setVisible(true); + columnsLabel.setVisible(true); + columns.setVisible(true); + } + } + }; + + private JLabel puzzleLabel; + private JLabel rowsLabel; + private JTextField rows; + private JLabel columnsLabel; + private JTextField columns; + + private JTextArea textArea; + private JScrollPane textInputScrollPane; + + private JButton ok = new JButton("Ok"); + private ActionListener okButtonListener = + new ActionListener() { + /** + * Attempts to open the puzzle editor interface for the given game with the given + * dimensions + * + * @param ae the event to be processed + */ + @Override + public void actionPerformed(ActionEvent ae) { + String game = + Config.convertDisplayNameToClassName( + (String) gameBox.getSelectedItem()); + + // Check if all 3 TextFields are filled + if (game.equals("ShortTruthTable") && textArea.getText().isEmpty()) { + System.out.println("Unfilled fields"); + return; + } + if (!game.equals("ShortTruthTable") + && (game.isEmpty() + || rows.getText().isEmpty() + || columns.getText().isEmpty())) { + System.out.println("Unfilled fields"); + return; + } + + try { + if (game.equals("ShortTruthTable")) { + homePanel.openEditorWithNewPuzzle( + "ShortTruthTable", textArea.getText().split("\n")); + } else { + homePanel.openEditorWithNewPuzzle( + game, + Integer.valueOf(rows.getText()), + Integer.valueOf(columns.getText())); + } + setVisible(false); + } catch (IllegalArgumentException e) { + System.out.println("Failed to open editor with new puzzle"); + e.printStackTrace(System.out); + } + } + }; + + private JButton cancel = new JButton("Cancel"); + private ActionListener cancelButtonListener = + new ActionListener() { + /** + * Dispose the puzzle creation dialog + * + * @param e the event to be processed + */ + @Override + public void actionPerformed(ActionEvent e) { + dispose(); + } + }; + + public CreatePuzzleDialog(JFrame parent, HomePanel homePanel) { + super(parent, true); + + this.homePanel = homePanel; + + initPuzzles(); + + Rectangle b = parent.getBounds(); + + setSize(350, 200); + setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); + + Container c = getContentPane(); + c.setLayout(null); + + puzzleLabel = new JLabel("Puzzle:"); + puzzleLabel.setBounds(10, 30, 70, 25); + gameBox.setBounds(80, 30, 190, 25); + + ok.setBounds(20, 130, 60, 25); + cancel.setBounds(170, 130, 90, 25); + + c.add(puzzleLabel); + c.add(gameBox); + + rows = new JTextField(); + columns = new JTextField(); + + rowsLabel = new JLabel("Rows:"); + columnsLabel = new JLabel("Columns:"); + + rowsLabel.setBounds(30, 70, 60, 25); + columnsLabel.setBounds(30, 95, 60, 25); + + rows.setBounds(100, 70, 60, 25); + columns.setBounds(100, 95, 60, 25); + + c.add(rowsLabel); + c.add(columnsLabel); + + c.add(rows); + c.add(columns); + + textArea = new JTextArea(); + textInputScrollPane = + new JScrollPane( + textArea, + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + textInputScrollPane.setBounds(10, 70, this.getWidth() - 30, 50); + c.add(textInputScrollPane); + + c.add(ok); + c.add(cancel); + + if (Objects.equals(this.gameBox.getSelectedItem(), "ShortTruthTable")) { textInputScrollPane.setVisible(true); rowsLabel.setVisible(false); rows.setVisible(false); columnsLabel.setVisible(false); columns.setVisible(false); - } else { + } else { textInputScrollPane.setVisible(false); rowsLabel.setVisible(true); rows.setVisible(true); columnsLabel.setVisible(true); columns.setVisible(true); - } - } - }; - - private JLabel puzzleLabel; - private JLabel rowsLabel; - private JTextField rows; - private JLabel columnsLabel; - private JTextField columns; - - private JTextArea textArea; - private JScrollPane textInputScrollPane; - - private JButton ok = new JButton("Ok"); - private ActionListener okButtonListener = - new ActionListener() { - /** - * Attempts to open the puzzle editor interface for the given game with the given dimensions - * - * @param ae the event to be processed - */ - @Override - public void actionPerformed(ActionEvent ae) { - String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); - - // Check if all 3 TextFields are filled - if (game.equals("ShortTruthTable") && textArea.getText().isEmpty()) { - System.out.println("Unfilled fields"); - return; - } - if (!game.equals("ShortTruthTable") - && (game.isEmpty() || rows.getText().isEmpty() || columns.getText().isEmpty())) { - System.out.println("Unfilled fields"); - return; - } - - try { - if (game.equals("ShortTruthTable")) { - homePanel.openEditorWithNewPuzzle("ShortTruthTable", textArea.getText().split("\n")); - } else { - homePanel.openEditorWithNewPuzzle( - game, Integer.valueOf(rows.getText()), Integer.valueOf(columns.getText())); - } - setVisible(false); - } catch (IllegalArgumentException e) { - System.out.println("Failed to open editor with new puzzle"); - e.printStackTrace(System.out); - } } - }; - - private JButton cancel = new JButton("Cancel"); - private ActionListener cancelButtonListener = - new ActionListener() { - /** - * Dispose the puzzle creation dialog - * - * @param e the event to be processed - */ - @Override - public void actionPerformed(ActionEvent e) { - dispose(); - } - }; - - public CreatePuzzleDialog(JFrame parent, HomePanel homePanel) { - super(parent, true); - - this.homePanel = homePanel; - - initPuzzles(); - - Rectangle b = parent.getBounds(); - - setSize(350, 200); - setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); - - Container c = getContentPane(); - c.setLayout(null); - - puzzleLabel = new JLabel("Puzzle:"); - puzzleLabel.setBounds(10, 30, 70, 25); - gameBox.setBounds(80, 30, 190, 25); - - ok.setBounds(20, 130, 60, 25); - cancel.setBounds(170, 130, 90, 25); - c.add(puzzleLabel); - c.add(gameBox); - - rows = new JTextField(); - columns = new JTextField(); - - rowsLabel = new JLabel("Rows:"); - columnsLabel = new JLabel("Columns:"); - - rowsLabel.setBounds(30, 70, 60, 25); - columnsLabel.setBounds(30, 95, 60, 25); - - rows.setBounds(100, 70, 60, 25); - columns.setBounds(100, 95, 60, 25); - - c.add(rowsLabel); - c.add(columnsLabel); - - c.add(rows); - c.add(columns); - - textArea = new JTextArea(); - textInputScrollPane = - new JScrollPane( - textArea, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - textInputScrollPane.setBounds(10, 70, this.getWidth() - 30, 50); - c.add(textInputScrollPane); - - c.add(ok); - c.add(cancel); + ActionListener cursorSelectedGame = CursorController.createListener(this, gameBoxListener); + gameBox.addActionListener(cursorSelectedGame); + ActionListener cursorPressedOk = CursorController.createListener(this, okButtonListener); + ok.addActionListener(cursorPressedOk); + ActionListener cursorPressedCancel = + CursorController.createListener(this, cancelButtonListener); + cancel.addActionListener(cursorPressedCancel); + } - if (Objects.equals(this.gameBox.getSelectedItem(), "ShortTruthTable")) { - textInputScrollPane.setVisible(true); - rowsLabel.setVisible(false); - rows.setVisible(false); - columnsLabel.setVisible(false); - columns.setVisible(false); - } else { - textInputScrollPane.setVisible(false); - rowsLabel.setVisible(true); - rows.setVisible(true); - columnsLabel.setVisible(true); - columns.setVisible(true); + public void initPuzzles() { + this.games = + GameBoardFacade.getInstance() + .getConfig() + .getFileCreationEnabledPuzzles() + .toArray(new String[0]); + Arrays.sort(this.games); + gameBox = new JComboBox(this.games); } - ActionListener cursorSelectedGame = CursorController.createListener(this, gameBoxListener); - gameBox.addActionListener(cursorSelectedGame); - ActionListener cursorPressedOk = CursorController.createListener(this, okButtonListener); - ok.addActionListener(cursorPressedOk); - ActionListener cursorPressedCancel = - CursorController.createListener(this, cancelButtonListener); - cancel.addActionListener(cursorPressedCancel); - } - - public void initPuzzles() { - this.games = - GameBoardFacade.getInstance() - .getConfig() - .getFileCreationEnabledPuzzles() - .toArray(new String[0]); - Arrays.sort(this.games); - gameBox = new JComboBox(this.games); - } - - // ^This method seems useless and never got covered - public void actionPerformed(ActionEvent e) { - if (e.getSource() == ok) { - String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); - - try { - if (game.equals("ShortTruthTable")) { - this.homePanel.openEditorWithNewPuzzle( - "ShortTruthTable", this.textArea.getText().split("\n")); + // ^This method seems useless and never got covered + public void actionPerformed(ActionEvent e) { + if (e.getSource() == ok) { + String game = Config.convertDisplayNameToClassName((String) gameBox.getSelectedItem()); + + try { + if (game.equals("ShortTruthTable")) { + this.homePanel.openEditorWithNewPuzzle( + "ShortTruthTable", this.textArea.getText().split("\n")); + } else { + this.homePanel.openEditorWithNewPuzzle( + game, + Integer.valueOf(this.rows.getText()), + Integer.valueOf(this.columns.getText())); + } + this.setVisible(false); + } catch (IllegalArgumentException exception) { + // Don't do anything. This is here to prevent the dialog from closing if the + // dimensions are + // invalid. + } } else { - this.homePanel.openEditorWithNewPuzzle( - game, Integer.valueOf(this.rows.getText()), Integer.valueOf(this.columns.getText())); + if (e.getSource() == cancel) { + this.setVisible(false); + } else { + // Unknown Action Event + } } - this.setVisible(false); - } catch (IllegalArgumentException exception) { - // Don't do anything. This is here to prevent the dialog from closing if the - // dimensions are - // invalid. - } - } else { - if (e.getSource() == cancel) { - this.setVisible(false); - } else { - // Unknown Action Event - } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/DynamicView.java b/src/main/java/edu/rpi/legup/ui/DynamicView.java index 1dea7a905..8d3024c86 100644 --- a/src/main/java/edu/rpi/legup/ui/DynamicView.java +++ b/src/main/java/edu/rpi/legup/ui/DynamicView.java @@ -18,203 +18,210 @@ public class DynamicView extends JPanel { - private ScrollView scrollView; - private JPanel zoomWrapper; - private JPanel zoomer; - private JLabel status; - - private static final Font ERROR_FONT = MaterialFonts.ITALIC; - private static final Color ERROR_COLOR = MaterialColors.RED_700; - - private static final Font INFO_FONT = MaterialFonts.REGULAR; - private static final Color INFO_COLOR = MaterialColors.GRAY_900; - - public DynamicView(ScrollView scrollView, DynamicViewType type) { - this.scrollView = scrollView; - - setLayout(new BorderLayout()); - - add(scrollView, CENTER); - add(setUpZoomer(type), SOUTH); - } - - /** - * Sets up the zoomer for the given DynamicViewType - * - * @param type The DynamicView that we are setting up the zoomer for (so the zoomer for the board - * view or the zoomer for the proof tree view) - * @return A JPanel containing the zoomer - */ - private JPanel setUpZoomer(DynamicViewType type) { - if (type == DynamicViewType.BOARD) { - return setUpBoardZoomer(); - } else { - if (type == DynamicViewType.PROOF_TREE) { - return setUpProofTreeZoomer(); - } + private ScrollView scrollView; + private JPanel zoomWrapper; + private JPanel zoomer; + private JLabel status; + + private static final Font ERROR_FONT = MaterialFonts.ITALIC; + private static final Color ERROR_COLOR = MaterialColors.RED_700; + + private static final Font INFO_FONT = MaterialFonts.REGULAR; + private static final Color INFO_COLOR = MaterialColors.GRAY_900; + + public DynamicView(ScrollView scrollView, DynamicViewType type) { + this.scrollView = scrollView; + + setLayout(new BorderLayout()); + + add(scrollView, CENTER); + add(setUpZoomer(type), SOUTH); } - // Should never reach here; if you reach here, that's a problem! - return null; - } - - /** - * Sets up the zoomer for the board view - * - * @return A JPanel containing the zoomer - */ - private JPanel setUpBoardZoomer() { - final String label = "Resize Board"; - ActionListener listener = (ActionListener) -> this.fitBoardViewToScreen(); - return this.setUpZoomerHelper(label, listener); - } - - /** - * Sets up the zoomer for the proof tree view - * - * @return A JPanel containing the zoomer - */ - private JPanel setUpProofTreeZoomer() { - final String label = "Resize Proof"; - ActionListener listener = - (ActionListener) -> - GameBoardFacade.getInstance().getLegupUI().getProofEditor().fitTreeViewToScreen(); - return this.setUpZoomerHelper(label, listener); - } - - /** - * Creates the zoomer - * - * @param label A string containing the label to be displayed on the fit to screen button - * @param listener A listener that determines what the resize button will do - * @return A JPanel containing the zoomer - */ - private JPanel setUpZoomerHelper(final String label, ActionListener listener) { - zoomWrapper = new JPanel(); - try { - zoomer = new JPanel(); - - // Create and add the resize button to the zoomer - JButton resizeButton = new JButton(label); - resizeButton.setFocusPainted(false); - resizeButton.setFocusPainted(false); - resizeButton.setEnabled(true); - resizeButton.setSize(100, 50); - resizeButton.addActionListener(listener); - zoomer.add(resizeButton); - - JLabel zoomLabel = new JLabel("100%"); - zoomLabel.setFont(MaterialFonts.getRegularFont(16f)); - - JSlider zoomSlider = new JSlider(25, 400, 100); - - JButton plus = - new JButton( - new ImageIcon( - ImageIO.read( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/imgs/add.png"))))); - plus.setFocusPainted(false); - plus.setFont(MaterialFonts.getRegularFont(10f)); - plus.setPreferredSize(new Dimension(20, 20)); - plus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() + 25)); - - JButton minus = - new JButton( - new ImageIcon( - ImageIO.read( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/imgs/remove.png"))))); - minus.setFocusPainted(false); - minus.setPreferredSize(new Dimension(20, 20)); - minus.setFont(MaterialFonts.getRegularFont(10f)); - minus.addActionListener((ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() - 25)); - this.scrollView.setWheelScrollingEnabled(true); - - zoomSlider.setPreferredSize(new Dimension(160, 30)); - - scrollView.addComponentListener( - new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - zoomSlider.setValue(scrollView.getZoom()); - zoomLabel.setText(zoomSlider.getValue() + "%"); + /** + * Sets up the zoomer for the given DynamicViewType + * + * @param type The DynamicView that we are setting up the zoomer for (so the zoomer for the + * board view or the zoomer for the proof tree view) + * @return A JPanel containing the zoomer + */ + private JPanel setUpZoomer(DynamicViewType type) { + if (type == DynamicViewType.BOARD) { + return setUpBoardZoomer(); + } else { + if (type == DynamicViewType.PROOF_TREE) { + return setUpProofTreeZoomer(); } - }); - - zoomSlider.addChangeListener( - (ChangeEvent e) -> { - scrollView.zoomTo(zoomSlider.getValue() / 100.0); - zoomLabel.setText(zoomSlider.getValue() + "%"); - }); - - zoomSlider.setMajorTickSpacing(100); - zoomSlider.setMinorTickSpacing(25); - zoomSlider.setPaintTicks(true); - - Hashtable labelTable = new Hashtable<>(); - labelTable.put(0, new JLabel("25%")); - labelTable.put(100, new JLabel("100%")); - labelTable.put(400, new JLabel("400%")); - zoomSlider.setLabelTable(labelTable); - - zoomer.setLayout(new FlowLayout()); - - zoomer.add(minus); - zoomer.add(zoomSlider); - zoomer.add(plus); - zoomer.add(zoomLabel); - - status = new JLabel(); - - zoomWrapper.setLayout(new BorderLayout()); - zoomWrapper.add(status, WEST); - zoomWrapper.add(zoomer, EAST); - } catch (IOException e) { - e.printStackTrace(); + } + + // Should never reach here; if you reach here, that's a problem! + return null; + } + + /** + * Sets up the zoomer for the board view + * + * @return A JPanel containing the zoomer + */ + private JPanel setUpBoardZoomer() { + final String label = "Resize Board"; + ActionListener listener = (ActionListener) -> this.fitBoardViewToScreen(); + return this.setUpZoomerHelper(label, listener); + } + + /** + * Sets up the zoomer for the proof tree view + * + * @return A JPanel containing the zoomer + */ + private JPanel setUpProofTreeZoomer() { + final String label = "Resize Proof"; + ActionListener listener = + (ActionListener) -> + GameBoardFacade.getInstance() + .getLegupUI() + .getProofEditor() + .fitTreeViewToScreen(); + return this.setUpZoomerHelper(label, listener); + } + + /** + * Creates the zoomer + * + * @param label A string containing the label to be displayed on the fit to screen button + * @param listener A listener that determines what the resize button will do + * @return A JPanel containing the zoomer + */ + private JPanel setUpZoomerHelper(final String label, ActionListener listener) { + zoomWrapper = new JPanel(); + try { + zoomer = new JPanel(); + + // Create and add the resize button to the zoomer + JButton resizeButton = new JButton(label); + resizeButton.setFocusPainted(false); + resizeButton.setFocusPainted(false); + resizeButton.setEnabled(true); + resizeButton.setSize(100, 50); + resizeButton.addActionListener(listener); + zoomer.add(resizeButton); + + JLabel zoomLabel = new JLabel("100%"); + zoomLabel.setFont(MaterialFonts.getRegularFont(16f)); + + JSlider zoomSlider = new JSlider(25, 400, 100); + + JButton plus = + new JButton( + new ImageIcon( + ImageIO.read( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource( + "edu/rpi/legup/imgs/add.png"))))); + plus.setFocusPainted(false); + plus.setFont(MaterialFonts.getRegularFont(10f)); + plus.setPreferredSize(new Dimension(20, 20)); + plus.addActionListener( + (ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() + 25)); + + JButton minus = + new JButton( + new ImageIcon( + ImageIO.read( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource( + "edu/rpi/legup/imgs/remove.png"))))); + minus.setFocusPainted(false); + minus.setPreferredSize(new Dimension(20, 20)); + minus.setFont(MaterialFonts.getRegularFont(10f)); + minus.addActionListener( + (ActionEvent e) -> zoomSlider.setValue(zoomSlider.getValue() - 25)); + this.scrollView.setWheelScrollingEnabled(true); + + zoomSlider.setPreferredSize(new Dimension(160, 30)); + + scrollView.addComponentListener( + new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + zoomSlider.setValue(scrollView.getZoom()); + zoomLabel.setText(zoomSlider.getValue() + "%"); + } + }); + + zoomSlider.addChangeListener( + (ChangeEvent e) -> { + scrollView.zoomTo(zoomSlider.getValue() / 100.0); + zoomLabel.setText(zoomSlider.getValue() + "%"); + }); + + zoomSlider.setMajorTickSpacing(100); + zoomSlider.setMinorTickSpacing(25); + zoomSlider.setPaintTicks(true); + + Hashtable labelTable = new Hashtable<>(); + labelTable.put(0, new JLabel("25%")); + labelTable.put(100, new JLabel("100%")); + labelTable.put(400, new JLabel("400%")); + zoomSlider.setLabelTable(labelTable); + + zoomer.setLayout(new FlowLayout()); + + zoomer.add(minus); + zoomer.add(zoomSlider); + zoomer.add(plus); + zoomer.add(zoomLabel); + + status = new JLabel(); + + zoomWrapper.setLayout(new BorderLayout()); + zoomWrapper.add(status, WEST); + zoomWrapper.add(zoomer, EAST); + } catch (IOException e) { + e.printStackTrace(); + } + return zoomWrapper; + } + + public ScrollView getScrollView() { + return this.scrollView; + } + + public JPanel getZoomWrapper() { + return this.zoomWrapper; + } + + public JPanel getZoomer() { + return this.zoomer; + } + + public void updateInfo(String message) { + status.setFont(INFO_FONT); + status.setForeground(INFO_COLOR); + status.setText(message); + } + + public void updateError(String message) { + status.setFont(ERROR_FONT); + status.setForeground(ERROR_COLOR); + status.setText(message); + } + + public void resetStatus() { + status.setText(""); + } + + public void reset() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + Board board1 = GameBoardFacade.getInstance().getBoard(); + board1.setModifiable(true); + Dimension bi = new Dimension(1200, 900); + this.getScrollView().zoomFit(); + } + + protected void fitBoardViewToScreen() { + scrollView.zoomFit(); } - return zoomWrapper; - } - - public ScrollView getScrollView() { - return this.scrollView; - } - - public JPanel getZoomWrapper() { - return this.zoomWrapper; - } - - public JPanel getZoomer() { - return this.zoomer; - } - - public void updateInfo(String message) { - status.setFont(INFO_FONT); - status.setForeground(INFO_COLOR); - status.setText(message); - } - - public void updateError(String message) { - status.setFont(ERROR_FONT); - status.setForeground(ERROR_COLOR); - status.setText(message); - } - - public void resetStatus() { - status.setText(""); - } - - public void reset() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - Board board1 = GameBoardFacade.getInstance().getBoard(); - board1.setModifiable(true); - Dimension bi = new Dimension(1200, 900); - this.getScrollView().zoomFit(); - } - - protected void fitBoardViewToScreen() { - scrollView.zoomFit(); - } } diff --git a/src/main/java/edu/rpi/legup/ui/DynamicViewType.java b/src/main/java/edu/rpi/legup/ui/DynamicViewType.java index cf345c4e1..8c2f285cd 100644 --- a/src/main/java/edu/rpi/legup/ui/DynamicViewType.java +++ b/src/main/java/edu/rpi/legup/ui/DynamicViewType.java @@ -1,6 +1,6 @@ package edu.rpi.legup.ui; public enum DynamicViewType { - BOARD, - PROOF_TREE + BOARD, + PROOF_TREE } diff --git a/src/main/java/edu/rpi/legup/ui/HomePanel.java b/src/main/java/edu/rpi/legup/ui/HomePanel.java index 120f39eb2..11f51eb0e 100644 --- a/src/main/java/edu/rpi/legup/ui/HomePanel.java +++ b/src/main/java/edu/rpi/legup/ui/HomePanel.java @@ -26,638 +26,648 @@ import org.xml.sax.helpers.DefaultHandler; public class HomePanel extends LegupPanel { - private static final Logger LOGGER = LogManager.getLogger(HomePanel.class.getName()); - private LegupUI legupUI; - private JFrame frame; - private JButton[] buttons; - private JLabel[] text; - private JMenuBar menuBar; - private JFileChooser folderBrowser; - - private final int buttonSize = 100; - - private ActionListener openProofListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Object[] items = legupUI.getProofEditor().promptPuzzle(); - if (items == null) { - // The attempt to prompt a puzzle ended gracefully (cancel) - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - legupUI.getProofEditor().loadPuzzle(fileName, puzzleFile); - } - }; - - private ActionListener openPuzzleListener = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Object[] items = legupUI.getPuzzleEditor().promptPuzzle(); - if (items == null) { - // The attempt to prompt a puzzle ended gracefully (cancel) - return; - } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - legupUI.getPuzzleEditor().loadPuzzle(fileName, puzzleFile); - } - }; - - public HomePanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.legupUI = legupUI; - this.frame = frame; - setLayout(new GridLayout(1, 2)); - initText(); - initButtons(); - } - - public JMenuBar getMenuBar() { - this.menuBar = new JMenuBar(); - JMenu settings = new JMenu("Settings"); - menuBar.add(settings); - JMenuItem preferences = new JMenuItem("Preferences"); - preferences.addActionListener( - a -> { - PreferencesDialog preferencesDialog = new PreferencesDialog(this.frame); - System.out.println("Preferences clicked"); - }); - settings.addSeparator(); - settings.add(preferences); - - JMenuItem contribute = new JMenuItem("Contribute to Legup"); - contribute.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop().browse(URI.create("https://github.com/Bram-Hub/Legup")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - settings.add(contribute); - - return this.menuBar; - } - - @Override - public void makeVisible() { - render(); - frame.setJMenuBar(this.getMenuBar()); - } - - private static ImageIcon resizeButtonIcon(ImageIcon icon, int width, int height) { - Image image = icon.getImage(); - Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); - return new ImageIcon(resizedImage); - } - - private void initButtons() { - this.buttons = new JButton[4]; - - this.buttons[0] = - new JButton("Solve Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } - }; - - URL button0IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/proof_file.png"); - ImageIcon button0Icon = new ImageIcon(button0IconLocation); - this.buttons[0].setFocusPainted(false); - this.buttons[0].setIcon(resizeButtonIcon(button0Icon, this.buttonSize, this.buttonSize)); - this.buttons[0].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[0].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[0].addActionListener(CursorController.createListener(this, openProofListener)); - - this.buttons[1] = - new JButton("Create Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } - }; - URL button1IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/new_puzzle_file.png"); - ImageIcon button1Icon = new ImageIcon(button1IconLocation); - this.buttons[1].setFocusPainted(false); - this.buttons[1].setIcon(resizeButtonIcon(button1Icon, this.buttonSize, this.buttonSize)); - this.buttons[1].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[1].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[1].addActionListener(l -> this.openNewPuzzleDialog()); - - this.buttons[2] = - new JButton("Edit Puzzle") { - { - setSize(buttonSize, buttonSize); - setMaximumSize(getSize()); - } - }; - URL button2IconLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/homepanel/puzzle_file.png"); - ImageIcon button2Icon = new ImageIcon(button2IconLocation); - this.buttons[2].setFocusPainted(false); - this.buttons[2].setIcon(resizeButtonIcon(button2Icon, this.buttonSize, this.buttonSize)); - this.buttons[2].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[2].setVerticalTextPosition(AbstractButton.BOTTOM); - this.buttons[2].addActionListener( - CursorController.createListener(this, openPuzzleListener)); // PLACEHOLDER - - for (int i = 0; i < this.buttons.length - 1; i++) { // -1 to avoid the batch grader button - this.buttons[i].setBounds(200, 200, 700, 700); - } - this.buttons[3] = new JButton("Batch Grader"); - this.buttons[3].setFocusPainted(false); - this.buttons[3].setHorizontalTextPosition(AbstractButton.CENTER); - this.buttons[3].setVerticalTextPosition(AbstractButton.BOTTOM); - - this.buttons[3].addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - try { - use_xml_to_check(); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - System.out.println("finished checking the folder"); - } - }); - } - - public void checkFolder() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ + private static final Logger LOGGER = LogManager.getLogger(HomePanel.class.getName()); + private LegupUI legupUI; + private JFrame frame; + private JButton[] buttons; + private JLabel[] text; + private JMenuBar menuBar; + private JFileChooser folderBrowser; + + private final int buttonSize = 100; + + private ActionListener openProofListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Object[] items = legupUI.getProofEditor().promptPuzzle(); + if (items == null) { + // The attempt to prompt a puzzle ended gracefully (cancel) + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + legupUI.getProofEditor().loadPuzzle(fileName, puzzleFile); + } + }; - JFileChooser folderBrowser = new JFileChooser(); - - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - File folder = folderBrowser.getSelectedFile(); - - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name"); - writer.append(","); - writer.append("File Name"); - writer.append(","); - writer.append("Solved?"); - writer.append("\n"); - - for (final File folderEntry : folder.listFiles(File::isDirectory)) { - writer.append(folderEntry.getName()); - writer.append(","); - int count1 = 0; - for (final File fileEntry : folderEntry.listFiles()) { - if (fileEntry.getName().charAt(0) == '.') { - continue; - } - count1++; - if (count1 > 1) { - writer.append(folderEntry.getName()); - writer.append(","); - } - writer.append(fileEntry.getName()); - writer.append(","); - String fileName = folderEntry.getAbsolutePath() + File.separator + fileEntry.getName(); - System.out.println("This is path " + fileName); - File puzzleFile = new File(fileName); - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(1); - legupUI.getProofEditor(); - GameBoardFacade.getInstance().loadPuzzle(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - legupUI.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - if (puzzle.isPuzzleComplete()) { - writer.append("Solved"); - System.out.println(fileEntry.getName() + " solved"); - } else { - writer.append("Not Solved"); - System.out.println(fileEntry.getName() + " not solved"); - } - writer.append("\n"); - } catch (InvalidFileFormatException e) { - LOGGER.error(e.getMessage()); - } - } - } - if (count1 == 0) { - writer.append("No file"); - writer.append("\n"); - } - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); - this.buttons[3].addActionListener((ActionEvent e) -> use_xml_to_check()); - } - } - - /** - * @effect batch grade using .xml parser - go through a collection of files and report their - * "solved?" status - */ - private void use_xml_to_check() { - /* Select a folder, go through each .xml file in the subfolders, look for "isSolved" flag */ - JFileChooser folderBrowser = new JFileChooser(); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - folderBrowser.setSelectedFile(null); - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - File folder = folderBrowser.getSelectedFile(); - - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Solved?,Last Saved\n"); - // Go through student folders, recurse for inner folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - String path = folderEntry.getName(); - // use this helper function to write to the .csv file - recursive_parser(folderEntry, writer, path, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); + private ActionListener openPuzzleListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Object[] items = legupUI.getPuzzleEditor().promptPuzzle(); + if (items == null) { + // The attempt to prompt a puzzle ended gracefully (cancel) + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + legupUI.getPuzzleEditor().loadPuzzle(fileName, puzzleFile); + } + }; + + public HomePanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.legupUI = legupUI; + this.frame = frame; + setLayout(new GridLayout(1, 2)); + initText(); + initButtons(); } - if (resultFile.exists()) { - try { - Desktop desktop = Desktop.getDesktop(); - desktop.open(resultFile); - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); - } + + public JMenuBar getMenuBar() { + this.menuBar = new JMenuBar(); + JMenu settings = new JMenu("Settings"); + menuBar.add(settings); + JMenuItem preferences = new JMenuItem("Preferences"); + preferences.addActionListener( + a -> { + PreferencesDialog preferencesDialog = new PreferencesDialog(this.frame); + System.out.println("Preferences clicked"); + }); + settings.addSeparator(); + settings.add(preferences); + + JMenuItem contribute = new JMenuItem("Contribute to Legup"); + contribute.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/Legup")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + settings.add(contribute); + + return this.menuBar; } - JOptionPane.showMessageDialog(null, "Batch grading complete."); - } - - /** - * @param file - the input file - * @return true if it is a .xml file, else return false - */ - public boolean isxmlfile(File file) { - boolean flag = true; - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - builder.parse(file); - flag = true; - } catch (Exception e) { - flag = false; + + @Override + public void makeVisible() { + render(); + frame.setJMenuBar(this.getMenuBar()); } - return flag; - } - - /** - * @param folder - the input folder - * @param writer - write to .csv - * @param path - the current path - * @param name - student's name (the first subfolders of the main folder) - * @throws IOException - */ - private void recursive_parser(File folder, BufferedWriter writer, String path, String name) - throws IOException { - // Empty folder - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,Ungradeable\n"); - return; + + private static ImageIcon resizeButtonIcon(ImageIcon icon, int width, int height) { + Image image = icon.getImage(); + Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); + return new ImageIcon(resizedImage); } - // Go through every other file in the folder - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser saxParser = spf.newSAXParser(); - for (final File fileEntry : Objects.requireNonNull(folder.listFiles())) { - if (fileEntry.getName().equals("result.csv")) { - continue; - } - // Recurse if it is a subfolder - if (fileEntry.isDirectory()) { - recursive_parser(fileEntry, writer, path + "/" + fileEntry.getName(), name); - continue; - } - // Set path name - String fName = fileEntry.getName(); - String fPath = fileEntry.getAbsolutePath(); - if (fileEntry.getName().charAt(0) == '.') { - continue; - } - // write data - writer.write(name); - writer.write(","); - writer.write(fName); - writer.write(","); - path = folder.getAbsolutePath() + File.separator + fileEntry.getName(); - System.out.println(path); - if (isxmlfile(fileEntry)) { - saxParser.parse( - path, - new DefaultHandler() { - @Override - public void startDocument() throws SAXException {} - boolean solvedFlagExists = false; - boolean puzzleTypeExists = false; + private void initButtons() { + this.buttons = new JButton[4]; - @Override - public void startElement( - String uri, String localName, String qName, Attributes attributes) - throws SAXException { - // append file type to the writer - if (qName.equals("puzzle") - && attributes.getQName(0) == "name" - && !puzzleTypeExists) { - try { - writer.write(attributes.getValue(0)); - writer.write(","); - puzzleTypeExists = true; - } catch (IOException e) { - throw new RuntimeException(e); + this.buttons[0] = + new JButton("Solve Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); } - } - // append the "solved?" status of the proof to the writer - else if (qName.equals("solved") && !solvedFlagExists) { - String isSolved = attributes.getValue(0); - String lastSaved = attributes.getValue(1); - if (isSolved != null) { - if (isSolved.equals("true")) { - try { - writer.write("Solved"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } else if (isSolved.equals("false")) { + }; + + URL button0IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/proof_file.png"); + ImageIcon button0Icon = new ImageIcon(button0IconLocation); + this.buttons[0].setFocusPainted(false); + this.buttons[0].setIcon(resizeButtonIcon(button0Icon, this.buttonSize, this.buttonSize)); + this.buttons[0].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[0].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[0].addActionListener(CursorController.createListener(this, openProofListener)); + + this.buttons[1] = + new JButton("Create Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } + }; + URL button1IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/new_puzzle_file.png"); + ImageIcon button1Icon = new ImageIcon(button1IconLocation); + this.buttons[1].setFocusPainted(false); + this.buttons[1].setIcon(resizeButtonIcon(button1Icon, this.buttonSize, this.buttonSize)); + this.buttons[1].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[1].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[1].addActionListener(l -> this.openNewPuzzleDialog()); + + this.buttons[2] = + new JButton("Edit Puzzle") { + { + setSize(buttonSize, buttonSize); + setMaximumSize(getSize()); + } + }; + URL button2IconLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/homepanel/puzzle_file.png"); + ImageIcon button2Icon = new ImageIcon(button2IconLocation); + this.buttons[2].setFocusPainted(false); + this.buttons[2].setIcon(resizeButtonIcon(button2Icon, this.buttonSize, this.buttonSize)); + this.buttons[2].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[2].setVerticalTextPosition(AbstractButton.BOTTOM); + this.buttons[2].addActionListener( + CursorController.createListener(this, openPuzzleListener)); // PLACEHOLDER + + for (int i = 0; i < this.buttons.length - 1; i++) { // -1 to avoid the batch grader button + this.buttons[i].setBounds(200, 200, 700, 700); + } + this.buttons[3] = new JButton("Batch Grader"); + this.buttons[3].setFocusPainted(false); + this.buttons[3].setHorizontalTextPosition(AbstractButton.CENTER); + this.buttons[3].setVerticalTextPosition(AbstractButton.BOTTOM); + + this.buttons[3].addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { try { - writer.write("Not Solved"); - } catch (IOException e) { - throw new RuntimeException(e); + use_xml_to_check(); + } catch (Exception ex) { + throw new RuntimeException(ex); } - } else { + System.out.println("finished checking the folder"); + } + }); + } + + public void checkFolder() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ + + JFileChooser folderBrowser = new JFileChooser(); + + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + File folder = folderBrowser.getSelectedFile(); + + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name"); + writer.append(","); + writer.append("File Name"); + writer.append(","); + writer.append("Solved?"); + writer.append("\n"); + + for (final File folderEntry : folder.listFiles(File::isDirectory)) { + writer.append(folderEntry.getName()); + writer.append(","); + int count1 = 0; + for (final File fileEntry : folderEntry.listFiles()) { + if (fileEntry.getName().charAt(0) == '.') { + continue; + } + count1++; + if (count1 > 1) { + writer.append(folderEntry.getName()); + writer.append(","); + } + writer.append(fileEntry.getName()); + writer.append(","); + String fileName = + folderEntry.getAbsolutePath() + File.separator + fileEntry.getName(); + System.out.println("This is path " + fileName); + File puzzleFile = new File(fileName); + if (puzzleFile != null && puzzleFile.exists()) { try { - writer.write("Error"); - } catch (IOException e) { - throw new RuntimeException(e); + legupUI.displayPanel(1); + legupUI.getProofEditor(); + GameBoardFacade.getInstance().loadPuzzle(fileName); + String puzzleName = + GameBoardFacade.getInstance().getPuzzleModule().getName(); + legupUI.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + if (puzzle.isPuzzleComplete()) { + writer.append("Solved"); + System.out.println(fileEntry.getName() + " solved"); + } else { + writer.append("Not Solved"); + System.out.println(fileEntry.getName() + " not solved"); + } + writer.append("\n"); + } catch (InvalidFileFormatException e) { + LOGGER.error(e.getMessage()); } - } } - // append when is this proof last saved - if (lastSaved != null) { - try { - writer.write(","); - writer.write(lastSaved); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - solvedFlagExists = true; - } } + if (count1 == 0) { + writer.append("No file"); + writer.append("\n"); + } + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + this.buttons[3].addActionListener((ActionEvent e) -> use_xml_to_check()); + } + } - @Override - public void characters(char[] ch, int start, int length) throws SAXException {} + /** + * @effect batch grade using .xml parser - go through a collection of files and report their + * "solved?" status + */ + private void use_xml_to_check() { + /* Select a folder, go through each .xml file in the subfolders, look for "isSolved" flag */ + JFileChooser folderBrowser = new JFileChooser(); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + folderBrowser.setSelectedFile(null); + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + File folder = folderBrowser.getSelectedFile(); + + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Solved?,Last Saved\n"); + // Go through student folders, recurse for inner folders + for (final File folderEntry : + Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + String path = folderEntry.getName(); + // use this helper function to write to the .csv file + recursive_parser(folderEntry, writer, path, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + } + if (resultFile.exists()) { + try { + Desktop desktop = Desktop.getDesktop(); + desktop.open(resultFile); + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); + } + } + JOptionPane.showMessageDialog(null, "Batch grading complete."); + } - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException {} + /** + * @param file - the input file + * @return true if it is a .xml file, else return false + */ + public boolean isxmlfile(File file) { + boolean flag = true; + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + builder.parse(file); + flag = true; + } catch (Exception e) { + flag = false; + } + return flag; + } - @Override - public void endDocument() throws SAXException { - if (!puzzleTypeExists) { - try { - writer.write("not a LEGUP puzzle!"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } else if (!solvedFlagExists) { - try { - writer.write("missing flag!"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - }); + /** + * @param folder - the input folder + * @param writer - write to .csv + * @param path - the current path + * @param name - student's name (the first subfolders of the main folder) + * @throws IOException + */ + private void recursive_parser(File folder, BufferedWriter writer, String path, String name) + throws IOException { + // Empty folder + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,Ungradeable\n"); + return; } - // If wrong file type, ungradeable - else { - writer.write("not a \".xml\" file!"); + // Go through every other file in the folder + try { + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser saxParser = spf.newSAXParser(); + for (final File fileEntry : Objects.requireNonNull(folder.listFiles())) { + if (fileEntry.getName().equals("result.csv")) { + continue; + } + // Recurse if it is a subfolder + if (fileEntry.isDirectory()) { + recursive_parser(fileEntry, writer, path + "/" + fileEntry.getName(), name); + continue; + } + // Set path name + String fName = fileEntry.getName(); + String fPath = fileEntry.getAbsolutePath(); + if (fileEntry.getName().charAt(0) == '.') { + continue; + } + // write data + writer.write(name); + writer.write(","); + writer.write(fName); + writer.write(","); + path = folder.getAbsolutePath() + File.separator + fileEntry.getName(); + System.out.println(path); + if (isxmlfile(fileEntry)) { + saxParser.parse( + path, + new DefaultHandler() { + @Override + public void startDocument() throws SAXException {} + + boolean solvedFlagExists = false; + boolean puzzleTypeExists = false; + + @Override + public void startElement( + String uri, + String localName, + String qName, + Attributes attributes) + throws SAXException { + // append file type to the writer + if (qName.equals("puzzle") + && attributes.getQName(0) == "name" + && !puzzleTypeExists) { + try { + writer.write(attributes.getValue(0)); + writer.write(","); + puzzleTypeExists = true; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + // append the "solved?" status of the proof to the writer + else if (qName.equals("solved") && !solvedFlagExists) { + String isSolved = attributes.getValue(0); + String lastSaved = attributes.getValue(1); + if (isSolved != null) { + if (isSolved.equals("true")) { + try { + writer.write("Solved"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else if (isSolved.equals("false")) { + try { + writer.write("Not Solved"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else { + try { + writer.write("Error"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + // append when is this proof last saved + if (lastSaved != null) { + try { + writer.write(","); + writer.write(lastSaved); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + solvedFlagExists = true; + } + } + + @Override + public void characters(char[] ch, int start, int length) + throws SAXException {} + + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException {} + + @Override + public void endDocument() throws SAXException { + if (!puzzleTypeExists) { + try { + writer.write("not a LEGUP puzzle!"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } else if (!solvedFlagExists) { + try { + writer.write("missing flag!"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + }); + } + // If wrong file type, ungradeable + else { + writer.write("not a \".xml\" file!"); + } + writer.write("\n"); + } + } catch (ParserConfigurationException | SAXException | IOException e) { + LOGGER.error(e.getMessage()); } - writer.write("\n"); - } - } catch (ParserConfigurationException | SAXException | IOException e) { - LOGGER.error(e.getMessage()); } - } - - private void initText() { - // TODO: add version text after auto-changing version label is implemented. (text[2] = - // version) - this.text = new JLabel[2]; - - JLabel welcome = new JLabel("Welcome to LEGUP"); - welcome.setFont(new Font("Roboto", Font.BOLD, 23)); - welcome.setAlignmentX(Component.CENTER_ALIGNMENT); - - JLabel credits = new JLabel("A project by Dr. Bram van Heuveln"); - credits.setFont(new Font("Roboto", Font.PLAIN, 12)); - credits.setAlignmentX(Component.CENTER_ALIGNMENT); - - JLabel version = new JLabel("Version 5.1.0"); // This should be autochanged in the future - version.setFont(new Font("Roboto", Font.ITALIC, 10)); - version.setAlignmentX(Component.CENTER_ALIGNMENT); - - this.text[0] = welcome; - this.text[1] = credits; - } - - private void render() { - this.removeAll(); - - this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); - this.legupUI.setTitle("LEGUP: A Better Way to Learn Formal Logic"); - - JPanel buttons = new JPanel(); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[0]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[1]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - buttons.add(this.buttons[2]); - buttons.add(Box.createRigidArea(new Dimension(5, 0))); - - JPanel batchGraderButton = new JPanel(); - batchGraderButton.add(this.buttons[3]); - batchGraderButton.setAlignmentX(Component.CENTER_ALIGNMENT); - - this.add(Box.createRigidArea(new Dimension(0, 5))); - for (int i = 0; i < this.text.length; i++) { - this.add(this.text[i]); + + private void initText() { + // TODO: add version text after auto-changing version label is implemented. (text[2] = + // version) + this.text = new JLabel[2]; + + JLabel welcome = new JLabel("Welcome to LEGUP"); + welcome.setFont(new Font("Roboto", Font.BOLD, 23)); + welcome.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel credits = new JLabel("A project by Dr. Bram van Heuveln"); + credits.setFont(new Font("Roboto", Font.PLAIN, 12)); + credits.setAlignmentX(Component.CENTER_ALIGNMENT); + + JLabel version = new JLabel("Version 5.1.0"); // This should be autochanged in the future + version.setFont(new Font("Roboto", Font.ITALIC, 10)); + version.setAlignmentX(Component.CENTER_ALIGNMENT); + + this.text[0] = welcome; + this.text[1] = credits; } - this.add(buttons); - this.add(batchGraderButton); - this.add(Box.createRigidArea(new Dimension(0, 5))); - } - - private void openNewPuzzleDialog() { - CreatePuzzleDialog cpd = new CreatePuzzleDialog(this.frame, this); - cpd.setVisible(true); - } - - private void checkProofAll() { - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - LegupPreferences preferences = LegupPreferences.getInstance(); - File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); - folderBrowser = new JFileChooser(preferredDirectory); - - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - - File folder = folderBrowser.getSelectedFile(); - - // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); - - // Go through student folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - // Write path - String path = folderEntry.getName(); - traverseDir(folderEntry, writer, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); + private void render() { + this.removeAll(); + + this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); + this.legupUI.setTitle("LEGUP: A Better Way to Learn Formal Logic"); + + JPanel buttons = new JPanel(); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[0]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[1]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + buttons.add(this.buttons[2]); + buttons.add(Box.createRigidArea(new Dimension(5, 0))); + + JPanel batchGraderButton = new JPanel(); + batchGraderButton.add(this.buttons[3]); + batchGraderButton.setAlignmentX(Component.CENTER_ALIGNMENT); + + this.add(Box.createRigidArea(new Dimension(0, 5))); + for (int i = 0; i < this.text.length; i++) { + this.add(this.text[i]); + } + this.add(buttons); + this.add(batchGraderButton); + this.add(Box.createRigidArea(new Dimension(0, 5))); } - JOptionPane.showMessageDialog(null, "Batch grading complete."); - } - - private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { - // Recursively traverse directory - GameBoardFacade facade = GameBoardFacade.getInstance(); - // Folder is empty - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,Ungradeable\n"); - return; + + private void openNewPuzzleDialog() { + CreatePuzzleDialog cpd = new CreatePuzzleDialog(this.frame, this); + cpd.setVisible(true); } - // Travese directory, recurse if sub-directory found - // If ungradeable, do not leave a score (0, 1) - for (final File f : Objects.requireNonNull(folder.listFiles())) { - // Recurse - if (f.isDirectory()) { - traverseDir(f, writer, path + "/" + f.getName()); - continue; - } - - // Set path name - writer.append(path).append(","); - - // Load puzzle, run checker - // If wrong file type, ungradeable - String fName = f.getName(); - String fPath = f.getAbsolutePath(); - File puzzleFile = new File(fPath); - if (puzzleFile.exists()) { - // Try to load file. If invalid, note in csv - try { - // Load puzzle, run checker - GameBoardFacade.getInstance().loadPuzzle(fPath); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - - // Write data - writer.append(fName).append(","); - writer.append(puzzle.getName()).append(","); - if (puzzle.isPuzzleComplete()) { - writer.append("Solved\n"); - } else { - writer.append("Unsolved\n"); - } - } catch (InvalidFileFormatException e) { - writer.append(fName).append("InvalidFile,Ungradeable\n"); + + private void checkProofAll() { + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ + + LegupPreferences preferences = LegupPreferences.getInstance(); + File preferredDirectory = + new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); + folderBrowser = new JFileChooser(preferredDirectory); + + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + + File folder = folderBrowser.getSelectedFile(); + + // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); + + // Go through student folders + for (final File folderEntry : + Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + // Write path + String path = folderEntry.getName(); + traverseDir(folderEntry, writer, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } - } else { - LOGGER.debug("Failed to run sim"); - } + JOptionPane.showMessageDialog(null, "Batch grading complete."); } - } - - public void openEditorWithNewPuzzle(String game, int rows, int columns) - throws IllegalArgumentException { - // Validate the dimensions - GameBoardFacade facade = GameBoardFacade.getInstance(); - boolean isValidDimensions = facade.validateDimensions(game, rows, columns); - if (!isValidDimensions) { - JOptionPane.showMessageDialog( - null, - "The dimensions you entered are invalid. Please double check \n" - + "the number of rows and columns and try again.", - "ERROR: Invalid Dimensions", - JOptionPane.ERROR_MESSAGE); - throw new IllegalArgumentException("ERROR: Invalid dimensions given"); + + private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { + // Recursively traverse directory + GameBoardFacade facade = GameBoardFacade.getInstance(); + // Folder is empty + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,Ungradeable\n"); + return; + } + // Travese directory, recurse if sub-directory found + // If ungradeable, do not leave a score (0, 1) + for (final File f : Objects.requireNonNull(folder.listFiles())) { + // Recurse + if (f.isDirectory()) { + traverseDir(f, writer, path + "/" + f.getName()); + continue; + } + + // Set path name + writer.append(path).append(","); + + // Load puzzle, run checker + // If wrong file type, ungradeable + String fName = f.getName(); + String fPath = f.getAbsolutePath(); + File puzzleFile = new File(fPath); + if (puzzleFile.exists()) { + // Try to load file. If invalid, note in csv + try { + // Load puzzle, run checker + GameBoardFacade.getInstance().loadPuzzle(fPath); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + + // Write data + writer.append(fName).append(","); + writer.append(puzzle.getName()).append(","); + if (puzzle.isPuzzleComplete()) { + writer.append("Solved\n"); + } else { + writer.append("Unsolved\n"); + } + } catch (InvalidFileFormatException e) { + writer.append(fName).append("InvalidFile,Ungradeable\n"); + } + } else { + LOGGER.debug("Failed to run sim"); + } + } } - // Set game type on the puzzle editor - this.legupUI.displayPanel(2); - this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, rows, columns); - } - - /** - * Opens the puzzle editor for the specified game with the given statements - * - * @param game a String containing the name of the game - * @param statements an array of statements - */ - public void openEditorWithNewPuzzle(String game, String[] statements) { - // Validate the text input - GameBoardFacade facade = GameBoardFacade.getInstance(); - boolean isValidTextInput = facade.validateTextInput(game, statements); - if (!isValidTextInput) { - JOptionPane.showMessageDialog( - null, - "The input you entered is invalid. Please double check \n" - + "your statements and try again.", - "ERROR: Invalid Text Input", - JOptionPane.ERROR_MESSAGE); - throw new IllegalArgumentException("ERROR: Invalid dimensions given"); + public void openEditorWithNewPuzzle(String game, int rows, int columns) + throws IllegalArgumentException { + // Validate the dimensions + GameBoardFacade facade = GameBoardFacade.getInstance(); + boolean isValidDimensions = facade.validateDimensions(game, rows, columns); + if (!isValidDimensions) { + JOptionPane.showMessageDialog( + null, + "The dimensions you entered are invalid. Please double check \n" + + "the number of rows and columns and try again.", + "ERROR: Invalid Dimensions", + JOptionPane.ERROR_MESSAGE); + throw new IllegalArgumentException("ERROR: Invalid dimensions given"); + } + + // Set game type on the puzzle editor + this.legupUI.displayPanel(2); + this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, rows, columns); } - // Set game type on the puzzle editor - this.legupUI.displayPanel(2); - this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, statements); - } + /** + * Opens the puzzle editor for the specified game with the given statements + * + * @param game a String containing the name of the game + * @param statements an array of statements + */ + public void openEditorWithNewPuzzle(String game, String[] statements) { + // Validate the text input + GameBoardFacade facade = GameBoardFacade.getInstance(); + boolean isValidTextInput = facade.validateTextInput(game, statements); + if (!isValidTextInput) { + JOptionPane.showMessageDialog( + null, + "The input you entered is invalid. Please double check \n" + + "your statements and try again.", + "ERROR: Invalid Text Input", + JOptionPane.ERROR_MESSAGE); + throw new IllegalArgumentException("ERROR: Invalid dimensions given"); + } + + // Set game type on the puzzle editor + this.legupUI.displayPanel(2); + this.legupUI.getPuzzleEditor().loadPuzzleFromHome(game, statements); + } } diff --git a/src/main/java/edu/rpi/legup/ui/LegupPanel.java b/src/main/java/edu/rpi/legup/ui/LegupPanel.java index d671e1c4d..d16167b3d 100644 --- a/src/main/java/edu/rpi/legup/ui/LegupPanel.java +++ b/src/main/java/edu/rpi/legup/ui/LegupPanel.java @@ -3,8 +3,8 @@ import javax.swing.*; public abstract class LegupPanel extends JPanel { - /** Alerts panel that it will be going visible now */ - protected final int TOOLBAR_ICON_SCALE = 40; + /** Alerts panel that it will be going visible now */ + protected final int TOOLBAR_ICON_SCALE = 40; - public abstract void makeVisible(); + public abstract void makeVisible(); } diff --git a/src/main/java/edu/rpi/legup/ui/LegupUI.java b/src/main/java/edu/rpi/legup/ui/LegupUI.java index 030a1df6b..eb8b1663c 100644 --- a/src/main/java/edu/rpi/legup/ui/LegupUI.java +++ b/src/main/java/edu/rpi/legup/ui/LegupUI.java @@ -15,189 +15,191 @@ import org.apache.logging.log4j.Logger; public class LegupUI extends JFrame implements WindowListener { - private static final Logger LOGGER = LogManager.getLogger(LegupUI.class.getName()); - - protected FileDialog fileDialog; - protected JPanel window; - protected LegupPanel[] panels; - - /** - * Identifies operating system - * - * @return operating system, either mac or win - */ - public static String getOS() { - String os = System.getProperty("os.name").toLowerCase(); - if (os.contains("mac")) { - os = "mac"; - } else { - os = "win"; - } - return os; - } - - /** LegupUI Constructor - creates a new LegupUI to setup the menu and toolbar */ - public LegupUI() { - setTitle("LEGUP"); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - LegupPreferences prefs = LegupPreferences.getInstance(); - - try { - if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { - UIManager.setLookAndFeel(new FlatDarkLaf()); - } else { - UIManager.setLookAndFeel(new FlatLightLaf()); - } - } catch (UnsupportedLookAndFeelException e) { - System.err.println("Not supported ui look and feel"); - } - - fileDialog = new FileDialog(this); - - initPanels(); - displayPanel(0); - - setIconImage( - new ImageIcon( - Objects.requireNonNull( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct" + " Rules.gif"))) - .getImage()); - - if (LegupPreferences.getInstance() - .getUserPref(LegupPreferences.START_FULL_SCREEN) - .equals(Boolean.toString(true))) { - setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); - } - - this.addWindowListener(this); - addKeyListener( - new KeyAdapter() { - /** - * Invoked when a key has been typed. This event occurs when a key press is followed by a - * key release. - * - * @param e - */ - @Override - public void keyTyped(KeyEvent e) { - System.err.println(e.getKeyChar()); - super.keyTyped(e); - } - }); - setMinimumSize(getPreferredSize()); - setVisible(true); - } - - private void initPanels() { - window = new JPanel(); - window.setLayout(new BorderLayout()); - add(window); - panels = new LegupPanel[3]; - - panels[0] = new HomePanel(this.fileDialog, this, this); - panels[1] = new ProofEditorPanel(this.fileDialog, this, this); - panels[2] = new PuzzleEditorPanel(this.fileDialog, this, this); - } - - protected void displayPanel(int option) { - if (option > panels.length || option < 0) { - throw new InvalidParameterException("Invalid option"); - } - this.window.removeAll(); - panels[option].makeVisible(); - this.window.add(panels[option]); - pack(); - setLocationRelativeTo(null); - revalidate(); - repaint(); - } - - public ProofEditorPanel getProofEditor() { - return (ProofEditorPanel) panels[1]; - } - - public PuzzleEditorPanel getPuzzleEditor() { - return (PuzzleEditorPanel) panels[2]; - } - - public void repaintTree() { - getProofEditor().repaintTree(); - } - - private void directions() { - JOptionPane.showMessageDialog( - null, - "For every move you make, you must provide a rules for it (located in the Rules" - + " panel).\n" - + "While working on the edu.rpi.legup.puzzle, you may click on the \"Check\"" - + " button to test your proof for correctness.", - "Directions", - JOptionPane.PLAIN_MESSAGE); - } - - public void showStatus(String status, boolean error) { - showStatus(status, error, 1); - } - - public void errorEncountered(String error) { - JOptionPane.showMessageDialog(null, error); - } - - public void showStatus(String status, boolean error, int timer) { - // TODO: implement - } - - // ask to edu.rpi.legup.save current proof - public boolean noquit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - @Override - public void windowOpened(WindowEvent e) {} - - public void windowClosing(WindowEvent e) { - if (GameBoardFacade.getInstance().getHistory().getIndex() > -1) { - if (noquit("Exiting LEGUP?")) { - this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - } else { - this.setDefaultCloseOperation(EXIT_ON_CLOSE); - } - } else { - this.setDefaultCloseOperation(EXIT_ON_CLOSE); - } - } - - public void windowClosed(WindowEvent e) { - System.exit(0); - } - - public void windowIconified(WindowEvent e) {} - - public void windowDeiconified(WindowEvent e) {} - - public void windowActivated(WindowEvent e) {} - - public void windowDeactivated(WindowEvent e) {} - - public BoardView getBoardView() { - return getProofEditor().getBoardView(); - } - - public BoardView getEditorBoardView() { - return getPuzzleEditor().getBoardView(); - } - - public DynamicView getDynamicBoardView() { - return getProofEditor().getDynamicBoardView(); - } - - public DynamicView getEditorDynamicBoardView() { - return getPuzzleEditor().getDynamicBoardView(); - } - - public TreePanel getTreePanel() { - return getProofEditor().getTreePanel(); - } + private static final Logger LOGGER = LogManager.getLogger(LegupUI.class.getName()); + + protected FileDialog fileDialog; + protected JPanel window; + protected LegupPanel[] panels; + + /** + * Identifies operating system + * + * @return operating system, either mac or win + */ + public static String getOS() { + String os = System.getProperty("os.name").toLowerCase(); + if (os.contains("mac")) { + os = "mac"; + } else { + os = "win"; + } + return os; + } + + /** LegupUI Constructor - creates a new LegupUI to setup the menu and toolbar */ + public LegupUI() { + setTitle("LEGUP"); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + LegupPreferences prefs = LegupPreferences.getInstance(); + + try { + if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { + UIManager.setLookAndFeel(new FlatDarkLaf()); + } else { + UIManager.setLookAndFeel(new FlatLightLaf()); + } + } catch (UnsupportedLookAndFeelException e) { + System.err.println("Not supported ui look and feel"); + } + + fileDialog = new FileDialog(this); + + initPanels(); + displayPanel(0); + + setIconImage( + new ImageIcon( + Objects.requireNonNull( + ClassLoader.getSystemClassLoader() + .getResource( + "edu/rpi/legup/images/Legup/Direct" + + " Rules.gif"))) + .getImage()); + + if (LegupPreferences.getInstance() + .getUserPref(LegupPreferences.START_FULL_SCREEN) + .equals(Boolean.toString(true))) { + setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); + } + + this.addWindowListener(this); + addKeyListener( + new KeyAdapter() { + /** + * Invoked when a key has been typed. This event occurs when a key press is + * followed by a key release. + * + * @param e + */ + @Override + public void keyTyped(KeyEvent e) { + System.err.println(e.getKeyChar()); + super.keyTyped(e); + } + }); + setMinimumSize(getPreferredSize()); + setVisible(true); + } + + private void initPanels() { + window = new JPanel(); + window.setLayout(new BorderLayout()); + add(window); + panels = new LegupPanel[3]; + + panels[0] = new HomePanel(this.fileDialog, this, this); + panels[1] = new ProofEditorPanel(this.fileDialog, this, this); + panels[2] = new PuzzleEditorPanel(this.fileDialog, this, this); + } + + protected void displayPanel(int option) { + if (option > panels.length || option < 0) { + throw new InvalidParameterException("Invalid option"); + } + this.window.removeAll(); + panels[option].makeVisible(); + this.window.add(panels[option]); + pack(); + setLocationRelativeTo(null); + revalidate(); + repaint(); + } + + public ProofEditorPanel getProofEditor() { + return (ProofEditorPanel) panels[1]; + } + + public PuzzleEditorPanel getPuzzleEditor() { + return (PuzzleEditorPanel) panels[2]; + } + + public void repaintTree() { + getProofEditor().repaintTree(); + } + + private void directions() { + JOptionPane.showMessageDialog( + null, + "For every move you make, you must provide a rules for it (located in the Rules" + + " panel).\n" + + "While working on the edu.rpi.legup.puzzle, you may click on the \"Check\"" + + " button to test your proof for correctness.", + "Directions", + JOptionPane.PLAIN_MESSAGE); + } + + public void showStatus(String status, boolean error) { + showStatus(status, error, 1); + } + + public void errorEncountered(String error) { + JOptionPane.showMessageDialog(null, error); + } + + public void showStatus(String status, boolean error, int timer) { + // TODO: implement + } + + // ask to edu.rpi.legup.save current proof + public boolean noquit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + @Override + public void windowOpened(WindowEvent e) {} + + public void windowClosing(WindowEvent e) { + if (GameBoardFacade.getInstance().getHistory().getIndex() > -1) { + if (noquit("Exiting LEGUP?")) { + this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + } else { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + } else { + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + } + } + + public void windowClosed(WindowEvent e) { + System.exit(0); + } + + public void windowIconified(WindowEvent e) {} + + public void windowDeiconified(WindowEvent e) {} + + public void windowActivated(WindowEvent e) {} + + public void windowDeactivated(WindowEvent e) {} + + public BoardView getBoardView() { + return getProofEditor().getBoardView(); + } + + public BoardView getEditorBoardView() { + return getPuzzleEditor().getBoardView(); + } + + public DynamicView getDynamicBoardView() { + return getProofEditor().getDynamicBoardView(); + } + + public DynamicView getEditorDynamicBoardView() { + return getPuzzleEditor().getDynamicBoardView(); + } + + public TreePanel getTreePanel() { + return getProofEditor().getTreePanel(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java b/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java index 43cb35584..01d696f19 100644 --- a/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java +++ b/src/main/java/edu/rpi/legup/ui/ManualPuzzleCreatorDialog.java @@ -5,5 +5,5 @@ public class ManualPuzzleCreatorDialog extends JDialog { - public ManualPuzzleCreatorDialog() {} + public ManualPuzzleCreatorDialog() {} } diff --git a/src/main/java/edu/rpi/legup/ui/PickGameDialog.java b/src/main/java/edu/rpi/legup/ui/PickGameDialog.java index acdc99bee..f703ffcbc 100644 --- a/src/main/java/edu/rpi/legup/ui/PickGameDialog.java +++ b/src/main/java/edu/rpi/legup/ui/PickGameDialog.java @@ -16,156 +16,156 @@ import javax.swing.JTextField; public class PickGameDialog extends JDialog implements ActionListener { - JLabel gameLabel = new JLabel("Game:"); - String[] games; - JComboBox gameBox; - - JLabel puzzleLabel = new JLabel("Puzzle:"); - String[][] puzzles; - String puzzle; - - JTextField puzzleBox; - - JButton puzzleButton = new JButton("..."); - JFileChooser puzzleChooser = new JFileChooser(); - - JButton ok = new JButton("Ok"); - JButton cancel = new JButton("Cancel"); - - JCheckBox autotreeCheckBox = new JCheckBox("Auto-tree"); - JCheckBox showtreeCheckBox = new JCheckBox("Show tree"); - JCheckBox autojustifyCheckBox = new JCheckBox("Auto-justify"); - - public boolean okPressed = false; - private boolean pickBoth; - - /** - * Initialize the dialog - * - * @param parent the parent JFrame - * @param pickBothAtOnce if true they can pick a game type and a specific edu.rpi.legup.puzzle, if - * false they can only pick a game type - */ - public PickGameDialog(JFrame parent, boolean pickBothAtOnce) { - super(parent, true); - - pickBoth = pickBothAtOnce; - initPuzzles(); - - Rectangle b = parent.getBounds(); - - setSize(350, 200); - setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); - setTitle("Select Puzzle"); - - // listeners - gameBox.addActionListener(this); - ok.addActionListener(this); - cancel.addActionListener(this); - - // add components - Container c = getContentPane(); - c.setLayout(null); - - if (pickBoth) { - gameLabel.setBounds(10, 10, 70, 25); - gameBox.setBounds(80, 10, 190, 25); - } else { - gameLabel.setBounds(10, 30, 70, 25); - gameBox.setBounds(80, 30, 190, 25); - } + JLabel gameLabel = new JLabel("Game:"); + String[] games; + JComboBox gameBox; - puzzleLabel.setBounds(10, 40, 70, 25); + JLabel puzzleLabel = new JLabel("Puzzle:"); + String[][] puzzles; + String puzzle; - puzzleBox.setBounds(80, 40, 190, 25); - puzzleButton.setBounds(270, 40, 25, 25); + JTextField puzzleBox; - ok.setBounds(20, 130, 60, 25); - cancel.setBounds(170, 130, 90, 25); + JButton puzzleButton = new JButton("..."); + JFileChooser puzzleChooser = new JFileChooser(); - c.add(gameLabel); - c.add(gameBox); + JButton ok = new JButton("Ok"); + JButton cancel = new JButton("Cancel"); - if (pickBoth) { - c.add(puzzleLabel); - c.add(puzzleBox); - } + JCheckBox autotreeCheckBox = new JCheckBox("Auto-tree"); + JCheckBox showtreeCheckBox = new JCheckBox("Show tree"); + JCheckBox autojustifyCheckBox = new JCheckBox("Auto-justify"); + + public boolean okPressed = false; + private boolean pickBoth; + + /** + * Initialize the dialog + * + * @param parent the parent JFrame + * @param pickBothAtOnce if true they can pick a game type and a specific edu.rpi.legup.puzzle, + * if false they can only pick a game type + */ + public PickGameDialog(JFrame parent, boolean pickBothAtOnce) { + super(parent, true); + + pickBoth = pickBothAtOnce; + initPuzzles(); + + Rectangle b = parent.getBounds(); + + setSize(350, 200); + setLocation((int) b.getCenterX() - getWidth() / 2, (int) b.getCenterY() - getHeight() / 2); + setTitle("Select Puzzle"); - c.add(puzzleButton); - puzzleButton.addActionListener(this); + // listeners + gameBox.addActionListener(this); + ok.addActionListener(this); + cancel.addActionListener(this); - c.add(ok); - c.add(cancel); + // add components + Container c = getContentPane(); + c.setLayout(null); - autotreeCheckBox.setBounds(20, 70, 100, 25); - showtreeCheckBox.setBounds(20, 90, 100, 25); - autojustifyCheckBox.setBounds(20, 110, 100, 25); + if (pickBoth) { + gameLabel.setBounds(10, 10, 70, 25); + gameBox.setBounds(80, 10, 190, 25); + } else { + gameLabel.setBounds(10, 30, 70, 25); + gameBox.setBounds(80, 30, 190, 25); + } + + puzzleLabel.setBounds(10, 40, 70, 25); + + puzzleBox.setBounds(80, 40, 190, 25); + puzzleButton.setBounds(270, 40, 25, 25); - c.add(autotreeCheckBox); - c.add(showtreeCheckBox); - c.add(autojustifyCheckBox); - } + ok.setBounds(20, 130, 60, 25); + cancel.setBounds(170, 130, 90, 25); + + c.add(gameLabel); + c.add(gameBox); + + if (pickBoth) { + c.add(puzzleLabel); + c.add(puzzleBox); + } - public void initPuzzles() { - Object[] o = GameBoardFacade.getInstance().getConfig().getPuzzleClassNames().toArray(); + c.add(puzzleButton); + puzzleButton.addActionListener(this); - games = new String[o.length]; + c.add(ok); + c.add(cancel); - for (int x = 0; x < o.length; ++x) { - games[x] = (String) o[x]; + autotreeCheckBox.setBounds(20, 70, 100, 25); + showtreeCheckBox.setBounds(20, 90, 100, 25); + autojustifyCheckBox.setBounds(20, 110, 100, 25); + + c.add(autotreeCheckBox); + c.add(showtreeCheckBox); + c.add(autojustifyCheckBox); } - puzzles = new String[games.length][]; - puzzleBox = new JTextField(); - for (int x = 0; x < games.length; ++x) { - puzzles[x] = new String[o.length]; + public void initPuzzles() { + Object[] o = GameBoardFacade.getInstance().getConfig().getPuzzleClassNames().toArray(); + + games = new String[o.length]; + + for (int x = 0; x < o.length; ++x) { + games[x] = (String) o[x]; + } - for (int y = 0; y < o.length; ++y) { - puzzles[x][y] = (String) o[y]; - } + puzzles = new String[games.length][]; + puzzleBox = new JTextField(); + for (int x = 0; x < games.length; ++x) { + puzzles[x] = new String[o.length]; + + for (int y = 0; y < o.length; ++y) { + puzzles[x][y] = (String) o[y]; + } + } + + gameBox = new JComboBox(games); + } + + public String getPuzzle() { + return puzzleBox.getText(); } - gameBox = new JComboBox(games); - } - - public String getPuzzle() { - return puzzleBox.getText(); - } - - public String getGame() { - return (String) gameBox.getSelectedItem(); - } - - public void actionPerformed(ActionEvent e) { - if (e.getSource() == gameBox) { - int index = gameBox.getSelectedIndex(); - } else { - if (e.getSource() == ok) { - okPressed = true; - setVisible(false); - } else { - if (e.getSource() == cancel) { - okPressed = false; - setVisible(false); + public String getGame() { + return (String) gameBox.getSelectedItem(); + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == gameBox) { + int index = gameBox.getSelectedIndex(); } else { - if (e.getSource() == puzzleButton) { - File f = - new File( - "puzzlefiles" - + File.separator - + gameBox.getSelectedItem().toString().toLowerCase() - + File.separator); - if (f.exists() && f.isDirectory()) { - puzzleChooser = new JFileChooser(f); + if (e.getSource() == ok) { + okPressed = true; + setVisible(false); } else { - puzzleChooser = new JFileChooser(); - } - if (puzzleChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - puzzleBox.setText(puzzleChooser.getSelectedFile().getAbsolutePath()); + if (e.getSource() == cancel) { + okPressed = false; + setVisible(false); + } else { + if (e.getSource() == puzzleButton) { + File f = + new File( + "puzzlefiles" + + File.separator + + gameBox.getSelectedItem().toString().toLowerCase() + + File.separator); + if (f.exists() && f.isDirectory()) { + puzzleChooser = new JFileChooser(f); + } else { + puzzleChooser = new JFileChooser(); + } + if (puzzleChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + puzzleBox.setText(puzzleChooser.getSelectedFile().getAbsolutePath()); + } + } + } } - } } - } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java b/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java index 68adb2bae..475f4bb68 100644 --- a/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java +++ b/src/main/java/edu/rpi/legup/ui/PreferencesDialog.java @@ -19,412 +19,419 @@ public class PreferencesDialog extends JDialog { - private RuleFrame rulesFrame; - - private static final Logger LOGGER = Logger.getLogger(PreferencesDialog.class.getName()); - - private JCheckBox fullScreen, - autoUpdate, - darkMode, - showMistakes, - showAnnotations, - allowDefault, - generateCases, - immFeedback, - colorBlind; - - private JTextField workDirectory; - - private static Image folderIcon; - - static { - try { - folderIcon = - ImageIO.read(PreferencesDialog.class.getResource("/edu/rpi/legup/imgs/folder.png")); - } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Unable to locate icons"); - } - } - - public static PreferencesDialog CreateDialogForProofEditor(Frame frame, RuleFrame rules) { - PreferencesDialog p = new PreferencesDialog(frame); - p.rulesFrame = rules; - return p; - } - - public PreferencesDialog(Frame frame) { - super(frame); - - setTitle("Preferences"); - - JPanel mainPanel = new JPanel(); - mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - mainPanel.setLayout(new BorderLayout()); - - mainPanel.add(createGeneralTab()); - - JPanel bottomPanel = new JPanel(); - bottomPanel.setBorder(null); - bottomPanel.setLayout(new BorderLayout()); - - JToolBar toolbar = new JToolBar(); - toolbar.setBorder(null); - JButton okButton = new JButton("Ok"); - okButton.addActionListener( - l -> { - applyPreferences(); - this.setVisible(false); - this.dispose(); - }); - toolbar.add(okButton); - JButton cancelButton = new JButton("Cancel"); - cancelButton.addActionListener( - l -> { - this.setVisible(false); - this.dispose(); - }); - toolbar.add(cancelButton); - JButton applyButton = new JButton("Apply"); - applyButton.addActionListener( - l -> { - applyPreferences(); - }); - toolbar.add(applyButton); - bottomPanel.add(toolbar, BorderLayout.EAST); - - mainPanel.add(bottomPanel, BorderLayout.SOUTH); - - setContentPane(mainPanel); - - setSize(600, 400); - setLocationRelativeTo(frame); - setVisible(true); - } - - private void toggleDarkMode(LegupPreferences prefs) { - try { - if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { - UIManager.setLookAndFeel(new FlatDarkLaf()); - } else { - UIManager.setLookAndFeel(new FlatLightLaf()); - } - com.formdev.flatlaf.FlatLaf.updateUI(); - } catch (UnsupportedLookAndFeelException e) { - System.err.println("Not supported ui look and feel"); - } - } - - private JScrollPane createGeneralTab() { - LegupPreferences prefs = LegupPreferences.getInstance(); - JScrollPane scrollPane = new JScrollPane(); - JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); - - contentPane.add(createLeftLabel("General Preferences")); - contentPane.add(createLineSeparator()); - - JPanel workRow = new JPanel(); - workRow.setLayout(new BorderLayout()); - JLabel workDirLabel = new JLabel("Work Directory"); - workDirLabel.setToolTipText("This is where the open and save dialogs will open to."); - workRow.add(workDirLabel, BorderLayout.WEST); - workDirectory = new JTextField(prefs.getUserPref(LegupPreferences.WORK_DIRECTORY)); - workRow.add(workDirectory, BorderLayout.CENTER); - JButton openDir = new JButton(new ImageIcon(folderIcon)); - openDir.addActionListener( - a -> { - JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(new File(workDirectory.getText())); - chooser.setDialogTitle("Choose work directory"); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setAcceptAllFileFilterUsed(false); - chooser.setVisible(true); - - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - File newFile = chooser.getSelectedFile(); - workDirectory.setText(newFile.toString()); - } - }); - workRow.add(openDir, BorderLayout.EAST); - workRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, workRow.getPreferredSize().height)); - contentPane.add(workRow); - - fullScreen = - new JCheckBox( - "Full Screen", Boolean.valueOf(prefs.getUserPref(LegupPreferences.START_FULL_SCREEN))); - fullScreen.setToolTipText("If checked this starts Legup in full screen."); - JPanel fullScreenRow = new JPanel(); - fullScreenRow.setLayout(new BorderLayout()); - fullScreenRow.add(fullScreen, BorderLayout.WEST); - fullScreenRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, fullScreenRow.getPreferredSize().height)); - contentPane.add(fullScreenRow); - - autoUpdate = - new JCheckBox( - "Automatically Check for Updates", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_UPDATE))); - autoUpdate.setToolTipText( - "If checked this automatically checks for updates on startup of Legup"); - JPanel autoUpdateRow = new JPanel(); - autoUpdateRow.setLayout(new BorderLayout()); - autoUpdateRow.add(autoUpdate, BorderLayout.WEST); - autoUpdateRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, autoUpdateRow.getPreferredSize().height)); - contentPane.add(autoUpdateRow); - // contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - darkMode = - new JCheckBox("Dark Mode", Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))); - darkMode.setToolTipText("This turns dark mode on and off"); - JPanel darkModeRow = new JPanel(); - darkModeRow.setLayout(new BorderLayout()); - darkModeRow.add(darkMode, BorderLayout.WEST); - darkModeRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, darkModeRow.getPreferredSize().height)); - contentPane.add(darkModeRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - contentPane.add(createLeftLabel("Board View Preferences")); - contentPane.add(createLineSeparator()); - showMistakes = - new JCheckBox( - "Show Mistakes", Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_MISTAKES))); - showMistakes.setToolTipText( - "If checked this show incorrectly applied rule applications in red on the board"); - JPanel showMistakesRow = new JPanel(); - showMistakesRow.setLayout(new BorderLayout()); - showMistakesRow.add(showMistakes, BorderLayout.WEST); - showMistakesRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); - contentPane.add(showMistakesRow); - - showAnnotations = - new JCheckBox( - "Show Annotations", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_ANNOTATIONS))); - showAnnotations.setToolTipText( - "If checked this show incorrectly applied rule applications in red on the board"); - JPanel showAnnotationsRow = new JPanel(); - showAnnotationsRow.setLayout(new BorderLayout()); - showAnnotationsRow.add(showAnnotations, BorderLayout.WEST); - showAnnotationsRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showAnnotationsRow.getPreferredSize().height)); - contentPane.add(showAnnotationsRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - contentPane.add(createLeftLabel("Tree View Preferences")); - contentPane.add(createLineSeparator()); - - allowDefault = - new JCheckBox( - "Allow Default Rule Applications", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES))); - allowDefault.setEnabled(false); - allowDefault.setToolTipText( - "If checked this automatically applies a rule where it can on the board"); - - JPanel allowDefaultRow = new JPanel(); - allowDefaultRow.setLayout(new BorderLayout()); - allowDefaultRow.add(allowDefault, BorderLayout.WEST); - allowDefaultRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, allowDefaultRow.getPreferredSize().height)); - contentPane.add(allowDefaultRow); - - generateCases = - new JCheckBox( - "Automatically Generate Cases", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_GENERATE_CASES))); - generateCases.setToolTipText( - "If checked this automatically generates all cases for a case rule"); - JPanel generateCasesRow = new JPanel(); - generateCasesRow.setLayout(new BorderLayout()); - generateCasesRow.add(generateCases, BorderLayout.WEST); - generateCasesRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, generateCasesRow.getPreferredSize().height)); - contentPane.add(generateCasesRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 10))); - - immFeedback = - new JCheckBox( - "Provide Immediate Feedback", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); - immFeedback.setToolTipText( - "If checked this will update the colors of the tree view elements immediately"); - JPanel immFeedbackRow = new JPanel(); - immFeedbackRow.setLayout(new BorderLayout()); - immFeedbackRow.add(immFeedback, BorderLayout.WEST); - immFeedbackRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); - contentPane.add(immFeedbackRow); - - contentPane.add(createLeftLabel("Instructor Preferences")); - contentPane.add(createLineSeparator()); - immFeedback = - new JCheckBox( - "Instructor Mode", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); - immFeedback.setToolTipText("Currently unimplemented, this does nothing right now"); - immFeedbackRow.setLayout(new BorderLayout()); - immFeedbackRow.add(immFeedback, BorderLayout.WEST); - immFeedbackRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); - contentPane.add(immFeedbackRow); - - contentPane.add(createLeftLabel("Color Preferences")); - contentPane.add(createLineSeparator()); - colorBlind = - new JCheckBox( - "Deuteranomaly(red/green colorblindness)", - Boolean.valueOf(prefs.getUserPref(LegupPreferences.COLOR_BLIND))); - - JPanel colorBlindRow = new JPanel(); - colorBlindRow.setLayout(new BorderLayout()); - colorBlindRow.add(colorBlind, BorderLayout.WEST); - colorBlindRow.setMaximumSize( - new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); - contentPane.add(colorBlindRow); - - scrollPane.setViewportView(contentPane); - return scrollPane; - } - - private JScrollPane createPuzzleTab(Puzzle puzzle) { - JScrollPane scrollPane = new JScrollPane(); - scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - - JPanel contentPane = new JPanel(); - contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); - - contentPane.add(createLeftLabel("Rules")); - contentPane.add(createLineSeparator()); - - contentPane.add(createLeftLabel("Direct Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getDirectRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + private RuleFrame rulesFrame; + + private static final Logger LOGGER = Logger.getLogger(PreferencesDialog.class.getName()); + + private JCheckBox fullScreen, + autoUpdate, + darkMode, + showMistakes, + showAnnotations, + allowDefault, + generateCases, + immFeedback, + colorBlind; + + private JTextField workDirectory; + + private static Image folderIcon; + + static { + try { + folderIcon = + ImageIO.read( + PreferencesDialog.class.getResource("/edu/rpi/legup/imgs/folder.png")); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Unable to locate icons"); + } } - contentPane.add(createLeftLabel("Case Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getCaseRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + public static PreferencesDialog CreateDialogForProofEditor(Frame frame, RuleFrame rules) { + PreferencesDialog p = new PreferencesDialog(frame); + p.rulesFrame = rules; + return p; } - contentPane.add(createLeftLabel("Contradiction Rules")); - contentPane.add(createLineSeparator()); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); - for (Rule rule : puzzle.getContradictionRules()) { - JPanel ruleRow = createRuleRow(rule); - contentPane.add(ruleRow); - contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + public PreferencesDialog(Frame frame) { + super(frame); + + setTitle("Preferences"); + + JPanel mainPanel = new JPanel(); + mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + mainPanel.setLayout(new BorderLayout()); + + mainPanel.add(createGeneralTab()); + + JPanel bottomPanel = new JPanel(); + bottomPanel.setBorder(null); + bottomPanel.setLayout(new BorderLayout()); + + JToolBar toolbar = new JToolBar(); + toolbar.setBorder(null); + JButton okButton = new JButton("Ok"); + okButton.addActionListener( + l -> { + applyPreferences(); + this.setVisible(false); + this.dispose(); + }); + toolbar.add(okButton); + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener( + l -> { + this.setVisible(false); + this.dispose(); + }); + toolbar.add(cancelButton); + JButton applyButton = new JButton("Apply"); + applyButton.addActionListener( + l -> { + applyPreferences(); + }); + toolbar.add(applyButton); + bottomPanel.add(toolbar, BorderLayout.EAST); + + mainPanel.add(bottomPanel, BorderLayout.SOUTH); + + setContentPane(mainPanel); + + setSize(600, 400); + setLocationRelativeTo(frame); + setVisible(true); } - scrollPane.setViewportView(contentPane); - return scrollPane; - } - - private JPanel createRuleRow(Rule rule) { - JPanel ruleRow = new JPanel(); - ruleRow.setLayout(new BorderLayout()); - - JLabel ruleLabel = new JLabel(rule.getRuleName()); - ruleRow.add(ruleLabel, BorderLayout.WEST); - - JLabel ruleAcc = new JLabel(); - ruleAcc.setHorizontalAlignment(JLabel.CENTER); - ruleAcc.setBorder(MaterialBorders.LIGHT_LINE_BORDER); - ruleAcc.setPreferredSize(new Dimension(60, 20)); - ruleAcc.addMouseListener( - new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent e) { - ruleAcc.requestFocusInWindow(); - } - }); - - ruleAcc.addKeyListener( - new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - int keyCode = e.getKeyCode(); - String combo = ""; - if (e.isControlDown()) { - combo += "Ctrl + "; + private void toggleDarkMode(LegupPreferences prefs) { + try { + if (Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))) { + UIManager.setLookAndFeel(new FlatDarkLaf()); } else { - if (e.isShiftDown()) { - combo += "Shift + "; - } else { - if (e.isAltDown()) { - combo += "Alt + "; - } - } + UIManager.setLookAndFeel(new FlatLightLaf()); } - if (keyCode == KeyEvent.VK_CONTROL - || keyCode == KeyEvent.VK_SHIFT - || keyCode == KeyEvent.VK_ALT) { - return; - } - combo += KeyEvent.getKeyText(keyCode); - ruleAcc.setText(combo); - } - }); - - ruleRow.add(ruleAcc, BorderLayout.EAST); - - ruleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, ruleRow.getPreferredSize().height)); - return ruleRow; - } - - private JPanel createLeftLabel(String text) { - JPanel labelRow = new JPanel(); - labelRow.setLayout(new BorderLayout()); - JLabel label = new JLabel(text); - label.setFont(MaterialFonts.BOLD); - label.setHorizontalAlignment(JLabel.LEFT); - labelRow.add(label, BorderLayout.WEST); - - labelRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, labelRow.getPreferredSize().height)); - return labelRow; - } - - private JSeparator createLineSeparator() { - JSeparator separator = new JSeparator(); - separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5)); - return separator; - } - - public void applyPreferences() { - LegupPreferences prefs = LegupPreferences.getInstance(); - prefs.setUserPref(LegupPreferences.WORK_DIRECTORY, workDirectory.getText()); - prefs.setUserPref( - LegupPreferences.START_FULL_SCREEN, Boolean.toString(fullScreen.isSelected())); - prefs.setUserPref(LegupPreferences.AUTO_UPDATE, Boolean.toString(autoUpdate.isSelected())); - prefs.setUserPref(LegupPreferences.DARK_MODE, Boolean.toString(darkMode.isSelected())); - prefs.setUserPref(LegupPreferences.SHOW_MISTAKES, Boolean.toString(showMistakes.isSelected())); - prefs.setUserPref( - LegupPreferences.SHOW_ANNOTATIONS, Boolean.toString(showAnnotations.isSelected())); - prefs.setUserPref( - LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); - prefs.setUserPref( - LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(generateCases.isSelected())); - prefs.setUserPref( - LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(immFeedback.isSelected())); - prefs.setUserPref(LegupPreferences.COLOR_BLIND, Boolean.toString(colorBlind.isSelected())); - - if (rulesFrame != null) { - rulesFrame.getCasePanel().updateRules(); - rulesFrame.getDirectRulePanel().updateRules(); - rulesFrame.getContradictionPanel().updateRules(); + com.formdev.flatlaf.FlatLaf.updateUI(); + } catch (UnsupportedLookAndFeelException e) { + System.err.println("Not supported ui look and feel"); + } + } + + private JScrollPane createGeneralTab() { + LegupPreferences prefs = LegupPreferences.getInstance(); + JScrollPane scrollPane = new JScrollPane(); + JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); + + contentPane.add(createLeftLabel("General Preferences")); + contentPane.add(createLineSeparator()); + + JPanel workRow = new JPanel(); + workRow.setLayout(new BorderLayout()); + JLabel workDirLabel = new JLabel("Work Directory"); + workDirLabel.setToolTipText("This is where the open and save dialogs will open to."); + workRow.add(workDirLabel, BorderLayout.WEST); + workDirectory = new JTextField(prefs.getUserPref(LegupPreferences.WORK_DIRECTORY)); + workRow.add(workDirectory, BorderLayout.CENTER); + JButton openDir = new JButton(new ImageIcon(folderIcon)); + openDir.addActionListener( + a -> { + JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(workDirectory.getText())); + chooser.setDialogTitle("Choose work directory"); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setAcceptAllFileFilterUsed(false); + chooser.setVisible(true); + + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + File newFile = chooser.getSelectedFile(); + workDirectory.setText(newFile.toString()); + } + }); + workRow.add(openDir, BorderLayout.EAST); + workRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, workRow.getPreferredSize().height)); + contentPane.add(workRow); + + fullScreen = + new JCheckBox( + "Full Screen", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.START_FULL_SCREEN))); + fullScreen.setToolTipText("If checked this starts Legup in full screen."); + JPanel fullScreenRow = new JPanel(); + fullScreenRow.setLayout(new BorderLayout()); + fullScreenRow.add(fullScreen, BorderLayout.WEST); + fullScreenRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, fullScreenRow.getPreferredSize().height)); + contentPane.add(fullScreenRow); + + autoUpdate = + new JCheckBox( + "Automatically Check for Updates", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_UPDATE))); + autoUpdate.setToolTipText( + "If checked this automatically checks for updates on startup of Legup"); + JPanel autoUpdateRow = new JPanel(); + autoUpdateRow.setLayout(new BorderLayout()); + autoUpdateRow.add(autoUpdate, BorderLayout.WEST); + autoUpdateRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, autoUpdateRow.getPreferredSize().height)); + contentPane.add(autoUpdateRow); + // contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + darkMode = + new JCheckBox( + "Dark Mode", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.DARK_MODE))); + darkMode.setToolTipText("This turns dark mode on and off"); + JPanel darkModeRow = new JPanel(); + darkModeRow.setLayout(new BorderLayout()); + darkModeRow.add(darkMode, BorderLayout.WEST); + darkModeRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, darkModeRow.getPreferredSize().height)); + contentPane.add(darkModeRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + contentPane.add(createLeftLabel("Board View Preferences")); + contentPane.add(createLineSeparator()); + showMistakes = + new JCheckBox( + "Show Mistakes", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_MISTAKES))); + showMistakes.setToolTipText( + "If checked this show incorrectly applied rule applications in red on the board"); + JPanel showMistakesRow = new JPanel(); + showMistakesRow.setLayout(new BorderLayout()); + showMistakesRow.add(showMistakes, BorderLayout.WEST); + showMistakesRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); + contentPane.add(showMistakesRow); + + showAnnotations = + new JCheckBox( + "Show Annotations", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.SHOW_ANNOTATIONS))); + showAnnotations.setToolTipText( + "If checked this show incorrectly applied rule applications in red on the board"); + JPanel showAnnotationsRow = new JPanel(); + showAnnotationsRow.setLayout(new BorderLayout()); + showAnnotationsRow.add(showAnnotations, BorderLayout.WEST); + showAnnotationsRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showAnnotationsRow.getPreferredSize().height)); + contentPane.add(showAnnotationsRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + contentPane.add(createLeftLabel("Tree View Preferences")); + contentPane.add(createLineSeparator()); + + allowDefault = + new JCheckBox( + "Allow Default Rule Applications", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES))); + allowDefault.setEnabled(false); + allowDefault.setToolTipText( + "If checked this automatically applies a rule where it can on the board"); + + JPanel allowDefaultRow = new JPanel(); + allowDefaultRow.setLayout(new BorderLayout()); + allowDefaultRow.add(allowDefault, BorderLayout.WEST); + allowDefaultRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, allowDefaultRow.getPreferredSize().height)); + contentPane.add(allowDefaultRow); + + generateCases = + new JCheckBox( + "Automatically Generate Cases", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.AUTO_GENERATE_CASES))); + generateCases.setToolTipText( + "If checked this automatically generates all cases for a case rule"); + JPanel generateCasesRow = new JPanel(); + generateCasesRow.setLayout(new BorderLayout()); + generateCasesRow.add(generateCases, BorderLayout.WEST); + generateCasesRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, generateCasesRow.getPreferredSize().height)); + contentPane.add(generateCasesRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 10))); + + immFeedback = + new JCheckBox( + "Provide Immediate Feedback", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); + immFeedback.setToolTipText( + "If checked this will update the colors of the tree view elements immediately"); + JPanel immFeedbackRow = new JPanel(); + immFeedbackRow.setLayout(new BorderLayout()); + immFeedbackRow.add(immFeedback, BorderLayout.WEST); + immFeedbackRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); + contentPane.add(immFeedbackRow); + + contentPane.add(createLeftLabel("Instructor Preferences")); + contentPane.add(createLineSeparator()); + immFeedback = + new JCheckBox( + "Instructor Mode", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK))); + immFeedback.setToolTipText("Currently unimplemented, this does nothing right now"); + immFeedbackRow.setLayout(new BorderLayout()); + immFeedbackRow.add(immFeedback, BorderLayout.WEST); + immFeedbackRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, immFeedbackRow.getPreferredSize().height)); + contentPane.add(immFeedbackRow); + + contentPane.add(createLeftLabel("Color Preferences")); + contentPane.add(createLineSeparator()); + colorBlind = + new JCheckBox( + "Deuteranomaly(red/green colorblindness)", + Boolean.valueOf(prefs.getUserPref(LegupPreferences.COLOR_BLIND))); + + JPanel colorBlindRow = new JPanel(); + colorBlindRow.setLayout(new BorderLayout()); + colorBlindRow.add(colorBlind, BorderLayout.WEST); + colorBlindRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, showMistakesRow.getPreferredSize().height)); + contentPane.add(colorBlindRow); + + scrollPane.setViewportView(contentPane); + return scrollPane; + } + + private JScrollPane createPuzzleTab(Puzzle puzzle) { + JScrollPane scrollPane = new JScrollPane(); + scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + + JPanel contentPane = new JPanel(); + contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); + + contentPane.add(createLeftLabel("Rules")); + contentPane.add(createLineSeparator()); + + contentPane.add(createLeftLabel("Direct Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getDirectRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + } + + contentPane.add(createLeftLabel("Case Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getCaseRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + } + + contentPane.add(createLeftLabel("Contradiction Rules")); + contentPane.add(createLineSeparator()); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + for (Rule rule : puzzle.getContradictionRules()) { + JPanel ruleRow = createRuleRow(rule); + contentPane.add(ruleRow); + contentPane.add(Box.createRigidArea(new Dimension(0, 5))); + } + + scrollPane.setViewportView(contentPane); + return scrollPane; } - // toggle dark mode based on updated NIGHT_MODE variable - toggleDarkMode(prefs); - } + private JPanel createRuleRow(Rule rule) { + JPanel ruleRow = new JPanel(); + ruleRow.setLayout(new BorderLayout()); + + JLabel ruleLabel = new JLabel(rule.getRuleName()); + ruleRow.add(ruleLabel, BorderLayout.WEST); + + JLabel ruleAcc = new JLabel(); + ruleAcc.setHorizontalAlignment(JLabel.CENTER); + ruleAcc.setBorder(MaterialBorders.LIGHT_LINE_BORDER); + ruleAcc.setPreferredSize(new Dimension(60, 20)); + ruleAcc.addMouseListener( + new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + ruleAcc.requestFocusInWindow(); + } + }); + + ruleAcc.addKeyListener( + new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + int keyCode = e.getKeyCode(); + String combo = ""; + if (e.isControlDown()) { + combo += "Ctrl + "; + } else { + if (e.isShiftDown()) { + combo += "Shift + "; + } else { + if (e.isAltDown()) { + combo += "Alt + "; + } + } + } + if (keyCode == KeyEvent.VK_CONTROL + || keyCode == KeyEvent.VK_SHIFT + || keyCode == KeyEvent.VK_ALT) { + return; + } + combo += KeyEvent.getKeyText(keyCode); + ruleAcc.setText(combo); + } + }); + + ruleRow.add(ruleAcc, BorderLayout.EAST); + + ruleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, ruleRow.getPreferredSize().height)); + return ruleRow; + } + + private JPanel createLeftLabel(String text) { + JPanel labelRow = new JPanel(); + labelRow.setLayout(new BorderLayout()); + JLabel label = new JLabel(text); + label.setFont(MaterialFonts.BOLD); + label.setHorizontalAlignment(JLabel.LEFT); + labelRow.add(label, BorderLayout.WEST); + + labelRow.setMaximumSize( + new Dimension(Integer.MAX_VALUE, labelRow.getPreferredSize().height)); + return labelRow; + } + + private JSeparator createLineSeparator() { + JSeparator separator = new JSeparator(); + separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 5)); + return separator; + } + + public void applyPreferences() { + LegupPreferences prefs = LegupPreferences.getInstance(); + prefs.setUserPref(LegupPreferences.WORK_DIRECTORY, workDirectory.getText()); + prefs.setUserPref( + LegupPreferences.START_FULL_SCREEN, Boolean.toString(fullScreen.isSelected())); + prefs.setUserPref(LegupPreferences.AUTO_UPDATE, Boolean.toString(autoUpdate.isSelected())); + prefs.setUserPref(LegupPreferences.DARK_MODE, Boolean.toString(darkMode.isSelected())); + prefs.setUserPref( + LegupPreferences.SHOW_MISTAKES, Boolean.toString(showMistakes.isSelected())); + prefs.setUserPref( + LegupPreferences.SHOW_ANNOTATIONS, Boolean.toString(showAnnotations.isSelected())); + prefs.setUserPref( + LegupPreferences.ALLOW_DEFAULT_RULES, Boolean.toString(allowDefault.isSelected())); + prefs.setUserPref( + LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(generateCases.isSelected())); + prefs.setUserPref( + LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(immFeedback.isSelected())); + prefs.setUserPref(LegupPreferences.COLOR_BLIND, Boolean.toString(colorBlind.isSelected())); + + if (rulesFrame != null) { + rulesFrame.getCasePanel().updateRules(); + rulesFrame.getDirectRulePanel().updateRules(); + rulesFrame.getContradictionPanel().updateRules(); + } + + // toggle dark mode based on updated NIGHT_MODE variable + toggleDarkMode(prefs); + } } diff --git a/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java b/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java index 4fe1c1ff6..956f83ba4 100644 --- a/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java +++ b/src/main/java/edu/rpi/legup/ui/ProofEditorPanel.java @@ -37,1050 +37,1090 @@ import org.apache.logging.log4j.Logger; public class ProofEditorPanel extends LegupPanel implements IHistoryListener { - private static final Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName()); - private JMenuBar mBar; - private TreePanel treePanel; - private FileDialog fileDialog; - private JFrame frame; - private RuleFrame ruleFrame; - private DynamicView dynamicBoardView; - private JSplitPane topHalfPanel, mainPanel; - private TitledBorder boardBorder; - - private JButton[] toolBarButtons; - private JMenu file; - private JMenuItem newPuzzle, - resetPuzzle, - saveProofAs, - saveProofChange, - helpTutorial, - preferences, - exit; - private JMenu edit; - private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen; - - private JMenu view; - - private JMenu proof; - private JMenuItem add, delete, merge, collapse; - private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback; - private JMenu about, help; - private JMenuItem helpLegup, aboutLegup; - - private JToolBar toolBar; - private BoardView boardView; - private JFileChooser folderBrowser; - - private LegupUI legupUI; - - public static final int ALLOW_HINTS = 1; - public static final int ALLOW_DEFAPP = 2; - public static final int ALLOW_FULLAI = 4; - public static final int ALLOW_JUST = 8; - public static final int REQ_STEP_JUST = 16; - public static final int IMD_FEEDBACK = 32; - public static final int INTERN_RO = 64; - public static final int AUTO_JUST = 128; - static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; - private static final String[] PROFILES = { - "No Assistance", - "Rigorous Proof", - "Casual Proof", - "Assisted Proof", - "Guided Proof", - "Training-Wheels Proof", - "No Restrictions" - }; - private static final int[] PROF_FLAGS = { - 0, - ALLOW_JUST | REQ_STEP_JUST, - ALLOW_JUST, - ALLOW_HINTS | ALLOW_JUST | AUTO_JUST, - ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST, - ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO, - ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST - }; - private JMenu proofMode = new JMenu("Proof Mode"); - private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length]; - - private static int CONFIG_INDEX = 0; - - protected JMenu ai = new JMenu("AI"); - protected JMenuItem runAI = new JMenuItem("Run AI to completion"); - protected JMenuItem setpAI = new JMenuItem("Run AI one Step"); - protected JMenuItem testAI = new JMenuItem("Test AI!"); - protected JMenuItem hintAI = new JMenuItem("Hint"); - - public ProofEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.fileDialog = fileDialog; - this.frame = frame; - this.legupUI = legupUI; - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(800, 700)); - } - - @Override - public void makeVisible() { - this.removeAll(); - - setupToolBar(); - setupContent(); - frame.setJMenuBar(getMenuBar()); - } - - public JMenuBar getMenuBar() { - if (mBar != null) return mBar; - mBar = new JMenuBar(); - - file = new JMenu("File"); - newPuzzle = new JMenuItem("Open"); - resetPuzzle = new JMenuItem("Reset Puzzle"); - // genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle - // generator - saveProofAs = new JMenuItem("Save As"); // create a new file to save - saveProofChange = new JMenuItem("Save"); // save to the current file - preferences = new JMenuItem("Preferences"); - helpTutorial = new JMenuItem("Help"); // jump to web page - exit = new JMenuItem("Exit"); - - edit = new JMenu("Edit"); - undo = new JMenuItem("Undo"); - redo = new JMenuItem("Redo"); - - fitBoardToScreen = new JMenuItem("Fit Board to Screen"); - fitTreeToScreen = new JMenuItem("Fit Tree to Screen"); - - view = new JMenu("View"); - - proof = new JMenu("Proof"); - - String os = LegupUI.getOS(); - - add = new JMenuItem("Add"); - add.addActionListener(a -> treePanel.add()); - if (os.equals("mac")) { - add.setAccelerator( - KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + private static final Logger LOGGER = LogManager.getLogger(ProofEditorPanel.class.getName()); + private JMenuBar mBar; + private TreePanel treePanel; + private FileDialog fileDialog; + private JFrame frame; + private RuleFrame ruleFrame; + private DynamicView dynamicBoardView; + private JSplitPane topHalfPanel, mainPanel; + private TitledBorder boardBorder; + + private JButton[] toolBarButtons; + private JMenu file; + private JMenuItem newPuzzle, + resetPuzzle, + saveProofAs, + saveProofChange, + helpTutorial, + preferences, + exit; + private JMenu edit; + private JMenuItem undo, redo, fitBoardToScreen, fitTreeToScreen; + + private JMenu view; + + private JMenu proof; + private JMenuItem add, delete, merge, collapse; + private JCheckBoxMenuItem allowDefault, caseRuleGen, imdFeedback; + private JMenu about, help; + private JMenuItem helpLegup, aboutLegup; + + private JToolBar toolBar; + private BoardView boardView; + private JFileChooser folderBrowser; + + private LegupUI legupUI; + + public static final int ALLOW_HINTS = 1; + public static final int ALLOW_DEFAPP = 2; + public static final int ALLOW_FULLAI = 4; + public static final int ALLOW_JUST = 8; + public static final int REQ_STEP_JUST = 16; + public static final int IMD_FEEDBACK = 32; + public static final int INTERN_RO = 64; + public static final int AUTO_JUST = 128; + static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; + private static final String[] PROFILES = { + "No Assistance", + "Rigorous Proof", + "Casual Proof", + "Assisted Proof", + "Guided Proof", + "Training-Wheels Proof", + "No Restrictions" + }; + private static final int[] PROF_FLAGS = { + 0, + ALLOW_JUST | REQ_STEP_JUST, + ALLOW_JUST, + ALLOW_HINTS | ALLOW_JUST | AUTO_JUST, + ALLOW_HINTS | ALLOW_JUST | REQ_STEP_JUST, + ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_JUST | IMD_FEEDBACK | INTERN_RO, + ALLOW_HINTS | ALLOW_DEFAPP | ALLOW_FULLAI | ALLOW_JUST + }; + private JMenu proofMode = new JMenu("Proof Mode"); + private JCheckBoxMenuItem[] proofModeItems = new JCheckBoxMenuItem[PROF_FLAGS.length]; + + private static int CONFIG_INDEX = 0; + + protected JMenu ai = new JMenu("AI"); + protected JMenuItem runAI = new JMenuItem("Run AI to completion"); + protected JMenuItem setpAI = new JMenuItem("Run AI one Step"); + protected JMenuItem testAI = new JMenuItem("Test AI!"); + protected JMenuItem hintAI = new JMenuItem("Hint"); + + public ProofEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.fileDialog = fileDialog; + this.frame = frame; + this.legupUI = legupUI; + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(800, 700)); } - proof.add(add); - - delete = new JMenuItem("Delete"); - delete.addActionListener(a -> treePanel.delete()); - if (os.equals("mac")) { - delete.setAccelerator( - KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); - } - proof.add(delete); - - merge = new JMenuItem("Merge"); - merge.addActionListener(a -> treePanel.merge()); - if (os.equals("mac")) { - merge.setAccelerator( - KeyStroke.getKeyStroke('M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK)); + + @Override + public void makeVisible() { + this.removeAll(); + + setupToolBar(); + setupContent(); + frame.setJMenuBar(getMenuBar()); } - proof.add(merge); - - collapse = new JMenuItem("Collapse"); - collapse.addActionListener(a -> treePanel.collapse()); - if (os.equals("mac")) { - collapse.setAccelerator( - KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); + + public JMenuBar getMenuBar() { + if (mBar != null) return mBar; + mBar = new JMenuBar(); + + file = new JMenu("File"); + newPuzzle = new JMenuItem("Open"); + resetPuzzle = new JMenuItem("Reset Puzzle"); + // genPuzzle = new JMenuItem("Puzzle Generators"); // TODO: implement puzzle + // generator + saveProofAs = new JMenuItem("Save As"); // create a new file to save + saveProofChange = new JMenuItem("Save"); // save to the current file + preferences = new JMenuItem("Preferences"); + helpTutorial = new JMenuItem("Help"); // jump to web page + exit = new JMenuItem("Exit"); + + edit = new JMenu("Edit"); + undo = new JMenuItem("Undo"); + redo = new JMenuItem("Redo"); + + fitBoardToScreen = new JMenuItem("Fit Board to Screen"); + fitTreeToScreen = new JMenuItem("Fit Tree to Screen"); + + view = new JMenu("View"); + + proof = new JMenu("Proof"); + + String os = LegupUI.getOS(); + + add = new JMenuItem("Add"); + add.addActionListener(a -> treePanel.add()); + if (os.equals("mac")) { + add.setAccelerator( + KeyStroke.getKeyStroke( + 'A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + add.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + } + proof.add(add); + + delete = new JMenuItem("Delete"); + delete.addActionListener(a -> treePanel.delete()); + if (os.equals("mac")) { + delete.setAccelerator( + KeyStroke.getKeyStroke( + 'D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + delete.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); + } + proof.add(delete); + + merge = new JMenuItem("Merge"); + merge.addActionListener(a -> treePanel.merge()); + if (os.equals("mac")) { + merge.setAccelerator( + KeyStroke.getKeyStroke( + 'M', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + merge.setAccelerator(KeyStroke.getKeyStroke('M', InputEvent.CTRL_DOWN_MASK)); + } + proof.add(merge); + + collapse = new JMenuItem("Collapse"); + collapse.addActionListener(a -> treePanel.collapse()); + if (os.equals("mac")) { + collapse.setAccelerator( + KeyStroke.getKeyStroke( + 'C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + collapse.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK)); + } + collapse.setEnabled(false); + proof.add(collapse); + + allowDefault = + new JCheckBoxMenuItem( + "Allow Default Rule Applications", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES) + .equalsIgnoreCase(Boolean.toString(true))); + allowDefault.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.ALLOW_DEFAULT_RULES, + Boolean.toString(allowDefault.isSelected())); + }); + proof.add(allowDefault); + + caseRuleGen = + new JCheckBoxMenuItem( + "Automatically generate cases for CaseRule", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) + .equalsIgnoreCase(Boolean.toString(true))); + caseRuleGen.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.AUTO_GENERATE_CASES, + Boolean.toString(caseRuleGen.isSelected())); + }); + proof.add(caseRuleGen); + + imdFeedback = + new JCheckBoxMenuItem( + "Provide immediate feedback", + LegupPreferences.getInstance() + .getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK) + .equalsIgnoreCase(Boolean.toString(true))); + imdFeedback.addChangeListener( + e -> { + LegupPreferences.getInstance() + .setUserPref( + LegupPreferences.IMMEDIATE_FEEDBACK, + Boolean.toString(imdFeedback.isSelected())); + }); + proof.add(imdFeedback); + + about = new JMenu("About"); + helpLegup = new JMenuItem("Help Legup"); + aboutLegup = new JMenuItem("About Legup"); + + mBar.add(file); + file.add(newPuzzle); + newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke( + 'N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); + } + + file.add(resetPuzzle); + resetPuzzle.addActionListener( + a -> { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle != null) { + Tree tree = GameBoardFacade.getInstance().getTree(); + TreeNode rootNode = tree.getRootNode(); + if (rootNode != null) { + int confirmReset = + JOptionPane.showConfirmDialog( + this, + "Reset Puzzle to Root Node?", + "Confirm Reset", + JOptionPane.YES_NO_OPTION); + if (confirmReset == JOptionPane.YES_OPTION) { + + List children = rootNode.getChildren(); + children.forEach( + t -> + puzzle.notifyTreeListeners( + l -> l.onTreeElementRemoved(t))); + children.forEach( + t -> + puzzle.notifyBoardListeners( + l -> l.onTreeElementChanged(t))); + rootNode.clearChildren(); + final TreeViewSelection selection = + new TreeViewSelection( + treePanel.getTreeView().getElementView(rootNode)); + puzzle.notifyTreeListeners( + l -> l.onTreeSelectionChanged(selection)); + puzzle.notifyBoardListeners( + listener -> + listener.onTreeElementChanged( + selection + .getFirstSelection() + .getTreeElement())); + GameBoardFacade.getInstance().getHistory().clear(); + } + } + } + }); + if (os.equals("mac")) { + resetPuzzle.setAccelerator( + KeyStroke.getKeyStroke( + 'R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK)); + } + file.addSeparator(); + + file.add(saveProofAs); + saveProofAs.addActionListener((ActionEvent) -> saveProofAs()); + + // save proof as... + if (os.equals("mac")) { + saveProofAs.setAccelerator( + KeyStroke.getKeyStroke( + 'S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); + } + + // save proof change + if (os.equals("mac")) { + saveProofChange.setAccelerator( + KeyStroke.getKeyStroke( + 'A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + } + + file.add(saveProofChange); + saveProofChange.addActionListener((ActionEvent) -> saveProofChange()); + file.addSeparator(); + + // preference + file.add(preferences); + preferences.addActionListener( + a -> { + PreferencesDialog preferencesDialog = + PreferencesDialog.CreateDialogForProofEditor( + this.frame, this.ruleFrame); + }); + file.addSeparator(); + + // help function + if (os.equals("mac")) { + helpTutorial.setAccelerator( + KeyStroke.getKeyStroke( + 'H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); + } + file.add(helpTutorial); + + helpTutorial.addActionListener((ActionEvent) -> helpTutorial()); + file.addSeparator(); + + // exit + file.add(exit); + exit.addActionListener((ActionEvent) -> exitEditor()); + if (os.equals("mac")) { + exit.setAccelerator( + KeyStroke.getKeyStroke( + 'Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); + } + mBar.add(edit); + + edit.add(undo); + undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); + if (os.equals("mac")) { + undo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + } + + edit.add(redo); + + // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) + Action redoAction = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + GameBoardFacade.getInstance().getHistory().redo(); + } + }; + if (os.equals("mac")) { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK), + "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "redoAction"); + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK)); + } else { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), + "redoAction"); + redo.getActionMap().put("redoAction", redoAction); + + // Button in menu will show CTRL-SHIFT-Z as primary keybind + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + } + + edit.add(fitBoardToScreen); + fitBoardToScreen.addActionListener( + (ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); + + edit.add(fitTreeToScreen); + fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen()); + + mBar.add(proof); + + about.add(aboutLegup); + aboutLegup.addActionListener( + l -> { + JOptionPane.showMessageDialog(null, "Version: 5.1.0"); + }); + + about.add(helpLegup); + helpLegup.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + + mBar.add(about); + + return mBar; } - collapse.setEnabled(false); - proof.add(collapse); - - allowDefault = - new JCheckBoxMenuItem( - "Allow Default Rule Applications", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.ALLOW_DEFAULT_RULES) - .equalsIgnoreCase(Boolean.toString(true))); - allowDefault.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.ALLOW_DEFAULT_RULES, - Boolean.toString(allowDefault.isSelected())); - }); - proof.add(allowDefault); - - caseRuleGen = - new JCheckBoxMenuItem( - "Automatically generate cases for CaseRule", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.AUTO_GENERATE_CASES) - .equalsIgnoreCase(Boolean.toString(true))); - caseRuleGen.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.AUTO_GENERATE_CASES, Boolean.toString(caseRuleGen.isSelected())); - }); - proof.add(caseRuleGen); - - imdFeedback = - new JCheckBoxMenuItem( - "Provide immediate feedback", - LegupPreferences.getInstance() - .getUserPref(LegupPreferences.IMMEDIATE_FEEDBACK) - .equalsIgnoreCase(Boolean.toString(true))); - imdFeedback.addChangeListener( - e -> { - LegupPreferences.getInstance() - .setUserPref( - LegupPreferences.IMMEDIATE_FEEDBACK, Boolean.toString(imdFeedback.isSelected())); - }); - proof.add(imdFeedback); - - about = new JMenu("About"); - helpLegup = new JMenuItem("Help Legup"); - aboutLegup = new JMenuItem("About Legup"); - - mBar.add(file); - file.add(newPuzzle); - newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); + + public void exitEditor() { + // Wipes the puzzle entirely as if LEGUP just started + GameBoardFacade.getInstance().clearPuzzle(); + this.legupUI.displayPanel(0); + treePanel = null; + boardView = null; } - file.add(resetPuzzle); - resetPuzzle.addActionListener( - a -> { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle != null) { - Tree tree = GameBoardFacade.getInstance().getTree(); - TreeNode rootNode = tree.getRootNode(); - if (rootNode != null) { - int confirmReset = - JOptionPane.showConfirmDialog( - this, - "Reset Puzzle to Root Node?", - "Confirm Reset", - JOptionPane.YES_NO_OPTION); - if (confirmReset == JOptionPane.YES_OPTION) { - - List children = rootNode.getChildren(); - children.forEach(t -> puzzle.notifyTreeListeners(l -> l.onTreeElementRemoved(t))); - children.forEach(t -> puzzle.notifyBoardListeners(l -> l.onTreeElementChanged(t))); - rootNode.clearChildren(); - final TreeViewSelection selection = - new TreeViewSelection(treePanel.getTreeView().getElementView(rootNode)); - puzzle.notifyTreeListeners(l -> l.onTreeSelectionChanged(selection)); - puzzle.notifyBoardListeners( - listener -> - listener.onTreeElementChanged( - selection.getFirstSelection().getTreeElement())); - GameBoardFacade.getInstance().getHistory().clear(); - } + // File opener + public Object[] promptPuzzle() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + if (facade.getBoard() != null) { + if (noquit("Opening a new puzzle?")) { + return new Object[0]; } - } - }); - if (os.equals("mac")) { - resetPuzzle.setAccelerator( - KeyStroke.getKeyStroke('R', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - resetPuzzle.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK)); - } - file.addSeparator(); + } - file.add(saveProofAs); - saveProofAs.addActionListener((ActionEvent) -> saveProofAs()); + LegupPreferences preferences = LegupPreferences.getInstance(); + String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); + if (preferences.getSavedPath() != "") { + preferredDirectory = preferences.getSavedPath(); + } - // save proof as... - if (os.equals("mac")) { - saveProofAs.setAccelerator( - KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - saveProofAs.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK)); - } + File preferredDirectoryFile = new File(preferredDirectory); + JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile); + String fileName = null; + File puzzleFile = null; + + fileBrowser.showOpenDialog(this); + fileBrowser.setVisible(true); + fileBrowser.setCurrentDirectory(new File(preferredDirectory)); + fileBrowser.setDialogTitle("Select Proof File"); + fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fileBrowser.setAcceptAllFileFilterUsed(false); + + File puzzlePath = fileBrowser.getSelectedFile(); + System.out.println(puzzlePath.getAbsolutePath()); + + if (puzzlePath != null) { + fileName = puzzlePath.getAbsolutePath(); + String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator)); + preferences.setSavedPath(lastDirectoryPath); + puzzleFile = puzzlePath; + } else { + // The attempt to prompt a puzzle ended gracefully (cancel) + return null; + } - // save proof change - if (os.equals("mac")) { - saveProofChange.setAccelerator( - KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - saveProofChange.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK)); + return new Object[] {fileName, puzzleFile}; } - file.add(saveProofChange); - saveProofChange.addActionListener((ActionEvent) -> saveProofChange()); - file.addSeparator(); - - // preference - file.add(preferences); - preferences.addActionListener( - a -> { - PreferencesDialog preferencesDialog = - PreferencesDialog.CreateDialogForProofEditor(this.frame, this.ruleFrame); - }); - file.addSeparator(); - - // help function - if (os.equals("mac")) { - helpTutorial.setAccelerator( - KeyStroke.getKeyStroke('H', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - helpTutorial.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK)); + public void loadPuzzle() { + Object[] items = promptPuzzle(); + // Return if items == null (cancel) + if (items == null) { + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + loadPuzzle(fileName, puzzleFile); } - file.add(helpTutorial); - - helpTutorial.addActionListener((ActionEvent) -> helpTutorial()); - file.addSeparator(); - - // exit - file.add(exit); - exit.addActionListener((ActionEvent) -> exitEditor()); - if (os.equals("mac")) { - exit.setAccelerator( - KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); + + public void loadPuzzle(String fileName, File puzzleFile) { + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(1); + GameBoardFacade.getInstance().loadPuzzle(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } catch (InvalidFileFormatException e) { + legupUI.displayPanel(0); + LOGGER.error(e.getMessage()); + if (e.getMessage() + .contains( + "Proof Tree construction error: could not find rule by ID")) { // TO + // DO: make error + // message not + // hardcoded + JOptionPane.showMessageDialog( + null, + "This file runs on an outdated version of Legup\n" + + "and is not compatible with the current version.", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } else { + JOptionPane.showMessageDialog( + null, + "File does not exist or it cannot be read", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } + } + } } - mBar.add(edit); - - edit.add(undo); - undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); - if (os.equals("mac")) { - undo.setAccelerator( - KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + + /** save the proof in the current file */ + private void direct_save() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } } - edit.add(redo); - - // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) - Action redoAction = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - GameBoardFacade.getInstance().getHistory().redo(); - } - }; - if (os.equals("mac")) { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() - + InputEvent.SHIFT_DOWN_MASK), - "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "redoAction"); - redo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); - } else { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), - "redoAction"); - redo.getActionMap().put("redoAction", redoAction); - - // Button in menu will show CTRL-SHIFT-Z as primary keybind - redo.setAccelerator( - KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + /** Create a new file and save proof to it */ + private void saveProofAs() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + + fileDialog.setMode(FileDialog.SAVE); + fileDialog.setTitle("Save As"); + String curFileName = GameBoardFacade.getInstance().getCurFileName(); + if (curFileName == null) { + fileDialog.setDirectory( + LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); + } else { + File curFile = new File(curFileName); + fileDialog.setDirectory(curFile.getParent()); + } + fileDialog.setVisible(true); + + String fileName = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + } + + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } } - edit.add(fitBoardToScreen); - fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); - - edit.add(fitTreeToScreen); - fitTreeToScreen.addActionListener((ActionEvent) -> this.fitTreeViewToScreen()); - - mBar.add(proof); - - about.add(aboutLegup); - aboutLegup.addActionListener( - l -> { - JOptionPane.showMessageDialog(null, "Version: 5.1.0"); - }); - - about.add(helpLegup); - helpLegup.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop() - .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - - mBar.add(about); - - return mBar; - } - - public void exitEditor() { - // Wipes the puzzle entirely as if LEGUP just started - GameBoardFacade.getInstance().clearPuzzle(); - this.legupUI.displayPanel(0); - treePanel = null; - boardView = null; - } - - // File opener - public Object[] promptPuzzle() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - if (facade.getBoard() != null) { - if (noquit("Opening a new puzzle?")) { - return new Object[0]; - } + // Hyperlink for help button; links to wiki page for tutorials + private void helpTutorial() { + // redirecting to certain help link in wiki + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String puz = puzzle.getName(); + String url; + switch (puz) { + case "LightUp": + url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules"; + break; + case "Nurikabe": + url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules"; + break; + case "TreeTent": + url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules"; + break; + case "Skyscrapers": + url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules"; + break; + case "ShortTruthTable": + url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules"; + break; + default: + url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial"; + } + Runtime rt = Runtime.getRuntime(); + try { + // rt.exec("rundll32 url.dll,FileProtocolHandler "+url); + java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); + } catch (IOException e) { + e.printStackTrace(); + } } - LegupPreferences preferences = LegupPreferences.getInstance(); - String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); - if (preferences.getSavedPath() != "") { - preferredDirectory = preferences.getSavedPath(); + // add the new function need to implement + public void add_drop() { + // add the mouse event then we can use the new listener to implement and + // we should create a need jbuttom for it to ship the rule we select. + JPanel panel = new JPanel(); + JButton moveing_buttom = new JButton(); + moveing_buttom.setFocusPainted(false); + moveing_buttom.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // get the selected rule + } + }); + panel.add(moveing_buttom); } - File preferredDirectoryFile = new File(preferredDirectory); - JFileChooser fileBrowser = new JFileChooser(preferredDirectoryFile); - String fileName = null; - File puzzleFile = null; - - fileBrowser.showOpenDialog(this); - fileBrowser.setVisible(true); - fileBrowser.setCurrentDirectory(new File(preferredDirectory)); - fileBrowser.setDialogTitle("Select Proof File"); - fileBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - fileBrowser.setAcceptAllFileFilterUsed(false); - - File puzzlePath = fileBrowser.getSelectedFile(); - System.out.println(puzzlePath.getAbsolutePath()); - - if (puzzlePath != null) { - fileName = puzzlePath.getAbsolutePath(); - String lastDirectoryPath = fileName.substring(0, fileName.lastIndexOf(File.separator)); - preferences.setSavedPath(lastDirectoryPath); - puzzleFile = puzzlePath; - } else { - // The attempt to prompt a puzzle ended gracefully (cancel) - return null; + // Quick save proof to the current file with a pop window to show "successfully saved" + private void saveProofChange() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + // Save confirmation + JOptionPane.showMessageDialog( + null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } } - return new Object[] {fileName, puzzleFile}; - } + // ask to edu.rpi.legup.save current proof + public boolean noquit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } - public void loadPuzzle() { - Object[] items = promptPuzzle(); - // Return if items == null (cancel) - if (items == null) { - return; + /** Sets the main content for the edu.rpi.legup.user interface */ + protected void setupContent() { + // JPanel consoleBox = new JPanel(new BorderLayout()); + JPanel treeBox = new JPanel(new BorderLayout()); + JPanel ruleBox = new JPanel(new BorderLayout()); + + RuleController ruleController = new RuleController(); + ruleFrame = new RuleFrame(ruleController); + ruleBox.add(ruleFrame, BorderLayout.WEST); + + treePanel = new TreePanel(); + + dynamicBoardView = + new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); + TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + JPanel boardPanel = new JPanel(new BorderLayout()); + topHalfPanel = + new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView); + mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel); + topHalfPanel.setPreferredSize(new Dimension(600, 400)); + mainPanel.setPreferredSize(new Dimension(600, 600)); + + boardPanel.add(mainPanel); + boardPanel.setVisible(true); + boardBorder = BorderFactory.createTitledBorder("Board"); + boardBorder.setTitleJustification(TitledBorder.CENTER); + + ruleBox.add(boardPanel); + treeBox.add(ruleBox); + this.add(treeBox); + // consoleBox.add(treeBox); + // + // getContentPane().add(consoleBox); + + // JPopupPanel popupPanel = new JPopupPanel(); + // setGlassPane(popupPanel); + // popupPanel.setVisible(true); + + mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100); + // frame.pack(); + revalidate(); } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - loadPuzzle(fileName, puzzleFile); - } - - public void loadPuzzle(String fileName, File puzzleFile) { - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(1); - GameBoardFacade.getInstance().loadPuzzle(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } catch (InvalidFileFormatException e) { - legupUI.displayPanel(0); - LOGGER.error(e.getMessage()); - if (e.getMessage() - .contains("Proof Tree construction error: could not find rule by ID")) { // TO - // DO: make error - // message not - // hardcoded - JOptionPane.showMessageDialog( - null, - "This file runs on an outdated version of Legup\n" - + "and is not compatible with the current version.", - "Error", - JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } else { - JOptionPane.showMessageDialog( - null, "File does not exist or it cannot be read", "Error", JOptionPane.ERROR_MESSAGE); - loadPuzzle(); + + private void setupToolBar() { + setToolBarButtons(new JButton[ToolbarName.values().length]); + for (int i = 0; i < ToolbarName.values().length; i++) { + String toolBarName = ToolbarName.values()[i].toString(); + URL resourceLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); + + // Scale the image icons down to make the buttons smaller + ImageIcon imageIcon = new ImageIcon(resourceLocation); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, + this.TOOLBAR_ICON_SCALE, + Image.SCALE_SMOOTH)); + + JButton button = new JButton(toolBarName, imageIcon); + button.setFocusPainted(false); + getToolBarButtons()[i] = button; } - } - } - } - /** save the proof in the current file */ - private void direct_save() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + toolBar = new JToolBar(); + toolBar.setFloatable(false); + toolBar.setRollover(true); + + for (int i = 0; i < getToolBarButtons().length; i++) { + for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { + if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { + toolBar.addSeparator(); + } + } + String toolBarName = ToolbarName.values()[i].toString(); + + toolBar.add(getToolBarButtons()[i]); + getToolBarButtons()[i].setToolTipText(toolBarName); + + getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); + getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } - } - } - /** Create a new file and save proof to it */ - private void saveProofAs() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; + // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent + // e) -> + // promptPuzzle()); + // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> + // saveProof()); + // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().undo()); + // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().redo()); + toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener( + (ActionEvent e) -> checkProof()); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); + + toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener( + (ActionEvent e) -> checkProofAll()); + + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true); + + this.add(toolBar, BorderLayout.NORTH); } - fileDialog.setMode(FileDialog.SAVE); - fileDialog.setTitle("Save As"); - String curFileName = GameBoardFacade.getInstance().getCurFileName(); - if (curFileName == null) { - fileDialog.setDirectory( - LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); - } else { - File curFile = new File(curFileName); - fileDialog.setDirectory(curFile.getParent()); + /** + * Sets the toolbar buttons + * + * @param toolBarButtons toolbar buttons + */ + public void setToolBarButtons(JButton[] toolBarButtons) { + this.toolBarButtons = toolBarButtons; } - fileDialog.setVisible(true); - String fileName = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + /** + * Gets the toolbar buttons + * + * @return toolbar buttons + */ + public JButton[] getToolBarButtons() { + return toolBarButtons; } - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + /** Checks the proof for correctness */ + private void checkProof() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + Tree tree = GameBoardFacade.getInstance().getTree(); + Board board = facade.getBoard(); + Board finalBoard = null; + boolean delayStatus = true; // board.evalDelayStatus(); + + repaintAll(); + + Puzzle puzzle = facade.getPuzzleModule(); + + if (puzzle.isPuzzleComplete()) { + // This is for submission which is not integrated yet + /*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); + if (confirm == JOptionPane.YES_OPTION) { + Submission submission = new Submission(board); + submission.submit(); + }*/ + JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct."); + } else { + String message = "\nThe game board is not solved."; + JOptionPane.showMessageDialog( + null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE); } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } } - } - - // Hyperlink for help button; links to wiki page for tutorials - private void helpTutorial() { - // redirecting to certain help link in wiki - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; + + private void repaintAll() { + boardView.repaint(); + treePanel.repaint(); } - String puz = puzzle.getName(); - String url; - switch (puz) { - case "LightUp": - url = "https://github.com/Bram-Hub/Legup/wiki/Light%20up-Rules"; - break; - case "Nurikabe": - url = "https://github.com/Bram-Hub/Legup/wiki/Nurikabe-Rules"; - break; - case "TreeTent": - url = "https://github.com/Bram-Hub/Legup/wiki/Tree-Tent-Rules"; - break; - case "Skyscrapers": - url = "https://github.com/Bram-Hub/Legup/wiki/Skyscrapers-Rules"; - break; - case "ShortTruthTable": - url = "https://github.com/Bram-Hub/Legup/wiki/Short-Truth-Table-Rules"; - break; - default: - url = "https://github.com/Bram-Hub/Legup/wiki/LEGUP-Tutorial"; + + public void setPuzzleView(Puzzle puzzle) { + this.boardView = puzzle.getBoardView(); + + dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); + this.topHalfPanel.setRightComponent(dynamicBoardView); + this.topHalfPanel.setVisible(true); + String boardType = boardView.getBoard().getClass().getSimpleName(); + boardType = boardType.substring(0, boardType.indexOf("Board")); + TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + this.treePanel.getTreeView().resetView(); + this.treePanel.getTreeView().setTree(puzzle.getTree()); + + puzzle.addTreeListener(treePanel.getTreeView()); + puzzle.addBoardListener(puzzle.getBoardView()); + + ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules()); + ruleFrame.getCasePanel().setRules(puzzle.getCaseRules()); + ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules()); + ruleFrame.getSearchPanel().setSearchBar(puzzle); + + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); + + reloadGui(); } - Runtime rt = Runtime.getRuntime(); - try { - // rt.exec("rundll32 url.dll,FileProtocolHandler "+url); - java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); - } catch (IOException e) { - e.printStackTrace(); + + public void reloadGui() { + repaintTree(); } - } - - // add the new function need to implement - public void add_drop() { - // add the mouse event then we can use the new listener to implement and - // we should create a need jbuttom for it to ship the rule we select. - JPanel panel = new JPanel(); - JButton moveing_buttom = new JButton(); - moveing_buttom.setFocusPainted(false); - moveing_buttom.addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // get the selected rule - } - }); - panel.add(moveing_buttom); - } - - // Quick save proof to the current file with a pop window to show "successfully saved" - private void saveProofChange() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; + + public void repaintTree() { + treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree()); } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + + /** Checks the proof for all files */ + private void checkProofAll() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + + /* + * Select dir to grade; recursively grade sub-dirs using traverseDir() + * Selected dir must have sub-dirs for each student: + * GradeThis + * | + * | -> Student 1 + * | | + * | | -> Proofs + */ + + LegupPreferences preferences = LegupPreferences.getInstance(); + File preferredDirectory = + new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); + folderBrowser = new JFileChooser(preferredDirectory); + + folderBrowser.showOpenDialog(this); + folderBrowser.setVisible(true); + folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); + folderBrowser.setDialogTitle("Select Directory"); + folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + folderBrowser.setAcceptAllFileFilterUsed(false); + + File folder = folderBrowser.getSelectedFile(); + + // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) + File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { + writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); + + // Go through student folders + for (final File folderEntry : + Objects.requireNonNull(folder.listFiles(File::isDirectory))) { + // Write path + String path = folderEntry.getName(); + traverseDir(folderEntry, writer, path); + } + } catch (IOException ex) { + LOGGER.error(ex.getMessage()); } - exporter.exportPuzzle(fileName); - // Save confirmation - JOptionPane.showMessageDialog( - null, "Successfully Saved", "Confirm", JOptionPane.INFORMATION_MESSAGE); - } catch (ExportFileException e) { - e.printStackTrace(); - } + JOptionPane.showMessageDialog(null, "Batch grading complete."); } - } - - // ask to edu.rpi.legup.save current proof - public boolean noquit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - /** Sets the main content for the edu.rpi.legup.user interface */ - protected void setupContent() { - // JPanel consoleBox = new JPanel(new BorderLayout()); - JPanel treeBox = new JPanel(new BorderLayout()); - JPanel ruleBox = new JPanel(new BorderLayout()); - - RuleController ruleController = new RuleController(); - ruleFrame = new RuleFrame(ruleController); - ruleBox.add(ruleFrame, BorderLayout.WEST); - - treePanel = new TreePanel(); - - dynamicBoardView = - new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); - TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - JPanel boardPanel = new JPanel(new BorderLayout()); - topHalfPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, ruleFrame, dynamicBoardView); - mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topHalfPanel, treePanel); - topHalfPanel.setPreferredSize(new Dimension(600, 400)); - mainPanel.setPreferredSize(new Dimension(600, 600)); - - boardPanel.add(mainPanel); - boardPanel.setVisible(true); - boardBorder = BorderFactory.createTitledBorder("Board"); - boardBorder.setTitleJustification(TitledBorder.CENTER); - - ruleBox.add(boardPanel); - treeBox.add(ruleBox); - this.add(treeBox); - // consoleBox.add(treeBox); - // - // getContentPane().add(consoleBox); - - // JPopupPanel popupPanel = new JPopupPanel(); - // setGlassPane(popupPanel); - // popupPanel.setVisible(true); - - mainPanel.setDividerLocation(mainPanel.getMaximumDividerLocation() + 100); - // frame.pack(); - revalidate(); - } - - private void setupToolBar() { - setToolBarButtons(new JButton[ToolbarName.values().length]); - for (int i = 0; i < ToolbarName.values().length; i++) { - String toolBarName = ToolbarName.values()[i].toString(); - URL resourceLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); - - // Scale the image icons down to make the buttons smaller - ImageIcon imageIcon = new ImageIcon(resourceLocation); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton button = new JButton(toolBarName, imageIcon); - button.setFocusPainted(false); - getToolBarButtons()[i] = button; + + private boolean basicCheckProof(int[][] origCells) { + return false; } - toolBar = new JToolBar(); - toolBar.setFloatable(false); - toolBar.setRollover(true); + private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { + // Recursively traverse directory + GameBoardFacade facade = GameBoardFacade.getInstance(); - for (int i = 0; i < getToolBarButtons().length; i++) { - for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { - if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { - toolBar.addSeparator(); + // Folder is empty + if (Objects.requireNonNull(folder.listFiles()).length == 0) { + writer.append(path).append(",Empty folder,,Ungradeable\n"); + return; } - } - String toolBarName = ToolbarName.values()[i].toString(); - toolBar.add(getToolBarButtons()[i]); - getToolBarButtons()[i].setToolTipText(toolBarName); + // Travese directory, recurse if sub-directory found + // If ungradeable, do not leave a score (0, 1) + for (final File f : Objects.requireNonNull(folder.listFiles())) { + // Recurse + if (f.isDirectory()) { + traverseDir(f, writer, path + "/" + f.getName()); + continue; + } - getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); - getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); + // Set path name + writer.append(path).append(","); + + // Load puzzle, run checker + // If wrong file type, ungradeable + String fName = f.getName(); + String fPath = f.getAbsolutePath(); + File puzzleFile = new File(fPath); + if (puzzleFile.exists()) { + // Try to load file. If invalid, note in csv + try { + // Load puzzle, run checker + GameBoardFacade.getInstance().loadPuzzle(fPath); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + facade = GameBoardFacade.getInstance(); + Puzzle puzzle = facade.getPuzzleModule(); + + // Write data + writer.append(fName).append(","); + writer.append(puzzle.getName()).append(","); + if (puzzle.isPuzzleComplete()) { + writer.append("1,Solved\n"); + } else { + writer.append("0,Unsolved\n"); + } + } catch (InvalidFileFormatException e) { + writer.append(fName).append(",Invalid,,Ungradeable\n"); + } + } else { + LOGGER.debug("Failed to run sim"); + } + } } - // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent - // e) -> - // promptPuzzle()); - // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> - // saveProof()); - // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().undo()); - // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().redo()); - toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.CHECK.ordinal()].addActionListener((ActionEvent e) -> checkProof()); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); - - toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].addActionListener( - (ActionEvent e) -> checkProofAll()); - - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.CHECK_ALL.ordinal()].setEnabled(true); - - this.add(toolBar, BorderLayout.NORTH); - } - - /** - * Sets the toolbar buttons - * - * @param toolBarButtons toolbar buttons - */ - public void setToolBarButtons(JButton[] toolBarButtons) { - this.toolBarButtons = toolBarButtons; - } - - /** - * Gets the toolbar buttons - * - * @return toolbar buttons - */ - public JButton[] getToolBarButtons() { - return toolBarButtons; - } - - /** Checks the proof for correctness */ - private void checkProof() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - Tree tree = GameBoardFacade.getInstance().getTree(); - Board board = facade.getBoard(); - Board finalBoard = null; - boolean delayStatus = true; // board.evalDelayStatus(); - - repaintAll(); - - Puzzle puzzle = facade.getPuzzleModule(); - - if (puzzle.isPuzzleComplete()) { - // This is for submission which is not integrated yet - /*int confirm = JOptionPane.showConfirmDialog(null, "Congratulations! Your proof is correct. Would you like to submit?", "Proof Submission", JOptionPane.YES_NO_OPTION); - if (confirm == JOptionPane.YES_OPTION) { - Submission submission = new Submission(board); - submission.submit(); - }*/ - JOptionPane.showMessageDialog(null, "Congratulations! Your proof is correct."); - } else { - String message = "\nThe game board is not solved."; - JOptionPane.showMessageDialog(null, message, "Invalid proof.", JOptionPane.ERROR_MESSAGE); + public BoardView getBoardView() { + return boardView; } - } - - private void repaintAll() { - boardView.repaint(); - treePanel.repaint(); - } - - public void setPuzzleView(Puzzle puzzle) { - this.boardView = puzzle.getBoardView(); - - dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); - this.topHalfPanel.setRightComponent(dynamicBoardView); - this.topHalfPanel.setVisible(true); - String boardType = boardView.getBoard().getClass().getSimpleName(); - boardType = boardType.substring(0, boardType.indexOf("Board")); - TitledBorder titleBoard = BorderFactory.createTitledBorder(boardType + " Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - this.treePanel.getTreeView().resetView(); - this.treePanel.getTreeView().setTree(puzzle.getTree()); - - puzzle.addTreeListener(treePanel.getTreeView()); - puzzle.addBoardListener(puzzle.getBoardView()); - - ruleFrame.getDirectRulePanel().setRules(puzzle.getDirectRules()); - ruleFrame.getCasePanel().setRules(puzzle.getCaseRules()); - ruleFrame.getContradictionPanel().setRules(puzzle.getContradictionRules()); - ruleFrame.getSearchPanel().setSearchBar(puzzle); - - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); - - reloadGui(); - } - - public void reloadGui() { - repaintTree(); - } - - public void repaintTree() { - treePanel.repaintTreeView(GameBoardFacade.getInstance().getTree()); - } - - /** Checks the proof for all files */ - private void checkProofAll() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - - /* - * Select dir to grade; recursively grade sub-dirs using traverseDir() - * Selected dir must have sub-dirs for each student: - * GradeThis - * | - * | -> Student 1 - * | | - * | | -> Proofs - */ - LegupPreferences preferences = LegupPreferences.getInstance(); - File preferredDirectory = new File(preferences.getUserPref(LegupPreferences.WORK_DIRECTORY)); - folderBrowser = new JFileChooser(preferredDirectory); - - folderBrowser.showOpenDialog(this); - folderBrowser.setVisible(true); - folderBrowser.setCurrentDirectory(new File(LegupPreferences.WORK_DIRECTORY)); - folderBrowser.setDialogTitle("Select Directory"); - folderBrowser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - folderBrowser.setAcceptAllFileFilterUsed(false); - - File folder = folderBrowser.getSelectedFile(); - - // Write csv file (Path,File-Name,Puzzle-Type,Score,Solved?) - File resultFile = new File(folder.getAbsolutePath() + File.separator + "result.csv"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) { - writer.append("Name,File Name,Puzzle Type,Score,Solved?\n"); - - // Go through student folders - for (final File folderEntry : Objects.requireNonNull(folder.listFiles(File::isDirectory))) { - // Write path - String path = folderEntry.getName(); - traverseDir(folderEntry, writer, path); - } - } catch (IOException ex) { - LOGGER.error(ex.getMessage()); + public DynamicView getDynamicBoardView() { + return dynamicBoardView; } - JOptionPane.showMessageDialog(null, "Batch grading complete."); - } - private boolean basicCheckProof(int[][] origCells) { - return false; - } + public TreePanel getTreePanel() { + return treePanel; + } - private void traverseDir(File folder, BufferedWriter writer, String path) throws IOException { - // Recursively traverse directory - GameBoardFacade facade = GameBoardFacade.getInstance(); + /** + * Called when a action is pushed onto the edu.rpi.legup.history stack + * + * @param command action to push onto the stack + */ + @Override + public void onPushChange(ICommand command) { + LOGGER.info("Pushing " + command.getClass().getSimpleName() + " to stack."); + undo.setEnabled(true); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(true); + redo.setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - // Folder is empty - if (Objects.requireNonNull(folder.listFiles()).length == 0) { - writer.append(path).append(",Empty folder,,Ungradeable\n"); - return; + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); } - // Travese directory, recurse if sub-directory found - // If ungradeable, do not leave a score (0, 1) - for (final File f : Objects.requireNonNull(folder.listFiles())) { - // Recurse - if (f.isDirectory()) { - traverseDir(f, writer, path + "/" + f.getName()); - continue; - } - - // Set path name - writer.append(path).append(","); - - // Load puzzle, run checker - // If wrong file type, ungradeable - String fName = f.getName(); - String fPath = f.getAbsolutePath(); - File puzzleFile = new File(fPath); - if (puzzleFile.exists()) { - // Try to load file. If invalid, note in csv - try { - // Load puzzle, run checker - GameBoardFacade.getInstance().loadPuzzle(fPath); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - facade = GameBoardFacade.getInstance(); - Puzzle puzzle = facade.getPuzzleModule(); - - // Write data - writer.append(fName).append(","); - writer.append(puzzle.getName()).append(","); - if (puzzle.isPuzzleComplete()) { - writer.append("1,Solved\n"); - } else { - writer.append("0,Unsolved\n"); - } - } catch (InvalidFileFormatException e) { - writer.append(fName).append(",Invalid,,Ungradeable\n"); - } - } else { - LOGGER.debug("Failed to run sim"); - } + /** Called when the history is cleared */ + @Override + public void onClearHistory() { + // undo.setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // redo.setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); } - } - - public BoardView getBoardView() { - return boardView; - } - - public DynamicView getDynamicBoardView() { - return dynamicBoardView; - } - - public TreePanel getTreePanel() { - return treePanel; - } - - /** - * Called when a action is pushed onto the edu.rpi.legup.history stack - * - * @param command action to push onto the stack - */ - @Override - public void onPushChange(ICommand command) { - LOGGER.info("Pushing " + command.getClass().getSimpleName() + " to stack."); - undo.setEnabled(true); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(true); - redo.setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); - } - - /** Called when the history is cleared */ - @Override - public void onClearHistory() { - // undo.setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // redo.setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - } - - /** - * Called when an action is redone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - @Override - public void onRedo(boolean isBottom, boolean isTop) { - undo.setEnabled(!isBottom); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); - redo.setEnabled(!isTop); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); - if (isBottom) { - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } else { - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + + /** + * Called when an action is redone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + @Override + public void onRedo(boolean isBottom, boolean isTop) { + undo.setEnabled(!isBottom); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); + redo.setEnabled(!isTop); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); + if (isBottom) { + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } else { + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + } } - } - - /** - * Called when an action is undone - * - * @param isBottom true if there are no more actions to undo, false otherwise - * @param isTop true if there are no more changes to redo, false otherwise - */ - @Override - public void onUndo(boolean isBottom, boolean isTop) { - undo.setEnabled(!isBottom); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); - redo.setEnabled(!isTop); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); - if (isBottom) { - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } else { - frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + + /** + * Called when an action is undone + * + * @param isBottom true if there are no more actions to undo, false otherwise + * @param isTop true if there are no more changes to redo, false otherwise + */ + @Override + public void onUndo(boolean isBottom, boolean isTop) { + undo.setEnabled(!isBottom); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(!isBottom); + redo.setEnabled(!isTop); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(!isTop); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + File puzzleFile = new File(GameBoardFacade.getInstance().getCurFileName()); + if (isBottom) { + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } else { + frame.setTitle(puzzleName + " - " + puzzleFile.getName() + " *"); + } } - } - - /** Submits the proof file */ - private void submit() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - Board board = facade.getBoard(); - boolean delayStatus = true; // board.evalDelayStatus(); - repaintAll(); - - Puzzle pm = facade.getPuzzleModule(); - if (pm.isPuzzleComplete() && delayStatus) { - // 0 means yes, 1 means no (Java's fault...) - int confirm = - JOptionPane.showConfirmDialog( - null, - "Are you sure you wish to submit?", - "Proof Submission", - JOptionPane.YES_NO_OPTION); - if (confirm == 0) { - Submission submission = new Submission(board); - submission.submit(); - } - } else { - JOptionPane.showConfirmDialog( - null, - "Your proof is incorrect! Are you sure you wish to submit?", - "Proof Submission", - JOptionPane.YES_NO_OPTION); - Submission submit = new Submission(board); + + /** Submits the proof file */ + private void submit() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + Board board = facade.getBoard(); + boolean delayStatus = true; // board.evalDelayStatus(); + repaintAll(); + + Puzzle pm = facade.getPuzzleModule(); + if (pm.isPuzzleComplete() && delayStatus) { + // 0 means yes, 1 means no (Java's fault...) + int confirm = + JOptionPane.showConfirmDialog( + null, + "Are you sure you wish to submit?", + "Proof Submission", + JOptionPane.YES_NO_OPTION); + if (confirm == 0) { + Submission submission = new Submission(board); + submission.submit(); + } + } else { + JOptionPane.showConfirmDialog( + null, + "Your proof is incorrect! Are you sure you wish to submit?", + "Proof Submission", + JOptionPane.YES_NO_OPTION); + Submission submit = new Submission(board); + } } - } - public void showStatus(String status, boolean error, int timer) { - // TODO: implement - } + public void showStatus(String status, boolean error, int timer) { + // TODO: implement + } - protected void fitTreeViewToScreen() { - this.treePanel.getTreeView().zoomFit(); - } + protected void fitTreeViewToScreen() { + this.treePanel.getTreeView().zoomFit(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java b/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java index 91a042c4d..b3cd30ffb 100644 --- a/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java +++ b/src/main/java/edu/rpi/legup/ui/PuzzleEditorPanel.java @@ -30,532 +30,550 @@ public class PuzzleEditorPanel extends LegupPanel implements IHistoryListener { - private static final Logger LOGGER = LogManager.getLogger(PuzzleEditorPanel.class.getName()); - private JMenu[] menus; - private JMenuItem helpLegup, aboutLegup; - private JMenuBar menuBar; - private JToolBar toolBar; - private JFrame frame; - private JButton[] buttons; - JSplitPane splitPanel; - private JButton[] toolBarButtons; - private JPanel elementPanel; - private DynamicView dynamicBoardView; - private BoardView boardView; - private TitledBorder boardBorder; - // private JSplitPane splitPanel, topHalfPanel; - private FileDialog fileDialog; - private JMenuItem undo, redo, fitBoardToScreen; - private ElementFrame elementFrame; - private JPanel treePanel; - private LegupUI legupUI; - private EditorElementController editorElementController; - static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; - - public PuzzleEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { - this.fileDialog = fileDialog; - this.frame = frame; - this.legupUI = legupUI; - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(800, 700)); - } - - protected void setupContent() { + private static final Logger LOGGER = LogManager.getLogger(PuzzleEditorPanel.class.getName()); + private JMenu[] menus; + private JMenuItem helpLegup, aboutLegup; + private JMenuBar menuBar; + private JToolBar toolBar; + private JFrame frame; + private JButton[] buttons; JSplitPane splitPanel; - JPanel elementBox = new JPanel(new BorderLayout()); - - editorElementController = new EditorElementController(); - elementFrame = new ElementFrame(editorElementController); - elementBox.add(elementFrame, BorderLayout.WEST); - - dynamicBoardView = - new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); - TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); - - JPanel boardPanel = new JPanel(new BorderLayout()); - splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, elementFrame, dynamicBoardView); - splitPanel.setPreferredSize(new Dimension(600, 400)); - - boardPanel.add(splitPanel); - boardBorder = BorderFactory.createTitledBorder("Board"); - boardBorder.setTitleJustification(TitledBorder.CENTER); - - elementBox.add(boardPanel); - this.add(elementBox); - - splitPanel.setDividerLocation(splitPanel.getMaximumDividerLocation() + 100); - this.splitPanel = splitPanel; - revalidate(); - } - - public void setMenuBar() { - String os = LegupUI.getOS(); - menuBar = new JMenuBar(); - menus = new JMenu[3]; - - // create menus - - // FILE - menus[0] = new JMenu("File"); - - // file>new - JMenuItem newPuzzle = new JMenuItem("New"); - newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); - } - // file>save - JMenuItem savePuzzle = new JMenuItem("Save As"); - savePuzzle.addActionListener((ActionEvent) -> savePuzzle()); - JMenuItem directSavePuzzle = new JMenuItem("Direct Save Proof "); - directSavePuzzle.addActionListener((ActionEvent) -> direct_save()); - if (os.equals("mac")) { - newPuzzle.setAccelerator( - KeyStroke.getKeyStroke('D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); + private JButton[] toolBarButtons; + private JPanel elementPanel; + private DynamicView dynamicBoardView; + private BoardView boardView; + private TitledBorder boardBorder; + // private JSplitPane splitPanel, topHalfPanel; + private FileDialog fileDialog; + private JMenuItem undo, redo, fitBoardToScreen; + private ElementFrame elementFrame; + private JPanel treePanel; + private LegupUI legupUI; + private EditorElementController editorElementController; + static final int[] TOOLBAR_SEPARATOR_BEFORE = {2, 4, 8}; + + public PuzzleEditorPanel(FileDialog fileDialog, JFrame frame, LegupUI legupUI) { + this.fileDialog = fileDialog; + this.frame = frame; + this.legupUI = legupUI; + setLayout(new BorderLayout()); + setPreferredSize(new Dimension(800, 700)); } - JMenuItem exit = new JMenuItem("Exit"); - exit.addActionListener((ActionEvent) -> exitEditor()); - if (os.equals("mac")) { - exit.setAccelerator( - KeyStroke.getKeyStroke('Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); - } - menus[0].add(newPuzzle); - menus[0].add(savePuzzle); - menus[0].add(directSavePuzzle); - menus[0].add(exit); - - // EDIT - menus[1] = new JMenu("Edit"); - // edit>undo - undo = new JMenuItem("Undo"); - // edit>redo - redo = new JMenuItem("Redo"); - fitBoardToScreen = new JMenuItem("Fit Board to Screen"); - - menus[1].add(undo); - undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); - if (os.equals("mac")) { - undo.setAccelerator( - KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); - } else { - undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + protected void setupContent() { + JSplitPane splitPanel; + JPanel elementBox = new JPanel(new BorderLayout()); + + editorElementController = new EditorElementController(); + elementFrame = new ElementFrame(editorElementController); + elementBox.add(elementFrame, BorderLayout.WEST); + + dynamicBoardView = + new DynamicView(new ScrollView(new BoardController()), DynamicViewType.BOARD); + TitledBorder titleBoard = BorderFactory.createTitledBorder("Board"); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + JPanel boardPanel = new JPanel(new BorderLayout()); + splitPanel = + new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, elementFrame, dynamicBoardView); + splitPanel.setPreferredSize(new Dimension(600, 400)); + + boardPanel.add(splitPanel); + boardBorder = BorderFactory.createTitledBorder("Board"); + boardBorder.setTitleJustification(TitledBorder.CENTER); + + elementBox.add(boardPanel); + this.add(elementBox); + + splitPanel.setDividerLocation(splitPanel.getMaximumDividerLocation() + 100); + this.splitPanel = splitPanel; + revalidate(); } - menus[1].add(redo); - - // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) - Action redoAction = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - GameBoardFacade.getInstance().getHistory().redo(); - } - }; - if (os.equals("mac")) { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() - + InputEvent.SHIFT_DOWN_MASK), - "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "redoAction"); - redo.setAccelerator( - KeyStroke.getKeyStroke( - 'Z', - Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_DOWN_MASK)); - } else { - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); - redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) - .put( - KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), - "redoAction"); - redo.getActionMap().put("redoAction", redoAction); - - // Button in menu will show CTRL-SHIFT-Z as primary keybind - redo.setAccelerator( - KeyStroke.getKeyStroke('Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + public void setMenuBar() { + String os = LegupUI.getOS(); + menuBar = new JMenuBar(); + menus = new JMenu[3]; + + // create menus + + // FILE + menus[0] = new JMenu("File"); + + // file>new + JMenuItem newPuzzle = new JMenuItem("New"); + newPuzzle.addActionListener((ActionEvent) -> loadPuzzle()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke( + 'N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('N', InputEvent.CTRL_DOWN_MASK)); + } + // file>save + JMenuItem savePuzzle = new JMenuItem("Save As"); + savePuzzle.addActionListener((ActionEvent) -> savePuzzle()); + JMenuItem directSavePuzzle = new JMenuItem("Direct Save Proof "); + directSavePuzzle.addActionListener((ActionEvent) -> direct_save()); + if (os.equals("mac")) { + newPuzzle.setAccelerator( + KeyStroke.getKeyStroke( + 'D', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + newPuzzle.setAccelerator(KeyStroke.getKeyStroke('D', InputEvent.CTRL_DOWN_MASK)); + } + + JMenuItem exit = new JMenuItem("Exit"); + exit.addActionListener((ActionEvent) -> exitEditor()); + if (os.equals("mac")) { + exit.setAccelerator( + KeyStroke.getKeyStroke( + 'Q', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + exit.setAccelerator(KeyStroke.getKeyStroke('Q', InputEvent.CTRL_DOWN_MASK)); + } + menus[0].add(newPuzzle); + menus[0].add(savePuzzle); + menus[0].add(directSavePuzzle); + menus[0].add(exit); + + // EDIT + menus[1] = new JMenu("Edit"); + // edit>undo + undo = new JMenuItem("Undo"); + // edit>redo + redo = new JMenuItem("Redo"); + fitBoardToScreen = new JMenuItem("Fit Board to Screen"); + + menus[1].add(undo); + undo.addActionListener((ActionEvent) -> GameBoardFacade.getInstance().getHistory().undo()); + if (os.equals("mac")) { + undo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); + } else { + undo.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK)); + } + + menus[1].add(redo); + + // Created action to support two keybinds (CTRL-SHIFT-Z, CTRL-Y) + Action redoAction = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + GameBoardFacade.getInstance().getHistory().redo(); + } + }; + if (os.equals("mac")) { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK), + "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "redoAction"); + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + + InputEvent.SHIFT_DOWN_MASK)); + } else { + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK), "redoAction"); + redo.getInputMap(WHEN_IN_FOCUSED_WINDOW) + .put( + KeyStroke.getKeyStroke( + 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), + "redoAction"); + redo.getActionMap().put("redoAction", redoAction); + + // Button in menu will show CTRL-SHIFT-Z as primary keybind + redo.setAccelerator( + KeyStroke.getKeyStroke( + 'Z', InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)); + } + + menus[1].add(fitBoardToScreen); + fitBoardToScreen.addActionListener( + (ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); + + // HELP + menus[2] = new JMenu("Help"); + helpLegup = new JMenuItem("Help Legup"); + aboutLegup = new JMenuItem("About Legup"); + menus[2].add(helpLegup); + menus[2].add(aboutLegup); + helpLegup.addActionListener( + l -> { + try { + java.awt.Desktop.getDesktop() + .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); + } catch (IOException e) { + LOGGER.error("Can't open web page"); + } + }); + menus[2].add(aboutLegup); + aboutLegup.addActionListener( + l -> { + JOptionPane.showMessageDialog(null, "Version: 5.1.0"); + }); + // add menus to menubar + for (JMenu menu : menus) { + menuBar.add(menu); + } + frame.setJMenuBar(menuBar); } - menus[1].add(fitBoardToScreen); - fitBoardToScreen.addActionListener((ActionEvent) -> dynamicBoardView.fitBoardViewToScreen()); - - // HELP - menus[2] = new JMenu("Help"); - helpLegup = new JMenuItem("Help Legup"); - aboutLegup = new JMenuItem("About Legup"); - menus[2].add(helpLegup); - menus[2].add(aboutLegup); - helpLegup.addActionListener( - l -> { - try { - java.awt.Desktop.getDesktop() - .browse(URI.create("https://github.com/Bram-Hub/LEGUP/wiki")); - } catch (IOException e) { - LOGGER.error("Can't open web page"); - } - }); - menus[2].add(aboutLegup); - aboutLegup.addActionListener( - l -> { - JOptionPane.showMessageDialog(null, "Version: 5.1.0"); - }); - // add menus to menubar - for (JMenu menu : menus) { - menuBar.add(menu); + public void exitEditor() { + // Wipes the puzzle entirely as if LEGUP just started + GameBoardFacade.getInstance().clearPuzzle(); + this.legupUI.displayPanel(0); + treePanel = null; + boardView = null; } - frame.setJMenuBar(menuBar); - } - - public void exitEditor() { - // Wipes the puzzle entirely as if LEGUP just started - GameBoardFacade.getInstance().clearPuzzle(); - this.legupUI.displayPanel(0); - treePanel = null; - boardView = null; - } - - @Override - public void makeVisible() { - this.removeAll(); - - setupToolBar(); - setupContent(); - setMenuBar(); - } - - private void setupToolBar() { - setToolBarButtons(new JButton[ToolbarName.values().length + 1]); - int lastone = 0; - for (int i = 0; i < ToolbarName.values().length - 1; i++) { - String toolBarName = ToolbarName.values()[i].toString(); - URL resourceLocation = - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); - - // Scale the image icons down to make the buttons smaller - ImageIcon imageIcon = new ImageIcon(resourceLocation); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton button = new JButton(toolBarName, imageIcon); - button.setFocusPainted(false); - getToolBarButtons()[i] = button; - lastone = i; + + @Override + public void makeVisible() { + this.removeAll(); + + setupToolBar(); + setupContent(); + setMenuBar(); } - URL check_and_save = - ClassLoader.getSystemClassLoader().getResource("edu/rpi/legup/images/Legup/Check.png"); - ImageIcon imageIcon = new ImageIcon(check_and_save); - Image image = imageIcon.getImage(); - imageIcon = - new ImageIcon( - image.getScaledInstance( - this.TOOLBAR_ICON_SCALE, this.TOOLBAR_ICON_SCALE, Image.SCALE_SMOOTH)); - - JButton checkandsave = new JButton("check and Save", imageIcon); - checkandsave.setFocusPainted(false); - checkandsave.addActionListener( - new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // savePuzzle(); - String filename = savePuzzle(); - File puzzlename = new File(filename); - System.out.println(filename); - - GameBoardFacade.getInstance().getLegupUI().displayPanel(1); - GameBoardFacade.getInstance() - .getLegupUI() - .getProofEditor() - .loadPuzzle(filename, new File(filename)); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzlename.getName()); - } - }); - getToolBarButtons()[lastone + 1] = checkandsave; - System.out.println("it is create new file"); - - toolBar = new JToolBar(); - toolBar.setFloatable(false); - toolBar.setRollover(true); - - for (int i = 0; i < getToolBarButtons().length - 1; i++) { - for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { - if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { - toolBar.addSeparator(); + private void setupToolBar() { + setToolBarButtons(new JButton[ToolbarName.values().length + 1]); + int lastone = 0; + for (int i = 0; i < ToolbarName.values().length - 1; i++) { + String toolBarName = ToolbarName.values()[i].toString(); + URL resourceLocation = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/" + toolBarName + ".png"); + + // Scale the image icons down to make the buttons smaller + ImageIcon imageIcon = new ImageIcon(resourceLocation); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, + this.TOOLBAR_ICON_SCALE, + Image.SCALE_SMOOTH)); + + JButton button = new JButton(toolBarName, imageIcon); + button.setFocusPainted(false); + getToolBarButtons()[i] = button; + lastone = i; } - } - String toolBarName = ToolbarName.values()[i].toString(); - toolBar.add(getToolBarButtons()[i]); - getToolBarButtons()[i].setToolTipText(toolBarName); + URL check_and_save = + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Check.png"); + ImageIcon imageIcon = new ImageIcon(check_and_save); + Image image = imageIcon.getImage(); + imageIcon = + new ImageIcon( + image.getScaledInstance( + this.TOOLBAR_ICON_SCALE, + this.TOOLBAR_ICON_SCALE, + Image.SCALE_SMOOTH)); + + JButton checkandsave = new JButton("check and Save", imageIcon); + checkandsave.setFocusPainted(false); + checkandsave.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // savePuzzle(); + String filename = savePuzzle(); + File puzzlename = new File(filename); + System.out.println(filename); + + GameBoardFacade.getInstance().getLegupUI().displayPanel(1); + GameBoardFacade.getInstance() + .getLegupUI() + .getProofEditor() + .loadPuzzle(filename, new File(filename)); + String puzzleName = + GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzlename.getName()); + } + }); + getToolBarButtons()[lastone + 1] = checkandsave; + System.out.println("it is create new file"); + + toolBar = new JToolBar(); + toolBar.setFloatable(false); + toolBar.setRollover(true); + + for (int i = 0; i < getToolBarButtons().length - 1; i++) { + for (int s = 0; s < TOOLBAR_SEPARATOR_BEFORE.length; s++) { + if (i == TOOLBAR_SEPARATOR_BEFORE[s]) { + toolBar.addSeparator(); + } + } + String toolBarName = ToolbarName.values()[i].toString(); + + toolBar.add(getToolBarButtons()[i]); + getToolBarButtons()[i].setToolTipText(toolBarName); + + getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); + getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); + } - getToolBarButtons()[i].setVerticalTextPosition(SwingConstants.BOTTOM); - getToolBarButtons()[i].setHorizontalTextPosition(SwingConstants.CENTER); + // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent + // e) -> + // promptPuzzle()); + // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> + // saveProof()); + // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().undo()); + // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> + // GameBoardFacade.getInstance().getHistory().redo()); + toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); + + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); + // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); + toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); + + this.add(toolBar, BorderLayout.NORTH); } - // toolBarButtons[ToolbarName.OPEN_PUZZLE.ordinal()].addActionListener((ActionEvent - // e) -> - // promptPuzzle()); - // toolBarButtons[ToolbarName.SAVE.ordinal()].addActionListener((ActionEvent e) -> - // saveProof()); - // toolBarButtons[ToolbarName.UNDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().undo()); - // toolBarButtons[ToolbarName.REDO.ordinal()].addActionListener((ActionEvent e) -> - // GameBoardFacade.getInstance().getHistory().redo()); - toolBarButtons[ToolbarName.HINT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].addActionListener((ActionEvent e) -> {}); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].addActionListener((ActionEvent e) -> {}); - - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.UNDO.ordinal()].setEnabled(false); - // toolBarButtons[ToolbarName.REDO.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.HINT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.SUBMIT.ordinal()].setEnabled(false); - toolBarButtons[ToolbarName.DIRECTIONS.ordinal()].setEnabled(false); - - this.add(toolBar, BorderLayout.NORTH); - } - - public void loadPuzzleFromHome(String game, int rows, int columns) - throws IllegalArgumentException { - GameBoardFacade facade = GameBoardFacade.getInstance(); - try { - facade.loadPuzzle(game, rows, columns); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (RuntimeException e) { - e.printStackTrace(); - LOGGER.error(e.getMessage()); + public void loadPuzzleFromHome(String game, int rows, int columns) + throws IllegalArgumentException { + GameBoardFacade facade = GameBoardFacade.getInstance(); + try { + facade.loadPuzzle(game, rows, columns); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (RuntimeException e) { + e.printStackTrace(); + LOGGER.error(e.getMessage()); + } } - } - - public void loadPuzzleFromHome(String game, String[] statements) { - GameBoardFacade facade = GameBoardFacade.getInstance(); - try { - facade.loadPuzzle(game, statements); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException(exception.getMessage()); - } catch (RuntimeException e) { - e.printStackTrace(); - LOGGER.error(e.getMessage()); + + public void loadPuzzleFromHome(String game, String[] statements) { + GameBoardFacade facade = GameBoardFacade.getInstance(); + try { + facade.loadPuzzle(game, statements); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(exception.getMessage()); + } catch (RuntimeException e) { + e.printStackTrace(); + LOGGER.error(e.getMessage()); + } } - } - - // File opener - public Object[] promptPuzzle() { - GameBoardFacade facade = GameBoardFacade.getInstance(); - if (facade.getBoard() != null) { - if (noQuit("Opening a new puzzle to edit?")) { - return new Object[0]; - } + + // File opener + public Object[] promptPuzzle() { + GameBoardFacade facade = GameBoardFacade.getInstance(); + if (facade.getBoard() != null) { + if (noQuit("Opening a new puzzle to edit?")) { + return new Object[0]; + } + } + if (fileDialog == null) { + fileDialog = new FileDialog(this.frame); + } + LegupPreferences preferences = LegupPreferences.getInstance(); + String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); + + fileDialog.setMode(FileDialog.LOAD); + fileDialog.setTitle("Select Puzzle"); + fileDialog.setDirectory(preferredDirectory); + fileDialog.setVisible(true); + String fileName = null; + File puzzleFile = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); + puzzleFile = new File(fileName); + } else { + // The attempt to prompt a puzzle ended gracefully (cancel) + return null; + } + + return new Object[] {fileName, puzzleFile}; } - if (fileDialog == null) { - fileDialog = new FileDialog(this.frame); + + public void loadPuzzle() { + Object[] items = promptPuzzle(); + // Return if items == null (cancel) + if (items == null) { + return; + } + String fileName = (String) items[0]; + File puzzleFile = (File) items[1]; + loadPuzzle(fileName, puzzleFile); } - LegupPreferences preferences = LegupPreferences.getInstance(); - String preferredDirectory = preferences.getUserPref(LegupPreferences.WORK_DIRECTORY); - - fileDialog.setMode(FileDialog.LOAD); - fileDialog.setTitle("Select Puzzle"); - fileDialog.setDirectory(preferredDirectory); - fileDialog.setVisible(true); - String fileName = null; - File puzzleFile = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - puzzleFile = new File(fileName); - } else { - // The attempt to prompt a puzzle ended gracefully (cancel) - return null; + + public void loadPuzzle(String fileName, File puzzleFile) { + if (puzzleFile != null && puzzleFile.exists()) { + try { + legupUI.displayPanel(2); + GameBoardFacade.getInstance().loadPuzzleEditor(fileName); + String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); + frame.setTitle(puzzleName + " - " + puzzleFile.getName()); + } catch (InvalidFileFormatException e) { + legupUI.displayPanel(0); + LOGGER.error(e.getMessage()); + JOptionPane.showMessageDialog( + null, + "File does not exist, cannot be read, or cannot be edited", + "Error", + JOptionPane.ERROR_MESSAGE); + loadPuzzle(); + } + } } - return new Object[] {fileName, puzzleFile}; - } + public boolean noQuit(String instr) { + int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); + return n != JOptionPane.YES_OPTION; + } + + @Override + public void onPushChange(ICommand command) {} + + @Override + public void onUndo(boolean isBottom, boolean isTop) {} - public void loadPuzzle() { - Object[] items = promptPuzzle(); - // Return if items == null (cancel) - if (items == null) { - return; + @Override + public void onRedo(boolean isBottom, boolean isTop) {} + + @Override + public void onClearHistory() { + // undo.setEnabled(false); + // redo.setEnabled(false); } - String fileName = (String) items[0]; - File puzzleFile = (File) items[1]; - loadPuzzle(fileName, puzzleFile); - } - - public void loadPuzzle(String fileName, File puzzleFile) { - if (puzzleFile != null && puzzleFile.exists()) { - try { - legupUI.displayPanel(2); - GameBoardFacade.getInstance().loadPuzzleEditor(fileName); - String puzzleName = GameBoardFacade.getInstance().getPuzzleModule().getName(); - frame.setTitle(puzzleName + " - " + puzzleFile.getName()); - } catch (InvalidFileFormatException e) { - legupUI.displayPanel(0); - LOGGER.error(e.getMessage()); - JOptionPane.showMessageDialog( - null, - "File does not exist, cannot be read, or cannot be edited", - "Error", - JOptionPane.ERROR_MESSAGE); - loadPuzzle(); - } + + public BoardView getBoardView() { + return boardView; } - } - - public boolean noQuit(String instr) { - int n = JOptionPane.showConfirmDialog(null, instr, "Confirm", JOptionPane.YES_NO_OPTION); - return n != JOptionPane.YES_OPTION; - } - - @Override - public void onPushChange(ICommand command) {} - - @Override - public void onUndo(boolean isBottom, boolean isTop) {} - - @Override - public void onRedo(boolean isBottom, boolean isTop) {} - - @Override - public void onClearHistory() { - // undo.setEnabled(false); - // redo.setEnabled(false); - } - - public BoardView getBoardView() { - return boardView; - } - - public JButton[] getToolBarButtons() { - return toolBarButtons; - } - - public void setToolBarButtons(JButton[] toolBarButtons) { - this.toolBarButtons = toolBarButtons; - } - - private void repaintAll() { - boardView.repaint(); - } - - public void setPuzzleView(Puzzle puzzle) { - this.boardView = puzzle.getBoardView(); - editorElementController.setElementController(boardView.getElementController()); - dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); - if (this.splitPanel != null) { - this.splitPanel.setRightComponent(dynamicBoardView); - this.splitPanel.setVisible(true); + + public JButton[] getToolBarButtons() { + return toolBarButtons; } - TitledBorder titleBoard = - BorderFactory.createTitledBorder(boardView.getClass().getSimpleName()); - titleBoard.setTitleJustification(TitledBorder.CENTER); - dynamicBoardView.setBorder(titleBoard); + public void setToolBarButtons(JButton[] toolBarButtons) { + this.toolBarButtons = toolBarButtons; + } - puzzle.addBoardListener(puzzle.getBoardView()); - System.out.println("Setting elements"); - if (this.elementFrame != null) { - elementFrame.setElements(puzzle); + private void repaintAll() { + boardView.repaint(); } - toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); - // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); - } + public void setPuzzleView(Puzzle puzzle) { + this.boardView = puzzle.getBoardView(); + editorElementController.setElementController(boardView.getElementController()); + dynamicBoardView = new DynamicView(boardView, DynamicViewType.BOARD); + if (this.splitPanel != null) { + this.splitPanel.setRightComponent(dynamicBoardView); + this.splitPanel.setVisible(true); + } - /** Saves a puzzle */ - private void direct_save() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return; - } - String fileName = GameBoardFacade.getInstance().getCurFileName(); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + TitledBorder titleBoard = + BorderFactory.createTitledBorder(boardView.getClass().getSimpleName()); + titleBoard.setTitleJustification(TitledBorder.CENTER); + dynamicBoardView.setBorder(titleBoard); + + puzzle.addBoardListener(puzzle.getBoardView()); + System.out.println("Setting elements"); + if (this.elementFrame != null) { + elementFrame.setElements(puzzle); } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } - } - } - private String savePuzzle() { - Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); - if (puzzle == null) { - return ""; + toolBarButtons[ToolbarName.CHECK.ordinal()].setEnabled(true); + // toolBarButtons[ToolbarName.SAVE.ordinal()].setEnabled(true); } - // for TreeTent, need to check validity before saving - if (Objects.equals(puzzle.getName(), "TreeTent")) { - if (!puzzle.checkValidity()) { - int input = - JOptionPane.showConfirmDialog( - null, "The puzzle you edited is not " + "valid, would you still like to save? "); - if (input != 0) { - return ""; + /** Saves a puzzle */ + private void direct_save() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return; + } + String fileName = GameBoardFacade.getInstance().getCurFileName(); + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } } - } } - if (fileDialog == null) { - fileDialog = new FileDialog(this.frame); - } + private String savePuzzle() { + Puzzle puzzle = GameBoardFacade.getInstance().getPuzzleModule(); + if (puzzle == null) { + return ""; + } - fileDialog.setMode(FileDialog.SAVE); - fileDialog.setTitle("Save Proof"); - String curFileName = GameBoardFacade.getInstance().getCurFileName(); - if (curFileName == null) { - fileDialog.setDirectory( - LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); - } else { - File curFile = new File(curFileName); - fileDialog.setDirectory(curFile.getParent()); - } - fileDialog.setVisible(true); + // for TreeTent, need to check validity before saving + if (Objects.equals(puzzle.getName(), "TreeTent")) { + if (!puzzle.checkValidity()) { + int input = + JOptionPane.showConfirmDialog( + null, + "The puzzle you edited is not " + + "valid, would you still like to save? "); + if (input != 0) { + return ""; + } + } + } - String fileName = null; - if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { - fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); - } + if (fileDialog == null) { + fileDialog = new FileDialog(this.frame); + } + + fileDialog.setMode(FileDialog.SAVE); + fileDialog.setTitle("Save Proof"); + String curFileName = GameBoardFacade.getInstance().getCurFileName(); + if (curFileName == null) { + fileDialog.setDirectory( + LegupPreferences.getInstance().getUserPref(LegupPreferences.WORK_DIRECTORY)); + } else { + File curFile = new File(curFileName); + fileDialog.setDirectory(curFile.getParent()); + } + fileDialog.setVisible(true); - if (fileName != null) { - try { - PuzzleExporter exporter = puzzle.getExporter(); - if (exporter == null) { - throw new ExportFileException("Puzzle exporter null"); + String fileName = null; + if (fileDialog.getDirectory() != null && fileDialog.getFile() != null) { + fileName = fileDialog.getDirectory() + File.separator + fileDialog.getFile(); } - exporter.exportPuzzle(fileName); - } catch (ExportFileException e) { - e.printStackTrace(); - } + + if (fileName != null) { + try { + PuzzleExporter exporter = puzzle.getExporter(); + if (exporter == null) { + throw new ExportFileException("Puzzle exporter null"); + } + exporter.exportPuzzle(fileName); + } catch (ExportFileException e) { + e.printStackTrace(); + } + } + return fileName; } - return fileName; - } - public DynamicView getDynamicBoardView() { - return dynamicBoardView; - } + public DynamicView getDynamicBoardView() { + return dynamicBoardView; + } } diff --git a/src/main/java/edu/rpi/legup/ui/ScrollView.java b/src/main/java/edu/rpi/legup/ui/ScrollView.java index 5d072ebf5..0bf8335a2 100644 --- a/src/main/java/edu/rpi/legup/ui/ScrollView.java +++ b/src/main/java/edu/rpi/legup/ui/ScrollView.java @@ -7,307 +7,310 @@ import javax.swing.*; public class ScrollView extends JScrollPane { - private static final Logger LOGGER = Logger.getLogger(ScrollView.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ScrollView.class.getName()); - private static final double minScale = 0.25; - private static final double maxScale = 4.0; - private static final double[] levels = {0.25, 1.0 / 3.0, 0.50, 2.0 / 3.0, 1.0, 2.0, 3.0, 4.0}; + private static final double minScale = 0.25; + private static final double maxScale = 4.0; + private static final double[] levels = {0.25, 1.0 / 3.0, 0.50, 2.0 / 3.0, 1.0, 2.0, 3.0, 4.0}; - private Dimension viewSize; - private Dimension zoomSize; - private TreeSet zoomLevels; + private Dimension viewSize; + private Dimension zoomSize; + private TreeSet zoomLevels; - private double scale; + private double scale; - private Controller controller; - private ZoomablePane canvas; - private ZoomWidget widget; + private Controller controller; + private ZoomablePane canvas; + private ZoomWidget widget; - /** - * ScrollView Constructor - creates a ScrollView object using the controller handle the ui events - * - * @param controller controller that handles the ui events - */ - public ScrollView(Controller controller) { - super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS); + /** + * ScrollView Constructor - creates a ScrollView object using the controller handle the ui + * events + * + * @param controller controller that handles the ui events + */ + public ScrollView(Controller controller) { + super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS); - viewSize = new Dimension(); - zoomSize = new Dimension(); - scale = 1.0; + viewSize = new Dimension(); + zoomSize = new Dimension(); + scale = 1.0; - this.canvas = new ZoomablePane(this); + this.canvas = new ZoomablePane(this); - viewport.setView(canvas); + viewport.setView(canvas); - zoomLevels = new TreeSet<>(); - for (Double level : levels) { - zoomLevels.add(level); + zoomLevels = new TreeSet<>(); + for (Double level : levels) { + zoomLevels.add(level); + } + + widget = new ZoomWidget(this); + setCorner(JScrollPane.LOWER_RIGHT_CORNER, widget); + + setWheelScrollingEnabled(false); + + this.controller = controller; + controller.setViewer(this); + canvas.addMouseMotionListener(controller); + canvas.addMouseListener(controller); + viewport.addMouseWheelListener(controller); + viewport.addMouseListener(controller); + viewport.addMouseMotionListener(controller); } - widget = new ZoomWidget(this); - setCorner(JScrollPane.LOWER_RIGHT_CORNER, widget); - - setWheelScrollingEnabled(false); - - this.controller = controller; - controller.setViewer(this); - canvas.addMouseMotionListener(controller); - canvas.addMouseListener(controller); - viewport.addMouseWheelListener(controller); - viewport.addMouseListener(controller); - viewport.addMouseMotionListener(controller); - } - - /** - * Creates a customized viewport for the scroll pane - * - * @return viewport for the scroll pane - */ - @Override - protected JViewport createViewport() { - return new JViewport() { - @Override - protected LayoutManager createLayoutManager() { - return new ViewportLayout() { - @Override - public void layoutContainer(Container parent) { - Point point = viewport.getViewPosition(); - // determine the maximum x and y view positions - int mx = canvas.getWidth() - viewport.getWidth(); - int my = canvas.getHeight() - viewport.getHeight(); - // obey edge boundaries - if (point.x < 0) { - point.x = 0; - } - if (point.x > mx) { - point.x = mx; + /** + * Creates a customized viewport for the scroll pane + * + * @return viewport for the scroll pane + */ + @Override + protected JViewport createViewport() { + return new JViewport() { + @Override + protected LayoutManager createLayoutManager() { + return new ViewportLayout() { + @Override + public void layoutContainer(Container parent) { + Point point = viewport.getViewPosition(); + // determine the maximum x and y view positions + int mx = canvas.getWidth() - viewport.getWidth(); + int my = canvas.getHeight() - viewport.getHeight(); + // obey edge boundaries + if (point.x < 0) { + point.x = 0; + } + if (point.x > mx) { + point.x = mx; + } + if (point.y < 0) { + point.y = 0; + } + if (point.y > my) { + point.y = my; + } + // center margins + if (mx < 0) { + point.x = mx / 2; + } + if (my < 0) { + point.y = my / 2; + } + viewport.setViewPosition(point); + } + }; } - if (point.y < 0) { - point.y = 0; - } - if (point.y > my) { - point.y = my; - } - // center margins - if (mx < 0) { - point.x = mx / 2; + }; + } + + /** Updates zoomSize and view viewSize with the new scale */ + private void updateSize() { + zoomSize.setSize((int) (viewSize.width * scale), (int) (viewSize.height * scale)); + viewport.setViewSize(zoomSize); + } + + /** + * Updates the viewport position + * + * @param point point to set the viewport to + * @param magnification magnification to set the viewport to + */ + public void updatePosition(Point point, double magnification) { + Point position = viewport.getViewPosition(); + position.x = (int) ((double) (point.x + position.x) * magnification - point.x + 0.0); + position.y = (int) ((double) (point.y + position.y) * magnification - point.y + 0.0); + viewport.setViewPosition(position); + } + + /** + * Zooms in or out on a position within the dynamicView + * + * @param n level of zoom - n less than 0 is zoom in, n greater than 0 is zoom out + * @param point position to zoom in on + */ + public void zoom(int n, Point point) { + // if no Point is given, keep current center + if (point == null) { + point = + new Point( + viewport.getWidth() / 2 + viewport.getX(), + viewport.getHeight() / 2 + viewport.getY()); + } + // magnification level + double mag = (double) n * 1.05; + // zoom in + if (n < 0) { + mag = -mag; + // check zoom bounds + if (scale * mag > maxScale) { + mag = maxScale / scale; } - if (my < 0) { - point.y = my / 2; + // update + scale *= mag; + updateSize(); + updatePosition(point, mag); + // zoom out + } else { + mag = 1 / mag; + // check zoom bounds + if (scale * mag < minScale) { + mag = minScale / scale; } - viewport.setViewPosition(point); - } - }; - } - }; - } - - /** Updates zoomSize and view viewSize with the new scale */ - private void updateSize() { - zoomSize.setSize((int) (viewSize.width * scale), (int) (viewSize.height * scale)); - viewport.setViewSize(zoomSize); - } - - /** - * Updates the viewport position - * - * @param point point to set the viewport to - * @param magnification magnification to set the viewport to - */ - public void updatePosition(Point point, double magnification) { - Point position = viewport.getViewPosition(); - position.x = (int) ((double) (point.x + position.x) * magnification - point.x + 0.0); - position.y = (int) ((double) (point.y + position.y) * magnification - point.y + 0.0); - viewport.setViewPosition(position); - } - - /** - * Zooms in or out on a position within the dynamicView - * - * @param n level of zoom - n less than 0 is zoom in, n greater than 0 is zoom out - * @param point position to zoom in on - */ - public void zoom(int n, Point point) { - // if no Point is given, keep current center - if (point == null) { - point = - new Point( - viewport.getWidth() / 2 + viewport.getX(), - viewport.getHeight() / 2 + viewport.getY()); + // update + scale *= mag; + updatePosition(point, mag); + updateSize(); + } + // update the scrollpane and subclass + revalidate(); } - // magnification level - double mag = (double) n * 1.05; - // zoom in - if (n < 0) { - mag = -mag; - // check zoom bounds - if (scale * mag > maxScale) { - mag = maxScale / scale; - } - // update - scale *= mag; - updateSize(); - updatePosition(point, mag); - // zoom out - } else { - mag = 1 / mag; - // check zoom bounds - if (scale * mag < minScale) { - mag = minScale / scale; - } - // update - scale *= mag; - updatePosition(point, mag); - updateSize(); + + public void zoomTo(double newScale) { + // check zoom bounds + if (newScale < minScale) { + newScale = minScale; + } + if (newScale > maxScale) { + newScale = maxScale; + } + if (newScale == scale) { + return; + } + // calculate the newScale and center point + double mag = newScale / scale; + Point p = + new Point( + viewport.getWidth() / 2 + viewport.getX(), + viewport.getHeight() / 2 + viewport.getY()); + + // set scale directly + scale = newScale; + // zoom in + if (mag > 1.0) { + updateSize(); + updatePosition(p, mag); + // zoom out + } else { + updatePosition(p, mag); + updateSize(); + } + // update the scrollpane and subclass + revalidate(); } - // update the scrollpane and subclass - revalidate(); - } - - public void zoomTo(double newScale) { - // check zoom bounds - if (newScale < minScale) { - newScale = minScale; + + /** Get the ideal zoom based on the viewSize */ + public void zoomFit() { + if (viewport.getWidth() != 0 && viewport.getHeight() != 0) { + double fitWidth = (viewport.getWidth() - 8.0) / viewSize.width; + double fitHeight = (viewport.getHeight() - 8.0) / viewSize.height; + + zoomTo(Math.min(fitWidth, fitHeight)); + } + } + + /** Zooms in to the next zoom level */ + public void zoomIn() { + // find the next valid zoom level + Double newScale = zoomLevels.higher(scale); + if (newScale != null) { + zoomTo(newScale); + } } - if (newScale > maxScale) { - newScale = maxScale; + + /** Zooms out to the previous zoom level */ + public void zoomOut() { + // find the next valid zoom level + Double newScale = zoomLevels.lower(scale); + if (newScale != null) { + zoomTo(newScale); + } } - if (newScale == scale) { - return; + + /** + * Converts canvas coordinates to draw coordinates + * + * @param point canvas coordinate + * @return draw coordinate as Point + */ + public Point getActualPoint(Point point) { + return new Point((int) (point.x / scale), (int) (point.y / scale)); } - // calculate the newScale and center point - double mag = newScale / scale; - Point p = - new Point( - viewport.getWidth() / 2 + viewport.getX(), viewport.getHeight() / 2 + viewport.getY()); - - // set scale directly - scale = newScale; - // zoom in - if (mag > 1.0) { - updateSize(); - updatePosition(p, mag); - // zoom out - } else { - updatePosition(p, mag); - updateSize(); + + /** + * Gets the zoom amount + * + * @return zoom scale + */ + public int getZoom() { + return (int) (scale * 100.0); } - // update the scrollpane and subclass - revalidate(); - } - /** Get the ideal zoom based on the viewSize */ - public void zoomFit() { - if (viewport.getWidth() != 0 && viewport.getHeight() != 0) { - double fitWidth = (viewport.getWidth() - 8.0) / viewSize.width; - double fitHeight = (viewport.getHeight() - 8.0) / viewSize.height; + /** + * Gets the scale for the dynamic dynamicView + * + * @return scale of the dynamic dynamicView + */ + public double getScale() { + return scale; + } - zoomTo(Math.min(fitWidth, fitHeight)); + /** + * Sets the background of the viewport + * + * @param c color of the background + */ + public void setBackground(Color c) { + viewport.setBackground(c); } - } - - /** Zooms in to the next zoom level */ - public void zoomIn() { - // find the next valid zoom level - Double newScale = zoomLevels.higher(scale); - if (newScale != null) { - zoomTo(newScale); + + /** + * Gets the dimension of the viewport + * + * @return dimension of the viewport + */ + public Dimension getSize() { + return viewSize; } - } - - /** Zooms out to the previous zoom level */ - public void zoomOut() { - // find the next valid zoom level - Double newScale = zoomLevels.lower(scale); - if (newScale != null) { - zoomTo(newScale); + + /** + * Sets the dimension of the viewport + * + * @param size new dimension of the viewport + */ + public void setSize(Dimension size) { + this.viewSize = size; + updateSize(); + } + + public ZoomablePane getCanvas() { + return canvas; + } + + /** + * Draws the ScrollView + * + * @param graphics2D Graphics2D object used for drawing + */ + protected void draw(Graphics2D graphics2D) { + graphics2D.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics2D.setRenderingHint( + RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + canvas.paint(graphics2D); + } + + /** + * Scroll up or down on the ScrollView + * + * @param mag The magnitude for scroll up positive is scroll up, negative is scroll down, + * recommend to use getWheelRotation() as the mag + */ + public void scroll(int mag) { + Point point = super.viewport.getViewPosition(); + // the point changing speed changes with the scale + point.y += mag * getZoom() / 20; + viewport.setViewPosition(point); + updateSize(); + revalidate(); } - } - - /** - * Converts canvas coordinates to draw coordinates - * - * @param point canvas coordinate - * @return draw coordinate as Point - */ - public Point getActualPoint(Point point) { - return new Point((int) (point.x / scale), (int) (point.y / scale)); - } - - /** - * Gets the zoom amount - * - * @return zoom scale - */ - public int getZoom() { - return (int) (scale * 100.0); - } - - /** - * Gets the scale for the dynamic dynamicView - * - * @return scale of the dynamic dynamicView - */ - public double getScale() { - return scale; - } - - /** - * Sets the background of the viewport - * - * @param c color of the background - */ - public void setBackground(Color c) { - viewport.setBackground(c); - } - - /** - * Gets the dimension of the viewport - * - * @return dimension of the viewport - */ - public Dimension getSize() { - return viewSize; - } - - /** - * Sets the dimension of the viewport - * - * @param size new dimension of the viewport - */ - public void setSize(Dimension size) { - this.viewSize = size; - updateSize(); - } - - public ZoomablePane getCanvas() { - return canvas; - } - - /** - * Draws the ScrollView - * - * @param graphics2D Graphics2D object used for drawing - */ - protected void draw(Graphics2D graphics2D) { - graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics2D.setRenderingHint( - RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); - canvas.paint(graphics2D); - } - - /** - * Scroll up or down on the ScrollView - * - * @param mag The magnitude for scroll up positive is scroll up, negative is scroll down, - * recommend to use getWheelRotation() as the mag - */ - public void scroll(int mag) { - Point point = super.viewport.getViewPosition(); - // the point changing speed changes with the scale - point.y += mag * getZoom() / 20; - viewport.setViewPosition(point); - updateSize(); - revalidate(); - } } diff --git a/src/main/java/edu/rpi/legup/ui/ToolbarName.java b/src/main/java/edu/rpi/legup/ui/ToolbarName.java index 1e0cbe7fb..ba02ebd2e 100644 --- a/src/main/java/edu/rpi/legup/ui/ToolbarName.java +++ b/src/main/java/edu/rpi/legup/ui/ToolbarName.java @@ -1,30 +1,30 @@ package edu.rpi.legup.ui; public enum ToolbarName { - HINT, - CHECK, - SUBMIT, - DIRECTIONS, - CHECK_ALL; + HINT, + CHECK, + SUBMIT, + DIRECTIONS, + CHECK_ALL; - /** - * Gets the String representation of the ToolbarName enum - * - * @return String representing the enum - */ - public String toString() { - String str = super.toString(); - str = str.replace("_", " "); - str = str.toLowerCase(); - str = str.substring(0, 1).toUpperCase() + str.substring(1); - for (int i = 0; i < str.length(); i++) { - if (str.charAt(i) == ' ') { - str = - str.substring(0, i + 1) - + str.substring(i + 1, i + 2).toUpperCase() - + str.substring(i + 2); - } + /** + * Gets the String representation of the ToolbarName enum + * + * @return String representing the enum + */ + public String toString() { + String str = super.toString(); + str = str.replace("_", " "); + str = str.toLowerCase(); + str = str.substring(0, 1).toUpperCase() + str.substring(1); + for (int i = 0; i < str.length(); i++) { + if (str.charAt(i) == ' ') { + str = + str.substring(0, i + 1) + + str.substring(i + 1, i + 2).toUpperCase() + + str.substring(i + 2); + } + } + return str; } - return str; - } } diff --git a/src/main/java/edu/rpi/legup/ui/WrapLayout.java b/src/main/java/edu/rpi/legup/ui/WrapLayout.java index 085e09738..1e25b36d2 100644 --- a/src/main/java/edu/rpi/legup/ui/WrapLayout.java +++ b/src/main/java/edu/rpi/legup/ui/WrapLayout.java @@ -6,162 +6,162 @@ /** FlowLayout subclass that fully supports wrapping of components. */ public class WrapLayout extends FlowLayout { - private Dimension preferredLayoutSize; - - /** - * Constructs a new WrapLayout with a left alignment and a default 5-unit horizontal - * and vertical gap. - */ - public WrapLayout() { - super(LEFT); - } - - /** - * Constructs a new FlowLayout with the specified alignment and a default 5-unit - * horizontal and vertical gap. The value of the alignment argument must be one of - * WrapLayout, WrapLayout, or WrapLayout. - * - * @param align the alignment value - */ - public WrapLayout(int align) { - super(align); - } - - /** - * Creates a new flow layout manager with the indicated alignment and the indicated horizontal and - * vertical gaps. - * - *

The value of the alignment argument must be one of WrapLayout, - * WrapLayout - * , or WrapLayout. - * - * @param align the alignment value - * @param hgap the horizontal gap between components - * @param vgap the vertical gap between components - */ - public WrapLayout(int align, int hgap, int vgap) { - super(align, hgap, vgap); - } - - /** - * Returns the preferred dimensions for this layout given the visible components in the specified - * target container. - * - * @param target the component which needs to be laid out - * @return the preferred dimensions to lay out the subcomponents of the specified container - */ - @Override - public Dimension preferredLayoutSize(Container target) { - return layoutSize(target, true); - } - - /** - * Returns the minimum dimensions needed to layout the visible components contained in the - * specified target container. - * - * @param target the component which needs to be laid out - * @return the minimum dimensions to lay out the subcomponents of the specified container - */ - @Override - public Dimension minimumLayoutSize(Container target) { - Dimension minimum = layoutSize(target, false); - minimum.width -= (getHgap() + 1); - return minimum; - } - - /** - * Returns the minimum or preferred dimension needed to layout the target container. - * - * @param target target to get layout dimension for - * @param preferred should preferred dimension be calculated - * @return the dimension to layout the target container - */ - private Dimension layoutSize(Container target, boolean preferred) { - synchronized (target.getTreeLock()) { - // Each row must fit with the width allocated to the containter. - // When the container width = 0, the preferred width of the container - // has not yet been calculated so lets ask for the maximum. - - int targetWidth = target.getSize().width; - - if (targetWidth == 0) { - targetWidth = Integer.MAX_VALUE; - } - - int hgap = getHgap(); - int vgap = getVgap(); - Insets insets = target.getInsets(); - int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); - int maxWidth = targetWidth - horizontalInsetsAndGap; - - // Fit components into the allowed width - - Dimension dim = new Dimension(0, 0); - int rowWidth = 0; - int rowHeight = 0; - - int nmembers = target.getComponentCount(); - - for (int i = 0; i < nmembers; i++) { - Component m = target.getComponent(i); - - if (m.isVisible()) { - Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); - - // Can't add the component to current row. Start a new row. - - if (rowWidth + d.width > maxWidth) { - addRow(dim, rowWidth, rowHeight); - rowWidth = 0; - rowHeight = 0; - } + private Dimension preferredLayoutSize; + + /** + * Constructs a new WrapLayout with a left alignment and a default 5-unit + * horizontal and vertical gap. + */ + public WrapLayout() { + super(LEFT); + } - // Add a horizontal gap for all components after the first + /** + * Constructs a new FlowLayout with the specified alignment and a default 5-unit + * horizontal and vertical gap. The value of the alignment argument must be one of + * WrapLayout, WrapLayout, or WrapLayout. + * + * @param align the alignment value + */ + public WrapLayout(int align) { + super(align); + } - if (rowWidth != 0) { - rowWidth += hgap; - } + /** + * Creates a new flow layout manager with the indicated alignment and the indicated horizontal + * and vertical gaps. + * + *

The value of the alignment argument must be one of WrapLayout, + * WrapLayout + * , or WrapLayout. + * + * @param align the alignment value + * @param hgap the horizontal gap between components + * @param vgap the vertical gap between components + */ + public WrapLayout(int align, int hgap, int vgap) { + super(align, hgap, vgap); + } - rowWidth += d.width; - rowHeight = Math.max(rowHeight, d.height); - } - } + /** + * Returns the preferred dimensions for this layout given the visible components in the + * specified target container. + * + * @param target the component which needs to be laid out + * @return the preferred dimensions to lay out the subcomponents of the specified container + */ + @Override + public Dimension preferredLayoutSize(Container target) { + return layoutSize(target, true); + } + + /** + * Returns the minimum dimensions needed to layout the visible components contained in the + * specified target container. + * + * @param target the component which needs to be laid out + * @return the minimum dimensions to lay out the subcomponents of the specified container + */ + @Override + public Dimension minimumLayoutSize(Container target) { + Dimension minimum = layoutSize(target, false); + minimum.width -= (getHgap() + 1); + return minimum; + } - addRow(dim, rowWidth, rowHeight); + /** + * Returns the minimum or preferred dimension needed to layout the target container. + * + * @param target target to get layout dimension for + * @param preferred should preferred dimension be calculated + * @return the dimension to layout the target container + */ + private Dimension layoutSize(Container target, boolean preferred) { + synchronized (target.getTreeLock()) { + // Each row must fit with the width allocated to the containter. + // When the container width = 0, the preferred width of the container + // has not yet been calculated so lets ask for the maximum. - dim.width += horizontalInsetsAndGap; - dim.height += insets.top + insets.bottom + vgap * 2; + int targetWidth = target.getSize().width; - // When using a scroll pane or the DecoratedLookAndFeel we need to - // make sure the preferred dimension is less than the dimension of the - // target containter so shrinking the container dimension works - // correctly. Removing the horizontal gap is an easy way to do this. + if (targetWidth == 0) { + targetWidth = Integer.MAX_VALUE; + } - Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); + int hgap = getHgap(); + int vgap = getVgap(); + Insets insets = target.getInsets(); + int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); + int maxWidth = targetWidth - horizontalInsetsAndGap; - if (scrollPane != null) { - dim.width -= (hgap + 1); - } + // Fit components into the allowed width - return dim; - } - } - - /** - * A new row has been completed. Use the dimensions of this row to update the preferred dimension - * for the container. - * - * @param dim update the width and height when appropriate - * @param rowWidth the width of the row to add - * @param rowHeight the height of the row to add - */ - private void addRow(Dimension dim, int rowWidth, int rowHeight) { - dim.width = Math.max(dim.width, rowWidth); - - if (dim.height > 0) { - dim.height += getVgap(); + Dimension dim = new Dimension(0, 0); + int rowWidth = 0; + int rowHeight = 0; + + int nmembers = target.getComponentCount(); + + for (int i = 0; i < nmembers; i++) { + Component m = target.getComponent(i); + + if (m.isVisible()) { + Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize(); + + // Can't add the component to current row. Start a new row. + + if (rowWidth + d.width > maxWidth) { + addRow(dim, rowWidth, rowHeight); + rowWidth = 0; + rowHeight = 0; + } + + // Add a horizontal gap for all components after the first + + if (rowWidth != 0) { + rowWidth += hgap; + } + + rowWidth += d.width; + rowHeight = Math.max(rowHeight, d.height); + } + } + + addRow(dim, rowWidth, rowHeight); + + dim.width += horizontalInsetsAndGap; + dim.height += insets.top + insets.bottom + vgap * 2; + + // When using a scroll pane or the DecoratedLookAndFeel we need to + // make sure the preferred dimension is less than the dimension of the + // target containter so shrinking the container dimension works + // correctly. Removing the horizontal gap is an easy way to do this. + + Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target); + + if (scrollPane != null) { + dim.width -= (hgap + 1); + } + + return dim; + } } - dim.height += rowHeight; - } + /** + * A new row has been completed. Use the dimensions of this row to update the preferred + * dimension for the container. + * + * @param dim update the width and height when appropriate + * @param rowWidth the width of the row to add + * @param rowHeight the height of the row to add + */ + private void addRow(Dimension dim, int rowWidth, int rowHeight) { + dim.width = Math.max(dim.width, rowWidth); + + if (dim.height > 0) { + dim.height += getVgap(); + } + + dim.height += rowHeight; + } } diff --git a/src/main/java/edu/rpi/legup/ui/ZoomWidget.java b/src/main/java/edu/rpi/legup/ui/ZoomWidget.java index 0afe0c2d1..aa5b65c4e 100644 --- a/src/main/java/edu/rpi/legup/ui/ZoomWidget.java +++ b/src/main/java/edu/rpi/legup/ui/ZoomWidget.java @@ -11,46 +11,46 @@ import javax.swing.event.ChangeListener; public class ZoomWidget extends JLabel { - private ScrollView parent; - private PopupSlider palette = new PopupSlider(); - private MouseAdapter open = - new MouseAdapter() { - public void mouseClicked(MouseEvent e) { - palette.slider.setValue(parent.getZoom()); - palette.show(e.getComponent(), 0, 0); - } - }; - - /** - * ZoomWidget Constructor creates a zoom widget for a ScrollView object - * - * @param parent dynamicView to which to the ZoomWidget is applied to - */ - public ZoomWidget(ScrollView parent) { - super(new ImageIcon("zoom.png")); - this.parent = parent; - addMouseListener(open); - } - - /** */ - private class PopupSlider extends JPopupMenu implements ChangeListener { - private static final long serialVersionUID = 8225019381200459814L; - - private JSlider slider; - - public PopupSlider() { - slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 200); - slider.setMajorTickSpacing(25); - slider.setPaintTicks(true); - - add(slider); - slider.addChangeListener(this); + private ScrollView parent; + private PopupSlider palette = new PopupSlider(); + private MouseAdapter open = + new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + palette.slider.setValue(parent.getZoom()); + palette.show(e.getComponent(), 0, 0); + } + }; + + /** + * ZoomWidget Constructor creates a zoom widget for a ScrollView object + * + * @param parent dynamicView to which to the ZoomWidget is applied to + */ + public ZoomWidget(ScrollView parent) { + super(new ImageIcon("zoom.png")); + this.parent = parent; + addMouseListener(open); } - public void stateChanged(ChangeEvent e) { - if (slider.getValueIsAdjusting()) { - parent.zoomTo((double) slider.getValue() / 100.0); - } + /** */ + private class PopupSlider extends JPopupMenu implements ChangeListener { + private static final long serialVersionUID = 8225019381200459814L; + + private JSlider slider; + + public PopupSlider() { + slider = new JSlider(SwingConstants.VERTICAL, 0, 400, 200); + slider.setMajorTickSpacing(25); + slider.setPaintTicks(true); + + add(slider); + slider.addChangeListener(this); + } + + public void stateChanged(ChangeEvent e) { + if (slider.getValueIsAdjusting()) { + parent.zoomTo((double) slider.getValue() / 100.0); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/ZoomablePane.java b/src/main/java/edu/rpi/legup/ui/ZoomablePane.java index 121047448..934d31c53 100644 --- a/src/main/java/edu/rpi/legup/ui/ZoomablePane.java +++ b/src/main/java/edu/rpi/legup/ui/ZoomablePane.java @@ -6,35 +6,35 @@ import javax.swing.*; public class ZoomablePane extends JLayeredPane { - private ScrollView viewer; + private ScrollView viewer; - /** - * ZoomablePane Constructor creates scalable JComponent - * - * @param viewer dynamic dynamicView - */ - public ZoomablePane(ScrollView viewer) { - this.viewer = viewer; - } + /** + * ZoomablePane Constructor creates scalable JComponent + * + * @param viewer dynamic dynamicView + */ + public ZoomablePane(ScrollView viewer) { + this.viewer = viewer; + } - /** - * Paints the JComponents - * - * @param graphics graphics object used to paint the JComponent - */ - public void paint(Graphics graphics) { - Graphics2D graphics2D = (Graphics2D) graphics; - graphics2D.scale(viewer.getScale(), viewer.getScale()); - viewer.draw(graphics2D); - } + /** + * Paints the JComponents + * + * @param graphics graphics object used to paint the JComponent + */ + public void paint(Graphics graphics) { + Graphics2D graphics2D = (Graphics2D) graphics; + graphics2D.scale(viewer.getScale(), viewer.getScale()); + viewer.draw(graphics2D); + } - /** - * Processes an event and sends it to the dynamicView - * - * @param e AWTEvent to process - */ - protected void processEvent(AWTEvent e) { - viewer.dispatchEvent(e); - super.processEvent(e); - } + /** + * Processes an event and sends it to the dynamicView + * + * @param e AWTEvent to process + */ + protected void processEvent(AWTEvent e) { + viewer.dispatchEvent(e); + super.processEvent(e); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java b/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java index f917ef9b0..ca03f1e25 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/BoardView.java @@ -12,197 +12,201 @@ import java.util.ArrayList; public abstract class BoardView extends ScrollView implements IBoardListener { - protected TreeElement treeElement; - protected Board board; - protected ArrayList elementViews; - protected ElementController elementController; - protected ElementSelection selection; - - /** - * BoardView Constructor creates a view for the board object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - * @param elementController controller that handles the ui events - */ - public BoardView(BoardController boardController, ElementController elementController) { - super(boardController); - this.treeElement = null; - this.board = null; - this.elementViews = new ArrayList<>(); - this.elementController = elementController; - this.selection = new ElementSelection(); - - elementController.setBoardView(this); - addMouseListener(elementController); - addMouseMotionListener(elementController); - addKeyListener(elementController); - } - - /** Initializes the initial dimension of the viewport for the BoardView */ - public abstract void initSize(); - - /** - * Gets the dimension of the board view - * - * @return dimension of the board view - */ - protected abstract Dimension getProperSize(); - - /** - * Gets the ElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return ElementView at the specified index - */ - public abstract ElementView getElement(int index); - - /** - * Sets the ElementView list - * - * @param elements ElementView list - */ - public void setElementViews(ArrayList elements) { - elementViews = elements; - } - - /** - * Gets the ElementView from the location specified or null if one does not exists at that - * location - * - * @param point location on the viewport - * @return ElementView at the specified location - */ - public ElementView getElement(Point point) { - Point scaledPoint = - new Point((int) Math.round(point.x / getScale()), (int) Math.round(point.y / getScale())); - for (ElementView element : elementViews) { - if (element.isWithinBounds(scaledPoint)) { - return element; - } - } - return null; - } - - /** - * Gets the ElementSelection for this BoardView - * - * @return the ElementSelection - */ - public ElementSelection getSelection() { - return selection; - } - - /** - * Gets the board associated with this view - * - * @return board - */ - public Board getBoard() { - return board; - } - - /** - * Sets the board associated with this view - * - * @param board board - */ - public void setBoard(Board board) { - if (this.board != board) { - this.board = board; - - if (board instanceof CaseBoard) { - setCasePickable(); - } else { + protected TreeElement treeElement; + protected Board board; + protected ArrayList elementViews; + protected ElementController elementController; + protected ElementSelection selection; + + /** + * BoardView Constructor creates a view for the board object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + * @param elementController controller that handles the ui events + */ + public BoardView(BoardController boardController, ElementController elementController) { + super(boardController); + this.treeElement = null; + this.board = null; + this.elementViews = new ArrayList<>(); + this.elementController = elementController; + this.selection = new ElementSelection(); + + elementController.setBoardView(this); + addMouseListener(elementController); + addMouseMotionListener(elementController); + addKeyListener(elementController); + } + + /** Initializes the initial dimension of the viewport for the BoardView */ + public abstract void initSize(); + + /** + * Gets the dimension of the board view + * + * @return dimension of the board view + */ + protected abstract Dimension getProperSize(); + + /** + * Gets the ElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return ElementView at the specified index + */ + public abstract ElementView getElement(int index); + + /** + * Sets the ElementView list + * + * @param elements ElementView list + */ + public void setElementViews(ArrayList elements) { + elementViews = elements; + } + + /** + * Gets the ElementView from the location specified or null if one does not exists at that + * location + * + * @param point location on the viewport + * @return ElementView at the specified location + */ + public ElementView getElement(Point point) { + Point scaledPoint = + new Point( + (int) Math.round(point.x / getScale()), + (int) Math.round(point.y / getScale())); + for (ElementView element : elementViews) { + if (element.isWithinBounds(scaledPoint)) { + return element; + } + } + return null; + } + + /** + * Gets the ElementSelection for this BoardView + * + * @return the ElementSelection + */ + public ElementSelection getSelection() { + return selection; + } + + /** + * Gets the board associated with this view + * + * @return board + */ + public Board getBoard() { + return board; + } + + /** + * Sets the board associated with this view + * + * @param board board + */ + public void setBoard(Board board) { + if (this.board != board) { + this.board = board; + + if (board instanceof CaseBoard) { + setCasePickable(); + } else { + for (ElementView elementView : elementViews) { + elementView.setPuzzleElement( + board.getPuzzleElement(elementView.getPuzzleElement())); + elementView.setShowCasePicker(false); + } + } + } + } + + protected void setCasePickable() { + CaseBoard caseBoard = (CaseBoard) board; + Board baseBoard = caseBoard.getBaseBoard(); + for (ElementView elementView : elementViews) { - elementView.setPuzzleElement(board.getPuzzleElement(elementView.getPuzzleElement())); - elementView.setShowCasePicker(false); + PuzzleElement puzzleElement = + baseBoard.getPuzzleElement(elementView.getPuzzleElement()); + elementView.setPuzzleElement(puzzleElement); + elementView.setShowCasePicker(true); + elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); + } + } + + /** + * Called when the tree element has changed. + * + * @param treeElement tree element + */ + @Override + public void onTreeElementChanged(TreeElement treeElement) { + this.treeElement = treeElement; + setBoard(treeElement.getBoard()); + repaint(); + } + + /** + * Called when the a case board has been added to the view. + * + * @param caseBoard case board to be added + */ + @Override + public void onCaseBoardAdded(CaseBoard caseBoard) { + setBoard(caseBoard); + repaint(); + } + + public TreeElement getTreeElement() { + return this.treeElement; + } + + /** + * Gets the amount of edu.rpi.legup.puzzle elements for this board + * + * @return the amount of edu.rpi.legup.puzzle elements for this board + */ + public int getElementCount() { + return elementViews.size(); + } + + /** + * Gets the PuzzleElements associated with the BoardView + * + * @return list of PuzzleElements + */ + public ArrayList getElementViews() { + return elementViews; + } + + public ElementController getElementController() { + return elementController; + } + + @Override + public void draw(Graphics2D graphics2D) { + drawBoard(graphics2D); + } + + public void drawBoard(Graphics2D graphics2D) { + for (ElementView element : elementViews) { + element.draw(graphics2D); } - } - } - } - - protected void setCasePickable() { - CaseBoard caseBoard = (CaseBoard) board; - Board baseBoard = caseBoard.getBaseBoard(); - - for (ElementView elementView : elementViews) { - PuzzleElement puzzleElement = baseBoard.getPuzzleElement(elementView.getPuzzleElement()); - elementView.setPuzzleElement(puzzleElement); - elementView.setShowCasePicker(true); - elementView.setCaseRulePickable(caseBoard.isPickable(puzzleElement, null)); - } - } - - /** - * Called when the tree element has changed. - * - * @param treeElement tree element - */ - @Override - public void onTreeElementChanged(TreeElement treeElement) { - this.treeElement = treeElement; - setBoard(treeElement.getBoard()); - repaint(); - } - - /** - * Called when the a case board has been added to the view. - * - * @param caseBoard case board to be added - */ - @Override - public void onCaseBoardAdded(CaseBoard caseBoard) { - setBoard(caseBoard); - repaint(); - } - - public TreeElement getTreeElement() { - return this.treeElement; - } - - /** - * Gets the amount of edu.rpi.legup.puzzle elements for this board - * - * @return the amount of edu.rpi.legup.puzzle elements for this board - */ - public int getElementCount() { - return elementViews.size(); - } - - /** - * Gets the PuzzleElements associated with the BoardView - * - * @return list of PuzzleElements - */ - public ArrayList getElementViews() { - return elementViews; - } - - public ElementController getElementController() { - return elementController; - } - - @Override - public void draw(Graphics2D graphics2D) { - drawBoard(graphics2D); - } - - public void drawBoard(Graphics2D graphics2D) { - for (ElementView element : elementViews) { - element.draw(graphics2D); - } - } - - /** - * Called when the board puzzleElement changed - * - * @param puzzleElement puzzleElement of the puzzleElement that changed - */ - @Override - public void onBoardDataChanged(PuzzleElement puzzleElement) { - repaint(); - } - - public abstract DataSelectionView getSelectionPopupMenu(); + } + + /** + * Called when the board puzzleElement changed + * + * @param puzzleElement puzzleElement of the puzzleElement that changed + */ + @Override + public void onBoardDataChanged(PuzzleElement puzzleElement) { + repaint(); + } + + public abstract DataSelectionView getSelectionPopupMenu(); } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java b/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java index 3c6e78f5d..cedfa08fe 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/DataSelectionView.java @@ -7,8 +7,8 @@ public class DataSelectionView extends JPopupMenu { - public DataSelectionView(ElementController controller) { - setBackground(Color.GRAY); - setBorder(new BevelBorder(BevelBorder.RAISED)); - } + public DataSelectionView(ElementController controller) { + setBackground(Color.GRAY); + setBorder(new BevelBorder(BevelBorder.RAISED)); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java b/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java index cce569af3..8e6f2cb18 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/ElementSelection.java @@ -4,71 +4,71 @@ import java.util.ArrayList; public class ElementSelection { - private ArrayList selection; - private ElementView hover; - private Point mousePoint; + private ArrayList selection; + private ElementView hover; + private Point mousePoint; - public ElementSelection() { - this.selection = new ArrayList<>(); - this.hover = null; - this.mousePoint = null; - } + public ElementSelection() { + this.selection = new ArrayList<>(); + this.hover = null; + this.mousePoint = null; + } - public ArrayList getSelection() { - return selection; - } + public ArrayList getSelection() { + return selection; + } - public ElementView getFirstSelection() { - return selection.size() == 0 ? null : selection.get(0); - } + public ElementView getFirstSelection() { + return selection.size() == 0 ? null : selection.get(0); + } - public void toggleSelection(ElementView elementView) { - if (selection.contains(elementView)) { - selection.remove(elementView); - elementView.setSelected(false); - } else { - selection.add(elementView); - elementView.setSelected(true); + public void toggleSelection(ElementView elementView) { + if (selection.contains(elementView)) { + selection.remove(elementView); + elementView.setSelected(false); + } else { + selection.add(elementView); + elementView.setSelected(true); + } } - } - public void newSelection(ElementView elementView) { - clearSelection(); - selection.add(elementView); - elementView.setSelected(true); - } + public void newSelection(ElementView elementView) { + clearSelection(); + selection.add(elementView); + elementView.setSelected(true); + } - public void clearSelection() { - for (ElementView elementView : selection) { - elementView.setSelected(false); + public void clearSelection() { + for (ElementView elementView : selection) { + elementView.setSelected(false); + } + selection.clear(); } - selection.clear(); - } - public ElementView getHover() { - return hover; - } + public ElementView getHover() { + return hover; + } - public void newHover(ElementView newHovered) { - newHovered.setHover(true); - if (hover != null) { - hover.setHover(false); + public void newHover(ElementView newHovered) { + newHovered.setHover(true); + if (hover != null) { + hover.setHover(false); + } + hover = newHovered; } - hover = newHovered; - } - public void clearHover() { - if (hover != null) { - hover.setHover(false); - hover = null; + public void clearHover() { + if (hover != null) { + hover.setHover(false); + hover = null; + } } - } - public Point getMousePoint() { - return mousePoint; - } + public Point getMousePoint() { + return mousePoint; + } - public void setMousePoint(Point point) { - this.mousePoint = point; - } + public void setMousePoint(Point point) { + this.mousePoint = point; + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java b/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java index 6cca76bcd..83b2cb099 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/ElementView.java @@ -10,331 +10,338 @@ import javax.swing.*; public abstract class ElementView implements Shape { - protected int index; - protected Point location; - protected Dimension size; - protected PuzzleElement puzzleElement; - private Color hoverColor; - private Color modifiedColor; - private Color caseColor; - private Color invalidColor; - private boolean showCasePicker; - private boolean isCaseRulePickable; - private boolean isHover; - private boolean isSelected; - - /** - * ElementView Constructor creates a puzzleElement view - * - * @param puzzleElement puzzleElement to which the view uses to draw - */ - public ElementView(PuzzleElement puzzleElement) { - this.puzzleElement = puzzleElement; - this.hoverColor = new Color(0x79, 0x86, 0xCB, 255); - this.modifiedColor = new Color(0x64, 0xDD, 0x17, 255); - this.caseColor = new Color(0x1A, 0x23, 0x7E, 200); - this.invalidColor = new Color(0xf4, 0x43, 0x36, 200); - this.isHover = false; - this.isSelected = false; - this.isCaseRulePickable = false; - } - - /** - * Determines if the specified point is within the ElementView - * - * @param point point to check - * @return true if the point is within the ElementView, false otherwise - */ - public boolean isWithinBounds(Point point) { - return point.x >= location.x - && point.x <= location.x + size.width - && point.y >= location.y - && point.y <= location.y + size.height; - } - - /** - * Draws the puzzle element on the screen - * - * @param graphics2D graphics2D object used for drawing - */ - public void draw(Graphics2D graphics2D) { - drawElement(graphics2D); - if (puzzleElement.isGiven()) { - drawGiven(graphics2D); - } - if (puzzleElement.isModified()) { - drawModified(graphics2D); - } - if (showCasePicker && isCaseRulePickable) { - drawCase(graphics2D); - } - if (isHover) { - drawHover(graphics2D); - } - } - - public void drawElement(Graphics2D graphics2D) { - graphics2D.setStroke(new BasicStroke(1)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 0.5f, location.y + 0.5f, size.width - 2, size.height - 2)); - - graphics2D.setColor(Color.BLACK); - FontMetrics metrics = graphics2D.getFontMetrics(graphics2D.getFont()); - String value = String.valueOf(puzzleElement.getData()); - int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; - int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); - graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); - } - - public void drawGiven(Graphics2D graphics2D) {} - - public void drawHover(Graphics2D graphics2D) { - graphics2D.setColor(hoverColor); - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public void drawModified(Graphics2D graphics2D) { - graphics2D.setColor(puzzleElement.isValid() ? modifiedColor : invalidColor); - graphics2D.setStroke(new BasicStroke(2)); - graphics2D.draw( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public void drawCase(Graphics2D graphics2D) { - graphics2D.setColor(caseColor); - graphics2D.fill( - new Rectangle2D.Double( - location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); - } - - public BufferedImage getImage() { - BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics2D = image.createGraphics(); - drawElement(graphics2D); - graphics2D.dispose(); - return image; - } - - /** - * Gets the index of the ElementView - * - * @return index of the ElementView - */ - public int getIndex() { - return index; - } - - /** - * Sets the index of the ElementView - * - * @param index index of the ElementView - */ - public void setIndex(int index) { - this.index = index; - } - - /** - * Gets the location of the ElementView - * - * @return location of the ElementView - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the ElementView - * - * @param location location of the ElementView - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Gets the dimension of the ElementView - * - * @return dimension of the ElementView - */ - public Dimension getSize() { - return size; - } - - /** - * Sets the dimension of the ElementView - * - * @param size dimension of the ElementView - */ - public void setSize(Dimension size) { - this.size = size; - } - - /** - * Gets the PuzzleElement associated with this view - * - * @return PuzzleElement associated with this view - */ - public PuzzleElement getPuzzleElement() { - return puzzleElement; - } - - /** - * Sets the PuzzleElement associated with this view - * - * @param data PuzzleElement associated with this view - */ - public void setPuzzleElement(PuzzleElement data) { - this.puzzleElement = data; - } - - public boolean isShowCasePicker() { - return showCasePicker; - } - - public void setShowCasePicker(boolean showCasePicker) { - this.showCasePicker = showCasePicker; - } - - /** - * Gets the isCaseRulePickable field to determine if this ElementView should be highlighted in - * some way to indicate if it can be chosen by the CaseRule - * - * @return true if the ElementView can be chosen for the CaseRule, false otherwise - */ - public boolean isCaseRulePickable() { - return isCaseRulePickable; - } - - /** - * Sets the isCaseRulePickable field to determine if this ElementView should be highlighted in - * some way to indicate if it can be chosen by the CaseRule - * - * @param isCaseRulePickable true if the ElementView can be chosen for the CaseRule, false - * otherwise - */ - public void setCaseRulePickable(boolean isCaseRulePickable) { - this.isCaseRulePickable = isCaseRulePickable; - } - - /** - * Gets the high-light color - * - * @return high-light color - */ - public Color getHoverColor() { - return hoverColor; - } - - /** - * Sets the high-light color - * - * @param hoverColor high-light color - */ - public void setHoverColor(Color hoverColor) { - this.hoverColor = hoverColor; - } - - /** - * Gets whether the puzzleElement is currently being hovered over - * - * @return true if the puzzleElement is currently being hover over, false otherwise - */ - public boolean isHover() { - return isHover; - } - - /** - * Sets whether the puzzleElement is being hover over - * - * @param hover true if the puzzleElement is correctly being hover over, false otherwise - */ - public void setHover(boolean hover) { - isHover = hover; - } - - /** - * Gets whether the puzzleElement is being selected - * - * @return tue if the puzzleElement is currently selected, false otherwise - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets whether the puzzleElement is being selected - * - * @param selected tue if the puzzleElement is currently selected, false otherwise - */ - public void setSelected(boolean selected) { - isSelected = selected; - } - - public JMenuItem getSelectionMenuItem() { - JMenuItem item = new JMenuItem(puzzleElement.getData() + ""); - return item; - } - - @Override - public boolean contains(double x, double y) { - return x >= location.x - && x <= location.x + size.width - && y >= location.y - && y <= location.y + size.height; - } - - @Override - public boolean contains(Point2D point) { - return contains(point.getX(), point.getY()); - } - - @Override - public boolean intersects(double x, double y, double width, double height) { - return (x + width >= location.x && x <= location.x + size.width) - || (y + height >= location.y && y <= location.y + size.height); - } - - @Override - public boolean intersects(Rectangle2D rectangle2D) { - return intersects( - rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); - } - - @Override - public boolean contains(double x, double y, double width, double height) { - return (x + width >= location.x && x <= location.x + size.width) - && (y + height >= location.y && y <= location.y + size.height); - } - - @Override - public boolean contains(Rectangle2D rectangle2D) { - return contains( - rectangle2D.getX(), rectangle2D.getY(), rectangle2D.getWidth(), rectangle2D.getHeight()); - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at); - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return new Rectangle(location.x, location.y, size.width, size.height) - .getPathIterator(at, flatness); - } - - @Override - public Rectangle getBounds() { - return new Rectangle(location.x, location.y, size.width, size.height); - } - - @Override - public Rectangle2D getBounds2D() { - return new Rectangle(location.x, location.y, size.width, size.height); - } + protected int index; + protected Point location; + protected Dimension size; + protected PuzzleElement puzzleElement; + private Color hoverColor; + private Color modifiedColor; + private Color caseColor; + private Color invalidColor; + private boolean showCasePicker; + private boolean isCaseRulePickable; + private boolean isHover; + private boolean isSelected; + + /** + * ElementView Constructor creates a puzzleElement view + * + * @param puzzleElement puzzleElement to which the view uses to draw + */ + public ElementView(PuzzleElement puzzleElement) { + this.puzzleElement = puzzleElement; + this.hoverColor = new Color(0x79, 0x86, 0xCB, 255); + this.modifiedColor = new Color(0x64, 0xDD, 0x17, 255); + this.caseColor = new Color(0x1A, 0x23, 0x7E, 200); + this.invalidColor = new Color(0xf4, 0x43, 0x36, 200); + this.isHover = false; + this.isSelected = false; + this.isCaseRulePickable = false; + } + + /** + * Determines if the specified point is within the ElementView + * + * @param point point to check + * @return true if the point is within the ElementView, false otherwise + */ + public boolean isWithinBounds(Point point) { + return point.x >= location.x + && point.x <= location.x + size.width + && point.y >= location.y + && point.y <= location.y + size.height; + } + + /** + * Draws the puzzle element on the screen + * + * @param graphics2D graphics2D object used for drawing + */ + public void draw(Graphics2D graphics2D) { + drawElement(graphics2D); + if (puzzleElement.isGiven()) { + drawGiven(graphics2D); + } + if (puzzleElement.isModified()) { + drawModified(graphics2D); + } + if (showCasePicker && isCaseRulePickable) { + drawCase(graphics2D); + } + if (isHover) { + drawHover(graphics2D); + } + } + + public void drawElement(Graphics2D graphics2D) { + graphics2D.setStroke(new BasicStroke(1)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 0.5f, location.y + 0.5f, size.width - 2, size.height - 2)); + + graphics2D.setColor(Color.BLACK); + FontMetrics metrics = graphics2D.getFontMetrics(graphics2D.getFont()); + String value = String.valueOf(puzzleElement.getData()); + int xText = location.x + (size.width - metrics.stringWidth(value)) / 2; + int yText = location.y + ((size.height - metrics.getHeight()) / 2) + metrics.getAscent(); + graphics2D.drawString(String.valueOf(puzzleElement.getData()), xText, yText); + } + + public void drawGiven(Graphics2D graphics2D) {} + + public void drawHover(Graphics2D graphics2D) { + graphics2D.setColor(hoverColor); + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public void drawModified(Graphics2D graphics2D) { + graphics2D.setColor(puzzleElement.isValid() ? modifiedColor : invalidColor); + graphics2D.setStroke(new BasicStroke(2)); + graphics2D.draw( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public void drawCase(Graphics2D graphics2D) { + graphics2D.setColor(caseColor); + graphics2D.fill( + new Rectangle2D.Double( + location.x + 1.5f, location.y + 1.5f, size.width - 3, size.height - 3)); + } + + public BufferedImage getImage() { + BufferedImage image = + new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); + Graphics2D graphics2D = image.createGraphics(); + drawElement(graphics2D); + graphics2D.dispose(); + return image; + } + + /** + * Gets the index of the ElementView + * + * @return index of the ElementView + */ + public int getIndex() { + return index; + } + + /** + * Sets the index of the ElementView + * + * @param index index of the ElementView + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Gets the location of the ElementView + * + * @return location of the ElementView + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the ElementView + * + * @param location location of the ElementView + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Gets the dimension of the ElementView + * + * @return dimension of the ElementView + */ + public Dimension getSize() { + return size; + } + + /** + * Sets the dimension of the ElementView + * + * @param size dimension of the ElementView + */ + public void setSize(Dimension size) { + this.size = size; + } + + /** + * Gets the PuzzleElement associated with this view + * + * @return PuzzleElement associated with this view + */ + public PuzzleElement getPuzzleElement() { + return puzzleElement; + } + + /** + * Sets the PuzzleElement associated with this view + * + * @param data PuzzleElement associated with this view + */ + public void setPuzzleElement(PuzzleElement data) { + this.puzzleElement = data; + } + + public boolean isShowCasePicker() { + return showCasePicker; + } + + public void setShowCasePicker(boolean showCasePicker) { + this.showCasePicker = showCasePicker; + } + + /** + * Gets the isCaseRulePickable field to determine if this ElementView should be highlighted in + * some way to indicate if it can be chosen by the CaseRule + * + * @return true if the ElementView can be chosen for the CaseRule, false otherwise + */ + public boolean isCaseRulePickable() { + return isCaseRulePickable; + } + + /** + * Sets the isCaseRulePickable field to determine if this ElementView should be highlighted in + * some way to indicate if it can be chosen by the CaseRule + * + * @param isCaseRulePickable true if the ElementView can be chosen for the CaseRule, false + * otherwise + */ + public void setCaseRulePickable(boolean isCaseRulePickable) { + this.isCaseRulePickable = isCaseRulePickable; + } + + /** + * Gets the high-light color + * + * @return high-light color + */ + public Color getHoverColor() { + return hoverColor; + } + + /** + * Sets the high-light color + * + * @param hoverColor high-light color + */ + public void setHoverColor(Color hoverColor) { + this.hoverColor = hoverColor; + } + + /** + * Gets whether the puzzleElement is currently being hovered over + * + * @return true if the puzzleElement is currently being hover over, false otherwise + */ + public boolean isHover() { + return isHover; + } + + /** + * Sets whether the puzzleElement is being hover over + * + * @param hover true if the puzzleElement is correctly being hover over, false otherwise + */ + public void setHover(boolean hover) { + isHover = hover; + } + + /** + * Gets whether the puzzleElement is being selected + * + * @return tue if the puzzleElement is currently selected, false otherwise + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets whether the puzzleElement is being selected + * + * @param selected tue if the puzzleElement is currently selected, false otherwise + */ + public void setSelected(boolean selected) { + isSelected = selected; + } + + public JMenuItem getSelectionMenuItem() { + JMenuItem item = new JMenuItem(puzzleElement.getData() + ""); + return item; + } + + @Override + public boolean contains(double x, double y) { + return x >= location.x + && x <= location.x + size.width + && y >= location.y + && y <= location.y + size.height; + } + + @Override + public boolean contains(Point2D point) { + return contains(point.getX(), point.getY()); + } + + @Override + public boolean intersects(double x, double y, double width, double height) { + return (x + width >= location.x && x <= location.x + size.width) + || (y + height >= location.y && y <= location.y + size.height); + } + + @Override + public boolean intersects(Rectangle2D rectangle2D) { + return intersects( + rectangle2D.getX(), + rectangle2D.getY(), + rectangle2D.getWidth(), + rectangle2D.getHeight()); + } + + @Override + public boolean contains(double x, double y, double width, double height) { + return (x + width >= location.x && x <= location.x + size.width) + && (y + height >= location.y && y <= location.y + size.height); + } + + @Override + public boolean contains(Rectangle2D rectangle2D) { + return contains( + rectangle2D.getX(), + rectangle2D.getY(), + rectangle2D.getWidth(), + rectangle2D.getHeight()); + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return new Rectangle(location.x, location.y, size.width, size.height).getPathIterator(at); + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return new Rectangle(location.x, location.y, size.width, size.height) + .getPathIterator(at, flatness); + } + + @Override + public Rectangle getBounds() { + return new Rectangle(location.x, location.y, size.width, size.height); + } + + @Override + public Rectangle2D getBounds2D() { + return new Rectangle(location.x, location.y, size.width, size.height); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java b/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java index 34f41b60d..c40303192 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/GridBoardView.java @@ -6,80 +6,82 @@ import java.awt.Dimension; public class GridBoardView extends BoardView { - protected Dimension gridSize; - protected Dimension elementSize; + protected Dimension gridSize; + protected Dimension elementSize; - /** - * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - * @param gridSize dimension of the grid - * @param elementController controller that handles the ui events - */ - public GridBoardView( - BoardController boardController, ElementController elementController, Dimension gridSize) { - this(boardController, elementController); - this.gridSize = gridSize; - this.elementSize = new Dimension(30, 30); - initSize(); - } + /** + * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + * @param gridSize dimension of the grid + * @param elementController controller that handles the ui events + */ + public GridBoardView( + BoardController boardController, + ElementController elementController, + Dimension gridSize) { + this(boardController, elementController); + this.gridSize = gridSize; + this.elementSize = new Dimension(30, 30); + initSize(); + } - /** - * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui - * events - * - * @param boardController controller that handles the ui events - */ - private GridBoardView(BoardController boardController, ElementController elementController) { - super(boardController, elementController); - setBackground(new Color(0xE0E0E0)); - } + /** + * GridBoardView Constructor creates a GridBoardView object using the controller handle the ui + * events + * + * @param boardController controller that handles the ui events + */ + private GridBoardView(BoardController boardController, ElementController elementController) { + super(boardController, elementController); + setBackground(new Color(0xE0E0E0)); + } - /** - * Gets the GridElementView from the puzzleElement index or null if out of bounds - * - * @param index index of the ElementView - * @return GridElementView at the specified index - */ - public GridElementView getElement(int index) { - if (index < elementViews.size()) { - return (GridElementView) elementViews.get(index); + /** + * Gets the GridElementView from the puzzleElement index or null if out of bounds + * + * @param index index of the ElementView + * @return GridElementView at the specified index + */ + public GridElementView getElement(int index) { + if (index < elementViews.size()) { + return (GridElementView) elementViews.get(index); + } + return null; } - return null; - } - public GridElementView getElement(int xIndex, int yIndex) { - if (xIndex < gridSize.width && yIndex < gridSize.height) { - return (GridElementView) elementViews.get(yIndex * gridSize.width + xIndex); + public GridElementView getElement(int xIndex, int yIndex) { + if (xIndex < gridSize.width && yIndex < gridSize.height) { + return (GridElementView) elementViews.get(yIndex * gridSize.width + xIndex); + } + return null; } - return null; - } - /** Initializes the initial dimension of the viewport for the GridBoardView */ - @Override - public void initSize() { - setSize(getProperSize()); - zoomFit(); - } + /** Initializes the initial dimension of the viewport for the GridBoardView */ + @Override + public void initSize() { + setSize(getProperSize()); + zoomFit(); + } - /** - * Helper method to determine the proper dimension of the grid view - * - * @return proper dimension of the grid view - */ - protected Dimension getProperSize() { - Dimension boardViewSize = new Dimension(); - boardViewSize.width = gridSize.width * elementSize.width; - boardViewSize.height = gridSize.height * elementSize.height; - return boardViewSize; - } + /** + * Helper method to determine the proper dimension of the grid view + * + * @return proper dimension of the grid view + */ + protected Dimension getProperSize() { + Dimension boardViewSize = new Dimension(); + boardViewSize.width = gridSize.width * elementSize.width; + boardViewSize.height = gridSize.height * elementSize.height; + return boardViewSize; + } - public DataSelectionView getSelectionPopupMenu() { - return null; - } + public DataSelectionView getSelectionPopupMenu() { + return null; + } - public Dimension getElementSize() { - return this.elementSize; - } + public Dimension getElementSize() { + return this.elementSize; + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java b/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java index 4a3d84261..440b3a693 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/GridElementView.java @@ -3,7 +3,7 @@ import edu.rpi.legup.model.gameboard.GridCell; public class GridElementView extends ElementView { - public GridElementView(GridCell cell) { - super(cell); - } + public GridElementView(GridCell cell) { + super(cell); + } } diff --git a/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java b/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java index ee8060e3c..b2d3e31dd 100644 --- a/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java +++ b/src/main/java/edu/rpi/legup/ui/boardview/SelectionItemView.java @@ -4,28 +4,28 @@ import javax.swing.*; public class SelectionItemView extends JMenuItem { - private PuzzleElement data; + private PuzzleElement data; - public SelectionItemView(PuzzleElement data, Icon icon) { - super(icon); - this.data = data; - } + public SelectionItemView(PuzzleElement data, Icon icon) { + super(icon); + this.data = data; + } - public SelectionItemView(PuzzleElement data, String display) { - super(display); - this.data = data; - } + public SelectionItemView(PuzzleElement data, String display) { + super(display); + this.data = data; + } - public SelectionItemView(PuzzleElement data, int display) { - super(String.valueOf(display)); - this.data = data; - } + public SelectionItemView(PuzzleElement data, int display) { + super(String.valueOf(display)); + this.data = data; + } - public SelectionItemView(PuzzleElement data) { - this(data, (Integer) data.getData()); - } + public SelectionItemView(PuzzleElement data) { + this(data, (Integer) data.getData()); + } - public PuzzleElement getData() { - return data; - } + public PuzzleElement getData() { + return data; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java index 613822c14..8469343f3 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/LegupLookAndFeel.java @@ -10,334 +10,338 @@ import javax.swing.plaf.basic.BasicLookAndFeel; public class LegupLookAndFeel extends BasicLookAndFeel { - /** - * Return a short string that identifies this look and feel, e.g. "CDE/Motif". This string should - * be appropriate for a menu item. Distinct look and feels should have different names, e.g. a - * subclass of MotifLookAndFeel that changes the way a few components are rendered should be - * called "CDE/Motif My Way"; something that would be useful to a user trying to select a L&F - * from a list of names. - * - * @return short identifier for the look and feel - */ - @Override - public String getName() { - return "Legup"; - } - - /** - * Return a string that identifies this look and feel. This string will be used by - * applications/services that want to recognize well known look and feel implementations. - * Presently the well known names are "Motif", "Windows", "Mac", "Metal". Note that a LookAndFeel - * derived from a well known superclass that doesn't make any fundamental changes to the look or - * feel shouldn't override this method. - * - * @return identifier for the look and feel - */ - @Override - public String getID() { - return "Legup Look and Feel"; - } - - /** - * Return a one line description of this look and feel implementation, e.g. "The CDE/Motif Look - * and Feel". This string is intended for the user, e.g. in the title of a window or in a ToolTip - * message. - * - * @return short description for the look and feel - */ - @Override - public String getDescription() { - return "Material design look and feel for Legup"; - } - - /** - * If the underlying platform has a "native" look and feel, and this is an implementation of it, - * return {@code true}. For example, when the underlying platform is Solaris running CDE a - * CDE/Motif look and feel implementation would return {@code true}. - * - * @return {@code true} if this look and feel represents the underlying platform look and feel - */ - @Override - public boolean isNativeLookAndFeel() { - return true; - } - - /** - * Return {@code true} if the underlying platform supports and or permits this look and feel. This - * method returns {@code false} if the look and feel depends on special resources or legal - * agreements that aren't defined for the current platform. - * - * @return {@code true} if this is a supported look and feel - * @see UIManager#setLookAndFeel - */ - @Override - public boolean isSupportedLookAndFeel() { - return true; - } - - /** - * Initializes the look and feel. While this method is public, it should only be invoked by the - * {@code UIManager} when a look and feel is installed as the current look and feel. This method - * is invoked before the {@code UIManager} invokes {@code getDefaults}. This method is intended to - * perform any initialization for the look and feel. Subclasses should do any one-time setup they - * need here, rather than in a static initializer, because look and feel class objects may be - * loaded just to discover that {@code isSupportedLookAndFeel()} returns {@code false}. - * - * @see #uninitialize - * @see UIManager#setLookAndFeel - */ - @Override - public void initialize() { - super.initialize(); - } - - /** - * Populates {@code table} with mappings from {@code uiClassID} to the fully qualified name of the - * ui class. The value for a particular {@code uiClassID} is {@code "javax.swing.plaf.basic.Basic - * + uiClassID"}. For example, the value for the {@code uiClassID} {@code TreeUI} is {@code - * "javax.swing.plaf.basic.BasicTreeUI"}. - * - * @param table the {@code UIDefaults} instance the entries are added to - * @throws NullPointerException if {@code table} is {@code null} - * @see LookAndFeel - * @see #getDefaults - */ - @Override - protected void initClassDefaults(UIDefaults table) { - super.initClassDefaults(table); - - table.put("ButtonUI", MaterialButtonUI.class.getCanonicalName()); - table.put("TextFieldUI", MaterialTextFieldUI.class.getCanonicalName()); - table.put("PasswordFieldUI", MaterialPasswordFieldUI.class.getCanonicalName()); - table.put("TableUI", MaterialTableUI.class.getCanonicalName()); - table.put("TableHeaderUI", MaterialTableHeaderUI.class.getCanonicalName()); - table.put("TreeUI", MaterialTreeUI.class.getCanonicalName()); - table.put("SpinnerUI", MaterialSpinnerUI.class.getCanonicalName()); - table.put("PanelUI", MaterialPanelUI.class.getCanonicalName()); - table.put("LabelUI", MaterialLabelUI.class.getCanonicalName()); - table.put("MenuItemUI", MaterialMenuItemUI.class.getCanonicalName()); - // table.put ("MenuBarUI", .class.getCanonicalName()); - table.put("MenuUI", MaterialMenuUI.class.getCanonicalName()); - table.put("CheckBoxUI", MaterialCheckBoxUI.class.getCanonicalName()); - table.put("RadioButtonUI", MaterialRadioButtonUI.class.getCanonicalName()); - table.put("TabbedPaneUI", MaterialTabbedPaneUI.class.getCanonicalName()); - table.put("ToggleButtonUI", MaterialToggleButtonUI.class.getCanonicalName()); - table.put("ScrollBarUI", MaterialScrollBarUI.class.getCanonicalName()); - table.put("ComboBoxUI", MaterialComboBoxUI.class.getCanonicalName()); - table.put("PopupMenuUI", MaterialPopupMenuUI.class.getCanonicalName()); - table.put("ToolBarUI", MaterialToolBarUI.class.getCanonicalName()); - table.put("SliderUI", MaterialSliderUI.class.getCanonicalName()); - table.put("ProgressBarUI", MaterialProgressBarUI.class.getCanonicalName()); - table.put("RadioButtonMenuItemUI", MaterialRadioButtonMenuItemUI.class.getCanonicalName()); - table.put("CheckBoxMenuItemUI", MaterialCheckBoxMenuItemUI.class.getCanonicalName()); - table.put("TextPaneUI", MaterialTextPaneUI.class.getCanonicalName()); - table.put("EditorPaneUI", MaterialEditorPaneUI.class.getCanonicalName()); - table.put("SeparatorUI", MaterialSeparatorUI.class.getCanonicalName()); - table.put("FileChooserUI", MaterialFileChooserUI.class.getCanonicalName()); - table.put("ToolTipUI", MaterialToolTipUI.class.getCanonicalName()); - table.put("SplitPaneUI", MaterialSplitPaneUI.class.getCanonicalName()); - // table.put ("ColorChooserUI", ); - } - - @Override - protected void initComponentDefaults(UIDefaults table) { - super.initComponentDefaults(table); - - table.put("Button.highlight", MaterialColors.GRAY_300); - table.put("Button.opaque", false); - table.put("Button.border", BorderFactory.createEmptyBorder(7, 17, 7, 17)); - table.put("Button.background", MaterialColors.GRAY_200); - table.put("Button.foreground", Color.BLACK); - table.put("Button.font", MaterialFonts.MEDIUM); - - table.put("CheckBox.font", MaterialFonts.REGULAR); - table.put("CheckBox.background", Color.WHITE); - table.put("CheckBox.foreground", Color.BLACK); - table.put("CheckBox.icon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); - table.put("CheckBox.selectedIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); - - table.put("ComboBox.font", MaterialFonts.REGULAR); - table.put("ComboBox.background", Color.WHITE); - table.put("ComboBox.foreground", Color.BLACK); - table.put( - "ComboBox.border", - BorderFactory.createCompoundBorder( - MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(0, 5, 0, 0))); - table.put("ComboBox.buttonBackground", MaterialColors.GRAY_300); - table.put("ComboBox.selectionBackground", Color.WHITE); - table.put("ComboBox.selectionForeground", Color.BLACK); - table.put("ComboBox.selectedInDropDownBackground", MaterialColors.GRAY_200); - - table.put("Label.font", MaterialFonts.REGULAR); - table.put("Label.background", Color.WHITE); - table.put("Label.foreground", Color.BLACK); - table.put("Label.border", BorderFactory.createEmptyBorder()); - - table.put("Menu.font", MaterialFonts.BOLD); - table.put("Menu.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("Menu.background", Color.WHITE); - table.put("Menu.foreground", Color.BLACK); - table.put("Menu.opaque", true); - table.put("Menu.selectionBackground", MaterialColors.GRAY_200); - table.put("Menu.selectionForeground", Color.BLACK); - table.put("Menu.disabledForeground", new Color(0, 0, 0, 100)); - table.put("Menu.menuPopupOffsetY", 3); - - table.put("MenuBar.font", MaterialFonts.BOLD); - table.put("MenuBar.background", Color.WHITE); - table.put("MenuBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); - table.put("MenuBar.foreground", Color.BLACK); - - table.put("MenuItem.disabledForeground", new Color(0, 0, 0, 100)); - table.put("MenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("MenuItem.selectionForeground", Color.BLACK); - table.put("MenuItem.font", MaterialFonts.MEDIUM); - table.put("MenuItem.background", Color.WHITE); - table.put("MenuItem.foreground", Color.BLACK); - table.put("MenuItem.border", BorderFactory.createEmptyBorder(5, 0, 5, 0)); - - table.put("OptionPane.background", Color.WHITE); - table.put("OptionPane.border", MaterialBorders.DEFAULT_SHADOW_BORDER); - table.put("OptionPane.font", MaterialFonts.REGULAR); - - table.put("Panel.font", MaterialFonts.REGULAR); - table.put("Panel.background", Color.WHITE); - table.put("Panel.border", BorderFactory.createEmptyBorder()); - - table.put("PopupMenu.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("PopupMenu.background", Color.WHITE); - table.put("PopupMenu.foreground", Color.BLACK); - - table.put("RadioButton.font", MaterialFonts.REGULAR); - table.put("RadioButton.background", Color.WHITE); - table.put("RadioButton.foreground", Color.BLACK); - table.put("RadioButton.icon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); - table.put("RadioButton.selectedIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); - - table.put("Spinner.font", MaterialFonts.REGULAR); - table.put("Spinner.background", Color.WHITE); - table.put("Spinner.foreground", Color.BLACK); - table.put("Spinner.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("Spinner.arrowButtonBackground", MaterialColors.GRAY_200); - table.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); - - table.put("ScrollBar.font", MaterialFonts.REGULAR); - table.put("ScrollBar.track", MaterialColors.GRAY_200); - table.put("ScrollBar.thumb", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbDarkShadow", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbHighlight", MaterialColors.GRAY_300); - table.put("ScrollBar.thumbShadow", MaterialColors.GRAY_300); - table.put("ScrollBar.arrowButtonBackground", MaterialColors.GRAY_300); - table.put("ScrollBar.arrowButtonBorder", BorderFactory.createEmptyBorder()); - - table.put("ScrollPane.background", Color.WHITE); - table.put("ScrollPane.border", BorderFactory.createEmptyBorder()); - table.put("ScrollPane.font", MaterialFonts.REGULAR); - - table.put("Slider.font", MaterialFonts.REGULAR); - table.put("Slider.background", Color.WHITE); - table.put("Slider.foreground", MaterialColors.GRAY_700); - table.put("Slider.trackColor", Color.BLACK); - // table.put ("Slider.border", - // BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, - // BorderFactory.createEmptyBorder (5, 5, 5, 5))); - - table.put("SplitPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("SplitPane.background", Color.WHITE); - table.put("SplitPane.dividerSize", 10); - table.put("SplitPaneDivider.border", MaterialBorders.LIGHT_SHADOW_BORDER); - - table.put("TabbedPane.font", MaterialFonts.REGULAR); - table.put("TabbedPane.background", Color.WHITE); - table.put("TabbedPane.foreground", Color.BLACK); - table.put("TabbedPane.border", BorderFactory.createEmptyBorder()); - table.put("TabbedPane.shadow", null); - table.put("TabbedPane.darkShadow", null); - table.put("TabbedPane.highlight", MaterialColors.GRAY_200); - table.put("TabbedPane.borderHighlightColor", MaterialColors.GRAY_300); - - table.put("Table.selectionBackground", MaterialColors.GRAY_100); - table.put("Table.selectionForeground", Color.BLACK); - table.put("Table.background", Color.WHITE); - table.put("Table.font", MaterialFonts.REGULAR); - table.put("Table.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("Table.gridColor", MaterialColors.GRAY_200); - table.put("TableHeader.background", MaterialColors.GRAY_200); - table.put("TableHeader.font", MaterialFonts.BOLD); - table.put( - "TableHeader.cellBorder", - BorderFactory.createCompoundBorder( - MaterialBorders.LIGHT_LINE_BORDER, BorderFactory.createEmptyBorder(5, 5, 5, 5))); - - table.put("TextArea.background", MaterialColors.GRAY_200); - table.put("TextArea.border", BorderFactory.createEmptyBorder()); - table.put("TextArea.foreground", Color.BLACK); - - table.put("ToggleButton.border", BorderFactory.createEmptyBorder()); - table.put("ToggleButton.font", MaterialFonts.REGULAR); - table.put("ToggleButton.background", Color.WHITE); - table.put("ToggleButton.foreground", Color.BLACK); - table.put("ToggleButton.icon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_OFF)); - table.put("ToggleButton.selectedIcon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_ON)); - - table.put("ToolBar.font", MaterialFonts.REGULAR); - table.put("ToolBar.background", Color.WHITE); - table.put("ToolBar.foreground", Color.BLACK); - table.put("ToolBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); - table.put("ToolBar.dockingBackground", MaterialColors.LIGHT_GREEN_A100); - table.put("ToolBar.floatingBackground", MaterialColors.GRAY_200); - - table.put("Tree.font", MaterialFonts.REGULAR); - table.put("Tree.selectionForeground", Color.BLACK); - table.put("Tree.foreground", Color.BLACK); - table.put("Tree.selectionBackground", MaterialColors.GRAY_200); - table.put("Tree.background", Color.WHITE); - table.put("Tree.closedIcon", new ImageIcon(MaterialImages.RIGHT_ARROW)); - table.put("Tree.openIcon", new ImageIcon(MaterialImages.DOWN_ARROW)); - table.put("Tree.selectionBorderColor", null); - - table.put("RadioButtonMenuItem.foreground", Color.BLACK); - table.put("RadioButtonMenuItem.selectionForeground", Color.BLACK); - // If it changes the background of the menuitem it must change this too, irrespective of its - // setting - table.put("RadioButtonMenuItem.background", UIManager.getColor("MenuItem.background")); - table.put("RadioButtonMenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("RadioButtonMenuItem.checkIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); - table.put( - "RadioButtonMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); - - // If it changes the background of the menuitem it must change this too, irrespective of its - // setting - table.put("CheckBoxMenuItem.background", UIManager.getColor("MenuItem.background")); - table.put("CheckBoxMenuItem.selectionBackground", MaterialColors.GRAY_200); - table.put("CheckBoxMenuItem.foreground", Color.BLACK); - table.put("CheckBoxMenuItem.selectionForeground", Color.BLACK); - table.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - table.put("CheckBoxMenuItem.checkIcon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); - table.put( - "CheckBoxMenuItem.selectedCheckIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); - - table.put("TextPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("TextPane.background", MaterialColors.GRAY_50); - table.put("TextPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); - table.put("TextPane.inactiveForeground", MaterialColors.GRAY_500); - table.put("TextPane.font", MaterialFonts.REGULAR); - - table.put("EditorPane.border", MaterialBorders.LIGHT_LINE_BORDER); - table.put("EditorPane.background", MaterialColors.GRAY_50); - table.put("EditorPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); - table.put("EditorPane.inactiveForeground", MaterialColors.GRAY_500); - table.put("EditorPane.font", MaterialFonts.REGULAR); - - table.put("Separator.background", MaterialColors.GRAY_300); - table.put("Separator.foreground", MaterialColors.GRAY_300); - - table.put("ToolTip.background", MaterialColors.GRAY_500); - table.put("ToolTip.foreground", MaterialColors.GRAY_50); - table.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); - - table.put("ColorChooser.background", MaterialColors.WHITE); - table.put("ColorChooser.foreground", MaterialColors.BLACK); - } + /** + * Return a short string that identifies this look and feel, e.g. "CDE/Motif". This string + * should be appropriate for a menu item. Distinct look and feels should have different names, + * e.g. a subclass of MotifLookAndFeel that changes the way a few components are rendered should + * be called "CDE/Motif My Way"; something that would be useful to a user trying to select a + * L&F from a list of names. + * + * @return short identifier for the look and feel + */ + @Override + public String getName() { + return "Legup"; + } + + /** + * Return a string that identifies this look and feel. This string will be used by + * applications/services that want to recognize well known look and feel implementations. + * Presently the well known names are "Motif", "Windows", "Mac", "Metal". Note that a + * LookAndFeel derived from a well known superclass that doesn't make any fundamental changes to + * the look or feel shouldn't override this method. + * + * @return identifier for the look and feel + */ + @Override + public String getID() { + return "Legup Look and Feel"; + } + + /** + * Return a one line description of this look and feel implementation, e.g. "The CDE/Motif Look + * and Feel". This string is intended for the user, e.g. in the title of a window or in a + * ToolTip message. + * + * @return short description for the look and feel + */ + @Override + public String getDescription() { + return "Material design look and feel for Legup"; + } + + /** + * If the underlying platform has a "native" look and feel, and this is an implementation of it, + * return {@code true}. For example, when the underlying platform is Solaris running CDE a + * CDE/Motif look and feel implementation would return {@code true}. + * + * @return {@code true} if this look and feel represents the underlying platform look and feel + */ + @Override + public boolean isNativeLookAndFeel() { + return true; + } + + /** + * Return {@code true} if the underlying platform supports and or permits this look and feel. + * This method returns {@code false} if the look and feel depends on special resources or legal + * agreements that aren't defined for the current platform. + * + * @return {@code true} if this is a supported look and feel + * @see UIManager#setLookAndFeel + */ + @Override + public boolean isSupportedLookAndFeel() { + return true; + } + + /** + * Initializes the look and feel. While this method is public, it should only be invoked by the + * {@code UIManager} when a look and feel is installed as the current look and feel. This method + * is invoked before the {@code UIManager} invokes {@code getDefaults}. This method is intended + * to perform any initialization for the look and feel. Subclasses should do any one-time setup + * they need here, rather than in a static initializer, because look and feel class objects may + * be loaded just to discover that {@code isSupportedLookAndFeel()} returns {@code false}. + * + * @see #uninitialize + * @see UIManager#setLookAndFeel + */ + @Override + public void initialize() { + super.initialize(); + } + + /** + * Populates {@code table} with mappings from {@code uiClassID} to the fully qualified name of + * the ui class. The value for a particular {@code uiClassID} is {@code + * "javax.swing.plaf.basic.Basic + uiClassID"}. For example, the value for the {@code uiClassID} + * {@code TreeUI} is {@code "javax.swing.plaf.basic.BasicTreeUI"}. + * + * @param table the {@code UIDefaults} instance the entries are added to + * @throws NullPointerException if {@code table} is {@code null} + * @see LookAndFeel + * @see #getDefaults + */ + @Override + protected void initClassDefaults(UIDefaults table) { + super.initClassDefaults(table); + + table.put("ButtonUI", MaterialButtonUI.class.getCanonicalName()); + table.put("TextFieldUI", MaterialTextFieldUI.class.getCanonicalName()); + table.put("PasswordFieldUI", MaterialPasswordFieldUI.class.getCanonicalName()); + table.put("TableUI", MaterialTableUI.class.getCanonicalName()); + table.put("TableHeaderUI", MaterialTableHeaderUI.class.getCanonicalName()); + table.put("TreeUI", MaterialTreeUI.class.getCanonicalName()); + table.put("SpinnerUI", MaterialSpinnerUI.class.getCanonicalName()); + table.put("PanelUI", MaterialPanelUI.class.getCanonicalName()); + table.put("LabelUI", MaterialLabelUI.class.getCanonicalName()); + table.put("MenuItemUI", MaterialMenuItemUI.class.getCanonicalName()); + // table.put ("MenuBarUI", .class.getCanonicalName()); + table.put("MenuUI", MaterialMenuUI.class.getCanonicalName()); + table.put("CheckBoxUI", MaterialCheckBoxUI.class.getCanonicalName()); + table.put("RadioButtonUI", MaterialRadioButtonUI.class.getCanonicalName()); + table.put("TabbedPaneUI", MaterialTabbedPaneUI.class.getCanonicalName()); + table.put("ToggleButtonUI", MaterialToggleButtonUI.class.getCanonicalName()); + table.put("ScrollBarUI", MaterialScrollBarUI.class.getCanonicalName()); + table.put("ComboBoxUI", MaterialComboBoxUI.class.getCanonicalName()); + table.put("PopupMenuUI", MaterialPopupMenuUI.class.getCanonicalName()); + table.put("ToolBarUI", MaterialToolBarUI.class.getCanonicalName()); + table.put("SliderUI", MaterialSliderUI.class.getCanonicalName()); + table.put("ProgressBarUI", MaterialProgressBarUI.class.getCanonicalName()); + table.put("RadioButtonMenuItemUI", MaterialRadioButtonMenuItemUI.class.getCanonicalName()); + table.put("CheckBoxMenuItemUI", MaterialCheckBoxMenuItemUI.class.getCanonicalName()); + table.put("TextPaneUI", MaterialTextPaneUI.class.getCanonicalName()); + table.put("EditorPaneUI", MaterialEditorPaneUI.class.getCanonicalName()); + table.put("SeparatorUI", MaterialSeparatorUI.class.getCanonicalName()); + table.put("FileChooserUI", MaterialFileChooserUI.class.getCanonicalName()); + table.put("ToolTipUI", MaterialToolTipUI.class.getCanonicalName()); + table.put("SplitPaneUI", MaterialSplitPaneUI.class.getCanonicalName()); + // table.put ("ColorChooserUI", ); + } + + @Override + protected void initComponentDefaults(UIDefaults table) { + super.initComponentDefaults(table); + + table.put("Button.highlight", MaterialColors.GRAY_300); + table.put("Button.opaque", false); + table.put("Button.border", BorderFactory.createEmptyBorder(7, 17, 7, 17)); + table.put("Button.background", MaterialColors.GRAY_200); + table.put("Button.foreground", Color.BLACK); + table.put("Button.font", MaterialFonts.MEDIUM); + + table.put("CheckBox.font", MaterialFonts.REGULAR); + table.put("CheckBox.background", Color.WHITE); + table.put("CheckBox.foreground", Color.BLACK); + table.put("CheckBox.icon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); + table.put("CheckBox.selectedIcon", new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); + + table.put("ComboBox.font", MaterialFonts.REGULAR); + table.put("ComboBox.background", Color.WHITE); + table.put("ComboBox.foreground", Color.BLACK); + table.put( + "ComboBox.border", + BorderFactory.createCompoundBorder( + MaterialBorders.LIGHT_LINE_BORDER, + BorderFactory.createEmptyBorder(0, 5, 0, 0))); + table.put("ComboBox.buttonBackground", MaterialColors.GRAY_300); + table.put("ComboBox.selectionBackground", Color.WHITE); + table.put("ComboBox.selectionForeground", Color.BLACK); + table.put("ComboBox.selectedInDropDownBackground", MaterialColors.GRAY_200); + + table.put("Label.font", MaterialFonts.REGULAR); + table.put("Label.background", Color.WHITE); + table.put("Label.foreground", Color.BLACK); + table.put("Label.border", BorderFactory.createEmptyBorder()); + + table.put("Menu.font", MaterialFonts.BOLD); + table.put("Menu.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("Menu.background", Color.WHITE); + table.put("Menu.foreground", Color.BLACK); + table.put("Menu.opaque", true); + table.put("Menu.selectionBackground", MaterialColors.GRAY_200); + table.put("Menu.selectionForeground", Color.BLACK); + table.put("Menu.disabledForeground", new Color(0, 0, 0, 100)); + table.put("Menu.menuPopupOffsetY", 3); + + table.put("MenuBar.font", MaterialFonts.BOLD); + table.put("MenuBar.background", Color.WHITE); + table.put("MenuBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); + table.put("MenuBar.foreground", Color.BLACK); + + table.put("MenuItem.disabledForeground", new Color(0, 0, 0, 100)); + table.put("MenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("MenuItem.selectionForeground", Color.BLACK); + table.put("MenuItem.font", MaterialFonts.MEDIUM); + table.put("MenuItem.background", Color.WHITE); + table.put("MenuItem.foreground", Color.BLACK); + table.put("MenuItem.border", BorderFactory.createEmptyBorder(5, 0, 5, 0)); + + table.put("OptionPane.background", Color.WHITE); + table.put("OptionPane.border", MaterialBorders.DEFAULT_SHADOW_BORDER); + table.put("OptionPane.font", MaterialFonts.REGULAR); + + table.put("Panel.font", MaterialFonts.REGULAR); + table.put("Panel.background", Color.WHITE); + table.put("Panel.border", BorderFactory.createEmptyBorder()); + + table.put("PopupMenu.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("PopupMenu.background", Color.WHITE); + table.put("PopupMenu.foreground", Color.BLACK); + + table.put("RadioButton.font", MaterialFonts.REGULAR); + table.put("RadioButton.background", Color.WHITE); + table.put("RadioButton.foreground", Color.BLACK); + table.put("RadioButton.icon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); + table.put("RadioButton.selectedIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); + + table.put("Spinner.font", MaterialFonts.REGULAR); + table.put("Spinner.background", Color.WHITE); + table.put("Spinner.foreground", Color.BLACK); + table.put("Spinner.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("Spinner.arrowButtonBackground", MaterialColors.GRAY_200); + table.put("Spinner.arrowButtonBorder", BorderFactory.createEmptyBorder()); + + table.put("ScrollBar.font", MaterialFonts.REGULAR); + table.put("ScrollBar.track", MaterialColors.GRAY_200); + table.put("ScrollBar.thumb", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbDarkShadow", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbHighlight", MaterialColors.GRAY_300); + table.put("ScrollBar.thumbShadow", MaterialColors.GRAY_300); + table.put("ScrollBar.arrowButtonBackground", MaterialColors.GRAY_300); + table.put("ScrollBar.arrowButtonBorder", BorderFactory.createEmptyBorder()); + + table.put("ScrollPane.background", Color.WHITE); + table.put("ScrollPane.border", BorderFactory.createEmptyBorder()); + table.put("ScrollPane.font", MaterialFonts.REGULAR); + + table.put("Slider.font", MaterialFonts.REGULAR); + table.put("Slider.background", Color.WHITE); + table.put("Slider.foreground", MaterialColors.GRAY_700); + table.put("Slider.trackColor", Color.BLACK); + // table.put ("Slider.border", + // BorderFactory.createCompoundBorder(MaterialBorders.LIGHT_LINE_BORDER, + // BorderFactory.createEmptyBorder (5, 5, 5, 5))); + + table.put("SplitPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("SplitPane.background", Color.WHITE); + table.put("SplitPane.dividerSize", 10); + table.put("SplitPaneDivider.border", MaterialBorders.LIGHT_SHADOW_BORDER); + + table.put("TabbedPane.font", MaterialFonts.REGULAR); + table.put("TabbedPane.background", Color.WHITE); + table.put("TabbedPane.foreground", Color.BLACK); + table.put("TabbedPane.border", BorderFactory.createEmptyBorder()); + table.put("TabbedPane.shadow", null); + table.put("TabbedPane.darkShadow", null); + table.put("TabbedPane.highlight", MaterialColors.GRAY_200); + table.put("TabbedPane.borderHighlightColor", MaterialColors.GRAY_300); + + table.put("Table.selectionBackground", MaterialColors.GRAY_100); + table.put("Table.selectionForeground", Color.BLACK); + table.put("Table.background", Color.WHITE); + table.put("Table.font", MaterialFonts.REGULAR); + table.put("Table.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("Table.gridColor", MaterialColors.GRAY_200); + table.put("TableHeader.background", MaterialColors.GRAY_200); + table.put("TableHeader.font", MaterialFonts.BOLD); + table.put( + "TableHeader.cellBorder", + BorderFactory.createCompoundBorder( + MaterialBorders.LIGHT_LINE_BORDER, + BorderFactory.createEmptyBorder(5, 5, 5, 5))); + + table.put("TextArea.background", MaterialColors.GRAY_200); + table.put("TextArea.border", BorderFactory.createEmptyBorder()); + table.put("TextArea.foreground", Color.BLACK); + + table.put("ToggleButton.border", BorderFactory.createEmptyBorder()); + table.put("ToggleButton.font", MaterialFonts.REGULAR); + table.put("ToggleButton.background", Color.WHITE); + table.put("ToggleButton.foreground", Color.BLACK); + table.put("ToggleButton.icon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_OFF)); + table.put("ToggleButton.selectedIcon", new ImageIcon(MaterialImages.TOGGLE_BUTTON_ON)); + + table.put("ToolBar.font", MaterialFonts.REGULAR); + table.put("ToolBar.background", Color.WHITE); + table.put("ToolBar.foreground", Color.BLACK); + table.put("ToolBar.border", MaterialBorders.LIGHT_SHADOW_BORDER); + table.put("ToolBar.dockingBackground", MaterialColors.LIGHT_GREEN_A100); + table.put("ToolBar.floatingBackground", MaterialColors.GRAY_200); + + table.put("Tree.font", MaterialFonts.REGULAR); + table.put("Tree.selectionForeground", Color.BLACK); + table.put("Tree.foreground", Color.BLACK); + table.put("Tree.selectionBackground", MaterialColors.GRAY_200); + table.put("Tree.background", Color.WHITE); + table.put("Tree.closedIcon", new ImageIcon(MaterialImages.RIGHT_ARROW)); + table.put("Tree.openIcon", new ImageIcon(MaterialImages.DOWN_ARROW)); + table.put("Tree.selectionBorderColor", null); + + table.put("RadioButtonMenuItem.foreground", Color.BLACK); + table.put("RadioButtonMenuItem.selectionForeground", Color.BLACK); + // If it changes the background of the menuitem it must change this too, irrespective of its + // setting + table.put("RadioButtonMenuItem.background", UIManager.getColor("MenuItem.background")); + table.put("RadioButtonMenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("RadioButtonMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("RadioButtonMenuItem.checkIcon", new ImageIcon(MaterialImages.RADIO_BUTTON_OFF)); + table.put( + "RadioButtonMenuItem.selectedCheckIcon", + new ImageIcon(MaterialImages.RADIO_BUTTON_ON)); + + // If it changes the background of the menuitem it must change this too, irrespective of its + // setting + table.put("CheckBoxMenuItem.background", UIManager.getColor("MenuItem.background")); + table.put("CheckBoxMenuItem.selectionBackground", MaterialColors.GRAY_200); + table.put("CheckBoxMenuItem.foreground", Color.BLACK); + table.put("CheckBoxMenuItem.selectionForeground", Color.BLACK); + table.put("CheckBoxMenuItem.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + table.put("CheckBoxMenuItem.checkIcon", new ImageIcon(MaterialImages.UNCHECKED_BOX)); + table.put( + "CheckBoxMenuItem.selectedCheckIcon", + new ImageIcon(MaterialImages.PAINTED_CHECKED_BOX)); + + table.put("TextPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("TextPane.background", MaterialColors.GRAY_50); + table.put("TextPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); + table.put("TextPane.inactiveForeground", MaterialColors.GRAY_500); + table.put("TextPane.font", MaterialFonts.REGULAR); + + table.put("EditorPane.border", MaterialBorders.LIGHT_LINE_BORDER); + table.put("EditorPane.background", MaterialColors.GRAY_50); + table.put("EditorPane.selectionBackground", MaterialColors.LIGHT_BLUE_200); + table.put("EditorPane.inactiveForeground", MaterialColors.GRAY_500); + table.put("EditorPane.font", MaterialFonts.REGULAR); + + table.put("Separator.background", MaterialColors.GRAY_300); + table.put("Separator.foreground", MaterialColors.GRAY_300); + + table.put("ToolTip.background", MaterialColors.GRAY_500); + table.put("ToolTip.foreground", MaterialColors.GRAY_50); + table.put("ToolTip.border", BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + table.put("ColorChooser.background", MaterialColors.WHITE); + table.put("ColorChooser.foreground", MaterialColors.BLACK); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java index a0fdc487a..db7d604a0 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUIMovement.java @@ -5,13 +5,13 @@ public class MaterialUIMovement { - private MaterialUIMovement() {} + private MaterialUIMovement() {} - public static void add(JComponent c, Color fadeTo, int steps, int interval) { - new MaterialUITimer(c, fadeTo, steps, interval); - } + public static void add(JComponent c, Color fadeTo, int steps, int interval) { + new MaterialUITimer(c, fadeTo, steps, interval); + } - public static void add(JComponent c, Color fadeTo) { - add(c, fadeTo, 5, 1000 / 30); - } + public static void add(JComponent c, Color fadeTo) { + add(c, fadeTo, 5, 1000 / 30); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java index b5ca8415f..f989185c7 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/animation/MaterialUITimer.java @@ -10,99 +10,99 @@ public class MaterialUITimer implements MouseListener, ActionListener { - private Color from, to; - private boolean forward; - private int alpha, steps; - private int[] forwardDeltas, backwardDeltas; - - private JComponent component; - private Timer timer; - - protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { - this.from = component.getBackground(); - this.to = to; - - this.forwardDeltas = new int[4]; - this.backwardDeltas = new int[4]; - - forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; - forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; - forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; - forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; - - backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; - backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; - backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; - backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; - - this.steps = steps; - - this.component = component; - this.component.addMouseListener(this); - timer = new Timer(interval, this); - } - - private Color nextColor() { - int rValue = from.getRed() - alpha * forwardDeltas[0]; - int gValue = from.getGreen() - alpha * forwardDeltas[1]; - int bValue = from.getBlue() - alpha * forwardDeltas[2]; - int aValue = from.getAlpha() - alpha * forwardDeltas[3]; - - return new Color(rValue, gValue, bValue, aValue); - } - - private Color previousColor() { - int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; - int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; - int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; - int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; - - return new Color(rValue, gValue, bValue, aValue); - } - - @Override - public void mousePressed(MouseEvent me) { - alpha = steps - 1; - forward = false; - timer.start(); - - alpha = 0; - forward = true; - timer.start(); - } - - @Override - public void mouseReleased(MouseEvent me) {} - - @Override - public void mouseClicked(MouseEvent me) {} - - @Override - public void mouseExited(MouseEvent me) { - alpha = steps - 1; - forward = false; - timer.start(); - } - - @Override - public void mouseEntered(MouseEvent me) { - alpha = 0; - forward = true; - timer.start(); - } - - @Override - public void actionPerformed(ActionEvent ae) { - if (forward) { - component.setBackground(nextColor()); - ++alpha; - } else { - component.setBackground(previousColor()); - --alpha; + private Color from, to; + private boolean forward; + private int alpha, steps; + private int[] forwardDeltas, backwardDeltas; + + private JComponent component; + private Timer timer; + + protected MaterialUITimer(JComponent component, Color to, int steps, int interval) { + this.from = component.getBackground(); + this.to = to; + + this.forwardDeltas = new int[4]; + this.backwardDeltas = new int[4]; + + forwardDeltas[0] = (from.getRed() - to.getRed()) / steps; + forwardDeltas[1] = (from.getGreen() - to.getGreen()) / steps; + forwardDeltas[2] = (from.getBlue() - to.getBlue()) / steps; + forwardDeltas[3] = (from.getAlpha() - to.getAlpha()) / steps; + + backwardDeltas[0] = (to.getRed() - from.getRed()) / steps; + backwardDeltas[1] = (to.getGreen() - from.getGreen()) / steps; + backwardDeltas[2] = (to.getBlue() - from.getBlue()) / steps; + backwardDeltas[3] = (to.getAlpha() - from.getAlpha()) / steps; + + this.steps = steps; + + this.component = component; + this.component.addMouseListener(this); + timer = new Timer(interval, this); + } + + private Color nextColor() { + int rValue = from.getRed() - alpha * forwardDeltas[0]; + int gValue = from.getGreen() - alpha * forwardDeltas[1]; + int bValue = from.getBlue() - alpha * forwardDeltas[2]; + int aValue = from.getAlpha() - alpha * forwardDeltas[3]; + + return new Color(rValue, gValue, bValue, aValue); + } + + private Color previousColor() { + int rValue = to.getRed() - (steps - alpha) * backwardDeltas[0]; + int gValue = to.getGreen() - (steps - alpha) * backwardDeltas[1]; + int bValue = to.getBlue() - (steps - alpha) * backwardDeltas[2]; + int aValue = to.getAlpha() - (steps - alpha) * backwardDeltas[3]; + + return new Color(rValue, gValue, bValue, aValue); + } + + @Override + public void mousePressed(MouseEvent me) { + alpha = steps - 1; + forward = false; + timer.start(); + + alpha = 0; + forward = true; + timer.start(); + } + + @Override + public void mouseReleased(MouseEvent me) {} + + @Override + public void mouseClicked(MouseEvent me) {} + + @Override + public void mouseExited(MouseEvent me) { + alpha = steps - 1; + forward = false; + timer.start(); + } + + @Override + public void mouseEntered(MouseEvent me) { + alpha = 0; + forward = true; + timer.start(); } - if (alpha == steps + 1 || alpha == -1) { - timer.stop(); + @Override + public void actionPerformed(ActionEvent ae) { + if (forward) { + component.setBackground(nextColor()); + ++alpha; + } else { + component.setBackground(previousColor()); + --alpha; + } + + if (alpha == steps + 1 || alpha == -1) { + timer.stop(); + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java index 5fbc8c1aa..debe6e215 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialButtonUI.java @@ -12,33 +12,33 @@ public class MaterialButtonUI extends BasicButtonUI { - public static ComponentUI createUI(final JComponent c) { - return new MaterialButtonUI(); - } + public static ComponentUI createUI(final JComponent c) { + return new MaterialButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - AbstractButton button = (AbstractButton) c; - MaterialUIMovement.add(c, MaterialColors.GRAY_300); - button.setOpaque(UIManager.getBoolean("Button.opaque")); - button.setBorder(UIManager.getBorder("Button.border")); - button.setBackground(UIManager.getColor("Button.background")); - button.setForeground(UIManager.getColor("Button.foreground")); - button.setFont(UIManager.getFont("Button.font")); - } + AbstractButton button = (AbstractButton) c; + MaterialUIMovement.add(c, MaterialColors.GRAY_300); + button.setOpaque(UIManager.getBoolean("Button.opaque")); + button.setBorder(UIManager.getBorder("Button.border")); + button.setBackground(UIManager.getColor("Button.background")); + button.setForeground(UIManager.getColor("Button.foreground")); + button.setFont(UIManager.getFont("Button.font")); + } - @Override - public void paint(Graphics g, JComponent c) { - AbstractButton b = (AbstractButton) c; - g = MaterialDrawingUtils.getAliasedGraphics(g); - paintBackground(g, b); - super.paint(g, c); - } + @Override + public void paint(Graphics g, JComponent c) { + AbstractButton b = (AbstractButton) c; + g = MaterialDrawingUtils.getAliasedGraphics(g); + paintBackground(g, b); + super.paint(g, c); + } - private void paintBackground(Graphics g, JComponent c) { - g.setColor(c.getBackground()); - g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 7, 7); - } + private void paintBackground(Graphics g, JComponent c) { + g.setColor(c.getBackground()); + g.fillRoundRect(0, 0, c.getWidth(), c.getHeight(), 7, 7); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java index 18870c571..8f0df3604 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxMenuItemUI.java @@ -15,48 +15,48 @@ */ public class MaterialCheckBoxMenuItemUI extends BasicCheckBoxMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialCheckBoxMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialCheckBoxMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintMenuItem( - Graphics g, - JComponent c, - Icon checkIcon, - Icon arrowIcon, - Color background, - Color foreground, - int defaultTextIconGap) { - JCheckBoxMenuItem checkBoxMenuItem = (JCheckBoxMenuItem) c; - if (checkBoxMenuItem.isSelected()) { - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - checkBoxMenuItem, - UIManager.getIcon("CheckBoxMenuItem.selectedCheckIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - return; + @Override + protected void paintMenuItem( + Graphics g, + JComponent c, + Icon checkIcon, + Icon arrowIcon, + Color background, + Color foreground, + int defaultTextIconGap) { + JCheckBoxMenuItem checkBoxMenuItem = (JCheckBoxMenuItem) c; + if (checkBoxMenuItem.isSelected()) { + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + checkBoxMenuItem, + UIManager.getIcon("CheckBoxMenuItem.selectedCheckIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + return; + } + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + checkBoxMenuItem, + UIManager.getIcon("CheckBoxMenuItem.checkIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); } - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - checkBoxMenuItem, - UIManager.getIcon("CheckBoxMenuItem.checkIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java index e851617f9..4a9725d52 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialCheckBoxUI.java @@ -11,24 +11,24 @@ // TODO cambio colore icone combo box public class MaterialCheckBoxUI extends BasicCheckBoxUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialCheckBoxUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialCheckBoxUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JCheckBox checkBox = (JCheckBox) c; - checkBox.setFont(UIManager.getFont("CheckBox.font")); - checkBox.setBackground(UIManager.getColor("CheckBox.background")); - checkBox.setForeground(UIManager.getColor("CheckBox.foreground")); - checkBox.setIcon(UIManager.getIcon("CheckBox.icon")); - checkBox.setSelectedIcon(UIManager.getIcon("CheckBox.selectedIcon")); - } + JCheckBox checkBox = (JCheckBox) c; + checkBox.setFont(UIManager.getFont("CheckBox.font")); + checkBox.setBackground(UIManager.getColor("CheckBox.background")); + checkBox.setForeground(UIManager.getColor("CheckBox.foreground")); + checkBox.setIcon(UIManager.getIcon("CheckBox.icon")); + checkBox.setSelectedIcon(UIManager.getIcon("CheckBox.selectedIcon")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java index e8e0957e1..73573d8f8 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxRenderer.java @@ -9,20 +9,21 @@ public class MaterialComboBoxRenderer extends BasicComboBoxRenderer { - @Override - public Component getListCellRendererComponent( - JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JComponent component = - (JComponent) - super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + @Override + public Component getListCellRendererComponent( + JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JComponent component = + (JComponent) + super.getListCellRendererComponent( + list, value, index, isSelected, cellHasFocus); - component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - component.setForeground(UIManager.getColor("ComboBox.foreground")); - component.setBackground( - isSelected || cellHasFocus - ? UIManager.getColor("ComboBox.selectedInDropDownBackground") - : UIManager.getColor("ComboBox.background")); + component.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + component.setForeground(UIManager.getColor("ComboBox.foreground")); + component.setBackground( + isSelected || cellHasFocus + ? UIManager.getColor("ComboBox.selectedInDropDownBackground") + : UIManager.getColor("ComboBox.background")); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java index 3cd934502..8cd52995b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialComboBoxUI.java @@ -15,42 +15,42 @@ public class MaterialComboBoxUI extends BasicComboBoxUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialComboBoxUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JComboBox comboBox = (JComboBox) c; - comboBox.setFont(UIManager.getFont("ComboBox.font")); - comboBox.setBackground(UIManager.getColor("ComboBox.background")); - comboBox.setForeground(UIManager.getColor("ComboBox.foreground")); - comboBox.setBorder(UIManager.getBorder("ComboBox.border")); - comboBox.setLightWeightPopupEnabled(true); - comboBox.setRenderer(new MaterialComboBoxRenderer()); - } - - @Override - protected JButton createArrowButton() { - Icon icon = UIManager.getIcon("ComboBox.buttonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.SOUTH); + public static ComponentUI createUI(JComponent c) { + return new MaterialComboBoxUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JComboBox comboBox = (JComboBox) c; + comboBox.setFont(UIManager.getFont("ComboBox.font")); + comboBox.setBackground(UIManager.getColor("ComboBox.background")); + comboBox.setForeground(UIManager.getColor("ComboBox.foreground")); + comboBox.setBorder(UIManager.getBorder("ComboBox.border")); + comboBox.setLightWeightPopupEnabled(true); + comboBox.setRenderer(new MaterialComboBoxRenderer()); + } + + @Override + protected JButton createArrowButton() { + Icon icon = UIManager.getIcon("ComboBox.buttonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.SOUTH); + } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ComboBox.buttonBackground")); + button.setBorder(BorderFactory.createEmptyBorder()); + + return button; + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ComboBox.buttonBackground")); - button.setBorder(BorderFactory.createEmptyBorder()); - - return button; - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java index df165a608..786f289bb 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialEditorPaneUI.java @@ -9,12 +9,12 @@ */ public class MaterialEditorPaneUI extends BasicEditorPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialEditorPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialEditorPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java index ffcca1064..b8046c569 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialFileChooserUI.java @@ -11,48 +11,48 @@ public class MaterialFileChooserUI extends MetalFileChooserUI { - public MaterialFileChooserUI(JFileChooser fileChooser) { - super(fileChooser); - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialFileChooserUI((JFileChooser) c); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - JFileChooser fileChooser = (JFileChooser) c; - MaterialFileChooserUI ui = (MaterialFileChooserUI) fileChooser.getUI(); - - ui.uninstallIcons(fileChooser); - ui.uninstallComponents(fileChooser); - ui.clearIconCache(); - - ui.computerIcon = new ImageIcon(MaterialImages.COMPUTER); - ui.directoryIcon = new ImageIcon(MaterialImages.FOLDER); - ui.fileIcon = new ImageIcon(MaterialImages.FILE); - ui.floppyDriveIcon = new ImageIcon(MaterialImages.FLOPPY_DRIVE); - ui.hardDriveIcon = new ImageIcon(MaterialImages.HARD_DRIVE); - - ui.homeFolderIcon = new ImageIcon(MaterialImages.HOME); - ui.listViewIcon = new ImageIcon(MaterialImages.LIST); - ui.detailsViewIcon = new ImageIcon(MaterialImages.DETAILS); - ui.newFolderIcon = new ImageIcon(MaterialImages.NEW_FOLDER); - ui.upFolderIcon = new ImageIcon(MaterialImages.BACK_ARROW); - - ui.openButtonText = "OPEN"; - ui.cancelButtonText = "CANCEL"; - ui.helpButtonText = "HELP"; - ui.saveButtonText = "SAVE"; - ui.directoryOpenButtonText = "OPEN"; - ui.updateButtonText = "UPDATE"; - - ui.installComponents(fileChooser); - } - - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + public MaterialFileChooserUI(JFileChooser fileChooser) { + super(fileChooser); + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialFileChooserUI((JFileChooser) c); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + JFileChooser fileChooser = (JFileChooser) c; + MaterialFileChooserUI ui = (MaterialFileChooserUI) fileChooser.getUI(); + + ui.uninstallIcons(fileChooser); + ui.uninstallComponents(fileChooser); + ui.clearIconCache(); + + ui.computerIcon = new ImageIcon(MaterialImages.COMPUTER); + ui.directoryIcon = new ImageIcon(MaterialImages.FOLDER); + ui.fileIcon = new ImageIcon(MaterialImages.FILE); + ui.floppyDriveIcon = new ImageIcon(MaterialImages.FLOPPY_DRIVE); + ui.hardDriveIcon = new ImageIcon(MaterialImages.HARD_DRIVE); + + ui.homeFolderIcon = new ImageIcon(MaterialImages.HOME); + ui.listViewIcon = new ImageIcon(MaterialImages.LIST); + ui.detailsViewIcon = new ImageIcon(MaterialImages.DETAILS); + ui.newFolderIcon = new ImageIcon(MaterialImages.NEW_FOLDER); + ui.upFolderIcon = new ImageIcon(MaterialImages.BACK_ARROW); + + ui.openButtonText = "OPEN"; + ui.cancelButtonText = "CANCEL"; + ui.helpButtonText = "HELP"; + ui.saveButtonText = "SAVE"; + ui.directoryOpenButtonText = "OPEN"; + ui.updateButtonText = "UPDATE"; + + ui.installComponents(fileChooser); + } + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java index de43761a9..e19fc1fed 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialLabelUI.java @@ -10,24 +10,24 @@ public class MaterialLabelUI extends BasicLabelUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialLabelUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialLabelUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JLabel label = (JLabel) c; - label.setOpaque(true); - label.setFont(UIManager.getFont("Label.font")); - label.setBackground(UIManager.getColor("Label.background")); - label.setForeground(UIManager.getColor("Label.foreground")); - label.setBorder(UIManager.getBorder("Label.border")); - } + JLabel label = (JLabel) c; + label.setOpaque(true); + label.setFont(UIManager.getFont("Label.font")); + label.setBackground(UIManager.getColor("Label.background")); + label.setForeground(UIManager.getColor("Label.foreground")); + label.setBorder(UIManager.getBorder("Label.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java index decb5908d..011d61862 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuBarUI.java @@ -10,23 +10,23 @@ public class MaterialMenuBarUI extends BasicMenuBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenuBar menuBar = (JMenuBar) c; - menuBar.setFont(UIManager.getFont("MenuBar.font")); - menuBar.setBackground(UIManager.getColor("MenuBar.background")); - menuBar.setBorder(UIManager.getBorder("MenuBar.border")); - menuBar.setForeground(UIManager.getColor("MenuBar.foreground")); - } + JMenuBar menuBar = (JMenuBar) c; + menuBar.setFont(UIManager.getFont("MenuBar.font")); + menuBar.setBackground(UIManager.getColor("MenuBar.background")); + menuBar.setBorder(UIManager.getBorder("MenuBar.border")); + menuBar.setForeground(UIManager.getColor("MenuBar.foreground")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java index 32b537bd1..a8c572b62 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuItemUI.java @@ -11,25 +11,25 @@ public class MaterialMenuItemUI extends BasicMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenuItem menuItem = (JMenuItem) c; - menuItem.setFont(UIManager.getFont("MenuItem.font")); - menuItem.setBackground(UIManager.getColor("MenuItem.background")); - menuItem.setForeground(UIManager.getColor("MenuItem.foreground")); - menuItem.setHorizontalAlignment(SwingConstants.LEFT); - menuItem.setVerticalAlignment(SwingConstants.CENTER); - menuItem.setBorder(UIManager.getBorder("MenuItem.border")); - } + JMenuItem menuItem = (JMenuItem) c; + menuItem.setFont(UIManager.getFont("MenuItem.font")); + menuItem.setBackground(UIManager.getColor("MenuItem.background")); + menuItem.setForeground(UIManager.getColor("MenuItem.foreground")); + menuItem.setHorizontalAlignment(SwingConstants.LEFT); + menuItem.setVerticalAlignment(SwingConstants.CENTER); + menuItem.setBorder(UIManager.getBorder("MenuItem.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java index d45c3f37f..16c1b9270 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialMenuUI.java @@ -10,24 +10,24 @@ public class MaterialMenuUI extends BasicMenuUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialMenuUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialMenuUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JMenu menu = (JMenu) c; - menu.setFont(UIManager.getFont("Menu.font")); - menu.setBorder(UIManager.getBorder("Menu.border")); - menu.setBackground(UIManager.getColor("Menu.background")); - menu.setForeground(UIManager.getColor("Menu.foreground")); - menu.setOpaque(UIManager.getBoolean("Menu.opaque")); - } + JMenu menu = (JMenu) c; + menu.setFont(UIManager.getFont("Menu.font")); + menu.setBorder(UIManager.getBorder("Menu.border")); + menu.setBackground(UIManager.getColor("Menu.background")); + menu.setForeground(UIManager.getColor("Menu.foreground")); + menu.setOpaque(UIManager.getBoolean("Menu.opaque")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java index 005d439d6..ae7a9be6b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPanelUI.java @@ -10,23 +10,23 @@ public class MaterialPanelUI extends BasicPanelUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialPanelUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialPanelUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JPanel panel = (JPanel) c; - panel.setOpaque(true); - panel.setFont(UIManager.getFont("Panel.font")); - panel.setBackground(UIManager.getColor("Panel.background")); - panel.setBorder(UIManager.getBorder("Panel.border")); - } + JPanel panel = (JPanel) c; + panel.setOpaque(true); + panel.setFont(UIManager.getFont("Panel.font")); + panel.setBackground(UIManager.getColor("Panel.background")); + panel.setBorder(UIManager.getBorder("Panel.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java index f4f02ff4f..d4778402b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPasswordFieldUI.java @@ -27,185 +27,192 @@ import javax.swing.text.View; public class MaterialPasswordFieldUI extends BasicPasswordFieldUI - implements FocusListener, PropertyChangeListener { - - private Color focusedBackground; - private Color unfocusedBackground; - private Color focusedSelectionBackground; - private Color unfocusedSelectionBackground; - - public static ComponentUI createUI(JComponent c) { - return new MaterialPasswordFieldUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JPasswordField passwordField = (JPasswordField) c; - passwordField.setOpaque(false); - passwordField.setBorder(BorderFactory.createEmptyBorder(5, 2, 10, 0)); - passwordField.setBackground(MaterialColors.LIGHT_BLUE_400); - - this.focusedBackground = passwordField.getBackground(); - this.unfocusedBackground = MaterialColors.GRAY_200; - - this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); - this.unfocusedSelectionBackground = unfocusedBackground; - } - - @Override - protected void installListeners() { - getComponent().addFocusListener(this); - getComponent().addPropertyChangeListener(this); - } - - @Override - protected void installKeyboardActions() { - super.installKeyboardActions(); - - Action selectAll = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().selectAll(); - } - }; - - Action delete = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (getComponent().getSelectedText() == null) { - int pos = getComponent().getCaretPosition() - 1; - - if (pos >= 0) { - getComponent().select(pos, pos + 1); - getComponent().replaceSelection(""); - } - } else { - getComponent().replaceSelection(""); - } - } - }; - - Action left = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); - } - }; - - Action right = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent() - .setCaretPosition( - Math.min( - getComponent().getText().length(), getComponent().getCaretPosition() + 1)); - } - }; - - // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to - // getMenuShortcutKeyMaskEx() - getComponent() - .getInputMap() - .put( - KeyStroke.getKeyStroke( - KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "selectAll"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); - - getComponent().getActionMap().put("selectAll", selectAll); - getComponent().getActionMap().put("delete", delete); - getComponent().getActionMap().put("left", left); - getComponent().getActionMap().put("right", right); - } - - @Override - public void paintSafely(Graphics g) { - JPasswordField c = (JPasswordField) getComponent(); - g = MaterialDrawingUtils.getAliasedGraphics(g); - - if (getComponent().hasFocus()) { - c.setBackground(focusedBackground); - c.setSelectionColor(focusedSelectionBackground); - } else { - c.setBackground(unfocusedBackground); - c.setSelectionColor(unfocusedSelectionBackground); + implements FocusListener, PropertyChangeListener { + + private Color focusedBackground; + private Color unfocusedBackground; + private Color focusedSelectionBackground; + private Color unfocusedSelectionBackground; + + public static ComponentUI createUI(JComponent c) { + return new MaterialPasswordFieldUI(); } - int x = getComponent().getInsets().left; - int y = getComponent().getInsets().top; - int w = - getComponent().getWidth() - - getComponent().getInsets().left - - getComponent().getInsets().right; - - g.setColor(c.getBackground()); - g.fillRect(x, c.getHeight() - y, w, 2); - - super.paintSafely(g); - } - - @Override - public void paintBackground(Graphics g) { - super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); - } - - @Override - public void focusGained(FocusEvent e) { - e.getComponent().setBackground(focusedBackground); - } - - @Override - public void focusLost(FocusEvent e) { - e.getComponent().setBackground(unfocusedBackground); - } - - @Override - public void propertyChange(PropertyChangeEvent pce) { - if (pce.getPropertyName().equals("background")) { - Color newColor = (Color) pce.getNewValue(); - - if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { - this.focusedBackground = (Color) pce.getNewValue(); - this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JPasswordField passwordField = (JPasswordField) c; + passwordField.setOpaque(false); + passwordField.setBorder(BorderFactory.createEmptyBorder(5, 2, 10, 0)); + passwordField.setBackground(MaterialColors.LIGHT_BLUE_400); + + this.focusedBackground = passwordField.getBackground(); + this.unfocusedBackground = MaterialColors.GRAY_200; + + this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); + this.unfocusedSelectionBackground = unfocusedBackground; } - } - @Override - public View create(Element elem) { - return new MaterialPasswordView(elem); - } + @Override + protected void installListeners() { + getComponent().addFocusListener(this); + getComponent().addPropertyChangeListener(this); + } - private static class MaterialPasswordView extends PasswordView { + @Override + protected void installKeyboardActions() { + super.installKeyboardActions(); + + Action selectAll = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().selectAll(); + } + }; + + Action delete = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (getComponent().getSelectedText() == null) { + int pos = getComponent().getCaretPosition() - 1; + + if (pos >= 0) { + getComponent().select(pos, pos + 1); + getComponent().replaceSelection(""); + } + } else { + getComponent().replaceSelection(""); + } + } + }; + + Action left = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.max(0, getComponent().getCaretPosition() - 1)); + } + }; + + Action right = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.min( + getComponent().getText().length(), + getComponent().getCaretPosition() + 1)); + } + }; + + // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to + // getMenuShortcutKeyMaskEx() + getComponent() + .getInputMap() + .put( + KeyStroke.getKeyStroke( + KeyEvent.VK_A, + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "selectAll"); + getComponent() + .getInputMap() + .put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); + + getComponent().getActionMap().put("selectAll", selectAll); + getComponent().getActionMap().put("delete", delete); + getComponent().getActionMap().put("left", left); + getComponent().getActionMap().put("right", right); + } - private MaterialPasswordView(Element elem) { - super(elem); + @Override + public void paintSafely(Graphics g) { + JPasswordField c = (JPasswordField) getComponent(); + g = MaterialDrawingUtils.getAliasedGraphics(g); + + if (getComponent().hasFocus()) { + c.setBackground(focusedBackground); + c.setSelectionColor(focusedSelectionBackground); + } else { + c.setBackground(unfocusedBackground); + c.setSelectionColor(unfocusedSelectionBackground); + } + + int x = getComponent().getInsets().left; + int y = getComponent().getInsets().top; + int w = + getComponent().getWidth() + - getComponent().getInsets().left + - getComponent().getInsets().right; + + g.setColor(c.getBackground()); + g.fillRect(x, c.getHeight() - y, w, 2); + + super.paintSafely(g); + } + + @Override + public void paintBackground(Graphics g) { + super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); } - // depreciated in Java 9 and above - replace method with float drawEchoCharacter(Graphics2D - // g, - // float x, float y, char c) @Override - protected int drawEchoCharacter(Graphics g, int x, int y, char c) { - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + public void focusGained(FocusEvent e) { + e.getComponent().setBackground(focusedBackground); + } + + @Override + public void focusLost(FocusEvent e) { + e.getComponent().setBackground(unfocusedBackground); + } + + @Override + public void propertyChange(PropertyChangeEvent pce) { + if (pce.getPropertyName().equals("background")) { + Color newColor = (Color) pce.getNewValue(); + + if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { + this.focusedBackground = (Color) pce.getNewValue(); + this.focusedSelectionBackground = + MaterialColors.bleach(this.focusedBackground, 0.3f); + } + } + } + + @Override + public View create(Element elem) { + return new MaterialPasswordView(elem); + } + + private static class MaterialPasswordView extends PasswordView { + + private MaterialPasswordView(Element elem) { + super(elem); + } + + // depreciated in Java 9 and above - replace method with float drawEchoCharacter(Graphics2D + // g, + // float x, float y, char c) + @Override + protected int drawEchoCharacter(Graphics g, int x, int y, char c) { + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - FontMetrics fm = g2.getFontMetrics(); - int r = fm.charWidth(c) - 2; + FontMetrics fm = g2.getFontMetrics(); + int r = fm.charWidth(c) - 2; - g2.setPaint(Color.BLACK); - g2.fillOval(x + 1, y + 5 - fm.getAscent(), r, r); - g2.dispose(); + g2.setPaint(Color.BLACK); + g2.fillOval(x + 1, y + 5 - fm.getAscent(), r, r); + g2.dispose(); - return x + fm.charWidth(c); + return x + fm.charWidth(c); + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java index a864e9a41..d7baaf5df 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialPopupMenuUI.java @@ -10,22 +10,22 @@ public class MaterialPopupMenuUI extends BasicPopupMenuUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialPopupMenuUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialPopupMenuUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JPopupMenu popupMenu = (JPopupMenu) c; - popupMenu.setBorder(UIManager.getBorder("PopupMenu.border")); - popupMenu.setBackground(UIManager.getColor("PopupMenu.background")); - popupMenu.setForeground(UIManager.getColor("PopupMenu.foreground")); - } + JPopupMenu popupMenu = (JPopupMenu) c; + popupMenu.setBorder(UIManager.getBorder("PopupMenu.border")); + popupMenu.setBackground(UIManager.getColor("PopupMenu.background")); + popupMenu.setForeground(UIManager.getColor("PopupMenu.foreground")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java index 062204e11..7f91a779f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialProgressBarUI.java @@ -14,22 +14,22 @@ */ public class MaterialProgressBarUI extends BasicProgressBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialProgressBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialProgressBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JProgressBar progressBar = (JProgressBar) c; - progressBar.setBorder(MaterialBorders.LIGHT_LINE_BORDER); - progressBar.setBackground(MaterialColors.GRAY_200); - progressBar.setForeground(MaterialColors.LIGHT_BLUE_400); - } + JProgressBar progressBar = (JProgressBar) c; + progressBar.setBorder(MaterialBorders.LIGHT_LINE_BORDER); + progressBar.setBackground(MaterialColors.GRAY_200); + progressBar.setForeground(MaterialColors.LIGHT_BLUE_400); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java index 92aa97726..69a9cae53 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonMenuItemUI.java @@ -15,51 +15,51 @@ */ public class MaterialRadioButtonMenuItemUI extends BasicRadioButtonMenuItemUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialRadioButtonMenuItemUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialRadioButtonMenuItemUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; - // j.setBackground(MaterialColors.WHITE); - j.setBorder(UIManager.getBorder("MenuItem.border")); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; + // j.setBackground(MaterialColors.WHITE); + j.setBorder(UIManager.getBorder("MenuItem.border")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintMenuItem( - Graphics g, - JComponent c, - Icon checkIcon, - Icon arrowIcon, - Color background, - Color foreground, - int defaultTextIconGap) { - JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; - if (j.isSelected()) { - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - c, - UIManager.getIcon("RadioButtonMenuItem.selectedCheckIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - return; + @Override + protected void paintMenuItem( + Graphics g, + JComponent c, + Icon checkIcon, + Icon arrowIcon, + Color background, + Color foreground, + int defaultTextIconGap) { + JRadioButtonMenuItem j = (JRadioButtonMenuItem) c; + if (j.isSelected()) { + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + c, + UIManager.getIcon("RadioButtonMenuItem.selectedCheckIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); + return; + } + super.paintMenuItem( + MaterialDrawingUtils.getAliasedGraphics(g), + c, + UIManager.getIcon("RadioButtonMenuItem.checkIcon"), + arrowIcon, + background, + foreground, + defaultTextIconGap); } - super.paintMenuItem( - MaterialDrawingUtils.getAliasedGraphics(g), - c, - UIManager.getIcon("RadioButtonMenuItem.checkIcon"), - arrowIcon, - background, - foreground, - defaultTextIconGap); - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java index 517d9086d..6418d4f17 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialRadioButtonUI.java @@ -14,24 +14,24 @@ // TODO cambio colore del radio button. public class MaterialRadioButtonUI extends BasicRadioButtonUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialRadioButtonUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialRadioButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JRadioButton radioButton = (JRadioButton) c; - radioButton.setFont(UIManager.getFont("RadioButton.font")); - radioButton.setBackground(UIManager.getColor("RadioButton.background")); - radioButton.setForeground(UIManager.getColor("RadioButton.foreground")); - radioButton.setIcon(UIManager.getIcon("RadioButton.icon")); - radioButton.setSelectedIcon(UIManager.getIcon("RadioButton.selectedIcon")); - } + JRadioButton radioButton = (JRadioButton) c; + radioButton.setFont(UIManager.getFont("RadioButton.font")); + radioButton.setBackground(UIManager.getColor("RadioButton.background")); + radioButton.setForeground(UIManager.getColor("RadioButton.foreground")); + radioButton.setIcon(UIManager.getIcon("RadioButton.icon")); + radioButton.setSelectedIcon(UIManager.getIcon("RadioButton.selectedIcon")); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java index c433ddf92..164209b3f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialScrollBarUI.java @@ -16,49 +16,49 @@ public class MaterialScrollBarUI extends BasicScrollBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialScrollBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialScrollBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JScrollBar scrollBar = (JScrollBar) c; - scrollBar.setFont(UIManager.getFont("ScrollBar.font")); - trackColor = UIManager.getColor("ScrollBar.track"); - thumbColor = UIManager.getColor("ScrollBar.thumb"); - thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); - thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); - thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); - } + JScrollBar scrollBar = (JScrollBar) c; + scrollBar.setFont(UIManager.getFont("ScrollBar.font")); + trackColor = UIManager.getColor("ScrollBar.track"); + thumbColor = UIManager.getColor("ScrollBar.thumb"); + thumbDarkShadowColor = UIManager.getColor("ScrollBar.thumbDarkShadow"); + thumbHighlightColor = UIManager.getColor("ScrollBar.thumbHighlight"); + thumbLightShadowColor = UIManager.getColor("ScrollBar.thumbShadow"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected JButton createDecreaseButton(int orientation) { - JButton button = new BasicArrowButton(orientation); + @Override + protected JButton createDecreaseButton(int orientation) { + JButton button = new BasicArrowButton(orientation); - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); - return button; - } + return button; + } - @Override - protected JButton createIncreaseButton(int orientation) { - JButton button = new BasicArrowButton(orientation); + @Override + protected JButton createIncreaseButton(int orientation) { + JButton button = new BasicArrowButton(orientation); - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("ScrollBar.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("ScrollBar.arrowButtonBorder")); - return button; - } + return button; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java index 36ee98b90..042b53d1b 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSeparatorUI.java @@ -8,17 +8,17 @@ public class MaterialSeparatorUI extends BasicSeparatorUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialSeparatorUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialSeparatorUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java index 3195c05e0..7ac2fe350 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSliderUI.java @@ -13,131 +13,131 @@ // TODO cambio grafica slider public class MaterialSliderUI extends BasicSliderUI { - private static final int NORMAL_THUMB_RADIUS = 6; - private static final int DRAG_THUMB_RADIUS = 10; - private static final Dimension THUMB_SIZE = - new Dimension(DRAG_THUMB_RADIUS * 2, DRAG_THUMB_RADIUS * 2); - - public MaterialSliderUI(JSlider slider) { - super(slider); - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialSliderUI((JSlider) c); - } - - private static void drawCircle(Graphics g, int x, int y, int radius) { - g.fillOval(x - radius, y - radius, radius * 2, radius * 2); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JSlider slider = (JSlider) c; - slider.setFont(UIManager.getFont("Slider.font")); - slider.setBackground(UIManager.getColor("Slider.background")); - slider.setForeground(UIManager.getColor("Slider.foreground")); - slider.setBorder(UIManager.getBorder("Slider.border")); - } - - @Override - public Dimension getThumbSize() { - return THUMB_SIZE; - } - - @Override - public void paintThumb(Graphics g) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - - int cx = thumbRect.x + thumbRect.width / 2; - int cy = thumbRect.y + thumbRect.height / 2; - - if (isDragging()) { - g.setColor(MaterialColors.bleach(slider.getForeground(), 0.5f)); - drawCircle(g, cx, cy, DRAG_THUMB_RADIUS); + private static final int NORMAL_THUMB_RADIUS = 6; + private static final int DRAG_THUMB_RADIUS = 10; + private static final Dimension THUMB_SIZE = + new Dimension(DRAG_THUMB_RADIUS * 2, DRAG_THUMB_RADIUS * 2); + + public MaterialSliderUI(JSlider slider) { + super(slider); + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialSliderUI((JSlider) c); } - g.setColor(slider.getForeground()); - drawCircle(g, cx, cy, NORMAL_THUMB_RADIUS); - - // need to redraw loaded part of progress line - Line loaded = getTrack(true); - g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); - } - - @Override - public void paintTrack(Graphics g) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - - g.setColor(UIManager.getColor("Slider.trackColor")); - Line unloaded = getTrack(false); - g.drawLine(unloaded.x1, unloaded.y1, unloaded.x2, unloaded.y2); - - g.setColor(slider.getForeground()); - Line loaded = getTrack(true); - g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); - } - - private Line getTrack(boolean loaded) { - if (slider.getOrientation() == JSlider.HORIZONTAL) { - Line left = - new Line( - trackRect.x, - thumbRect.y + thumbRect.height / 2, - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2); - Line right = - new Line( - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2, - trackRect.x + trackRect.width, - thumbRect.y + thumbRect.height / 2); - - if (loaded) { - return slider.getInverted() ? right : left; - } else { - return slider.getInverted() ? left : right; - } - } else { - Line top = - new Line( - thumbRect.x + thumbRect.width / 2, - trackRect.y, - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2); - Line bottom = - new Line( - thumbRect.x + thumbRect.width / 2, - thumbRect.y + thumbRect.height / 2, - thumbRect.x + thumbRect.width / 2, - trackRect.y + trackRect.height); - - if (loaded) { - return slider.getInverted() ? top : bottom; - } else { - return slider.getInverted() ? bottom : top; - } + private static void drawCircle(Graphics g, int x, int y, int radius) { + g.fillOval(x - radius, y - radius, radius * 2, radius * 2); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JSlider slider = (JSlider) c; + slider.setFont(UIManager.getFont("Slider.font")); + slider.setBackground(UIManager.getColor("Slider.background")); + slider.setForeground(UIManager.getColor("Slider.foreground")); + slider.setBorder(UIManager.getBorder("Slider.border")); } - } - @Override - public void paintFocus(Graphics g) {} + @Override + public Dimension getThumbSize() { + return THUMB_SIZE; + } + + @Override + public void paintThumb(Graphics g) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + + int cx = thumbRect.x + thumbRect.width / 2; + int cy = thumbRect.y + thumbRect.height / 2; + + if (isDragging()) { + g.setColor(MaterialColors.bleach(slider.getForeground(), 0.5f)); + drawCircle(g, cx, cy, DRAG_THUMB_RADIUS); + } + + g.setColor(slider.getForeground()); + drawCircle(g, cx, cy, NORMAL_THUMB_RADIUS); - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + // need to redraw loaded part of progress line + Line loaded = getTrack(true); + g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + } + + @Override + public void paintTrack(Graphics g) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + + g.setColor(UIManager.getColor("Slider.trackColor")); + Line unloaded = getTrack(false); + g.drawLine(unloaded.x1, unloaded.y1, unloaded.x2, unloaded.y2); + + g.setColor(slider.getForeground()); + Line loaded = getTrack(true); + g.drawLine(loaded.x1, loaded.y1, loaded.x2, loaded.y2); + } + + private Line getTrack(boolean loaded) { + if (slider.getOrientation() == JSlider.HORIZONTAL) { + Line left = + new Line( + trackRect.x, + thumbRect.y + thumbRect.height / 2, + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2); + Line right = + new Line( + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2, + trackRect.x + trackRect.width, + thumbRect.y + thumbRect.height / 2); + + if (loaded) { + return slider.getInverted() ? right : left; + } else { + return slider.getInverted() ? left : right; + } + } else { + Line top = + new Line( + thumbRect.x + thumbRect.width / 2, + trackRect.y, + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2); + Line bottom = + new Line( + thumbRect.x + thumbRect.width / 2, + thumbRect.y + thumbRect.height / 2, + thumbRect.x + thumbRect.width / 2, + trackRect.y + trackRect.height); + + if (loaded) { + return slider.getInverted() ? top : bottom; + } else { + return slider.getInverted() ? bottom : top; + } + } + } + + @Override + public void paintFocus(Graphics g) {} + + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - private static class Line { + private static class Line { - int x1, y1, x2, y2; + int x1, y1, x2, y2; - Line(int x1, int y1, int x2, int y2) { - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; + Line(int x1, int y1, int x2, int y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java index 71428661a..ecfcbab17 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSpinnerUI.java @@ -15,68 +15,68 @@ public class MaterialSpinnerUI extends BasicSpinnerUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialSpinnerUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); + public static ComponentUI createUI(JComponent c) { + return new MaterialSpinnerUI(); + } - JSpinner spinner = (JSpinner) c; - spinner.setOpaque(false); - spinner.setFont(UIManager.getFont("Spinner.font")); - spinner.setBackground(UIManager.getColor("Spinner.background")); - spinner.setForeground(UIManager.getColor("Spinner.foreground")); - spinner.setBorder(UIManager.getBorder("Spinner.border")); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); - @Override - protected JComponent createEditor() { - JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) super.createEditor(); - editor.getTextField().setUI(new MaterialTextFieldUI(false)); + JSpinner spinner = (JSpinner) c; + spinner.setOpaque(false); + spinner.setFont(UIManager.getFont("Spinner.font")); + spinner.setBackground(UIManager.getColor("Spinner.background")); + spinner.setForeground(UIManager.getColor("Spinner.foreground")); + spinner.setBorder(UIManager.getBorder("Spinner.border")); + } - return editor; - } + @Override + protected JComponent createEditor() { + JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) super.createEditor(); + editor.getTextField().setUI(new MaterialTextFieldUI(false)); - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + return editor; + } - @Override - protected Component createNextButton() { - Icon icon = UIManager.getIcon("Spinner.nextButtonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.NORTH); + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); - installNextButtonListeners(button); - return button; - } + @Override + protected Component createNextButton() { + Icon icon = UIManager.getIcon("Spinner.nextButtonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.NORTH); + } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); + installNextButtonListeners(button); - @Override - protected Component createPreviousButton() { - Icon icon = UIManager.getIcon("Spinner.previousButtonIcon"); - JButton button; - if (icon != null) { - button = new JButton(icon); - } else { - button = new BasicArrowButton(SwingConstants.SOUTH); + return button; } - button.setFocusPainted(false); - button.setOpaque(true); - button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); - button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); - installPreviousButtonListeners(button); - return button; - } + @Override + protected Component createPreviousButton() { + Icon icon = UIManager.getIcon("Spinner.previousButtonIcon"); + JButton button; + if (icon != null) { + button = new JButton(icon); + } else { + button = new BasicArrowButton(SwingConstants.SOUTH); + } + button.setFocusPainted(false); + button.setOpaque(true); + button.setBackground(UIManager.getColor("Spinner.arrowButtonBackground")); + button.setBorder(UIManager.getBorder("Spinner.arrowButtonBorder")); + installPreviousButtonListeners(button); + + return button; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java index c33ea201a..0ec5db987 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneDivider.java @@ -4,20 +4,20 @@ import javax.swing.plaf.basic.BasicSplitPaneUI; public class MaterialSplitPaneDivider extends BasicSplitPaneDivider { - public MaterialSplitPaneDivider(BasicSplitPaneUI ui) { - super(ui); - // oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, - // "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); - // oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, - // "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); - // centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), - // ui, "SplitPane.centerOneTouchButtons", true); - // setLayout(new DividerLayout()); - // setBasicSplitPaneUI(ui); - // orientation = splitPane.getOrientation(); - // setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? - // Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : - // Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); - // setBackground(UIManager.getColor("SplitPane.background")); - } + public MaterialSplitPaneDivider(BasicSplitPaneUI ui) { + super(ui); + // oneTouchSize = DefaultLookup.getInt(ui.getSplitPane(), ui, + // "SplitPane.oneTouchButtonSize", ONE_TOUCH_SIZE); + // oneTouchOffset = DefaultLookup.getInt(ui.getSplitPane(), ui, + // "SplitPane.oneTouchButtonOffset", ONE_TOUCH_OFFSET); + // centerOneTouchButtons = DefaultLookup.getBoolean(ui.getSplitPane(), + // ui, "SplitPane.centerOneTouchButtons", true); + // setLayout(new DividerLayout()); + // setBasicSplitPaneUI(ui); + // orientation = splitPane.getOrientation(); + // setCursor((orientation == JSplitPane.HORIZONTAL_SPLIT) ? + // Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) : + // Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)); + // setBackground(UIManager.getColor("SplitPane.background")); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java index d95f3f766..33cee1316 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialSplitPaneUI.java @@ -4,24 +4,24 @@ import javax.swing.plaf.basic.BasicSplitPaneUI; public class MaterialSplitPaneUI extends BasicSplitPaneUI { - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JSplitPane splitPane = (JSplitPane) c; - splitPane.setOpaque(false); - splitPane.setBorder(UIManager.getBorder("SplitPane.border")); - splitPane.setBackground(UIManager.getColor("SplitPane.background")); - splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); - } + JSplitPane splitPane = (JSplitPane) c; + splitPane.setOpaque(false); + splitPane.setBorder(UIManager.getBorder("SplitPane.border")); + splitPane.setBackground(UIManager.getColor("SplitPane.background")); + splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); + } - // /** - // * Creates the default divider. - // * - // * @return the default divider - // */ - // @Override - // public BasicSplitPaneDivider createDefaultDivider() { - // return new MaterialSplitPaneDivider(this); - // } + // /** + // * Creates the default divider. + // * + // * @return the default divider + // */ + // @Override + // public BasicSplitPaneDivider createDefaultDivider() { + // return new MaterialSplitPaneDivider(this); + // } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java index bcc6d68f4..878ed8479 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTabbedPaneUI.java @@ -11,72 +11,86 @@ public class MaterialTabbedPaneUI extends BasicTabbedPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTabbedPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTabbedPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JTabbedPane tabbedPane = (JTabbedPane) c; - tabbedPane.setOpaque(false); - tabbedPane.setFont(UIManager.getFont("TabbedPane.font")); - tabbedPane.setBackground(UIManager.getColor("TabbedPane.background")); - tabbedPane.setForeground(UIManager.getColor("TabbedPane.foreground")); - tabbedPane.setBorder(UIManager.getBorder("TabbedPane.border")); + JTabbedPane tabbedPane = (JTabbedPane) c; + tabbedPane.setOpaque(false); + tabbedPane.setFont(UIManager.getFont("TabbedPane.font")); + tabbedPane.setBackground(UIManager.getColor("TabbedPane.background")); + tabbedPane.setForeground(UIManager.getColor("TabbedPane.foreground")); + tabbedPane.setBorder(UIManager.getBorder("TabbedPane.border")); - darkShadow = UIManager.getColor("TabbedPane.darkShadow"); - shadow = UIManager.getColor("TabbedPane.shadow"); - lightHighlight = UIManager.getColor("TabbedPane.highlight"); - } + darkShadow = UIManager.getColor("TabbedPane.darkShadow"); + shadow = UIManager.getColor("TabbedPane.shadow"); + lightHighlight = UIManager.getColor("TabbedPane.highlight"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } - @Override - protected void paintTabBackground( - Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { - g.setColor(isSelected ? lightHighlight : tabPane.getBackground()); - g.fillRect(x, y, w, h); - } + @Override + protected void paintTabBackground( + Graphics g, + int tabPlacement, + int tabIndex, + int x, + int y, + int w, + int h, + boolean isSelected) { + g.setColor(isSelected ? lightHighlight : tabPane.getBackground()); + g.fillRect(x, y, w, h); + } - @Override - protected void paintTabBorder( - Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { - g.setColor(UIManager.getColor("TabbedPane.borderHighlightColor")); - g.drawRect(x, y, w, h); - } + @Override + protected void paintTabBorder( + Graphics g, + int tabPlacement, + int tabIndex, + int x, + int y, + int w, + int h, + boolean isSelected) { + g.setColor(UIManager.getColor("TabbedPane.borderHighlightColor")); + g.drawRect(x, y, w, h); + } - @Override - protected void paintFocusIndicator( - Graphics g, - int tabPlacement, - Rectangle[] rects, - int tabIndex, - Rectangle iconRect, - Rectangle textRect, - boolean isSelected) { - // do nothing - } + @Override + protected void paintFocusIndicator( + Graphics g, + int tabPlacement, + Rectangle[] rects, + int tabIndex, + Rectangle iconRect, + Rectangle textRect, + boolean isSelected) { + // do nothing + } - @Override - protected void paintTab( - Graphics g, - int tabPlacement, - Rectangle[] rects, - int tabIndex, - Rectangle iconRect, - Rectangle textRect) { - // for some reason tabs aren't painted properly by paint() - super.paintTab( - MaterialDrawingUtils.getAliasedGraphics(g), - tabPlacement, - rects, - tabIndex, - iconRect, - textRect); - } + @Override + protected void paintTab( + Graphics g, + int tabPlacement, + Rectangle[] rects, + int tabIndex, + Rectangle iconRect, + Rectangle textRect) { + // for some reason tabs aren't painted properly by paint() + super.paintTab( + MaterialDrawingUtils.getAliasedGraphics(g), + tabPlacement, + rects, + tabIndex, + iconRect, + textRect); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java index 3f8cdc80b..b4e07e95f 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellEditor.java @@ -7,25 +7,26 @@ public class MaterialTableCellEditor extends DefaultCellEditor { - public MaterialTableCellEditor() { - super(init()); - } + public MaterialTableCellEditor() { + super(init()); + } - private static JTextField init() { - JTextField textField = new JTextField(); - textField.setUI(new MaterialTextFieldUI(false)); + private static JTextField init() { + JTextField textField = new JTextField(); + textField.setUI(new MaterialTextFieldUI(false)); - return textField; - } + return textField; + } - @Override - public Component getTableCellEditorComponent( - JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { - JTextField textField = - (JTextField) - super.getTableCellEditorComponent(table, value, isSelected, rowIndex, vColIndex); - textField.setText(value.toString()); + @Override + public Component getTableCellEditorComponent( + JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { + JTextField textField = + (JTextField) + super.getTableCellEditorComponent( + table, value, isSelected, rowIndex, vColIndex); + textField.setText(value.toString()); - return textField; - } + return textField; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java index 2dd33246a..8fe0438e8 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableCellRenderer.java @@ -9,19 +9,20 @@ public class MaterialTableCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent( - JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - JComponent component = - (JComponent) - super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JComponent component = + (JComponent) + super.getTableCellRendererComponent( + table, value, isSelected, hasFocus, row, column); - // hides yellow selection highlight - component.setBorder(BorderFactory.createEmptyBorder()); + // hides yellow selection highlight + component.setBorder(BorderFactory.createEmptyBorder()); - this.setHorizontalAlignment(SwingConstants.CENTER); - this.setVerticalAlignment(SwingConstants.CENTER); + this.setHorizontalAlignment(SwingConstants.CENTER); + this.setVerticalAlignment(SwingConstants.CENTER); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java index 458b8062a..01f4db191 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderCellRenderer.java @@ -9,19 +9,20 @@ public class MaterialTableHeaderCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent( - JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - JComponent component = - (JComponent) - super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - component.setBorder(UIManager.getBorder("TableHeader.cellBorder")); - component.setFont(UIManager.getFont("TableHeader.font")); - component.setBackground(UIManager.getColor("TableHeader.background")); + @Override + public Component getTableCellRendererComponent( + JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + JComponent component = + (JComponent) + super.getTableCellRendererComponent( + table, value, isSelected, hasFocus, row, column); + component.setBorder(UIManager.getBorder("TableHeader.cellBorder")); + component.setFont(UIManager.getFont("TableHeader.font")); + component.setBackground(UIManager.getColor("TableHeader.background")); - this.setHorizontalAlignment(SwingConstants.CENTER); - this.setVerticalAlignment(SwingConstants.CENTER); + this.setHorizontalAlignment(SwingConstants.CENTER); + this.setVerticalAlignment(SwingConstants.CENTER); - return component; - } + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java index e039aba97..7a1eadb92 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableHeaderUI.java @@ -9,20 +9,20 @@ public class MaterialTableHeaderUI extends BasicTableHeaderUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTableHeaderUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTableHeaderUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JTableHeader header = (JTableHeader) c; - header.setDefaultRenderer(new MaterialTableHeaderCellRenderer()); - } + JTableHeader header = (JTableHeader) c; + header.setDefaultRenderer(new MaterialTableHeaderCellRenderer()); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java index af3d7fbc5..91c68c973 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTableUI.java @@ -10,37 +10,37 @@ public class MaterialTableUI extends BasicTableUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTableUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTable table = (JTable) c; - table.setOpaque(false); - table.setSelectionForeground(UIManager.getColor("Table.selectionForeground")); - table.setBackground(UIManager.getColor("Table.background")); - table.setFont(UIManager.getFont("Table.font")); - table.setBorder(UIManager.getBorder("Table.border")); - table.setGridColor(UIManager.getColor("Table.gridColor")); - table.setSelectionBackground(UIManager.getColor("Table.selectionBackground")); - - table.getTableHeader().setResizingAllowed(true); - int rowHeight = UIManager.getInt("Table.rowHeight"); - if (rowHeight > 0) { - table.setRowHeight(rowHeight); - } else { - table.setRowHeight(table.getRowHeight() + 25); + public static ComponentUI createUI(JComponent c) { + return new MaterialTableUI(); } - table.setDefaultRenderer(Object.class, new MaterialTableCellRenderer()); - table.setDefaultEditor(Object.class, new MaterialTableCellEditor()); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTable table = (JTable) c; + table.setOpaque(false); + table.setSelectionForeground(UIManager.getColor("Table.selectionForeground")); + table.setBackground(UIManager.getColor("Table.background")); + table.setFont(UIManager.getFont("Table.font")); + table.setBorder(UIManager.getBorder("Table.border")); + table.setGridColor(UIManager.getColor("Table.gridColor")); + table.setSelectionBackground(UIManager.getColor("Table.selectionBackground")); + + table.getTableHeader().setResizingAllowed(true); + int rowHeight = UIManager.getInt("Table.rowHeight"); + if (rowHeight > 0) { + table.setRowHeight(rowHeight); + } else { + table.setRowHeight(table.getRowHeight() + 25); + } + + table.setDefaultRenderer(Object.class, new MaterialTableCellRenderer()); + table.setDefaultEditor(Object.class, new MaterialTableCellEditor()); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java index 874392573..5cfd2fc88 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextFieldUI.java @@ -22,189 +22,196 @@ import javax.swing.plaf.basic.BasicTextFieldUI; public class MaterialTextFieldUI extends BasicTextFieldUI - implements FocusListener, PropertyChangeListener { - - private Color focusedBackground; - private Color unfocusedBackground; - private Color focusedSelectionBackground; - private Color unfocusedSelectionBackground; - private boolean drawLine; - - public MaterialTextFieldUI() { - this(true); - } - - public MaterialTextFieldUI(boolean drawLine) { - super(); - this.drawLine = drawLine; - } - - public static ComponentUI createUI(JComponent c) { - return new MaterialTextFieldUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - - JTextField textField = (JTextField) c; - textField.setOpaque(false); - textField.setBorder( - drawLine - ? BorderFactory.createEmptyBorder(5, 2, 10, 0) - : BorderFactory.createEmptyBorder(2, 2, 2, 2)); - - textField.setBackground(MaterialColors.LIGHT_BLUE_400); - textField.setFont(MaterialFonts.REGULAR); - - this.focusedBackground = textField.getBackground(); - this.unfocusedBackground = MaterialColors.GRAY_200; - - this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); - this.unfocusedSelectionBackground = unfocusedBackground; - } - - @Override - protected void installListeners() { - super.installListeners(); - getComponent().addFocusListener(this); - getComponent().addPropertyChangeListener(this); - } - - @Override - protected void installKeyboardActions() { - super.installKeyboardActions(); - - Action selectAll = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().selectAll(); - } - }; - - Action delete = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (getComponent().getSelectedText() == null) { - int pos = getComponent().getCaretPosition() - 1; - - if (pos >= 0) { - getComponent().select(pos, pos + 1); - getComponent().replaceSelection(""); - } - } else { - getComponent().replaceSelection(""); - } - } - }; - - Action left = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent().setCaretPosition(Math.max(0, getComponent().getCaretPosition() - 1)); - } - }; - - Action right = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - getComponent() - .setCaretPosition( - Math.min( - getComponent().getText().length(), getComponent().getCaretPosition() + 1)); - } - }; - - Action enter = - new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - ((JTextField) getComponent()).postActionEvent(); - } - }; - - // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to - // getMenuShortcutKeyMaskEx() - getComponent() - .getInputMap() - .put( - KeyStroke.getKeyStroke( - KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), - "selectAll"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); - getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); - - getComponent().getActionMap().put("selectAll", selectAll); - getComponent().getActionMap().put("delete", delete); - getComponent().getActionMap().put("left", left); - getComponent().getActionMap().put("right", right); - getComponent().getActionMap().put("enter", enter); - } - - @Override - public void paintSafely(Graphics g) { - JTextField c = (JTextField) getComponent(); - g = MaterialDrawingUtils.getAliasedGraphics(g); - - Color lineColor; - - if (getComponent().hasFocus()) { - lineColor = focusedBackground; - c.setSelectionColor(focusedSelectionBackground); - } else { - lineColor = unfocusedBackground; - c.setSelectionColor(unfocusedSelectionBackground); + implements FocusListener, PropertyChangeListener { + + private Color focusedBackground; + private Color unfocusedBackground; + private Color focusedSelectionBackground; + private Color unfocusedSelectionBackground; + private boolean drawLine; + + public MaterialTextFieldUI() { + this(true); + } + + public MaterialTextFieldUI(boolean drawLine) { + super(); + this.drawLine = drawLine; + } + + public static ComponentUI createUI(JComponent c) { + return new MaterialTextFieldUI(); } - g.setColor(lineColor); - getComponent().setBackground(lineColor); + @Override + public void installUI(JComponent c) { + super.installUI(c); + + JTextField textField = (JTextField) c; + textField.setOpaque(false); + textField.setBorder( + drawLine + ? BorderFactory.createEmptyBorder(5, 2, 10, 0) + : BorderFactory.createEmptyBorder(2, 2, 2, 2)); + + textField.setBackground(MaterialColors.LIGHT_BLUE_400); + textField.setFont(MaterialFonts.REGULAR); + + this.focusedBackground = textField.getBackground(); + this.unfocusedBackground = MaterialColors.GRAY_200; + + this.focusedSelectionBackground = MaterialColors.bleach(focusedBackground, 0.3f); + this.unfocusedSelectionBackground = unfocusedBackground; + } - if (drawLine) { - int x = getComponent().getInsets().left; - int y = getComponent().getInsets().top; - int w = - getComponent().getWidth() - - getComponent().getInsets().left - - getComponent().getInsets().right; + @Override + protected void installListeners() { + super.installListeners(); + getComponent().addFocusListener(this); + getComponent().addPropertyChangeListener(this); + } - g.fillRect(x, c.getHeight() - y, w, 2); + @Override + protected void installKeyboardActions() { + super.installKeyboardActions(); + + Action selectAll = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent().selectAll(); + } + }; + + Action delete = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (getComponent().getSelectedText() == null) { + int pos = getComponent().getCaretPosition() - 1; + + if (pos >= 0) { + getComponent().select(pos, pos + 1); + getComponent().replaceSelection(""); + } + } else { + getComponent().replaceSelection(""); + } + } + }; + + Action left = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.max(0, getComponent().getCaretPosition() - 1)); + } + }; + + Action right = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + getComponent() + .setCaretPosition( + Math.min( + getComponent().getText().length(), + getComponent().getCaretPosition() + 1)); + } + }; + + Action enter = + new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + ((JTextField) getComponent()).postActionEvent(); + } + }; + + // note getMenuShortcutKeyMask() is deprecated in Java 10 - change to + // getMenuShortcutKeyMaskEx() + getComponent() + .getInputMap() + .put( + KeyStroke.getKeyStroke( + KeyEvent.VK_A, + Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), + "selectAll"); + getComponent() + .getInputMap() + .put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right"); + getComponent().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter"); + + getComponent().getActionMap().put("selectAll", selectAll); + getComponent().getActionMap().put("delete", delete); + getComponent().getActionMap().put("left", left); + getComponent().getActionMap().put("right", right); + getComponent().getActionMap().put("enter", enter); } - super.paintSafely(g); - } + @Override + public void paintSafely(Graphics g) { + JTextField c = (JTextField) getComponent(); + g = MaterialDrawingUtils.getAliasedGraphics(g); + + Color lineColor; + + if (getComponent().hasFocus()) { + lineColor = focusedBackground; + c.setSelectionColor(focusedSelectionBackground); + } else { + lineColor = unfocusedBackground; + c.setSelectionColor(unfocusedSelectionBackground); + } + + g.setColor(lineColor); + getComponent().setBackground(lineColor); + + if (drawLine) { + int x = getComponent().getInsets().left; + int y = getComponent().getInsets().top; + int w = + getComponent().getWidth() + - getComponent().getInsets().left + - getComponent().getInsets().right; + + g.fillRect(x, c.getHeight() - y, w, 2); + } - @Override - public void paintBackground(final Graphics g) { - super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); - } + super.paintSafely(g); + } + + @Override + public void paintBackground(final Graphics g) { + super.paintBackground(MaterialDrawingUtils.getAliasedGraphics(g)); + } - @Override - public void focusGained(FocusEvent e) { - e.getComponent().setBackground(focusedBackground); - } + @Override + public void focusGained(FocusEvent e) { + e.getComponent().setBackground(focusedBackground); + } - @Override - public void focusLost(FocusEvent e) { - e.getComponent().setBackground(unfocusedBackground); - } + @Override + public void focusLost(FocusEvent e) { + e.getComponent().setBackground(unfocusedBackground); + } - @Override - public void propertyChange(PropertyChangeEvent pce) { - super.propertyChange(pce); + @Override + public void propertyChange(PropertyChangeEvent pce) { + super.propertyChange(pce); - if (pce.getPropertyName().equals("background")) { - Color newColor = (Color) pce.getNewValue(); + if (pce.getPropertyName().equals("background")) { + Color newColor = (Color) pce.getNewValue(); - if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { - this.focusedBackground = (Color) pce.getNewValue(); - this.focusedSelectionBackground = MaterialColors.bleach(this.focusedBackground, 0.3f); - } + if (!newColor.equals(focusedBackground) && !newColor.equals(unfocusedBackground)) { + this.focusedBackground = (Color) pce.getNewValue(); + this.focusedSelectionBackground = + MaterialColors.bleach(this.focusedBackground, 0.3f); + } + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java index 61fba8d33..f70048468 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTextPaneUI.java @@ -9,12 +9,12 @@ */ public class MaterialTextPaneUI extends BasicTextPaneUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTextPaneUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTextPaneUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java index 42786abba..3749366e9 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToggleButtonUI.java @@ -10,28 +10,28 @@ public class MaterialToggleButtonUI extends BasicToggleButtonUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToggleButtonUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToggleButtonUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); + @Override + public void installUI(JComponent c) { + super.installUI(c); - JToggleButton toggleButton = (JToggleButton) c; - toggleButton.setBorder(UIManager.getBorder("ToggleButton.border")); - toggleButton.setFont(UIManager.getFont("ToggleButton.font")); - toggleButton.setBackground(UIManager.getColor("ToggleButton.background")); - toggleButton.setForeground(UIManager.getColor("ToggleButton.foreground")); + JToggleButton toggleButton = (JToggleButton) c; + toggleButton.setBorder(UIManager.getBorder("ToggleButton.border")); + toggleButton.setFont(UIManager.getFont("ToggleButton.font")); + toggleButton.setBackground(UIManager.getColor("ToggleButton.background")); + toggleButton.setForeground(UIManager.getColor("ToggleButton.foreground")); - if (toggleButton.getIcon() == null && toggleButton.getSelectedIcon() == null) { - toggleButton.setIcon(UIManager.getIcon("ToggleButton.icon")); - toggleButton.setSelectedIcon(UIManager.getIcon("ToggleButton.selectedIcon")); + if (toggleButton.getIcon() == null && toggleButton.getSelectedIcon() == null) { + toggleButton.setIcon(UIManager.getIcon("ToggleButton.icon")); + toggleButton.setSelectedIcon(UIManager.getIcon("ToggleButton.selectedIcon")); + } } - } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java index 58a752c59..10251eb73 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolBarUI.java @@ -10,28 +10,28 @@ public class MaterialToolBarUI extends BasicToolBarUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToolBarUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToolBarUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - JToolBar toolBar = (JToolBar) c; + @Override + public void installUI(JComponent c) { + super.installUI(c); + JToolBar toolBar = (JToolBar) c; - toolBar.setFont(UIManager.getFont("ToolBar.font")); - toolBar.setBackground(UIManager.getColor("ToolBar.background")); - toolBar.setForeground(UIManager.getColor("ToolBar.foreground")); - toolBar.setBorder(UIManager.getBorder("ToolBar.border")); + toolBar.setFont(UIManager.getFont("ToolBar.font")); + toolBar.setBackground(UIManager.getColor("ToolBar.background")); + toolBar.setForeground(UIManager.getColor("ToolBar.foreground")); + toolBar.setBorder(UIManager.getBorder("ToolBar.border")); - this.dockingBorderColor = null; - this.floatingBorderColor = null; - this.dockingColor = UIManager.getColor("ToolBar.dockingBackground"); - this.floatingColor = UIManager.getColor("ToolBar.floatingBackground"); - } + this.dockingBorderColor = null; + this.floatingBorderColor = null; + this.dockingColor = UIManager.getColor("ToolBar.dockingBackground"); + this.floatingColor = UIManager.getColor("ToolBar.floatingBackground"); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java index 2b023c920..87e415e4c 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialToolTipUI.java @@ -8,17 +8,17 @@ public class MaterialToolTipUI extends BasicToolTipUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialToolTipUI(); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialToolTipUI(); + } - @Override - public void installUI(JComponent c) { - super.installUI(c); - } + @Override + public void installUI(JComponent c) { + super.installUI(c); + } - @Override - public void paint(Graphics g, JComponent c) { - super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); - } + @Override + public void paint(Graphics g, JComponent c) { + super.paint(MaterialDrawingUtils.getAliasedGraphics(g), c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java index 6565ca731..ee9b0fcff 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellEditor.java @@ -11,43 +11,43 @@ public class MaterialTreeCellEditor extends DefaultTreeCellEditor { - private JTextField textField; - - public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { - super(tree, renderer); - init(); - } - - public MaterialTreeCellEditor( - JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { - super(tree, renderer, editor); - init(); - } - - private void init() { - textField = new JTextField(); - textField.setUI(new MaterialTextFieldUI()); - - textField.addKeyListener( - new KeyAdapter() { - @Override - public void keyTyped(KeyEvent e) { - if (e.getKeyChar() == KeyEvent.VK_ENTER) { - stopCellEditing(); - } - } - }); - } - - @Override - public Component getTreeCellEditorComponent( - JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { - textField.setText(value.toString()); - return textField; - } - - @Override - public Object getCellEditorValue() { - return textField.getText(); - } + private JTextField textField; + + public MaterialTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) { + super(tree, renderer); + init(); + } + + public MaterialTreeCellEditor( + JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor) { + super(tree, renderer, editor); + init(); + } + + private void init() { + textField = new JTextField(); + textField.setUI(new MaterialTextFieldUI()); + + textField.addKeyListener( + new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + if (e.getKeyChar() == KeyEvent.VK_ENTER) { + stopCellEditing(); + } + } + }); + } + + @Override + public Component getTreeCellEditorComponent( + JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { + textField.setText(value.toString()); + return textField; + } + + @Override + public Object getCellEditorValue() { + return textField.getText(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java index f4e85bba2..6ac5acabb 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeCellRenderer.java @@ -9,37 +9,37 @@ public class MaterialTreeCellRenderer extends DefaultTreeCellRenderer { - public MaterialTreeCellRenderer() { - setTextSelectionColor(UIManager.getColor("Tree.selectionForeground")); - setTextNonSelectionColor(UIManager.getColor("Tree.foreground")); - - setBackgroundSelectionColor(UIManager.getColor("Tree.selectionBackground")); - setBackgroundNonSelectionColor(UIManager.getColor("Tree.background")); - - setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor")); - - setClosedIcon(UIManager.getIcon("Tree.closedIcon")); - setOpenIcon(UIManager.getIcon("Tree.openIcon")); - setLeafIcon(null); - - setFont(UIManager.getFont("Tree.font")); - } - - @Override - public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean isSelected, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { - JComponent component = - (JComponent) - super.getTreeCellRendererComponent( - tree, value, isSelected, expanded, leaf, row, hasFocus); - component.setBorder(BorderFactory.createEmptyBorder(5, 2, 5, 2)); - - return component; - } + public MaterialTreeCellRenderer() { + setTextSelectionColor(UIManager.getColor("Tree.selectionForeground")); + setTextNonSelectionColor(UIManager.getColor("Tree.foreground")); + + setBackgroundSelectionColor(UIManager.getColor("Tree.selectionBackground")); + setBackgroundNonSelectionColor(UIManager.getColor("Tree.background")); + + setBorderSelectionColor(UIManager.getColor("Tree.selectionBorderColor")); + + setClosedIcon(UIManager.getIcon("Tree.closedIcon")); + setOpenIcon(UIManager.getIcon("Tree.openIcon")); + setLeafIcon(null); + + setFont(UIManager.getFont("Tree.font")); + } + + @Override + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean isSelected, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + JComponent component = + (JComponent) + super.getTreeCellRendererComponent( + tree, value, isSelected, expanded, leaf, row, hasFocus); + component.setBorder(BorderFactory.createEmptyBorder(5, 2, 5, 2)); + + return component; + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java index f21b0dfaa..7d38c62f3 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/components/MaterialTreeUI.java @@ -12,33 +12,33 @@ public class MaterialTreeUI extends BasicTreeUI { - public static ComponentUI createUI(JComponent c) { - return new MaterialTreeUI(); - } - - @Override - public void installUI(JComponent c) { - super.installUI(c); - JTree tree = (JTree) c; - - DefaultTreeCellRenderer renderer = new MaterialTreeCellRenderer(); - TreeCellEditor editor = new MaterialTreeCellEditor(tree, renderer); - - tree.setCellRenderer(renderer); - tree.setCellEditor(editor); - - tree.setFont(UIManager.getFont("Tree.font")); - tree.setRowHeight(0); - tree.setInvokesStopCellEditing(true); - - MaterialTreeUI ui = (MaterialTreeUI) tree.getUI(); - ui.setLeftChildIndent(10); - ui.setRightChildIndent(10); - } - - @Override - public void paint(Graphics g, JComponent c) { - g = MaterialDrawingUtils.getAliasedGraphics(g); - super.paint(g, c); - } + public static ComponentUI createUI(JComponent c) { + return new MaterialTreeUI(); + } + + @Override + public void installUI(JComponent c) { + super.installUI(c); + JTree tree = (JTree) c; + + DefaultTreeCellRenderer renderer = new MaterialTreeCellRenderer(); + TreeCellEditor editor = new MaterialTreeCellEditor(tree, renderer); + + tree.setCellRenderer(renderer); + tree.setCellEditor(editor); + + tree.setFont(UIManager.getFont("Tree.font")); + tree.setRowHeight(0); + tree.setInvokesStopCellEditing(true); + + MaterialTreeUI ui = (MaterialTreeUI) tree.getUI(); + ui.setLeftChildIndent(10); + ui.setRightChildIndent(10); + } + + @Override + public void paint(Graphics g, JComponent c) { + g = MaterialDrawingUtils.getAliasedGraphics(g); + super.paint(g, c); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java index e0b9ca436..ce3244d4d 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/DropShadowBorder.java @@ -29,389 +29,410 @@ */ public class DropShadowBorder extends AbstractBorder implements Border { - private static final Map> CACHE = - new HashMap>(); - private Color lineColor; - private int lineWidth; - private int shadowSize; - private float shadowOpacity; - private int cornerSize; - private boolean showTopShadow; - private boolean showLeftShadow; - private boolean showBottomShadow; - private boolean showRightShadow; - - public DropShadowBorder() { - this(UIManager.getColor("Control"), 1, 5); - } - - public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) { - this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true); - } - - public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) { - this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true); - } - - public DropShadowBorder( - Color lineColor, - int lineWidth, - int shadowSize, - float shadowOpacity, - int cornerSize, - boolean showTopShadow, - boolean showLeftShadow, - boolean showBottomShadow, - boolean showRightShadow) { - this.lineColor = lineColor; - this.lineWidth = lineWidth; - this.shadowSize = shadowSize; - this.shadowOpacity = shadowOpacity; - this.cornerSize = cornerSize; - this.showTopShadow = showTopShadow; - this.showLeftShadow = showLeftShadow; - this.showBottomShadow = showBottomShadow; - this.showRightShadow = showRightShadow; - } - - /** */ - public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { - /* - * 1) Get images for this border - * 2) Paint the images for each side of the border that should be painted - */ - Map images = getImages(null); - - // compute the edges of the components -- not including the border - // Insets borderInsets = getBorderInsets (c); - // int leftEdge = x + borderInsets.left - lineWidth; - // int rightEdge = x + width - borderInsets.right; - // int topEdge = y + borderInsets.top - lineWidth; - // int bottomEdge = y + height - borderInsets.bottom; - Graphics2D g2 = (Graphics2D) graphics; - g2.setColor(lineColor); - - // The location and size of the shadows depends on which shadows are being - // drawn. For instance, if the left & bottom shadows are being drawn, then - // the left shadows extends all the way down to the corner, a corner is drawn, - // and then the bottom shadows begins at the corner. If, however, only the - // bottom shadows is drawn, then the bottom-left corner is drawn to the - // right of the corner, and the bottom shadows is somewhat shorter than before. - - Point topLeftShadowPoint = null; - if (showLeftShadow || showTopShadow) { - topLeftShadowPoint = new Point(); - if (showLeftShadow && !showTopShadow) { - topLeftShadowPoint.setLocation(x, y + shadowSize); - } else { - if (showLeftShadow && showTopShadow) { - topLeftShadowPoint.setLocation(x, y); - } else { - if (!showLeftShadow && showTopShadow) { - topLeftShadowPoint.setLocation(x + shadowSize, y); - } - } - } + private static final Map> CACHE = + new HashMap>(); + private Color lineColor; + private int lineWidth; + private int shadowSize; + private float shadowOpacity; + private int cornerSize; + private boolean showTopShadow; + private boolean showLeftShadow; + private boolean showBottomShadow; + private boolean showRightShadow; + + public DropShadowBorder() { + this(UIManager.getColor("Control"), 1, 5); } - Point bottomLeftShadowPoint = null; - if (showLeftShadow || showBottomShadow) { - bottomLeftShadowPoint = new Point(); - if (showLeftShadow && !showBottomShadow) { - bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); - } else { - if (showLeftShadow && showBottomShadow) { - bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); - } else { - if (!showLeftShadow && showBottomShadow) { - bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); - } - } - } + public DropShadowBorder(Color lineColor, int lineWidth, int shadowSize) { + this(lineColor, lineWidth, shadowSize, .5f, 12, false, false, true, true); } - Point bottomRightShadowPoint = null; - if (showRightShadow || showBottomShadow) { - bottomRightShadowPoint = new Point(); - if (showRightShadow && !showBottomShadow) { - bottomRightShadowPoint.setLocation( - x + width - shadowSize, y + height - shadowSize - shadowSize); - } else { - if (showRightShadow && showBottomShadow) { - bottomRightShadowPoint.setLocation(x + width - shadowSize, y + height - shadowSize); - } else { - if (!showRightShadow && showBottomShadow) { - bottomRightShadowPoint.setLocation( - x + width - shadowSize - shadowSize, y + height - shadowSize); - } + public DropShadowBorder(Color lineColor, int lineWidth, boolean showLeftShadow) { + this(lineColor, lineWidth, 5, .5f, 12, false, showLeftShadow, true, true); + } + + public DropShadowBorder( + Color lineColor, + int lineWidth, + int shadowSize, + float shadowOpacity, + int cornerSize, + boolean showTopShadow, + boolean showLeftShadow, + boolean showBottomShadow, + boolean showRightShadow) { + this.lineColor = lineColor; + this.lineWidth = lineWidth; + this.shadowSize = shadowSize; + this.shadowOpacity = shadowOpacity; + this.cornerSize = cornerSize; + this.showTopShadow = showTopShadow; + this.showLeftShadow = showLeftShadow; + this.showBottomShadow = showBottomShadow; + this.showRightShadow = showRightShadow; + } + + /** */ + public void paintBorder(Component c, Graphics graphics, int x, int y, int width, int height) { + /* + * 1) Get images for this border + * 2) Paint the images for each side of the border that should be painted + */ + Map images = getImages(null); + + // compute the edges of the components -- not including the border + // Insets borderInsets = getBorderInsets (c); + // int leftEdge = x + borderInsets.left - lineWidth; + // int rightEdge = x + width - borderInsets.right; + // int topEdge = y + borderInsets.top - lineWidth; + // int bottomEdge = y + height - borderInsets.bottom; + Graphics2D g2 = (Graphics2D) graphics; + g2.setColor(lineColor); + + // The location and size of the shadows depends on which shadows are being + // drawn. For instance, if the left & bottom shadows are being drawn, then + // the left shadows extends all the way down to the corner, a corner is drawn, + // and then the bottom shadows begins at the corner. If, however, only the + // bottom shadows is drawn, then the bottom-left corner is drawn to the + // right of the corner, and the bottom shadows is somewhat shorter than before. + + Point topLeftShadowPoint = null; + if (showLeftShadow || showTopShadow) { + topLeftShadowPoint = new Point(); + if (showLeftShadow && !showTopShadow) { + topLeftShadowPoint.setLocation(x, y + shadowSize); + } else { + if (showLeftShadow && showTopShadow) { + topLeftShadowPoint.setLocation(x, y); + } else { + if (!showLeftShadow && showTopShadow) { + topLeftShadowPoint.setLocation(x + shadowSize, y); + } + } + } + } + + Point bottomLeftShadowPoint = null; + if (showLeftShadow || showBottomShadow) { + bottomLeftShadowPoint = new Point(); + if (showLeftShadow && !showBottomShadow) { + bottomLeftShadowPoint.setLocation(x, y + height - shadowSize - shadowSize); + } else { + if (showLeftShadow && showBottomShadow) { + bottomLeftShadowPoint.setLocation(x, y + height - shadowSize); + } else { + if (!showLeftShadow && showBottomShadow) { + bottomLeftShadowPoint.setLocation(x + shadowSize, y + height - shadowSize); + } + } + } + } + + Point bottomRightShadowPoint = null; + if (showRightShadow || showBottomShadow) { + bottomRightShadowPoint = new Point(); + if (showRightShadow && !showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize, y + height - shadowSize - shadowSize); + } else { + if (showRightShadow && showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize, y + height - shadowSize); + } else { + if (!showRightShadow && showBottomShadow) { + bottomRightShadowPoint.setLocation( + x + width - shadowSize - shadowSize, y + height - shadowSize); + } + } + } + } + + Point topRightShadowPoint = null; + if (showRightShadow || showTopShadow) { + topRightShadowPoint = new Point(); + if (showRightShadow && !showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize); + } else { + if (showRightShadow && showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize, y); + } else { + if (!showRightShadow && showTopShadow) { + topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); + } + } + } + } + + if (showLeftShadow) { + Rectangle leftShadowRect = + new Rectangle( + x, + (int) (topLeftShadowPoint.getY() + shadowSize), + shadowSize, + (int) + (bottomLeftShadowPoint.getY() + - topLeftShadowPoint.getY() + - shadowSize)); + g2.drawImage( + images.get(Position.LEFT) + .getScaledInstance( + leftShadowRect.width, leftShadowRect.height, Image.SCALE_FAST), + leftShadowRect.x, + leftShadowRect.y, + null); + } + + if (showBottomShadow) { + Rectangle bottomShadowRect = + new Rectangle( + (int) (bottomLeftShadowPoint.getX() + shadowSize), + y + height - shadowSize, + (int) + (bottomRightShadowPoint.getX() + - bottomLeftShadowPoint.getX() + - shadowSize), + shadowSize); + g2.drawImage( + images.get(Position.BOTTOM) + .getScaledInstance( + bottomShadowRect.width, + bottomShadowRect.height, + Image.SCALE_FAST), + bottomShadowRect.x, + bottomShadowRect.y, + null); + } + + if (showRightShadow) { + Rectangle rightShadowRect = + new Rectangle( + x + width - shadowSize, + (int) (topRightShadowPoint.getY() + shadowSize), + shadowSize, + (int) + (bottomRightShadowPoint.getY() + - topRightShadowPoint.getY() + - shadowSize)); + g2.drawImage( + images.get(Position.RIGHT) + .getScaledInstance( + rightShadowRect.width, + rightShadowRect.height, + Image.SCALE_FAST), + rightShadowRect.x, + rightShadowRect.y, + null); + } + + if (showTopShadow) { + Rectangle topShadowRect = + new Rectangle( + (int) topLeftShadowPoint.getX() + shadowSize, + y, + (int) + (topRightShadowPoint.getX() + - topLeftShadowPoint.getX() + - shadowSize), + shadowSize); + g2.drawImage( + images.get(Position.TOP) + .getScaledInstance( + topShadowRect.width, topShadowRect.height, Image.SCALE_FAST), + topShadowRect.x, + topShadowRect.y, + null); + } + + if (showLeftShadow || showTopShadow) { + g2.drawImage( + images.get(Position.TOP_LEFT), + null, + (int) topLeftShadowPoint.getX(), + (int) topLeftShadowPoint.getY()); + } + if (showLeftShadow || showBottomShadow) { + g2.drawImage( + images.get(Position.BOTTOM_LEFT), + null, + (int) bottomLeftShadowPoint.getX(), + (int) bottomLeftShadowPoint.getY()); + } + if (showRightShadow || showBottomShadow) { + g2.drawImage( + images.get(Position.BOTTOM_RIGHT), + null, + (int) bottomRightShadowPoint.getX(), + (int) bottomRightShadowPoint.getY()); + } + if (showRightShadow || showTopShadow) { + g2.drawImage( + images.get(Position.TOP_RIGHT), + null, + (int) topRightShadowPoint.getX(), + (int) topRightShadowPoint.getY()); } - } } - Point topRightShadowPoint = null; - if (showRightShadow || showTopShadow) { - topRightShadowPoint = new Point(); - if (showRightShadow && !showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize, y + shadowSize); - } else { - if (showRightShadow && showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize, y); - } else { - if (!showRightShadow && showTopShadow) { - topRightShadowPoint.setLocation(x + width - shadowSize - shadowSize, y); - } + private Map getImages(Graphics2D g2) { + // first, check to see if an image for this size has already been rendered + // if so, use the cache. Else, draw and save + Map images = CACHE.get(shadowSize); + if (images == null) { + images = new HashMap(); + + /* + * Do draw a drop shadows, I have to: + * 1) Create a rounded rectangle + * 2) Create a BufferedImage to draw the rounded rect in + * 3) Translate the graphics for the image, so that the rectangle + * is centered in the drawn space. The border around the rectangle + * needs to be shadowWidth wide, so that there is space for the + * shadows to be drawn. + * 4) Draw the rounded rect as black, with an opacity of 50% + * 5) Create the BLUR_KERNEL + * 6) Blur the image + * 7) copy off the corners, sides, etc into images to be used for + * drawing the Border + */ + int rectWidth = cornerSize + 1; + RoundRectangle2D rect = + new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); + int imageWidth = rectWidth + shadowSize * 2; + BufferedImage image = + new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); + Graphics2D buffer = (Graphics2D) image.getGraphics(); + buffer.setRenderingHint( + RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + buffer.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + buffer.setRenderingHint( + RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + buffer.setRenderingHint( + RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_ON); + buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); + buffer.translate(shadowSize, shadowSize); + buffer.fill(rect); + float blurry = 1.0f / (float) (shadowSize * shadowSize); // 1.0f / (float)(shadowSize * + // shadowSize); + float[] blurKernel = new float[shadowSize * shadowSize]; + for (int i = 0; i < blurKernel.length; i++) { + blurKernel[i] = blurry; + } + ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); + BufferedImage targetImage = + new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); + ((Graphics2D) targetImage.getGraphics()) + .drawImage(image, blur, -(shadowSize / 2), -(shadowSize / 2)); + + int x = 1; + int y = 1; + int w = shadowSize; + int h = shadowSize; + images.put(Position.TOP_LEFT, targetImage.getSubimage(x, y, w, h)); + x = 1; + y = h; + w = shadowSize; + h = 1; + images.put(Position.LEFT, targetImage.getSubimage(x, y, w, h)); + x = 1; + y = rectWidth; + w = shadowSize; + h = shadowSize; + images.put(Position.BOTTOM_LEFT, targetImage.getSubimage(x, y, w, h)); + x = cornerSize + 1; + y = rectWidth; + w = 1; + h = shadowSize; + images.put(Position.BOTTOM, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = x; + w = shadowSize; + h = shadowSize; + images.put(Position.BOTTOM_RIGHT, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = cornerSize + 1; + w = shadowSize; + h = 1; + images.put(Position.RIGHT, targetImage.getSubimage(x, y, w, h)); + x = rectWidth; + y = 1; + w = shadowSize; + h = shadowSize; + images.put(Position.TOP_RIGHT, targetImage.getSubimage(x, y, w, h)); + x = shadowSize; + y = 1; + w = 1; + h = shadowSize; + images.put(Position.TOP, targetImage.getSubimage(x, y, w, h)); + + buffer.dispose(); + image.flush(); } - } + return images; + } + + /** */ + public Insets getBorderInsets(Component c) { + int top = 4 + (showTopShadow ? lineWidth + shadowSize : lineWidth); + int left = 4 + (showLeftShadow ? lineWidth + shadowSize : lineWidth); + int bottom = 4 + (showBottomShadow ? lineWidth + shadowSize : lineWidth); + int right = 4 + (showRightShadow ? lineWidth + shadowSize : lineWidth); + + return new Insets(top, left, bottom, right); } - if (showLeftShadow) { - Rectangle leftShadowRect = - new Rectangle( - x, - (int) (topLeftShadowPoint.getY() + shadowSize), - shadowSize, - (int) (bottomLeftShadowPoint.getY() - topLeftShadowPoint.getY() - shadowSize)); - g2.drawImage( - images - .get(Position.LEFT) - .getScaledInstance(leftShadowRect.width, leftShadowRect.height, Image.SCALE_FAST), - leftShadowRect.x, - leftShadowRect.y, - null); + /** */ + public boolean isBorderOpaque() { + return true; } - if (showBottomShadow) { - Rectangle bottomShadowRect = - new Rectangle( - (int) (bottomLeftShadowPoint.getX() + shadowSize), - y + height - shadowSize, - (int) (bottomRightShadowPoint.getX() - bottomLeftShadowPoint.getX() - shadowSize), - shadowSize); - g2.drawImage( - images - .get(Position.BOTTOM) - .getScaledInstance(bottomShadowRect.width, bottomShadowRect.height, Image.SCALE_FAST), - bottomShadowRect.x, - bottomShadowRect.y, - null); + public boolean isShowTopShadow() { + return showTopShadow; } - if (showRightShadow) { - Rectangle rightShadowRect = - new Rectangle( - x + width - shadowSize, - (int) (topRightShadowPoint.getY() + shadowSize), - shadowSize, - (int) (bottomRightShadowPoint.getY() - topRightShadowPoint.getY() - shadowSize)); - g2.drawImage( - images - .get(Position.RIGHT) - .getScaledInstance(rightShadowRect.width, rightShadowRect.height, Image.SCALE_FAST), - rightShadowRect.x, - rightShadowRect.y, - null); + public boolean isShowLeftShadow() { + return showLeftShadow; } - if (showTopShadow) { - Rectangle topShadowRect = - new Rectangle( - (int) topLeftShadowPoint.getX() + shadowSize, - y, - (int) (topRightShadowPoint.getX() - topLeftShadowPoint.getX() - shadowSize), - shadowSize); - g2.drawImage( - images - .get(Position.TOP) - .getScaledInstance(topShadowRect.width, topShadowRect.height, Image.SCALE_FAST), - topShadowRect.x, - topShadowRect.y, - null); + public boolean isShowRightShadow() { + return showRightShadow; } - if (showLeftShadow || showTopShadow) { - g2.drawImage( - images.get(Position.TOP_LEFT), - null, - (int) topLeftShadowPoint.getX(), - (int) topLeftShadowPoint.getY()); + public boolean isShowBottomShadow() { + return showBottomShadow; } - if (showLeftShadow || showBottomShadow) { - g2.drawImage( - images.get(Position.BOTTOM_LEFT), - null, - (int) bottomLeftShadowPoint.getX(), - (int) bottomLeftShadowPoint.getY()); + + public int getLineWidth() { + return lineWidth; } - if (showRightShadow || showBottomShadow) { - g2.drawImage( - images.get(Position.BOTTOM_RIGHT), - null, - (int) bottomRightShadowPoint.getX(), - (int) bottomRightShadowPoint.getY()); + + public Color getLineColor() { + return lineColor; } - if (showRightShadow || showTopShadow) { - g2.drawImage( - images.get(Position.TOP_RIGHT), - null, - (int) topRightShadowPoint.getX(), - (int) topRightShadowPoint.getY()); + + public int getShadowSize() { + return shadowSize; } - } - - private Map getImages(Graphics2D g2) { - // first, check to see if an image for this size has already been rendered - // if so, use the cache. Else, draw and save - Map images = CACHE.get(shadowSize); - if (images == null) { - images = new HashMap(); - - /* - * Do draw a drop shadows, I have to: - * 1) Create a rounded rectangle - * 2) Create a BufferedImage to draw the rounded rect in - * 3) Translate the graphics for the image, so that the rectangle - * is centered in the drawn space. The border around the rectangle - * needs to be shadowWidth wide, so that there is space for the - * shadows to be drawn. - * 4) Draw the rounded rect as black, with an opacity of 50% - * 5) Create the BLUR_KERNEL - * 6) Blur the image - * 7) copy off the corners, sides, etc into images to be used for - * drawing the Border - */ - int rectWidth = cornerSize + 1; - RoundRectangle2D rect = - new RoundRectangle2D.Double(0, 0, rectWidth, rectWidth, cornerSize, cornerSize); - int imageWidth = rectWidth + shadowSize * 2; - BufferedImage image = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); - Graphics2D buffer = (Graphics2D) image.getGraphics(); - buffer.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - buffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - buffer.setRenderingHint( - RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - buffer.setRenderingHint( - RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - buffer.setColor(new Color(0.0f, 0.0f, 0.0f, shadowOpacity)); - buffer.translate(shadowSize, shadowSize); - buffer.fill(rect); - float blurry = 1.0f / (float) (shadowSize * shadowSize); // 1.0f / (float)(shadowSize * - // shadowSize); - float[] blurKernel = new float[shadowSize * shadowSize]; - for (int i = 0; i < blurKernel.length; i++) { - blurKernel[i] = blurry; - } - ConvolveOp blur = new ConvolveOp(new Kernel(shadowSize, shadowSize, blurKernel)); - BufferedImage targetImage = - new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_ARGB); - ((Graphics2D) targetImage.getGraphics()) - .drawImage(image, blur, -(shadowSize / 2), -(shadowSize / 2)); - - int x = 1; - int y = 1; - int w = shadowSize; - int h = shadowSize; - images.put(Position.TOP_LEFT, targetImage.getSubimage(x, y, w, h)); - x = 1; - y = h; - w = shadowSize; - h = 1; - images.put(Position.LEFT, targetImage.getSubimage(x, y, w, h)); - x = 1; - y = rectWidth; - w = shadowSize; - h = shadowSize; - images.put(Position.BOTTOM_LEFT, targetImage.getSubimage(x, y, w, h)); - x = cornerSize + 1; - y = rectWidth; - w = 1; - h = shadowSize; - images.put(Position.BOTTOM, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = x; - w = shadowSize; - h = shadowSize; - images.put(Position.BOTTOM_RIGHT, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = cornerSize + 1; - w = shadowSize; - h = 1; - images.put(Position.RIGHT, targetImage.getSubimage(x, y, w, h)); - x = rectWidth; - y = 1; - w = shadowSize; - h = shadowSize; - images.put(Position.TOP_RIGHT, targetImage.getSubimage(x, y, w, h)); - x = shadowSize; - y = 1; - w = 1; - h = shadowSize; - images.put(Position.TOP, targetImage.getSubimage(x, y, w, h)); - - buffer.dispose(); - image.flush(); + + public float getShadowOpacity() { + return shadowOpacity; + } + + public int getCornerSize() { + return cornerSize; + } + + private enum Position { + TOP, + TOP_LEFT, + LEFT, + BOTTOM_LEFT, + BOTTOM, + BOTTOM_RIGHT, + RIGHT, + TOP_RIGHT } - return images; - } - - /** */ - public Insets getBorderInsets(Component c) { - int top = 4 + (showTopShadow ? lineWidth + shadowSize : lineWidth); - int left = 4 + (showLeftShadow ? lineWidth + shadowSize : lineWidth); - int bottom = 4 + (showBottomShadow ? lineWidth + shadowSize : lineWidth); - int right = 4 + (showRightShadow ? lineWidth + shadowSize : lineWidth); - - return new Insets(top, left, bottom, right); - } - - /** */ - public boolean isBorderOpaque() { - return true; - } - - public boolean isShowTopShadow() { - return showTopShadow; - } - - public boolean isShowLeftShadow() { - return showLeftShadow; - } - - public boolean isShowRightShadow() { - return showRightShadow; - } - - public boolean isShowBottomShadow() { - return showBottomShadow; - } - - public int getLineWidth() { - return lineWidth; - } - - public Color getLineColor() { - return lineColor; - } - - public int getShadowSize() { - return shadowSize; - } - - public float getShadowOpacity() { - return shadowOpacity; - } - - public int getCornerSize() { - return cornerSize; - } - - private enum Position { - TOP, - TOP_LEFT, - LEFT, - BOTTOM_LEFT, - BOTTOM, - BOTTOM_RIGHT, - RIGHT, - TOP_RIGHT - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java index 049ce78af..8c2e3eeec 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialBorders.java @@ -6,15 +6,15 @@ public class MaterialBorders { - public static final Border LIGHT_LINE_BORDER = - BorderFactory.createLineBorder(MaterialColors.GRAY_200, 1); - public static final Border THICK_LINE_BORDER = - BorderFactory.createLineBorder(MaterialColors.GRAY_200, 2); + public static final Border LIGHT_LINE_BORDER = + BorderFactory.createLineBorder(MaterialColors.GRAY_200, 1); + public static final Border THICK_LINE_BORDER = + BorderFactory.createLineBorder(MaterialColors.GRAY_200, 2); - public static final Border LIGHT_SHADOW_BORDER = - new DropShadowBorder(Color.BLACK, 0, 4, 0.3f, 12, true, true, true, true); - public static final Border DEFAULT_SHADOW_BORDER = - new DropShadowBorder(Color.BLACK, 5, 5, 0.3f, 12, true, true, true, true); + public static final Border LIGHT_SHADOW_BORDER = + new DropShadowBorder(Color.BLACK, 0, 4, 0.3f, 12, true, true, true, true); + public static final Border DEFAULT_SHADOW_BORDER = + new DropShadowBorder(Color.BLACK, 5, 5, 0.3f, 12, true, true, true, true); - private MaterialBorders() {} + private MaterialBorders() {} } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java index f9678d403..00cb0720a 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialColors.java @@ -3,270 +3,270 @@ import java.awt.*; public class MaterialColors { - public static final Color RED_50 = new Color(255, 235, 238); - public static final Color RED_100 = new Color(255, 205, 210); - public static final Color RED_200 = new Color(239, 154, 154); - public static final Color RED_300 = new Color(229, 115, 115); - public static final Color RED_400 = new Color(239, 83, 80); - public static final Color RED_500 = new Color(244, 67, 54); - public static final Color RED_600 = new Color(229, 57, 53); - public static final Color RED_700 = new Color(211, 47, 47); - public static final Color RED_800 = new Color(198, 40, 40); - public static final Color RED_900 = new Color(183, 28, 28); - public static final Color RED_A100 = new Color(255, 138, 128); - public static final Color RED_A200 = new Color(255, 82, 82); - public static final Color RED_A400 = new Color(255, 23, 68); - public static final Color RED_A700 = new Color(213, 0, 0); - public static final Color PINK_50 = new Color(252, 228, 236); - public static final Color PINK_100 = new Color(248, 187, 208); - public static final Color PINK_200 = new Color(244, 143, 177); - public static final Color PINK_300 = new Color(240, 98, 146); - public static final Color PINK_400 = new Color(236, 64, 122); - public static final Color PINK_500 = new Color(233, 30, 99); - public static final Color PINK_600 = new Color(216, 27, 96); - public static final Color PINK_700 = new Color(194, 24, 91); - public static final Color PINK_800 = new Color(173, 20, 87); - public static final Color PINK_900 = new Color(136, 14, 79); - public static final Color PINK_A100 = new Color(255, 128, 171); - public static final Color PINK_A200 = new Color(255, 64, 129); - public static final Color PINK_A400 = new Color(245, 0, 87); - public static final Color PINK_A700 = new Color(197, 17, 98); - public static final Color PURPLE_50 = new Color(243, 229, 245); - public static final Color PURPLE_100 = new Color(225, 190, 231); - public static final Color PURPLE_200 = new Color(206, 147, 216); - public static final Color PURPLE_300 = new Color(186, 104, 200); - public static final Color PURPLE_400 = new Color(171, 71, 188); - public static final Color PURPLE_500 = new Color(156, 39, 176); - public static final Color PURPLE_600 = new Color(142, 36, 170); - public static final Color PURPLE_700 = new Color(123, 31, 162); - public static final Color PURPLE_800 = new Color(106, 27, 154); - public static final Color PURPLE_900 = new Color(74, 20, 140); - public static final Color PURPLE_A100 = new Color(234, 128, 252); - public static final Color PURPLE_A200 = new Color(224, 64, 251); - public static final Color PURPLE_A400 = new Color(213, 0, 249); - public static final Color PURPLE_A700 = new Color(170, 0, 255); - public static final Color DEEP_PURPLE_50 = new Color(237, 231, 246); - public static final Color DEEP_PURPLE_100 = new Color(209, 196, 233); - public static final Color DEEP_PURPLE_200 = new Color(179, 157, 219); - public static final Color DEEP_PURPLE_300 = new Color(149, 117, 205); - public static final Color DEEP_PURPLE_400 = new Color(126, 87, 194); - public static final Color DEEP_PURPLE_500 = new Color(103, 58, 183); - public static final Color DEEP_PURPLE_600 = new Color(94, 53, 177); - public static final Color DEEP_PURPLE_700 = new Color(81, 45, 168); - public static final Color DEEP_PURPLE_800 = new Color(69, 39, 160); - public static final Color DEEP_PURPLE_900 = new Color(49, 27, 146); - public static final Color DEEP_PURPLE_A100 = new Color(179, 136, 255); - public static final Color DEEP_PURPLE_A200 = new Color(124, 77, 255); - public static final Color DEEP_PURPLE_A400 = new Color(101, 31, 255); - public static final Color DEEP_PURPLE_A700 = new Color(98, 0, 234); - public static final Color INDIGO_50 = new Color(232, 234, 246); - public static final Color INDIGO_100 = new Color(197, 202, 233); - public static final Color INDIGO_200 = new Color(159, 168, 218); - public static final Color INDIGO_300 = new Color(121, 134, 203); - public static final Color INDIGO_400 = new Color(92, 107, 192); - public static final Color INDIGO_500 = new Color(63, 81, 181); - public static final Color INDIGO_600 = new Color(57, 73, 171); - public static final Color INDIGO_700 = new Color(48, 63, 159); - public static final Color INDIGO_800 = new Color(40, 53, 147); - public static final Color INDIGO_900 = new Color(26, 35, 126); - public static final Color INDIGO_A100 = new Color(140, 158, 255); - public static final Color INDIGO_A200 = new Color(83, 109, 254); - public static final Color INDIGO_A400 = new Color(61, 90, 254); - public static final Color INDIGO_A700 = new Color(48, 79, 254); - public static final Color BLUE_50 = new Color(227, 242, 253); - public static final Color BLUE_100 = new Color(187, 222, 251); - public static final Color BLUE_200 = new Color(144, 202, 249); - public static final Color BLUE_300 = new Color(100, 181, 246); - public static final Color BLUE_400 = new Color(66, 165, 245); - public static final Color BLUE_500 = new Color(33, 150, 243); - public static final Color BLUE_600 = new Color(30, 136, 229); - public static final Color BLUE_700 = new Color(25, 118, 210); - public static final Color BLUE_800 = new Color(21, 101, 192); - public static final Color BLUE_900 = new Color(13, 71, 161); - public static final Color BLUE_A100 = new Color(130, 177, 255); - public static final Color BLUE_A200 = new Color(68, 138, 255); - public static final Color BLUE_A400 = new Color(41, 121, 255); - public static final Color BLUE_A700 = new Color(41, 98, 255); - public static final Color LIGHT_BLUE_50 = new Color(225, 245, 254); - public static final Color LIGHT_BLUE_100 = new Color(179, 229, 252); - public static final Color LIGHT_BLUE_200 = new Color(129, 212, 250); - public static final Color LIGHT_BLUE_300 = new Color(79, 195, 247); - public static final Color LIGHT_BLUE_400 = new Color(41, 182, 246); - public static final Color LIGHT_BLUE_500 = new Color(3, 169, 244); - public static final Color LIGHT_BLUE_600 = new Color(3, 155, 229); - public static final Color LIGHT_BLUE_700 = new Color(2, 136, 209); - public static final Color LIGHT_BLUE_800 = new Color(2, 119, 189); - public static final Color LIGHT_BLUE_900 = new Color(1, 87, 155); - public static final Color LIGHT_BLUE_A100 = new Color(128, 216, 255); - public static final Color LIGHT_BLUE_A200 = new Color(64, 196, 255); - public static final Color LIGHT_BLUE_A400 = new Color(0, 176, 255); - public static final Color LIGHT_BLUE_A700 = new Color(0, 145, 234); - public static final Color CYAN_50 = new Color(224, 247, 250); - public static final Color CYAN_100 = new Color(178, 235, 242); - public static final Color CYAN_200 = new Color(128, 222, 234); - public static final Color CYAN_300 = new Color(77, 208, 225); - public static final Color CYAN_400 = new Color(38, 198, 218); - public static final Color CYAN_500 = new Color(0, 188, 212); - public static final Color CYAN_600 = new Color(0, 172, 193); - public static final Color CYAN_700 = new Color(0, 151, 167); - public static final Color CYAN_800 = new Color(0, 131, 143); - public static final Color CYAN_900 = new Color(0, 96, 100); - public static final Color CYAN_A100 = new Color(132, 255, 255); - public static final Color CYAN_A200 = new Color(24, 255, 255); - public static final Color CYAN_A400 = new Color(0, 229, 255); - public static final Color CYAN_A700 = new Color(0, 184, 212); - public static final Color TEAL_50 = new Color(224, 242, 241); - public static final Color TEAL_100 = new Color(178, 223, 219); - public static final Color TEAL_200 = new Color(128, 203, 196); - public static final Color TEAL_300 = new Color(77, 182, 172); - public static final Color TEAL_400 = new Color(38, 166, 154); - public static final Color TEAL_500 = new Color(0, 150, 136); - public static final Color TEAL_600 = new Color(0, 137, 123); - public static final Color TEAL_700 = new Color(0, 121, 107); - public static final Color TEAL_800 = new Color(0, 105, 92); - public static final Color TEAL_900 = new Color(0, 77, 64); - public static final Color TEAL_A100 = new Color(167, 255, 235); - public static final Color TEAL_A200 = new Color(100, 255, 218); - public static final Color TEAL_A400 = new Color(29, 233, 182); - public static final Color TEAL_A700 = new Color(0, 191, 165); - public static final Color GREEN_50 = new Color(232, 245, 233); - public static final Color GREEN_100 = new Color(200, 230, 201); - public static final Color GREEN_200 = new Color(165, 214, 167); - public static final Color GREEN_300 = new Color(129, 199, 132); - public static final Color GREEN_400 = new Color(102, 187, 106); - public static final Color GREEN_500 = new Color(76, 175, 80); - public static final Color GREEN_600 = new Color(67, 160, 71); - public static final Color GREEN_700 = new Color(56, 142, 60); - public static final Color GREEN_800 = new Color(46, 125, 50); - public static final Color GREEN_900 = new Color(27, 94, 32); - public static final Color GREEN_A100 = new Color(185, 246, 202); - public static final Color GREEN_A200 = new Color(105, 240, 174); - public static final Color GREEN_A400 = new Color(0, 230, 118); - public static final Color GREEN_A700 = new Color(0, 200, 83); - public static final Color LIGHT_GREEN_50 = new Color(241, 248, 233); - public static final Color LIGHT_GREEN_100 = new Color(220, 237, 200); - public static final Color LIGHT_GREEN_200 = new Color(197, 225, 165); - public static final Color LIGHT_GREEN_300 = new Color(174, 213, 129); - public static final Color LIGHT_GREEN_400 = new Color(156, 204, 101); - public static final Color LIGHT_GREEN_500 = new Color(139, 195, 74); - public static final Color LIGHT_GREEN_600 = new Color(124, 179, 66); - public static final Color LIGHT_GREEN_700 = new Color(104, 159, 56); - public static final Color LIGHT_GREEN_800 = new Color(85, 139, 47); - public static final Color LIGHT_GREEN_900 = new Color(51, 105, 30); - public static final Color LIGHT_GREEN_A100 = new Color(204, 255, 144); - public static final Color LIGHT_GREEN_A200 = new Color(178, 255, 89); - public static final Color LIGHT_GREEN_A400 = new Color(118, 255, 3); - public static final Color LIGHT_GREEN_A700 = new Color(100, 221, 23); - public static final Color LIME_50 = new Color(249, 251, 231); - public static final Color LIME_100 = new Color(240, 244, 195); - public static final Color LIME_200 = new Color(230, 238, 156); - public static final Color LIME_300 = new Color(220, 231, 117); - public static final Color LIME_400 = new Color(212, 225, 87); - public static final Color LIME_500 = new Color(205, 220, 57); - public static final Color LIME_600 = new Color(192, 202, 51); - public static final Color LIME_700 = new Color(175, 180, 43); - public static final Color LIME_800 = new Color(158, 157, 36); - public static final Color LIME_900 = new Color(130, 119, 23); - public static final Color LIME_A100 = new Color(244, 255, 129); - public static final Color LIME_A200 = new Color(238, 255, 65); - public static final Color LIME_A400 = new Color(198, 255, 0); - public static final Color LIME_A700 = new Color(174, 234, 0); - public static final Color YELLOW_50 = new Color(255, 253, 231); - public static final Color YELLOW_100 = new Color(255, 249, 196); - public static final Color YELLOW_200 = new Color(255, 245, 157); - public static final Color YELLOW_300 = new Color(255, 241, 118); - public static final Color YELLOW_400 = new Color(255, 238, 88); - public static final Color YELLOW_500 = new Color(255, 235, 59); - public static final Color YELLOW_600 = new Color(253, 216, 53); - public static final Color YELLOW_700 = new Color(251, 192, 45); - public static final Color YELLOW_800 = new Color(249, 168, 37); - public static final Color YELLOW_900 = new Color(245, 127, 23); - public static final Color YELLOW_A100 = new Color(255, 255, 141); - public static final Color YELLOW_A200 = new Color(255, 255, 0); - public static final Color YELLOW_A400 = new Color(255, 234, 0); - public static final Color YELLOW_A700 = new Color(255, 214, 0); - public static final Color AMBER_50 = new Color(255, 248, 225); - public static final Color AMBER_100 = new Color(255, 236, 179); - public static final Color AMBER_200 = new Color(255, 224, 130); - public static final Color AMBER_300 = new Color(255, 213, 79); - public static final Color AMBER_400 = new Color(255, 202, 40); - public static final Color AMBER_500 = new Color(255, 193, 7); - public static final Color AMBER_600 = new Color(255, 179, 0); - public static final Color AMBER_700 = new Color(255, 160, 0); - public static final Color AMBER_800 = new Color(255, 143, 0); - public static final Color AMBER_900 = new Color(255, 111, 0); - public static final Color AMBER_A100 = new Color(255, 229, 127); - public static final Color AMBER_A200 = new Color(255, 215, 64); - public static final Color AMBER_A400 = new Color(255, 196, 0); - public static final Color AMBER_A700 = new Color(255, 171, 0); - public static final Color ORANGE_50 = new Color(255, 243, 224); - public static final Color ORANGE_100 = new Color(255, 224, 178); - public static final Color ORANGE_200 = new Color(255, 204, 128); - public static final Color ORANGE_300 = new Color(255, 183, 77); - public static final Color ORANGE_400 = new Color(255, 167, 38); - public static final Color ORANGE_500 = new Color(255, 152, 0); - public static final Color ORANGE_600 = new Color(251, 140, 0); - public static final Color ORANGE_700 = new Color(245, 124, 0); - public static final Color ORANGE_800 = new Color(239, 108, 0); - public static final Color ORANGE_900 = new Color(230, 81, 0); - public static final Color ORANGE_A100 = new Color(255, 209, 128); - public static final Color ORANGE_A200 = new Color(255, 171, 64); - public static final Color ORANGE_A400 = new Color(255, 145, 0); - public static final Color ORANGE_A700 = new Color(255, 109, 0); - public static final Color DEEP_ORANGE_50 = new Color(251, 233, 231); - public static final Color DEEP_ORANGE_100 = new Color(255, 204, 188); - public static final Color DEEP_ORANGE_200 = new Color(255, 171, 145); - public static final Color DEEP_ORANGE_300 = new Color(255, 138, 101); - public static final Color DEEP_ORANGE_400 = new Color(255, 112, 67); - public static final Color DEEP_ORANGE_500 = new Color(255, 87, 34); - public static final Color DEEP_ORANGE_600 = new Color(244, 81, 30); - public static final Color DEEP_ORANGE_700 = new Color(230, 74, 25); - public static final Color DEEP_ORANGE_800 = new Color(216, 67, 21); - public static final Color DEEP_ORANGE_900 = new Color(191, 54, 12); - public static final Color DEEP_ORANGE_A100 = new Color(255, 158, 128); - public static final Color DEEP_ORANGE_A200 = new Color(255, 110, 64); - public static final Color DEEP_ORANGE_A400 = new Color(255, 61, 0); - public static final Color DEEP_ORANGE_A700 = new Color(221, 44, 0); - public static final Color BROWN_50 = new Color(239, 235, 233); - public static final Color BROWN_100 = new Color(215, 204, 200); - public static final Color BROWN_200 = new Color(188, 170, 164); - public static final Color BROWN_300 = new Color(161, 136, 127); - public static final Color BROWN_400 = new Color(141, 110, 99); - public static final Color BROWN_500 = new Color(121, 85, 72); - public static final Color BROWN_600 = new Color(109, 76, 65); - public static final Color BROWN_700 = new Color(93, 64, 55); - public static final Color BROWN_800 = new Color(78, 52, 46); - public static final Color BROWN_900 = new Color(62, 39, 35); - public static final Color GRAY_50 = new Color(250, 250, 250); - public static final Color GRAY_100 = new Color(245, 245, 245); - public static final Color GRAY_200 = new Color(238, 238, 238); - public static final Color GRAY_300 = new Color(224, 224, 224); - public static final Color GRAY_400 = new Color(189, 189, 189); - public static final Color GRAY_500 = new Color(158, 158, 158); - public static final Color GRAY_600 = new Color(117, 117, 117); - public static final Color GRAY_700 = new Color(97, 97, 97); - public static final Color GRAY_800 = new Color(66, 66, 66); - public static final Color GRAY_900 = new Color(33, 33, 33); - public static final Color BLUE_GRAY_50 = new Color(236, 239, 241); - public static final Color BLUE_GRAY_100 = new Color(207, 216, 220); - public static final Color BLUE_GRAY_200 = new Color(176, 190, 197); - public static final Color BLUE_GRAY_300 = new Color(144, 164, 174); - public static final Color BLUE_GRAY_400 = new Color(120, 144, 156); - public static final Color BLUE_GRAY_500 = new Color(96, 125, 139); - public static final Color BLUE_GRAY_600 = new Color(84, 110, 122); - public static final Color BLUE_GRAY_700 = new Color(69, 90, 100); - public static final Color BLUE_GRAY_800 = new Color(55, 71, 79); - public static final Color BLUE_GRAY_900 = new Color(38, 50, 56); - public static final Color BLACK = new Color(0, 0, 0); - public static final Color WHITE = new Color(255, 255, 255); - public static final Color TRANSPARENT = new Color(0, 0, 0, 255); + public static final Color RED_50 = new Color(255, 235, 238); + public static final Color RED_100 = new Color(255, 205, 210); + public static final Color RED_200 = new Color(239, 154, 154); + public static final Color RED_300 = new Color(229, 115, 115); + public static final Color RED_400 = new Color(239, 83, 80); + public static final Color RED_500 = new Color(244, 67, 54); + public static final Color RED_600 = new Color(229, 57, 53); + public static final Color RED_700 = new Color(211, 47, 47); + public static final Color RED_800 = new Color(198, 40, 40); + public static final Color RED_900 = new Color(183, 28, 28); + public static final Color RED_A100 = new Color(255, 138, 128); + public static final Color RED_A200 = new Color(255, 82, 82); + public static final Color RED_A400 = new Color(255, 23, 68); + public static final Color RED_A700 = new Color(213, 0, 0); + public static final Color PINK_50 = new Color(252, 228, 236); + public static final Color PINK_100 = new Color(248, 187, 208); + public static final Color PINK_200 = new Color(244, 143, 177); + public static final Color PINK_300 = new Color(240, 98, 146); + public static final Color PINK_400 = new Color(236, 64, 122); + public static final Color PINK_500 = new Color(233, 30, 99); + public static final Color PINK_600 = new Color(216, 27, 96); + public static final Color PINK_700 = new Color(194, 24, 91); + public static final Color PINK_800 = new Color(173, 20, 87); + public static final Color PINK_900 = new Color(136, 14, 79); + public static final Color PINK_A100 = new Color(255, 128, 171); + public static final Color PINK_A200 = new Color(255, 64, 129); + public static final Color PINK_A400 = new Color(245, 0, 87); + public static final Color PINK_A700 = new Color(197, 17, 98); + public static final Color PURPLE_50 = new Color(243, 229, 245); + public static final Color PURPLE_100 = new Color(225, 190, 231); + public static final Color PURPLE_200 = new Color(206, 147, 216); + public static final Color PURPLE_300 = new Color(186, 104, 200); + public static final Color PURPLE_400 = new Color(171, 71, 188); + public static final Color PURPLE_500 = new Color(156, 39, 176); + public static final Color PURPLE_600 = new Color(142, 36, 170); + public static final Color PURPLE_700 = new Color(123, 31, 162); + public static final Color PURPLE_800 = new Color(106, 27, 154); + public static final Color PURPLE_900 = new Color(74, 20, 140); + public static final Color PURPLE_A100 = new Color(234, 128, 252); + public static final Color PURPLE_A200 = new Color(224, 64, 251); + public static final Color PURPLE_A400 = new Color(213, 0, 249); + public static final Color PURPLE_A700 = new Color(170, 0, 255); + public static final Color DEEP_PURPLE_50 = new Color(237, 231, 246); + public static final Color DEEP_PURPLE_100 = new Color(209, 196, 233); + public static final Color DEEP_PURPLE_200 = new Color(179, 157, 219); + public static final Color DEEP_PURPLE_300 = new Color(149, 117, 205); + public static final Color DEEP_PURPLE_400 = new Color(126, 87, 194); + public static final Color DEEP_PURPLE_500 = new Color(103, 58, 183); + public static final Color DEEP_PURPLE_600 = new Color(94, 53, 177); + public static final Color DEEP_PURPLE_700 = new Color(81, 45, 168); + public static final Color DEEP_PURPLE_800 = new Color(69, 39, 160); + public static final Color DEEP_PURPLE_900 = new Color(49, 27, 146); + public static final Color DEEP_PURPLE_A100 = new Color(179, 136, 255); + public static final Color DEEP_PURPLE_A200 = new Color(124, 77, 255); + public static final Color DEEP_PURPLE_A400 = new Color(101, 31, 255); + public static final Color DEEP_PURPLE_A700 = new Color(98, 0, 234); + public static final Color INDIGO_50 = new Color(232, 234, 246); + public static final Color INDIGO_100 = new Color(197, 202, 233); + public static final Color INDIGO_200 = new Color(159, 168, 218); + public static final Color INDIGO_300 = new Color(121, 134, 203); + public static final Color INDIGO_400 = new Color(92, 107, 192); + public static final Color INDIGO_500 = new Color(63, 81, 181); + public static final Color INDIGO_600 = new Color(57, 73, 171); + public static final Color INDIGO_700 = new Color(48, 63, 159); + public static final Color INDIGO_800 = new Color(40, 53, 147); + public static final Color INDIGO_900 = new Color(26, 35, 126); + public static final Color INDIGO_A100 = new Color(140, 158, 255); + public static final Color INDIGO_A200 = new Color(83, 109, 254); + public static final Color INDIGO_A400 = new Color(61, 90, 254); + public static final Color INDIGO_A700 = new Color(48, 79, 254); + public static final Color BLUE_50 = new Color(227, 242, 253); + public static final Color BLUE_100 = new Color(187, 222, 251); + public static final Color BLUE_200 = new Color(144, 202, 249); + public static final Color BLUE_300 = new Color(100, 181, 246); + public static final Color BLUE_400 = new Color(66, 165, 245); + public static final Color BLUE_500 = new Color(33, 150, 243); + public static final Color BLUE_600 = new Color(30, 136, 229); + public static final Color BLUE_700 = new Color(25, 118, 210); + public static final Color BLUE_800 = new Color(21, 101, 192); + public static final Color BLUE_900 = new Color(13, 71, 161); + public static final Color BLUE_A100 = new Color(130, 177, 255); + public static final Color BLUE_A200 = new Color(68, 138, 255); + public static final Color BLUE_A400 = new Color(41, 121, 255); + public static final Color BLUE_A700 = new Color(41, 98, 255); + public static final Color LIGHT_BLUE_50 = new Color(225, 245, 254); + public static final Color LIGHT_BLUE_100 = new Color(179, 229, 252); + public static final Color LIGHT_BLUE_200 = new Color(129, 212, 250); + public static final Color LIGHT_BLUE_300 = new Color(79, 195, 247); + public static final Color LIGHT_BLUE_400 = new Color(41, 182, 246); + public static final Color LIGHT_BLUE_500 = new Color(3, 169, 244); + public static final Color LIGHT_BLUE_600 = new Color(3, 155, 229); + public static final Color LIGHT_BLUE_700 = new Color(2, 136, 209); + public static final Color LIGHT_BLUE_800 = new Color(2, 119, 189); + public static final Color LIGHT_BLUE_900 = new Color(1, 87, 155); + public static final Color LIGHT_BLUE_A100 = new Color(128, 216, 255); + public static final Color LIGHT_BLUE_A200 = new Color(64, 196, 255); + public static final Color LIGHT_BLUE_A400 = new Color(0, 176, 255); + public static final Color LIGHT_BLUE_A700 = new Color(0, 145, 234); + public static final Color CYAN_50 = new Color(224, 247, 250); + public static final Color CYAN_100 = new Color(178, 235, 242); + public static final Color CYAN_200 = new Color(128, 222, 234); + public static final Color CYAN_300 = new Color(77, 208, 225); + public static final Color CYAN_400 = new Color(38, 198, 218); + public static final Color CYAN_500 = new Color(0, 188, 212); + public static final Color CYAN_600 = new Color(0, 172, 193); + public static final Color CYAN_700 = new Color(0, 151, 167); + public static final Color CYAN_800 = new Color(0, 131, 143); + public static final Color CYAN_900 = new Color(0, 96, 100); + public static final Color CYAN_A100 = new Color(132, 255, 255); + public static final Color CYAN_A200 = new Color(24, 255, 255); + public static final Color CYAN_A400 = new Color(0, 229, 255); + public static final Color CYAN_A700 = new Color(0, 184, 212); + public static final Color TEAL_50 = new Color(224, 242, 241); + public static final Color TEAL_100 = new Color(178, 223, 219); + public static final Color TEAL_200 = new Color(128, 203, 196); + public static final Color TEAL_300 = new Color(77, 182, 172); + public static final Color TEAL_400 = new Color(38, 166, 154); + public static final Color TEAL_500 = new Color(0, 150, 136); + public static final Color TEAL_600 = new Color(0, 137, 123); + public static final Color TEAL_700 = new Color(0, 121, 107); + public static final Color TEAL_800 = new Color(0, 105, 92); + public static final Color TEAL_900 = new Color(0, 77, 64); + public static final Color TEAL_A100 = new Color(167, 255, 235); + public static final Color TEAL_A200 = new Color(100, 255, 218); + public static final Color TEAL_A400 = new Color(29, 233, 182); + public static final Color TEAL_A700 = new Color(0, 191, 165); + public static final Color GREEN_50 = new Color(232, 245, 233); + public static final Color GREEN_100 = new Color(200, 230, 201); + public static final Color GREEN_200 = new Color(165, 214, 167); + public static final Color GREEN_300 = new Color(129, 199, 132); + public static final Color GREEN_400 = new Color(102, 187, 106); + public static final Color GREEN_500 = new Color(76, 175, 80); + public static final Color GREEN_600 = new Color(67, 160, 71); + public static final Color GREEN_700 = new Color(56, 142, 60); + public static final Color GREEN_800 = new Color(46, 125, 50); + public static final Color GREEN_900 = new Color(27, 94, 32); + public static final Color GREEN_A100 = new Color(185, 246, 202); + public static final Color GREEN_A200 = new Color(105, 240, 174); + public static final Color GREEN_A400 = new Color(0, 230, 118); + public static final Color GREEN_A700 = new Color(0, 200, 83); + public static final Color LIGHT_GREEN_50 = new Color(241, 248, 233); + public static final Color LIGHT_GREEN_100 = new Color(220, 237, 200); + public static final Color LIGHT_GREEN_200 = new Color(197, 225, 165); + public static final Color LIGHT_GREEN_300 = new Color(174, 213, 129); + public static final Color LIGHT_GREEN_400 = new Color(156, 204, 101); + public static final Color LIGHT_GREEN_500 = new Color(139, 195, 74); + public static final Color LIGHT_GREEN_600 = new Color(124, 179, 66); + public static final Color LIGHT_GREEN_700 = new Color(104, 159, 56); + public static final Color LIGHT_GREEN_800 = new Color(85, 139, 47); + public static final Color LIGHT_GREEN_900 = new Color(51, 105, 30); + public static final Color LIGHT_GREEN_A100 = new Color(204, 255, 144); + public static final Color LIGHT_GREEN_A200 = new Color(178, 255, 89); + public static final Color LIGHT_GREEN_A400 = new Color(118, 255, 3); + public static final Color LIGHT_GREEN_A700 = new Color(100, 221, 23); + public static final Color LIME_50 = new Color(249, 251, 231); + public static final Color LIME_100 = new Color(240, 244, 195); + public static final Color LIME_200 = new Color(230, 238, 156); + public static final Color LIME_300 = new Color(220, 231, 117); + public static final Color LIME_400 = new Color(212, 225, 87); + public static final Color LIME_500 = new Color(205, 220, 57); + public static final Color LIME_600 = new Color(192, 202, 51); + public static final Color LIME_700 = new Color(175, 180, 43); + public static final Color LIME_800 = new Color(158, 157, 36); + public static final Color LIME_900 = new Color(130, 119, 23); + public static final Color LIME_A100 = new Color(244, 255, 129); + public static final Color LIME_A200 = new Color(238, 255, 65); + public static final Color LIME_A400 = new Color(198, 255, 0); + public static final Color LIME_A700 = new Color(174, 234, 0); + public static final Color YELLOW_50 = new Color(255, 253, 231); + public static final Color YELLOW_100 = new Color(255, 249, 196); + public static final Color YELLOW_200 = new Color(255, 245, 157); + public static final Color YELLOW_300 = new Color(255, 241, 118); + public static final Color YELLOW_400 = new Color(255, 238, 88); + public static final Color YELLOW_500 = new Color(255, 235, 59); + public static final Color YELLOW_600 = new Color(253, 216, 53); + public static final Color YELLOW_700 = new Color(251, 192, 45); + public static final Color YELLOW_800 = new Color(249, 168, 37); + public static final Color YELLOW_900 = new Color(245, 127, 23); + public static final Color YELLOW_A100 = new Color(255, 255, 141); + public static final Color YELLOW_A200 = new Color(255, 255, 0); + public static final Color YELLOW_A400 = new Color(255, 234, 0); + public static final Color YELLOW_A700 = new Color(255, 214, 0); + public static final Color AMBER_50 = new Color(255, 248, 225); + public static final Color AMBER_100 = new Color(255, 236, 179); + public static final Color AMBER_200 = new Color(255, 224, 130); + public static final Color AMBER_300 = new Color(255, 213, 79); + public static final Color AMBER_400 = new Color(255, 202, 40); + public static final Color AMBER_500 = new Color(255, 193, 7); + public static final Color AMBER_600 = new Color(255, 179, 0); + public static final Color AMBER_700 = new Color(255, 160, 0); + public static final Color AMBER_800 = new Color(255, 143, 0); + public static final Color AMBER_900 = new Color(255, 111, 0); + public static final Color AMBER_A100 = new Color(255, 229, 127); + public static final Color AMBER_A200 = new Color(255, 215, 64); + public static final Color AMBER_A400 = new Color(255, 196, 0); + public static final Color AMBER_A700 = new Color(255, 171, 0); + public static final Color ORANGE_50 = new Color(255, 243, 224); + public static final Color ORANGE_100 = new Color(255, 224, 178); + public static final Color ORANGE_200 = new Color(255, 204, 128); + public static final Color ORANGE_300 = new Color(255, 183, 77); + public static final Color ORANGE_400 = new Color(255, 167, 38); + public static final Color ORANGE_500 = new Color(255, 152, 0); + public static final Color ORANGE_600 = new Color(251, 140, 0); + public static final Color ORANGE_700 = new Color(245, 124, 0); + public static final Color ORANGE_800 = new Color(239, 108, 0); + public static final Color ORANGE_900 = new Color(230, 81, 0); + public static final Color ORANGE_A100 = new Color(255, 209, 128); + public static final Color ORANGE_A200 = new Color(255, 171, 64); + public static final Color ORANGE_A400 = new Color(255, 145, 0); + public static final Color ORANGE_A700 = new Color(255, 109, 0); + public static final Color DEEP_ORANGE_50 = new Color(251, 233, 231); + public static final Color DEEP_ORANGE_100 = new Color(255, 204, 188); + public static final Color DEEP_ORANGE_200 = new Color(255, 171, 145); + public static final Color DEEP_ORANGE_300 = new Color(255, 138, 101); + public static final Color DEEP_ORANGE_400 = new Color(255, 112, 67); + public static final Color DEEP_ORANGE_500 = new Color(255, 87, 34); + public static final Color DEEP_ORANGE_600 = new Color(244, 81, 30); + public static final Color DEEP_ORANGE_700 = new Color(230, 74, 25); + public static final Color DEEP_ORANGE_800 = new Color(216, 67, 21); + public static final Color DEEP_ORANGE_900 = new Color(191, 54, 12); + public static final Color DEEP_ORANGE_A100 = new Color(255, 158, 128); + public static final Color DEEP_ORANGE_A200 = new Color(255, 110, 64); + public static final Color DEEP_ORANGE_A400 = new Color(255, 61, 0); + public static final Color DEEP_ORANGE_A700 = new Color(221, 44, 0); + public static final Color BROWN_50 = new Color(239, 235, 233); + public static final Color BROWN_100 = new Color(215, 204, 200); + public static final Color BROWN_200 = new Color(188, 170, 164); + public static final Color BROWN_300 = new Color(161, 136, 127); + public static final Color BROWN_400 = new Color(141, 110, 99); + public static final Color BROWN_500 = new Color(121, 85, 72); + public static final Color BROWN_600 = new Color(109, 76, 65); + public static final Color BROWN_700 = new Color(93, 64, 55); + public static final Color BROWN_800 = new Color(78, 52, 46); + public static final Color BROWN_900 = new Color(62, 39, 35); + public static final Color GRAY_50 = new Color(250, 250, 250); + public static final Color GRAY_100 = new Color(245, 245, 245); + public static final Color GRAY_200 = new Color(238, 238, 238); + public static final Color GRAY_300 = new Color(224, 224, 224); + public static final Color GRAY_400 = new Color(189, 189, 189); + public static final Color GRAY_500 = new Color(158, 158, 158); + public static final Color GRAY_600 = new Color(117, 117, 117); + public static final Color GRAY_700 = new Color(97, 97, 97); + public static final Color GRAY_800 = new Color(66, 66, 66); + public static final Color GRAY_900 = new Color(33, 33, 33); + public static final Color BLUE_GRAY_50 = new Color(236, 239, 241); + public static final Color BLUE_GRAY_100 = new Color(207, 216, 220); + public static final Color BLUE_GRAY_200 = new Color(176, 190, 197); + public static final Color BLUE_GRAY_300 = new Color(144, 164, 174); + public static final Color BLUE_GRAY_400 = new Color(120, 144, 156); + public static final Color BLUE_GRAY_500 = new Color(96, 125, 139); + public static final Color BLUE_GRAY_600 = new Color(84, 110, 122); + public static final Color BLUE_GRAY_700 = new Color(69, 90, 100); + public static final Color BLUE_GRAY_800 = new Color(55, 71, 79); + public static final Color BLUE_GRAY_900 = new Color(38, 50, 56); + public static final Color BLACK = new Color(0, 0, 0); + public static final Color WHITE = new Color(255, 255, 255); + public static final Color TRANSPARENT = new Color(0, 0, 0, 255); - private MaterialColors() {} + private MaterialColors() {} - public static Color bleach(Color color, float amount) { - int red = (int) ((color.getRed() * (1 - amount) / 255 + amount) * 255); - int green = (int) ((color.getGreen() * (1 - amount) / 255 + amount) * 255); - int blue = (int) ((color.getBlue() * (1 - amount) / 255 + amount) * 255); - return new Color(red, green, blue); - } + public static Color bleach(Color color, float amount) { + int red = (int) ((color.getRed() * (1 - amount) / 255 + amount) * 255); + int green = (int) ((color.getGreen() * (1 - amount) / 255 + amount) * 255); + int blue = (int) ((color.getBlue() * (1 - amount) / 255 + amount) * 255); + return new Color(red, green, blue); + } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java index 30c4fdeda..f5e209b0d 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialDrawingUtils.java @@ -8,28 +8,28 @@ public class MaterialDrawingUtils { - static { - System.setProperty("awt.useSystemAAFontSettings", "on"); - System.setProperty("swing.aatext", "true"); - System.setProperty("sun.java2d.xrender", "true"); - } + static { + System.setProperty("awt.useSystemAAFontSettings", "on"); + System.setProperty("swing.aatext", "true"); + System.setProperty("sun.java2d.xrender", "true"); + } - public static Graphics getAliasedGraphics(Graphics g) { - Map hints = - (Map) - Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); - if (hints != null) { - hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + public static Graphics getAliasedGraphics(Graphics g) { + Map hints = + (Map) + Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); + if (hints != null) { + hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - Graphics2D g2d = (Graphics2D) g; - g2d.addRenderingHints(hints); + Graphics2D g2d = (Graphics2D) g; + g2d.addRenderingHints(hints); - // g2d.addRenderingHints (new RenderingHints (RenderingHints.KEY_ANTIALIASING, - // RenderingHints.VALUE_ANTIALIAS_ON)); - return g2d; - } else { - // Desktop hints not supported on this platform - return g; + // g2d.addRenderingHints (new RenderingHints (RenderingHints.KEY_ANTIALIASING, + // RenderingHints.VALUE_ANTIALIAS_ON)); + return g2d; + } else { + // Desktop hints not supported on this platform + return g; + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java index cb6a79f86..e5d1de56c 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialFonts.java @@ -9,51 +9,52 @@ public class MaterialFonts { - private static final Map fontSettings = new HashMap<>(); - - public static final Font BLACK = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Black.ttf"); - public static final Font BLACK_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BlackItalic.ttf"); - public static final Font BOLD = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Bold.ttf"); - public static final Font BOLD_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BoldItalic.ttf"); - public static final Font ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Italic.ttf"); - public static final Font LIGHT = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Light.ttf"); - public static final Font LIGHT_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-LightItalic.ttf"); - public static final Font MEDIUM = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Medium.ttf"); - public static final Font MEDIUM_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-MediumItalic.ttf"); - public static final Font REGULAR = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf"); - public static final Font THIN = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Thin.ttf"); - public static final Font THIN_ITALIC = - loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-ThinItalic.ttf"); - - private static Font loadFont(String fontPath) { - if (fontSettings.isEmpty()) { - fontSettings.put(TextAttribute.SIZE, 14f); - fontSettings.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + private static final Map fontSettings = new HashMap<>(); + + public static final Font BLACK = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Black.ttf"); + public static final Font BLACK_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BlackItalic.ttf"); + public static final Font BOLD = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Bold.ttf"); + public static final Font BOLD_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-BoldItalic.ttf"); + public static final Font ITALIC = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Italic.ttf"); + public static final Font LIGHT = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Light.ttf"); + public static final Font LIGHT_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-LightItalic.ttf"); + public static final Font MEDIUM = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Medium.ttf"); + public static final Font MEDIUM_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-MediumItalic.ttf"); + public static final Font REGULAR = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf"); + public static final Font THIN = loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-Thin.ttf"); + public static final Font THIN_ITALIC = + loadFont("/edu/rpi/legup/fonts/Roboto/Roboto-ThinItalic.ttf"); + + private static Font loadFont(String fontPath) { + if (fontSettings.isEmpty()) { + fontSettings.put(TextAttribute.SIZE, 14f); + fontSettings.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + } + + try (InputStream inputStream = MaterialFonts.class.getResourceAsStream(fontPath)) { + return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(fontSettings); + } catch (IOException | FontFormatException e) { + e.printStackTrace(); + throw new RuntimeException("Font " + fontPath + " wasn't loaded"); + } } - try (InputStream inputStream = MaterialFonts.class.getResourceAsStream(fontPath)) { - return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(fontSettings); - } catch (IOException | FontFormatException e) { - e.printStackTrace(); - throw new RuntimeException("Font " + fontPath + " wasn't loaded"); + public static Font getRegularFont(float size) { + final Map map = new HashMap<>(); + map.put(TextAttribute.SIZE, size); + map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + + try (InputStream inputStream = + MaterialFonts.class.getResourceAsStream( + "/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf")) { + return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(map); + } catch (IOException | FontFormatException e) { + e.printStackTrace(); + throw new RuntimeException("Font regular wasn't loaded"); + } } - } - - public static Font getRegularFont(float size) { - final Map map = new HashMap<>(); - map.put(TextAttribute.SIZE, size); - map.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); - - try (InputStream inputStream = - MaterialFonts.class.getResourceAsStream("/edu/rpi/legup/fonts/Roboto/Roboto-Regular.ttf")) { - return Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(map); - } catch (IOException | FontFormatException e) { - e.printStackTrace(); - throw new RuntimeException("Font regular wasn't loaded"); - } - } } diff --git a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java index 93abff7a2..a1a716c76 100644 --- a/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java +++ b/src/main/java/edu/rpi/legup/ui/lookandfeel/materialdesign/MaterialImages.java @@ -7,41 +7,43 @@ public class MaterialImages { - public static final BufferedImage RIGHT_ARROW = loadImg("/edu/rpi/legup/imgs/right_arrow.png"); - public static final BufferedImage DOWN_ARROW = loadImg("/edu/rpi/legup/imgs/down_arrow.png"); - public static final BufferedImage UP_ARROW = loadImg("/edu/rpi/legup/imgs/up_arrow.png"); - public static final BufferedImage PAINTED_CHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/painted_checked_box.png"); - public static final BufferedImage OUTLINED_CHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/outlined_checked_box.png"); - public static final BufferedImage UNCHECKED_BOX = - loadImg("/edu/rpi/legup/imgs/unchecked_box.png"); - public static final BufferedImage RADIO_BUTTON_ON = - loadImg("/edu/rpi/legup/imgs/radio_button_on.png"); - public static final BufferedImage RADIO_BUTTON_OFF = - loadImg("/edu/rpi/legup/imgs/radio_button_off.png"); - public static final BufferedImage TOGGLE_BUTTON_ON = loadImg("/edu/rpi/legup/imgs/toggle_on.png"); - public static final BufferedImage TOGGLE_BUTTON_OFF = - loadImg("/edu/rpi/legup/imgs/toggle_off.png"); - public static final BufferedImage BACK_ARROW = loadImg("/edu/rpi/legup/imgs/back_arrow.png"); - public static final BufferedImage COMPUTER = loadImg("/edu/rpi/legup/imgs/computer.png"); - public static final BufferedImage FILE = loadImg("/edu/rpi/legup/imgs/file.png"); - public static final BufferedImage FLOPPY_DRIVE = loadImg("/edu/rpi/legup/imgs/floppy_drive.png"); - public static final BufferedImage FOLDER = loadImg("/edu/rpi/legup/imgs/folder.png"); - public static final BufferedImage HARD_DRIVE = loadImg("/edu/rpi/legup/imgs/hard_drive.png"); - public static final BufferedImage HOME = loadImg("/edu/rpi/legup/imgs/home.png"); - public static final BufferedImage LIST = loadImg("/edu/rpi/legup/imgs/list.png"); - public static final BufferedImage NEW_FOLDER = loadImg("/edu/rpi/legup/imgs/new_folder.png"); - public static final BufferedImage DETAILS = loadImg("/edu/rpi/legup/imgs/details.png"); + public static final BufferedImage RIGHT_ARROW = loadImg("/edu/rpi/legup/imgs/right_arrow.png"); + public static final BufferedImage DOWN_ARROW = loadImg("/edu/rpi/legup/imgs/down_arrow.png"); + public static final BufferedImage UP_ARROW = loadImg("/edu/rpi/legup/imgs/up_arrow.png"); + public static final BufferedImage PAINTED_CHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/painted_checked_box.png"); + public static final BufferedImage OUTLINED_CHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/outlined_checked_box.png"); + public static final BufferedImage UNCHECKED_BOX = + loadImg("/edu/rpi/legup/imgs/unchecked_box.png"); + public static final BufferedImage RADIO_BUTTON_ON = + loadImg("/edu/rpi/legup/imgs/radio_button_on.png"); + public static final BufferedImage RADIO_BUTTON_OFF = + loadImg("/edu/rpi/legup/imgs/radio_button_off.png"); + public static final BufferedImage TOGGLE_BUTTON_ON = + loadImg("/edu/rpi/legup/imgs/toggle_on.png"); + public static final BufferedImage TOGGLE_BUTTON_OFF = + loadImg("/edu/rpi/legup/imgs/toggle_off.png"); + public static final BufferedImage BACK_ARROW = loadImg("/edu/rpi/legup/imgs/back_arrow.png"); + public static final BufferedImage COMPUTER = loadImg("/edu/rpi/legup/imgs/computer.png"); + public static final BufferedImage FILE = loadImg("/edu/rpi/legup/imgs/file.png"); + public static final BufferedImage FLOPPY_DRIVE = + loadImg("/edu/rpi/legup/imgs/floppy_drive.png"); + public static final BufferedImage FOLDER = loadImg("/edu/rpi/legup/imgs/folder.png"); + public static final BufferedImage HARD_DRIVE = loadImg("/edu/rpi/legup/imgs/hard_drive.png"); + public static final BufferedImage HOME = loadImg("/edu/rpi/legup/imgs/home.png"); + public static final BufferedImage LIST = loadImg("/edu/rpi/legup/imgs/list.png"); + public static final BufferedImage NEW_FOLDER = loadImg("/edu/rpi/legup/imgs/new_folder.png"); + public static final BufferedImage DETAILS = loadImg("/edu/rpi/legup/imgs/details.png"); - private MaterialImages() {} + private MaterialImages() {} - private static BufferedImage loadImg(String imgPath) { - try (InputStream inputStream = MaterialImages.class.getResourceAsStream(imgPath)) { - return ImageIO.read(inputStream); - } catch (IOException e) { - e.printStackTrace(); - throw new RuntimeException("Image " + imgPath + " wasn't loaded"); + private static BufferedImage loadImg(String imgPath) { + try (InputStream inputStream = MaterialImages.class.getResourceAsStream(imgPath)) { + return ImageIO.read(inputStream); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Image " + imgPath + " wasn't loaded"); + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java index c3c70db31..1fb0a16ab 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRulePanel.java @@ -3,18 +3,18 @@ import javax.swing.ImageIcon; public class CaseRulePanel extends RulePanel { - /** - * CaseRulePanel Constructor creates a CaseRulePanel - * - * @param ruleFrame rule frame that this CaseRulePanel is contained in - */ - CaseRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Case Rules.gif")); - this.name = "Case Rules"; - this.toolTip = "Case Rules"; - } + /** + * CaseRulePanel Constructor creates a CaseRulePanel + * + * @param ruleFrame rule frame that this CaseRulePanel is contained in + */ + CaseRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Case Rules.gif")); + this.name = "Case Rules"; + this.toolTip = "Case Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java index 1e7d6066c..ae9444db2 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/CaseRuleSelectionView.java @@ -6,16 +6,16 @@ public class CaseRuleSelectionView extends JPanel { - public CaseRuleSelectionView(RuleButton ruleButton) { - setLayout(new WrapLayout()); - Button button1 = new Button(ruleButton.getX() + ", " + ruleButton.getY()); - button1.setSize(50, 50); - Button button2 = new Button("How"); - button2.setSize(50, 50); + public CaseRuleSelectionView(RuleButton ruleButton) { + setLayout(new WrapLayout()); + Button button1 = new Button(ruleButton.getX() + ", " + ruleButton.getY()); + button1.setSize(50, 50); + Button button2 = new Button("How"); + button2.setSize(50, 50); - add(button1); - add(button2); + add(button1); + add(button2); - revalidate(); - } + revalidate(); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java index 5f5fb6aaf..f695491fb 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/ContradictionRulePanel.java @@ -3,18 +3,18 @@ import javax.swing.*; public class ContradictionRulePanel extends RulePanel { - /** - * ContradictionRulePanel Constructor creates a ContradictionRulePanel - * - * @param ruleFrame rule frame that this ContradictionRulePanel is contained in - */ - ContradictionRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Contradictions.gif")); - this.name = "Contradiction Rules"; - this.toolTip = "Contradiction Rules"; - } + /** + * ContradictionRulePanel Constructor creates a ContradictionRulePanel + * + * @param ruleFrame rule frame that this ContradictionRulePanel is contained in + */ + ContradictionRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Contradictions.gif")); + this.name = "Contradiction Rules"; + this.toolTip = "Contradiction Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java index a89811a64..2795f2df7 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/DirectRulePanel.java @@ -5,20 +5,20 @@ import org.apache.logging.log4j.Logger; public class DirectRulePanel extends RulePanel { - private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); + private static final Logger LOGGER = LogManager.getLogger(DirectRulePanel.class.getName()); - /** - * DirectRulePanel Constructor creates a basic rule panel - * - * @param ruleFrame rule frame that this basic rule panel is contained in - */ - DirectRulePanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Direct Rules"; - this.toolTip = "Direct Rules"; - } + /** + * DirectRulePanel Constructor creates a basic rule panel + * + * @param ruleFrame rule frame that this basic rule panel is contained in + */ + DirectRulePanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Direct Rules"; + this.toolTip = "Direct Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java index 6100b6964..e9c274250 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleButton.java @@ -4,36 +4,36 @@ import javax.swing.*; public class RuleButton extends JButton { - private Rule rule; + private Rule rule; - /** - * RuleButton Constructor - creates a button for a rule - * - * @param rule rule to create the button - */ - RuleButton(Rule rule) { - super( - rule.getRuleName(), - rule.getImageIcon()); // display rules' name under rule when load the icon - this.rule = rule; - this.setFocusPainted(false); - } + /** + * RuleButton Constructor - creates a button for a rule + * + * @param rule rule to create the button + */ + RuleButton(Rule rule) { + super( + rule.getRuleName(), + rule.getImageIcon()); // display rules' name under rule when load the icon + this.rule = rule; + this.setFocusPainted(false); + } - /** - * Gets the Rule from this button - * - * @return Rule from this button - */ - public Rule getRule() { - return rule; - } + /** + * Gets the Rule from this button + * + * @return Rule from this button + */ + public Rule getRule() { + return rule; + } - /** - * Sets the Rule for this button - * - * @param rule Rule for this button - */ - void setRule(Rule rule) { - this.rule = rule; - } + /** + * Sets the Rule for this button + * + * @param rule Rule for this button + */ + void setRule(Rule rule) { + this.rule = rule; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java index 2f31f24dc..6279f93a4 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RuleFrame.java @@ -11,165 +11,168 @@ import javax.swing.border.TitledBorder; public class RuleFrame extends JPanel { - private static final String checkBox = " \u2714 "; - private static final String xBox = " \u2718 "; - private static final String htmlHead = ""; - private static final String htmlTail = ""; - - private DirectRulePanel DirectRulePanel; - private ContradictionRulePanel contradictionPanel; - private CaseRulePanel casePanel; - - private SearchBarPanel searchPanel; - - private JTabbedPane tabbedPane; - private JLabel status; - private ButtonGroup buttonGroup; - - private RuleController controller; - - public RuleFrame(RuleController controller) { - - MaterialTabbedPaneUI tabOverride = - new MaterialTabbedPaneUI() { - // this prevents the tabs from moving around when you select them - @Override - protected boolean shouldRotateTabRuns(int i) { - return false; - } - }; - - this.controller = controller; - - this.tabbedPane = new JTabbedPane(); - this.tabbedPane.setUI(tabOverride); - this.status = new JLabel(); - this.buttonGroup = new ButtonGroup(); - - DirectRulePanel = new DirectRulePanel(this); - JScrollPane newbrp = new JScrollPane(DirectRulePanel); - newbrp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab( - DirectRulePanel.getName(), DirectRulePanel.getIcon(), newbrp, DirectRulePanel.getToolTip()); - - casePanel = new CaseRulePanel(this); - JScrollPane newcp = new JScrollPane(casePanel); - newcp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(casePanel.name, casePanel.icon, newcp, casePanel.toolTip); - - contradictionPanel = new ContradictionRulePanel(this); - JScrollPane newp = new JScrollPane(contradictionPanel); - newp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab( - contradictionPanel.name, contradictionPanel.icon, newp, contradictionPanel.toolTip); - - searchPanel = new SearchBarPanel(this); - JScrollPane newsp = new JScrollPane(searchPanel); - newsp.getVerticalScrollBar().setUnitIncrement(16); - tabbedPane.addTab(searchPanel.name, searchPanel.icon, newsp, searchPanel.toolTip); - - setLayout(new BorderLayout()); - setMinimumSize(new Dimension(250, 256)); - setPreferredSize(new Dimension(355, 256)); - - add(tabbedPane); - add(status, BorderLayout.SOUTH); - - TitledBorder title = BorderFactory.createTitledBorder("Rules"); - title.setTitleJustification(TitledBorder.CENTER); - setBorder(title); - } - - /** - * Gets the button group for the rule frame - * - * @return button group - */ - public ButtonGroup getButtonGroup() { - return buttonGroup; - } - - public void setSelectionByRule(Rule rule) { - DirectRulePanel.setSelectionByRule(rule); - casePanel.setSelectionByRule(rule); - contradictionPanel.setSelectionByRule(rule); - } - - /** Reset the rules button and status string */ - public void resetRuleButtons() { - resetStatus(); - } - - /** Reset the status label to the empty string */ - public void resetStatus() { - // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().updateStatus(); - } - - /** Resets the dimension of the rule frame */ - public void resetSize() { - int buttonWidth = - ((RulePanel) tabbedPane.getSelectedComponent()).getRuleButtons()[0].getWidth(); - this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); - } - - /** - * Set the status label to a value. Use resetStatus to clear it. - * - * @param check true iff we want a check box, if false we'll have a red x box - * @param text the text we're setting the label to display - */ - public void setStatus(boolean check, String text) { - String box = (check ? checkBox : xBox); - // status.setText(htmlHead + box + text + htmlTail); - // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().getStatus().setText(htmlHead + box + text + htmlTail); - } - - /** - * Sets all the rules for the rule frame - * - * @param puzzle edu.rpi.legup.puzzle game - */ - public void setRules(Puzzle puzzle) { - DirectRulePanel.setRules(puzzle.getDirectRules()); - contradictionPanel.setRules(puzzle.getContradictionRules()); - casePanel.setRules(puzzle.getCaseRules()); - } - - /** - * Board puzzleElement has changed - * - * @param board board state - */ - public void boardDataChanged(Board board) { - this.resetStatus(); - } - - /** - * Gets the RuleController for this RuleFrame - * - * @return rule controller - */ - public RuleController getController() { - return controller; - } - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - public DirectRulePanel getDirectRulePanel() { - return DirectRulePanel; - } - - public CaseRulePanel getCasePanel() { - return casePanel; - } - - public ContradictionRulePanel getContradictionPanel() { - return contradictionPanel; - } - - public SearchBarPanel getSearchPanel() { - return searchPanel; - } + private static final String checkBox = " \u2714 "; + private static final String xBox = " \u2718 "; + private static final String htmlHead = ""; + private static final String htmlTail = ""; + + private DirectRulePanel DirectRulePanel; + private ContradictionRulePanel contradictionPanel; + private CaseRulePanel casePanel; + + private SearchBarPanel searchPanel; + + private JTabbedPane tabbedPane; + private JLabel status; + private ButtonGroup buttonGroup; + + private RuleController controller; + + public RuleFrame(RuleController controller) { + + MaterialTabbedPaneUI tabOverride = + new MaterialTabbedPaneUI() { + // this prevents the tabs from moving around when you select them + @Override + protected boolean shouldRotateTabRuns(int i) { + return false; + } + }; + + this.controller = controller; + + this.tabbedPane = new JTabbedPane(); + this.tabbedPane.setUI(tabOverride); + this.status = new JLabel(); + this.buttonGroup = new ButtonGroup(); + + DirectRulePanel = new DirectRulePanel(this); + JScrollPane newbrp = new JScrollPane(DirectRulePanel); + newbrp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab( + DirectRulePanel.getName(), + DirectRulePanel.getIcon(), + newbrp, + DirectRulePanel.getToolTip()); + + casePanel = new CaseRulePanel(this); + JScrollPane newcp = new JScrollPane(casePanel); + newcp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab(casePanel.name, casePanel.icon, newcp, casePanel.toolTip); + + contradictionPanel = new ContradictionRulePanel(this); + JScrollPane newp = new JScrollPane(contradictionPanel); + newp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab( + contradictionPanel.name, contradictionPanel.icon, newp, contradictionPanel.toolTip); + + searchPanel = new SearchBarPanel(this); + JScrollPane newsp = new JScrollPane(searchPanel); + newsp.getVerticalScrollBar().setUnitIncrement(16); + tabbedPane.addTab(searchPanel.name, searchPanel.icon, newsp, searchPanel.toolTip); + + setLayout(new BorderLayout()); + setMinimumSize(new Dimension(250, 256)); + setPreferredSize(new Dimension(355, 256)); + + add(tabbedPane); + add(status, BorderLayout.SOUTH); + + TitledBorder title = BorderFactory.createTitledBorder("Rules"); + title.setTitleJustification(TitledBorder.CENTER); + setBorder(title); + } + + /** + * Gets the button group for the rule frame + * + * @return button group + */ + public ButtonGroup getButtonGroup() { + return buttonGroup; + } + + public void setSelectionByRule(Rule rule) { + DirectRulePanel.setSelectionByRule(rule); + casePanel.setSelectionByRule(rule); + contradictionPanel.setSelectionByRule(rule); + } + + /** Reset the rules button and status string */ + public void resetRuleButtons() { + resetStatus(); + } + + /** Reset the status label to the empty string */ + public void resetStatus() { + // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().updateStatus(); + } + + /** Resets the dimension of the rule frame */ + public void resetSize() { + int buttonWidth = + ((RulePanel) tabbedPane.getSelectedComponent()).getRuleButtons()[0].getWidth(); + this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); + } + + /** + * Set the status label to a value. Use resetStatus to clear it. + * + * @param check true iff we want a check box, if false we'll have a red x box + * @param text the text we're setting the label to display + */ + public void setStatus(boolean check, String text) { + String box = (check ? checkBox : xBox); + // status.setText(htmlHead + box + text + htmlTail); + // ((GridUI)GameBoardFacade.getInstance().getLegupUI()).getTreePanel().getStatus().setText(htmlHead + box + text + htmlTail); + } + + /** + * Sets all the rules for the rule frame + * + * @param puzzle edu.rpi.legup.puzzle game + */ + public void setRules(Puzzle puzzle) { + DirectRulePanel.setRules(puzzle.getDirectRules()); + contradictionPanel.setRules(puzzle.getContradictionRules()); + casePanel.setRules(puzzle.getCaseRules()); + } + + /** + * Board puzzleElement has changed + * + * @param board board state + */ + public void boardDataChanged(Board board) { + this.resetStatus(); + } + + /** + * Gets the RuleController for this RuleFrame + * + * @return rule controller + */ + public RuleController getController() { + return controller; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public DirectRulePanel getDirectRulePanel() { + return DirectRulePanel; + } + + public CaseRulePanel getCasePanel() { + return casePanel; + } + + public ContradictionRulePanel getContradictionPanel() { + return contradictionPanel; + } + + public SearchBarPanel getSearchPanel() { + return searchPanel; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java index 50bd8a110..5d985d5c2 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/RulePanel.java @@ -10,336 +10,343 @@ import javax.swing.*; public abstract class RulePanel extends JPanel { - protected ImageIcon icon; - protected String name; - protected String toolTip; - - protected RuleButton[] ruleButtons; - protected JPanel searchBarPanel; - JTextField textField; - protected RuleFrame ruleFrame; - protected List rules; - - /** - * RulePanel Constructor creates a RulePanel - * - * @param ruleFrame rule frame that this RulePanel is contained in - */ - public RulePanel(RuleFrame ruleFrame) { - this.ruleFrame = ruleFrame; - this.rules = new ArrayList<>(); - setLayout(new WrapLayout()); - } - - /** - * Gets the rule rule buttons - * - * @return rule ruleButtons - */ - public RuleButton[] getRuleButtons() { - return ruleButtons; - } - - /** - * Sets the rules for this rule panel - * - * @param rules list of the rules - */ - public void setRules(List rules) { - this.rules = rules; - clearButtons(); - - ruleButtons = new RuleButton[rules.size()]; - - for (int i = 0; i < rules.size(); i++) { - Rule rule = rules.get(i); - - ruleButtons[i] = new RuleButton(rule); - ruleButtons[i].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[i].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[i].setVerticalTextPosition(JButton.BOTTOM); - - ruleFrame.getButtonGroup().add(ruleButtons[i]); - ruleButtons[i].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); // showing description - ruleButtons[i].addActionListener(ruleFrame.getController()); - add(ruleButtons[i]); + protected ImageIcon icon; + protected String name; + protected String toolTip; + + protected RuleButton[] ruleButtons; + protected JPanel searchBarPanel; + JTextField textField; + protected RuleFrame ruleFrame; + protected List rules; + + /** + * RulePanel Constructor creates a RulePanel + * + * @param ruleFrame rule frame that this RulePanel is contained in + */ + public RulePanel(RuleFrame ruleFrame) { + this.ruleFrame = ruleFrame; + this.rules = new ArrayList<>(); + setLayout(new WrapLayout()); } - revalidate(); - } - public void updateRules() { - for (Rule rule : rules) { - rule.loadImage(); + /** + * Gets the rule rule buttons + * + * @return rule ruleButtons + */ + public RuleButton[] getRuleButtons() { + return ruleButtons; } - setRules(rules); - } - - /** - * Search a certain rule in all the puzzles and set it for the searchBarPanel - * - * @param puzzle puzzle where the rule is being searched for - * @param ruleName rule that is being compared to each puzzle - *

This function is the searching algorithm for "public void setSearchBar(Puzzle - * allPuzzle)" (below) - *

It takes two param Puzzle puzzle and String ruleName puzzle contains rules, this - * function will compare each rule of puzzle with ruleName, to find exact same, similar rules, - * or all the rules with same start letter (if input is a signal letter) - */ - public void searchForRule(Puzzle puzzle, String ruleName) { - - List> allrules = new ArrayList>(3); - allrules.add(0, puzzle.getDirectRules()); - allrules.add(1, puzzle.getCaseRules()); - allrules.add(2, puzzle.getContradictionRules()); - - ruleButtons = new RuleButton[100]; - int similarfound = 0; - - for (int i = 0; i < allrules.size(); i++) { - for (int j = 0; j < allrules.get(i).size(); j++) { - Rule rule = allrules.get(i).get(j); - if ((ruleName).equals(rule.getRuleName().toUpperCase())) { - - ruleButtons[0] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[0]); - - ruleButtons[0].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[0].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[0].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[0].setToolTipText(rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[0].addActionListener(ruleFrame.getController()); - add(ruleButtons[0]); - revalidate(); - return; - - } else { - if (similarityCheck(ruleName, rule.getRuleName().toUpperCase()) > 0.2) { - ruleButtons[similarfound] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); - - ruleButtons[similarfound].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[similarfound].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[similarfound].addActionListener(ruleFrame.getController()); - add(ruleButtons[similarfound]); - similarfound += 1; - revalidate(); - } else { - if ((ruleName.charAt(0)) == (rule.getRuleName().toUpperCase()).charAt(0)) { - ruleButtons[similarfound] = new RuleButton(rule); - ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); - - ruleButtons[similarfound].setPreferredSize( - new Dimension(150, 150)); // adjust the size of each RuleButton - ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); - ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); - - ruleButtons[similarfound].setToolTipText( - rule.getRuleName() + ": " + rule.getDescription()); - ruleButtons[similarfound].addActionListener(ruleFrame.getController()); - add(ruleButtons[similarfound]); - similarfound += 1; - revalidate(); - } - } + + /** + * Sets the rules for this rule panel + * + * @param rules list of the rules + */ + public void setRules(List rules) { + this.rules = rules; + clearButtons(); + + ruleButtons = new RuleButton[rules.size()]; + + for (int i = 0; i < rules.size(); i++) { + Rule rule = rules.get(i); + + ruleButtons[i] = new RuleButton(rule); + ruleButtons[i].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[i].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[i].setVerticalTextPosition(JButton.BOTTOM); + + ruleFrame.getButtonGroup().add(ruleButtons[i]); + ruleButtons[i].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); // showing description + ruleButtons[i].addActionListener(ruleFrame.getController()); + add(ruleButtons[i]); } - } + revalidate(); } - if (ruleButtons[0] == null) { - JOptionPane.showMessageDialog( - null, "Please input the correct rule name", "Confirm", JOptionPane.INFORMATION_MESSAGE); - } - } - - /** - * Calculates the similarity (a number within 0 and 1) between two strings. This function will - * take two para String s1 and String s2, which s1 is the user's input and s2 is the compared - * really rule name - * - * @param s1 user's input - * @param s2 the compared really rule name - * @return a similarity degree between 0 and 1 similarityCheck will use a helper function to - * calculate a similarity degree(from 0 to 1). closer to 0 means less similar, and closer to 1 - * means more similar. - */ - public static double similarityCheck(String s1, String s2) { - String longer = s1, shorter = s2; - if (s1.length() < s2.length()) { // longer should always have greater length - longer = s2; - shorter = s1; - } - int longerLength = longer.length(); - if (longerLength == 0) { - return 1.0; /* both strings are zero length */ + public void updateRules() { + for (Rule rule : rules) { + rule.loadImage(); + } + setRules(rules); } - return (longerLength - editDistance(longer, shorter)) / (double) longerLength; - } - - /** - * Help function for similarityCheck(); - * - * @param s1 user's input - * @param s2 the compared really rule name - * @return a similarity degree between 0 and 1 - */ - public static int editDistance(String s1, String s2) { - s1 = s1.toLowerCase(); - s2 = s2.toLowerCase(); - - int[] costs = new int[s2.length() + 1]; - for (int i = 0; i <= s1.length(); i++) { - int lastValue = i; - for (int j = 0; j <= s2.length(); j++) { - if (i == 0) { - costs[j] = j; - } else { - if (j > 0) { - int newValue = costs[j - 1]; - if (s1.charAt(i - 1) != s2.charAt(j - 1)) { - newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; + + /** + * Search a certain rule in all the puzzles and set it for the searchBarPanel + * + * @param puzzle puzzle where the rule is being searched for + * @param ruleName rule that is being compared to each puzzle + *

This function is the searching algorithm for "public void setSearchBar(Puzzle + * allPuzzle)" (below) + *

It takes two param Puzzle puzzle and String ruleName puzzle contains rules, this + * function will compare each rule of puzzle with ruleName, to find exact same, similar + * rules, or all the rules with same start letter (if input is a signal letter) + */ + public void searchForRule(Puzzle puzzle, String ruleName) { + + List> allrules = new ArrayList>(3); + allrules.add(0, puzzle.getDirectRules()); + allrules.add(1, puzzle.getCaseRules()); + allrules.add(2, puzzle.getContradictionRules()); + + ruleButtons = new RuleButton[100]; + int similarfound = 0; + + for (int i = 0; i < allrules.size(); i++) { + for (int j = 0; j < allrules.get(i).size(); j++) { + Rule rule = allrules.get(i).get(j); + if ((ruleName).equals(rule.getRuleName().toUpperCase())) { + + ruleButtons[0] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[0]); + + ruleButtons[0].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[0].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[0].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[0].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[0].addActionListener(ruleFrame.getController()); + add(ruleButtons[0]); + revalidate(); + return; + + } else { + if (similarityCheck(ruleName, rule.getRuleName().toUpperCase()) > 0.2) { + ruleButtons[similarfound] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); + + ruleButtons[similarfound].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[similarfound].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[similarfound].addActionListener(ruleFrame.getController()); + add(ruleButtons[similarfound]); + similarfound += 1; + revalidate(); + } else { + if ((ruleName.charAt(0)) == (rule.getRuleName().toUpperCase()).charAt(0)) { + ruleButtons[similarfound] = new RuleButton(rule); + ruleFrame.getButtonGroup().add(ruleButtons[similarfound]); + + ruleButtons[similarfound].setPreferredSize( + new Dimension(150, 150)); // adjust the size of each RuleButton + ruleButtons[similarfound].setHorizontalTextPosition(JButton.CENTER); + ruleButtons[similarfound].setVerticalTextPosition(JButton.BOTTOM); + + ruleButtons[similarfound].setToolTipText( + rule.getRuleName() + ": " + rule.getDescription()); + ruleButtons[similarfound].addActionListener(ruleFrame.getController()); + add(ruleButtons[similarfound]); + similarfound += 1; + revalidate(); + } + } + } } - costs[j - 1] = lastValue; - lastValue = newValue; - } } - } - if (i > 0) { - costs[s2.length()] = lastValue; - } + + if (ruleButtons[0] == null) { + JOptionPane.showMessageDialog( + null, + "Please input the correct rule name", + "Confirm", + JOptionPane.INFORMATION_MESSAGE); + } } - return costs[s2.length()]; - } - - /** - * Sets the search bar for SearchBarPanel search bar allows user to input a name to get relative - * rules once a name is entered and click ok will load (a/several) rule icon, which has all the - * functions just as other rule icons. - * - * @param allPuzzle name of rule input - */ - public void setSearchBar(Puzzle allPuzzle) { - - searchBarPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 6, 6)); - - textField = new JTextField(); - ruleFrame.addComponentListener( - new ComponentAdapter() { - public void componentResized(ComponentEvent componentEvent) { - Component c = componentEvent.getComponent(); - textField.setColumns((8 + (c.getWidth() - 250) / 10) - 1); - } - }); - - add(searchBarPanel); - JLabel findLabel = new JLabel("Search:"); - searchBarPanel.add(findLabel); - searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); - searchBarPanel.add(textField); - searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); - JButton findButton = new JButton("Go"); - ActionListener action = - new ActionListener() { - @Override - public void actionPerformed(ActionEvent event) { - if (ruleButtons != null) { - for (int i = 0; i != ruleButtons.length; i++) { - if (ruleButtons[i] == null) { - continue; + + /** + * Calculates the similarity (a number within 0 and 1) between two strings. This function will + * take two para String s1 and String s2, which s1 is the user's input and s2 is the compared + * really rule name + * + * @param s1 user's input + * @param s2 the compared really rule name + * @return a similarity degree between 0 and 1 similarityCheck will use a helper function to + * calculate a similarity degree(from 0 to 1). closer to 0 means less similar, and closer to + * 1 means more similar. + */ + public static double similarityCheck(String s1, String s2) { + String longer = s1, shorter = s2; + if (s1.length() < s2.length()) { // longer should always have greater length + longer = s2; + shorter = s1; + } + int longerLength = longer.length(); + if (longerLength == 0) { + return 1.0; /* both strings are zero length */ + } + return (longerLength - editDistance(longer, shorter)) / (double) longerLength; + } + + /** + * Help function for similarityCheck(); + * + * @param s1 user's input + * @param s2 the compared really rule name + * @return a similarity degree between 0 and 1 + */ + public static int editDistance(String s1, String s2) { + s1 = s1.toLowerCase(); + s2 = s2.toLowerCase(); + + int[] costs = new int[s2.length() + 1]; + for (int i = 0; i <= s1.length(); i++) { + int lastValue = i; + for (int j = 0; j <= s2.length(); j++) { + if (i == 0) { + costs[j] = j; + } else { + if (j > 0) { + int newValue = costs[j - 1]; + if (s1.charAt(i - 1) != s2.charAt(j - 1)) { + newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1; + } + costs[j - 1] = lastValue; + lastValue = newValue; + } } - ruleButtons[i].removeActionListener(ruleFrame.getController()); - } } - String inputRule = textField.getText().toUpperCase().trim(); + if (i > 0) { + costs[s2.length()] = lastValue; + } + } + return costs[s2.length()]; + } - if (!inputRule.isEmpty()) { - if (ruleButtons != null) { + /** + * Sets the search bar for SearchBarPanel search bar allows user to input a name to get relative + * rules once a name is entered and click ok will load (a/several) rule icon, which has all the + * functions just as other rule icons. + * + * @param allPuzzle name of rule input + */ + public void setSearchBar(Puzzle allPuzzle) { + + searchBarPanel = new JPanel(new FlowLayout(SwingConstants.LEADING, 6, 6)); + + textField = new JTextField(); + ruleFrame.addComponentListener( + new ComponentAdapter() { + public void componentResized(ComponentEvent componentEvent) { + Component c = componentEvent.getComponent(); + textField.setColumns((8 + (c.getWidth() - 250) / 10) - 1); + } + }); + + add(searchBarPanel); + JLabel findLabel = new JLabel("Search:"); + searchBarPanel.add(findLabel); + searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); + searchBarPanel.add(textField); + searchBarPanel.add(Box.createRigidArea(new Dimension(1, 0))); + JButton findButton = new JButton("Go"); + ActionListener action = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + if (ruleButtons != null) { + for (int i = 0; i != ruleButtons.length; i++) { + if (ruleButtons[i] == null) { + continue; + } + ruleButtons[i].removeActionListener(ruleFrame.getController()); + } + } + String inputRule = textField.getText().toUpperCase().trim(); + + if (!inputRule.isEmpty()) { + if (ruleButtons != null) { + + for (int x = 0; x < ruleButtons.length; ++x) { + if (ruleButtons[x] == null) { + continue; + } + remove(ruleButtons[x]); + } + } + searchForRule(allPuzzle, inputRule); + } else { + JOptionPane.showMessageDialog( + null, + "Please give a name", + "Confirm", + JOptionPane.INFORMATION_MESSAGE); + } + } + }; + textField.addActionListener(action); + findButton.addActionListener(action); + searchBarPanel.add(findButton); + } - for (int x = 0; x < ruleButtons.length; ++x) { - if (ruleButtons[x] == null) { - continue; - } - remove(ruleButtons[x]); + /** + * Sets the selection by the specified rule + * + * @param rule rule to set the selection to + */ + public void setSelectionByRule(Rule rule) { + if (ruleButtons != null) { + for (int i = 0; i < ruleButtons.length; i++) { + if (rules.get(i).equals(rule)) { + ruleButtons[i].setSelected(true); + break; } - } - searchForRule(allPuzzle, inputRule); - } else { - JOptionPane.showMessageDialog( - null, "Please give a name", "Confirm", JOptionPane.INFORMATION_MESSAGE); } - } - }; - textField.addActionListener(action); - findButton.addActionListener(action); - searchBarPanel.add(findButton); - } - - /** - * Sets the selection by the specified rule - * - * @param rule rule to set the selection to - */ - public void setSelectionByRule(Rule rule) { - if (ruleButtons != null) { - for (int i = 0; i < ruleButtons.length; i++) { - if (rules.get(i).equals(rule)) { - ruleButtons[i].setSelected(true); - break; } - } } - } - - /** Clears the rule buttons off this panel */ - protected void clearButtons() { - if (ruleButtons != null) { - removeAll(); - for (int x = 0; x < ruleButtons.length; ++x) { - ruleButtons[x].removeActionListener(ruleFrame.getController()); - } + + /** Clears the rule buttons off this panel */ + protected void clearButtons() { + if (ruleButtons != null) { + removeAll(); + for (int x = 0; x < ruleButtons.length; ++x) { + ruleButtons[x].removeActionListener(ruleFrame.getController()); + } + } + } + + /** + * Gets the rules associated with this panel + * + * @return the rules + */ + public List getRules() { + return rules; + } + + public ImageIcon getIcon() { + return icon; + } + + public void setIcon(ImageIcon icon) { + this.icon = icon; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + public String getToolTip() { + return toolTip; + } + + public void setToolTip(String toolTip) { + this.toolTip = toolTip; } - } - - /** - * Gets the rules associated with this panel - * - * @return the rules - */ - public List getRules() { - return rules; - } - - public ImageIcon getIcon() { - return icon; - } - - public void setIcon(ImageIcon icon) { - this.icon = icon; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getToolTip() { - return toolTip; - } - - public void setToolTip(String toolTip) { - this.toolTip = toolTip; - } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java index b0dddc2c7..aba4707cd 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/rulesview/SearchBarPanel.java @@ -3,19 +3,19 @@ import javax.swing.*; public class SearchBarPanel extends RulePanel { - /** - * SearchBarPanel Constructor creates a SearchBarPanel - * - * @param ruleFrame rule frame that this SearchBarPanel is contained in - *

This class is used to create a panel named "search bar" - */ - SearchBarPanel(RuleFrame ruleFrame) { - super(ruleFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Zoom In.png")); - this.name = "Search Rules"; - this.toolTip = "Search Rules"; - } + /** + * SearchBarPanel Constructor creates a SearchBarPanel + * + * @param ruleFrame rule frame that this SearchBarPanel is contained in + *

This class is used to create a panel named "search bar" + */ + SearchBarPanel(RuleFrame ruleFrame) { + super(ruleFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Zoom In.png")); + this.name = "Search Rules"; + this.toolTip = "Search Rules"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java index 00b8ec0bb..33c04717d 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeElementView.java @@ -5,169 +5,169 @@ import java.awt.*; public abstract class TreeElementView implements Shape { - protected TreeElement treeElement; - protected double span; - protected int depth; - protected boolean isSelected; - protected boolean isHover; - protected TreeElementType type; - protected boolean isVisible; - protected boolean isCollapsed; - - /** - * TreeElementView Constructor creates a tree puzzleElement view - * - * @param type tree puzzleElement type - * @param treeElement tree puzzleElement puzzleElement associated with this view - */ - protected TreeElementView(TreeElementType type, TreeElement treeElement) { - this.type = type; - this.treeElement = treeElement; - this.isSelected = false; - this.isHover = false; - this.isVisible = true; - } - - /** - * Draws the tree puzzleElement view - * - * @param graphics2D graphics2D object used to draw the tree puzzleElement view - */ - public abstract void draw(Graphics2D graphics2D); - - /** - * Gets the span for the sub tree rooted at this view - * - * @return span bounded y span - */ - public double getSpan() { - return span; - } - - /** - * Sets the span for the sub tree rooted at this view. - * - * @param span bounded y span - */ - public void setSpan(double span) { - this.span = span; - } - - /** - * Gets the depth of this tree puzzleElement in the tree - * - * @return depth of this tree puzzleElement - */ - public int getDepth() { - return depth; - } - - /** - * Sets the depth of this tree puzzleElement in the tree - * - * @param depth depth of this tree puzzleElement - */ - public void setDepth(int depth) { - this.depth = depth; - } - - /** - * Gets the tree puzzleElement type for this view - * - * @return tree puzzleElement type - */ - public TreeElementType getType() { - return type; - } - - /** - * Gets the tree puzzleElement associated with this view - * - * @return tree puzzleElement associated with this view - */ - public TreeElement getTreeElement() { - return treeElement; - } - - /** - * Sets the tree puzzleElement associated with this view - * - * @param treeElement tree puzzleElement associated with this view - */ - public void setTreeElement(TreeElement treeElement) { - this.treeElement = treeElement; - } - - /** - * Gets the mouse selection - * - * @return mouse selection - */ - public boolean isSelected() { - return isSelected; - } - - /** - * Sets the mouse selection - * - * @param isSelected mouse selection - */ - public void setSelected(boolean isSelected) { - this.isSelected = isSelected; - } - - /** - * Gets the mouse hover - * - * @return mouse hover - */ - public boolean isHover() { - return isHover; - } - - /** - * Sets the mouse hover - * - * @param isHovered mouse hover - */ - public void setHover(boolean isHovered) { - this.isHover = isHovered; - } - - /** - * Gets the visibility of the tree puzzleElement. Tells the TreeView whether or not to draw the - * tree puzzleElement - * - * @return visibility of the tree puzzleElement - */ - public boolean isVisible() { - return isVisible; - } - - /** - * Sets the visibility of the tree puzzleElement - * - * @param isVisible visibility of the tree puzzleElement - */ - public void setVisible(boolean isVisible) { - this.isVisible = isVisible; - } - - /** - * Is this tree node view collapsed in the view - * - * @return true if the node is collapsed, false otherwise - */ - public boolean isCollapsed() { - return isCollapsed; - } - - /** - * Sets the tree node view collapsed field - * - * @param isCollapsed true if the node is collapsed, false otherwise - */ - public void setCollapsed(boolean isCollapsed) { - this.isCollapsed = isCollapsed; - } + protected TreeElement treeElement; + protected double span; + protected int depth; + protected boolean isSelected; + protected boolean isHover; + protected TreeElementType type; + protected boolean isVisible; + protected boolean isCollapsed; + + /** + * TreeElementView Constructor creates a tree puzzleElement view + * + * @param type tree puzzleElement type + * @param treeElement tree puzzleElement puzzleElement associated with this view + */ + protected TreeElementView(TreeElementType type, TreeElement treeElement) { + this.type = type; + this.treeElement = treeElement; + this.isSelected = false; + this.isHover = false; + this.isVisible = true; + } + + /** + * Draws the tree puzzleElement view + * + * @param graphics2D graphics2D object used to draw the tree puzzleElement view + */ + public abstract void draw(Graphics2D graphics2D); + + /** + * Gets the span for the sub tree rooted at this view + * + * @return span bounded y span + */ + public double getSpan() { + return span; + } + + /** + * Sets the span for the sub tree rooted at this view. + * + * @param span bounded y span + */ + public void setSpan(double span) { + this.span = span; + } + + /** + * Gets the depth of this tree puzzleElement in the tree + * + * @return depth of this tree puzzleElement + */ + public int getDepth() { + return depth; + } + + /** + * Sets the depth of this tree puzzleElement in the tree + * + * @param depth depth of this tree puzzleElement + */ + public void setDepth(int depth) { + this.depth = depth; + } + + /** + * Gets the tree puzzleElement type for this view + * + * @return tree puzzleElement type + */ + public TreeElementType getType() { + return type; + } + + /** + * Gets the tree puzzleElement associated with this view + * + * @return tree puzzleElement associated with this view + */ + public TreeElement getTreeElement() { + return treeElement; + } + + /** + * Sets the tree puzzleElement associated with this view + * + * @param treeElement tree puzzleElement associated with this view + */ + public void setTreeElement(TreeElement treeElement) { + this.treeElement = treeElement; + } + + /** + * Gets the mouse selection + * + * @return mouse selection + */ + public boolean isSelected() { + return isSelected; + } + + /** + * Sets the mouse selection + * + * @param isSelected mouse selection + */ + public void setSelected(boolean isSelected) { + this.isSelected = isSelected; + } + + /** + * Gets the mouse hover + * + * @return mouse hover + */ + public boolean isHover() { + return isHover; + } + + /** + * Sets the mouse hover + * + * @param isHovered mouse hover + */ + public void setHover(boolean isHovered) { + this.isHover = isHovered; + } + + /** + * Gets the visibility of the tree puzzleElement. Tells the TreeView whether or not to draw the + * tree puzzleElement + * + * @return visibility of the tree puzzleElement + */ + public boolean isVisible() { + return isVisible; + } + + /** + * Sets the visibility of the tree puzzleElement + * + * @param isVisible visibility of the tree puzzleElement + */ + public void setVisible(boolean isVisible) { + this.isVisible = isVisible; + } + + /** + * Is this tree node view collapsed in the view + * + * @return true if the node is collapsed, false otherwise + */ + public boolean isCollapsed() { + return isCollapsed; + } + + /** + * Sets the tree node view collapsed field + * + * @param isCollapsed true if the node is collapsed, false otherwise + */ + public void setCollapsed(boolean isCollapsed) { + this.isCollapsed = isCollapsed; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java index dbb4dfcb4..990d96620 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeNodeView.java @@ -8,285 +8,305 @@ import java.util.ArrayList; public class TreeNodeView extends TreeElementView { - static final int RADIUS = 25; - static final int DIAMETER = 2 * RADIUS; - - private static final Stroke MAIN_STROKE = new BasicStroke(3); - private static final Stroke SELECTION_STROKE = new BasicStroke(2); - - private static final Color NODE_COLOR_ROOT = new Color(100, 100, 100); - private static final Color NODE_MINOR_COLOR_ROOT = new Color(75, 75, 75); - - private static final Color NODE_COLOR_DEFAULT = new Color(0xFFEB3B); - private static final Color NODE_MINOR_COLOR_DEFAULT = new Color(216, 197, 52); - - private static final Color NODE_COLOR_CONTRADICTION = new Color(178, 10, 16); - private static final Color NODE_MINOR_COLOR_CONTRADICTION = new Color(119, 13, 16); - - private static final Color OUTLINE_COLOR = new Color(0x212121); - private static final Color SELECTION_COLOR = new Color(0x1E88E5); - private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); - - private static final Color HOVER_COLOR = new Color(0x90CAF9); - private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); - - private Point location; - - private TreeTransitionView parentView; - private ArrayList childrenViews; - - private boolean isCollapsed; - private boolean isContradictoryState; - - /** - * TreeNodeView Constructor creates a node for display - * - * @param treeNode treeElement associated with this transition - */ - public TreeNodeView(TreeNode treeNode) { - super(TreeElementType.NODE, treeNode); - this.treeElement = treeNode; - this.location = new Point(); - this.parentView = null; - this.childrenViews = new ArrayList<>(); - this.isCollapsed = false; - this.isContradictoryState = false; - this.isVisible = true; - } - - /** - * Draws the TreeNodeView - * - * @param graphics2D graphics2D used for drawing - */ - public void draw(Graphics2D graphics2D) { - if (isVisible() && treeElement != null) { - if (getTreeElement().getParent() != null - && getTreeElement().getParent().isJustified() - && getTreeElement().getParent().getRule().getRuleType() == RuleType.CONTRADICTION) { - isContradictoryState = true; - graphics2D.setColor(NODE_COLOR_CONTRADICTION); - graphics2D.drawLine( - location.x - RADIUS, location.y - RADIUS, location.x + RADIUS, location.y + RADIUS); - graphics2D.drawLine( - location.x + RADIUS, location.y - RADIUS, location.x - RADIUS, location.y + RADIUS); - } else { - isContradictoryState = false; - graphics2D.setStroke(MAIN_STROKE); - boolean isContraBranch = getTreeElement().isContradictoryBranch(); - - if (isSelected) { - graphics2D.setColor(SELECTION_COLOR); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_SELECTION_COLOR); - graphics2D.drawOval( - location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); - } else { - if (isHover) { - graphics2D.setColor(HOVER_COLOR); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_HOVER_COLOR); - graphics2D.drawOval( - location.x - RADIUS - 4, location.y - RADIUS - 4, DIAMETER + 8, DIAMETER + 8); - } else { - graphics2D.setColor(isContraBranch ? NODE_COLOR_CONTRADICTION : NODE_COLOR_DEFAULT); - graphics2D.fillOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawOval(location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); - } + static final int RADIUS = 25; + static final int DIAMETER = 2 * RADIUS; + + private static final Stroke MAIN_STROKE = new BasicStroke(3); + private static final Stroke SELECTION_STROKE = new BasicStroke(2); + + private static final Color NODE_COLOR_ROOT = new Color(100, 100, 100); + private static final Color NODE_MINOR_COLOR_ROOT = new Color(75, 75, 75); + + private static final Color NODE_COLOR_DEFAULT = new Color(0xFFEB3B); + private static final Color NODE_MINOR_COLOR_DEFAULT = new Color(216, 197, 52); + + private static final Color NODE_COLOR_CONTRADICTION = new Color(178, 10, 16); + private static final Color NODE_MINOR_COLOR_CONTRADICTION = new Color(119, 13, 16); + + private static final Color OUTLINE_COLOR = new Color(0x212121); + private static final Color SELECTION_COLOR = new Color(0x1E88E5); + private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); + + private static final Color HOVER_COLOR = new Color(0x90CAF9); + private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); + + private Point location; + + private TreeTransitionView parentView; + private ArrayList childrenViews; + + private boolean isCollapsed; + private boolean isContradictoryState; + + /** + * TreeNodeView Constructor creates a node for display + * + * @param treeNode treeElement associated with this transition + */ + public TreeNodeView(TreeNode treeNode) { + super(TreeElementType.NODE, treeNode); + this.treeElement = treeNode; + this.location = new Point(); + this.parentView = null; + this.childrenViews = new ArrayList<>(); + this.isCollapsed = false; + this.isContradictoryState = false; + this.isVisible = true; + } + + /** + * Draws the TreeNodeView + * + * @param graphics2D graphics2D used for drawing + */ + public void draw(Graphics2D graphics2D) { + if (isVisible() && treeElement != null) { + if (getTreeElement().getParent() != null + && getTreeElement().getParent().isJustified() + && getTreeElement().getParent().getRule().getRuleType() + == RuleType.CONTRADICTION) { + isContradictoryState = true; + graphics2D.setColor(NODE_COLOR_CONTRADICTION); + graphics2D.drawLine( + location.x - RADIUS, + location.y - RADIUS, + location.x + RADIUS, + location.y + RADIUS); + graphics2D.drawLine( + location.x + RADIUS, + location.y - RADIUS, + location.x - RADIUS, + location.y + RADIUS); + } else { + isContradictoryState = false; + graphics2D.setStroke(MAIN_STROKE); + boolean isContraBranch = getTreeElement().isContradictoryBranch(); + + if (isSelected) { + graphics2D.setColor(SELECTION_COLOR); + graphics2D.fillOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_SELECTION_COLOR); + graphics2D.drawOval( + location.x - RADIUS - 4, + location.y - RADIUS - 4, + DIAMETER + 8, + DIAMETER + 8); + } else { + if (isHover) { + graphics2D.setColor(HOVER_COLOR); + graphics2D.fillOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_HOVER_COLOR); + graphics2D.drawOval( + location.x - RADIUS - 4, + location.y - RADIUS - 4, + DIAMETER + 8, + DIAMETER + 8); + } else { + graphics2D.setColor( + isContraBranch ? NODE_COLOR_CONTRADICTION : NODE_COLOR_DEFAULT); + graphics2D.fillOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawOval( + location.x - RADIUS, location.y - RADIUS, DIAMETER, DIAMETER); + } + } + } } - } } - } - - public boolean isContradictoryState() { - return isContradictoryState; - } - - /** - * Gets the list of children views associated with this tree node - * - * @return list of children views for this tree node - */ - public ArrayList getChildrenViews() { - return childrenViews; - } - - /** - * Sets the list of children views associated with this tree node - * - * @param childrenViews list of children views for this tree node - */ - public void setChildrenViews(ArrayList childrenViews) { - this.childrenViews = childrenViews; - } - - /** - * Adds a TreeTransitionView to the list of children views - * - * @param nodeView TreeTransitionView to add to the list of children views - */ - public void addChildrenView(TreeTransitionView nodeView) { - childrenViews.add(nodeView); - } - - /** - * Removes a TreeTransitionView from the list of children views - * - * @param nodeView TreeTransitionView to remove from the list of children views - */ - public void removeChildrenView(TreeTransitionView nodeView) { - childrenViews.remove(nodeView); - } - - /** - * Sets the parent tree transition view - * - * @param parentView parent tree transition view - */ - public void setParentView(TreeTransitionView parentView) { - this.parentView = parentView; - } - - /** - * Gets the parent tree transition view - * - * @return parent tree transition view - */ - public TreeTransitionView getParentView() { - return parentView; - } - - /** - * Gets the tree node associated with this view - * - * @return tree node - */ - public TreeNode getTreeElement() { - return (TreeNode) treeElement; - } - - /** - * Gets the location of the tree node - * - * @return location of the tree node - */ - public Point getLocation() { - return location; - } - - /** - * Sets the location of the tree node - * - * @param location location of the tree node - */ - public void setLocation(Point location) { - this.location = location; - } - - /** - * Gets the x location of the tree node - * - * @return x location - */ - public int getX() { - return location.x; - } - - /** - * Sets the x location of the tree node - * - * @param x x location - */ - public void setX(int x) { - location.x = x; - } - - /** - * Gets the y location of the tree node - * - * @return y location - */ - public int getY() { - return location.y; - } - - /** - * Sets the y location of the tree node - * - * @param y y location - */ - public void setY(int y) { - location.y = y; - } - - /** - * Gets the radius of the tree node - * - * @return radius - */ - public int getRadius() { - return RADIUS; - } - - @Override - public Rectangle getBounds() { - return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); - } - - @Override - public Rectangle2D getBounds2D() { - return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); - } - - @Override - public boolean contains(double x, double y) { - return Math.sqrt(Math.pow(x - location.x, 2) + Math.pow(y - location.y, 2)) <= RADIUS; - } - - @Override - public boolean contains(Point2D p) { - return contains(p.getX(), p.getY()); - } - - @Override - public boolean intersects(double x, double y, double w, double h) { - return false; - } - - @Override - public boolean intersects(Rectangle2D r) { - return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); - } - - @Override - public boolean contains(double x, double y, double w, double h) { - return false; - } - - @Override - public boolean contains(Rectangle2D r) { - return false; - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return null; - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return null; - } + + public boolean isContradictoryState() { + return isContradictoryState; + } + + /** + * Gets the list of children views associated with this tree node + * + * @return list of children views for this tree node + */ + public ArrayList getChildrenViews() { + return childrenViews; + } + + /** + * Sets the list of children views associated with this tree node + * + * @param childrenViews list of children views for this tree node + */ + public void setChildrenViews(ArrayList childrenViews) { + this.childrenViews = childrenViews; + } + + /** + * Adds a TreeTransitionView to the list of children views + * + * @param nodeView TreeTransitionView to add to the list of children views + */ + public void addChildrenView(TreeTransitionView nodeView) { + childrenViews.add(nodeView); + } + + /** + * Removes a TreeTransitionView from the list of children views + * + * @param nodeView TreeTransitionView to remove from the list of children views + */ + public void removeChildrenView(TreeTransitionView nodeView) { + childrenViews.remove(nodeView); + } + + /** + * Sets the parent tree transition view + * + * @param parentView parent tree transition view + */ + public void setParentView(TreeTransitionView parentView) { + this.parentView = parentView; + } + + /** + * Gets the parent tree transition view + * + * @return parent tree transition view + */ + public TreeTransitionView getParentView() { + return parentView; + } + + /** + * Gets the tree node associated with this view + * + * @return tree node + */ + public TreeNode getTreeElement() { + return (TreeNode) treeElement; + } + + /** + * Gets the location of the tree node + * + * @return location of the tree node + */ + public Point getLocation() { + return location; + } + + /** + * Sets the location of the tree node + * + * @param location location of the tree node + */ + public void setLocation(Point location) { + this.location = location; + } + + /** + * Gets the x location of the tree node + * + * @return x location + */ + public int getX() { + return location.x; + } + + /** + * Sets the x location of the tree node + * + * @param x x location + */ + public void setX(int x) { + location.x = x; + } + + /** + * Gets the y location of the tree node + * + * @return y location + */ + public int getY() { + return location.y; + } + + /** + * Sets the y location of the tree node + * + * @param y y location + */ + public void setY(int y) { + location.y = y; + } + + /** + * Gets the radius of the tree node + * + * @return radius + */ + public int getRadius() { + return RADIUS; + } + + @Override + public Rectangle getBounds() { + return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); + } + + @Override + public Rectangle2D getBounds2D() { + return new Rectangle(location.x, location.y, DIAMETER, DIAMETER); + } + + @Override + public boolean contains(double x, double y) { + return Math.sqrt(Math.pow(x - location.x, 2) + Math.pow(y - location.y, 2)) <= RADIUS; + } + + @Override + public boolean contains(Point2D p) { + return contains(p.getX(), p.getY()); + } + + @Override + public boolean intersects(double x, double y, double w, double h) { + return false; + } + + @Override + public boolean intersects(Rectangle2D r) { + return intersects(r.getX(), r.getY(), r.getWidth(), r.getHeight()); + } + + @Override + public boolean contains(double x, double y, double w, double h) { + return false; + } + + @Override + public boolean contains(Rectangle2D r) { + return false; + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return null; + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return null; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java index f73ab02fe..b6a29f2b5 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreePanel.java @@ -18,123 +18,123 @@ import javax.swing.border.TitledBorder; public class TreePanel extends JPanel { - public boolean modifiedSinceSave = false; - public boolean modifiedSinceUndoPush = false; - public int updateStatusTimer = 0; + public boolean modifiedSinceSave = false; + public boolean modifiedSinceUndoPush = false; + public int updateStatusTimer = 0; - private JPanel main; - private TreeView treeView; - private TreeToolbarPanel toolbar; - // private LegupUI legupUI; + private JPanel main; + private TreeView treeView; + private TreeToolbarPanel toolbar; + // private LegupUI legupUI; - private JLabel status; + private JLabel status; - public TreePanel(/*LegupUI legupUI*/ ) { - // this.legupUI = legupUI; + public TreePanel(/*LegupUI legupUI*/ ) { + // this.legupUI = legupUI; - main = new JPanel(); + main = new JPanel(); - main.setLayout(new BorderLayout()); + main.setLayout(new BorderLayout()); - TreeController treeController = new TreeController(); - treeView = new TreeView(treeController); - treeController.setViewer(treeView); + TreeController treeController = new TreeController(); + treeView = new TreeView(treeController); + treeController.setViewer(treeView); - toolbar = new TreeToolbarPanel(this); + toolbar = new TreeToolbarPanel(this); - DynamicView dynamicTreeView = new DynamicView(treeView, DynamicViewType.PROOF_TREE); - main.add(dynamicTreeView, BorderLayout.CENTER); - dynamicTreeView.add(toolbar, BorderLayout.WEST); + DynamicView dynamicTreeView = new DynamicView(treeView, DynamicViewType.PROOF_TREE); + main.add(dynamicTreeView, BorderLayout.CENTER); + dynamicTreeView.add(toolbar, BorderLayout.WEST); - status = new JLabel(); - status.setPreferredSize(new Dimension(150, 15)); - dynamicTreeView.getZoomWrapper().add(status, BorderLayout.CENTER); + status = new JLabel(); + status.setPreferredSize(new Dimension(150, 15)); + dynamicTreeView.getZoomWrapper().add(status, BorderLayout.CENTER); - TitledBorder title = BorderFactory.createTitledBorder("Proof Tree"); - title.setTitleJustification(TitledBorder.CENTER); - main.setBorder(title); + TitledBorder title = BorderFactory.createTitledBorder("Proof Tree"); + title.setTitleJustification(TitledBorder.CENTER); + main.setBorder(title); - setLayout(new BorderLayout()); - add(main); + setLayout(new BorderLayout()); + add(main); - updateStatusTimer = 0; - } + updateStatusTimer = 0; + } + + public void repaintTreeView(Tree tree) { + treeView.updateTreeView(tree); + } - public void repaintTreeView(Tree tree) { - treeView.updateTreeView(tree); - } + public void boardDataChanged(Board board) { + modifiedSinceSave = true; + modifiedSinceUndoPush = true; + updateStatus(); + // colorTransitions(); + } - public void boardDataChanged(Board board) { - modifiedSinceSave = true; - modifiedSinceUndoPush = true; - updateStatus(); - // colorTransitions(); - } + public void updateStatus() { + updateStatusTimer = ((updateStatusTimer - 1) > 0) ? (updateStatusTimer - 1) : 0; + if (updateStatusTimer > 0) { + return; + } + this.status.setText(""); + } - public void updateStatus() { - updateStatusTimer = ((updateStatusTimer - 1) > 0) ? (updateStatusTimer - 1) : 0; - if (updateStatusTimer > 0) { - return; + public void updateStatus(String statusString) { + status.setForeground(Color.BLACK); + status.setFont(MaterialFonts.REGULAR); + status.setText(statusString); } - this.status.setText(""); - } - - public void updateStatus(String statusString) { - status.setForeground(Color.BLACK); - status.setFont(MaterialFonts.REGULAR); - status.setText(statusString); - } - - public void updateError(String error) { - status.setForeground(Color.RED); - status.setFont(MaterialFonts.ITALIC); - status.setText(error); - } - - public TreeView getTreeView() { - return treeView; - } - - public void add() { - TreeViewSelection selection = treeView.getSelection(); - - AddTreeElementCommand add = new AddTreeElementCommand(selection); - if (add.canExecute()) { - add.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(add); - } else { - updateError(add.getError()); + + public void updateError(String error) { + status.setForeground(Color.RED); + status.setFont(MaterialFonts.ITALIC); + status.setText(error); + } + + public TreeView getTreeView() { + return treeView; + } + + public void add() { + TreeViewSelection selection = treeView.getSelection(); + + AddTreeElementCommand add = new AddTreeElementCommand(selection); + if (add.canExecute()) { + add.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(add); + } else { + updateError(add.getError()); + } } - } - public void delete() { - TreeViewSelection selection = treeView.getSelection(); + public void delete() { + TreeViewSelection selection = treeView.getSelection(); - DeleteTreeElementCommand del = new DeleteTreeElementCommand(selection); - if (del.canExecute()) { - del.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(del); - } else { - updateError(del.getError()); + DeleteTreeElementCommand del = new DeleteTreeElementCommand(selection); + if (del.canExecute()) { + del.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(del); + } else { + updateError(del.getError()); + } } - } - public void merge() { - TreeViewSelection selection = treeView.getSelection(); + public void merge() { + TreeViewSelection selection = treeView.getSelection(); - ICommand merge = new MergeCommand(selection); - if (merge.canExecute()) { - merge.execute(); - GameBoardFacade.getInstance().getHistory().pushChange(merge); - } else { - updateError(merge.getError()); + ICommand merge = new MergeCommand(selection); + if (merge.canExecute()) { + merge.execute(); + GameBoardFacade.getInstance().getHistory().pushChange(merge); + } else { + updateError(merge.getError()); + } } - } - public void collapse() { - TreeViewSelection selection = treeView.getSelection(); - for (TreeElementView view : selection.getSelectedViews()) { - view.setCollapsed(!view.isCollapsed()); + public void collapse() { + TreeViewSelection selection = treeView.getSelection(); + for (TreeElementView view : selection.getSelectedViews()) { + view.setCollapsed(!view.isCollapsed()); + } } - } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java index 45bf518b2..002092155 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarButton.java @@ -5,18 +5,18 @@ public class TreeToolBarButton extends JButton { - private TreeToolBarName name; - private final Dimension MINIMUM_DIMENSION = new Dimension(60, 60); + private TreeToolBarName name; + private final Dimension MINIMUM_DIMENSION = new Dimension(60, 60); - public TreeToolBarButton(ImageIcon imageIcon, TreeToolBarName name) { - super(imageIcon); - this.name = name; - this.setSize(MINIMUM_DIMENSION.width, MINIMUM_DIMENSION.height); - this.setMinimumSize(this.MINIMUM_DIMENSION); - this.setFocusPainted(false); - } + public TreeToolBarButton(ImageIcon imageIcon, TreeToolBarName name) { + super(imageIcon); + this.name = name; + this.setSize(MINIMUM_DIMENSION.width, MINIMUM_DIMENSION.height); + this.setMinimumSize(this.MINIMUM_DIMENSION); + this.setFocusPainted(false); + } - public TreeToolBarName getToolBarName() { - return name; - } + public TreeToolBarName getToolBarName() { + return name; + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java index d1a009b7e..c805021be 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolBarName.java @@ -1,8 +1,8 @@ package edu.rpi.legup.ui.proofeditorui.treeview; public enum TreeToolBarName { - ADD_CHILD, - DEL_CHILD, - MERGE, - COLLAPSE + ADD_CHILD, + DEL_CHILD, + MERGE, + COLLAPSE } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java index 3923de25b..8f3ebfc23 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeToolbarPanel.java @@ -4,50 +4,58 @@ import javax.swing.*; public class TreeToolbarPanel extends JPanel { - private TreePanel treePanel; - private TreeToolBarButton addChild, delChild, merge, collapse; - - /** - * TreeToolbarPanel Constructor - creates the tree tool mBar panel - * - * @param treePanel treePanel input - */ - public TreeToolbarPanel(TreePanel treePanel) { - this.treePanel = treePanel; - this.setLayout(new GridLayout(4, 1, 0, 2)); - - addChild = - new TreeToolBarButton( - new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/AddChild.png")), - TreeToolBarName.ADD_CHILD); - delChild = - new TreeToolBarButton( - new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/DelChild.png")), - TreeToolBarName.DEL_CHILD); - merge = - new TreeToolBarButton( - new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Merge.png")), - TreeToolBarName.MERGE); - collapse = - new TreeToolBarButton( - new ImageIcon(ClassLoader.getSystemResource("edu/rpi/legup/images/Legup/Collapse.png")), - TreeToolBarName.COLLAPSE); - - add(addChild); - addChild.addActionListener(a -> treePanel.add()); - addChild.setToolTipText("Add tree element"); - - add(delChild); - delChild.addActionListener(a -> treePanel.delete()); - delChild.setToolTipText("Remove selected tree elements"); - - add(merge); - merge.addActionListener(a -> treePanel.merge()); - merge.setToolTipText("Merge selected tree nodes"); - - add(collapse); - collapse.addActionListener(a -> treePanel.collapse()); - collapse.setToolTipText("Collapse nodes"); - collapse.setEnabled(false); - } + private TreePanel treePanel; + private TreeToolBarButton addChild, delChild, merge, collapse; + + /** + * TreeToolbarPanel Constructor - creates the tree tool mBar panel + * + * @param treePanel treePanel input + */ + public TreeToolbarPanel(TreePanel treePanel) { + this.treePanel = treePanel; + this.setLayout(new GridLayout(4, 1, 0, 2)); + + addChild = + new TreeToolBarButton( + new ImageIcon( + ClassLoader.getSystemResource( + "edu/rpi/legup/images/Legup/AddChild.png")), + TreeToolBarName.ADD_CHILD); + delChild = + new TreeToolBarButton( + new ImageIcon( + ClassLoader.getSystemResource( + "edu/rpi/legup/images/Legup/DelChild.png")), + TreeToolBarName.DEL_CHILD); + merge = + new TreeToolBarButton( + new ImageIcon( + ClassLoader.getSystemResource( + "edu/rpi/legup/images/Legup/Merge.png")), + TreeToolBarName.MERGE); + collapse = + new TreeToolBarButton( + new ImageIcon( + ClassLoader.getSystemResource( + "edu/rpi/legup/images/Legup/Collapse.png")), + TreeToolBarName.COLLAPSE); + + add(addChild); + addChild.addActionListener(a -> treePanel.add()); + addChild.setToolTipText("Add tree element"); + + add(delChild); + delChild.addActionListener(a -> treePanel.delete()); + delChild.setToolTipText("Remove selected tree elements"); + + add(merge); + merge.addActionListener(a -> treePanel.merge()); + merge.setToolTipText("Merge selected tree nodes"); + + add(collapse); + collapse.addActionListener(a -> treePanel.collapse()); + collapse.setToolTipText("Collapse nodes"); + collapse.setEnabled(false); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java index 652514be6..b022ac596 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeTransitionView.java @@ -11,344 +11,344 @@ import java.util.List; public class TreeTransitionView extends TreeElementView { - static final int RADIUS = 25; - static final int DIAMETER = 2 * RADIUS; - static final int GAP = 5; - - private static final Stroke MAIN_STROKE = new BasicStroke(3); - private static final Stroke SELECTION_STROKE = new BasicStroke(2); - - private static final Color OUTLINE_COLOR = Color.BLACK; - private static final Color CORRECT_COLOR = Color.GREEN; - private static final Color INCORRECT_COLOR = Color.RED; - private static final Color DEFAULT_COLOR = Color.GRAY; - private static final Color X_COLOR = Color.RED; - - private static final Color CORRECT_COLOR_COLORBLIND = new Color(0, 0, 255); - private static final Color INCORRECT_COLOR_COLORBLIND = new Color(255, 0, 0); - - private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); - - private static final Color HOVER_COLOR = new Color(0x90CAF9); - private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); - - private TreeNodeView childView; - private ArrayList parentViews; - private Polygon arrowhead; - - private List lineStartPoints; - private Point lineEndPoint; - - private Point endPoint; - - /** - * TreeTransitionView Constructor creates a transition arrow for display - * - * @param transition tree transition associated with this view - */ - public TreeTransitionView(TreeTransition transition) { - super(TreeElementType.TRANSITION, transition); - this.parentViews = new ArrayList<>(); - this.isCollapsed = false; - this.endPoint = new Point(); - this.lineStartPoints = new ArrayList<>(); - this.lineEndPoint = new Point(); - } - - /** - * TreeTransitionView Constructor creates a transition arrow for display - * - * @param transition tree transition associated with this view - * @param parentView TreeNodeView of the parent associated with this transition - */ - public TreeTransitionView(TreeTransition transition, TreeNodeView parentView) { - this(transition); - this.parentViews.add(parentView); - this.lineStartPoints.add(new Point()); - } - - /** - * Draws the TreeTransitionView - * - * @param graphics2D graphics2D used for drawing - */ - public void draw(Graphics2D graphics2D) { - arrowhead = createTransitionTriangle(RADIUS); - - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.setStroke(MAIN_STROKE); - - for (Point lineStartPoint : lineStartPoints) { - CubicCurve2D c = new CubicCurve2D.Double(); - double ctrlx1 = lineEndPoint.x - 25; - double ctrly1 = lineStartPoint.y; - double ctrlx2 = lineEndPoint.x - 25; - double ctrly2 = lineEndPoint.y; - - c.setCurve( - lineStartPoint.x, - lineStartPoint.y, - ctrlx1, - ctrly1, - ctrlx2, - ctrly2, - lineEndPoint.x, - lineEndPoint.y); - graphics2D.draw(c); + static final int RADIUS = 25; + static final int DIAMETER = 2 * RADIUS; + static final int GAP = 5; + + private static final Stroke MAIN_STROKE = new BasicStroke(3); + private static final Stroke SELECTION_STROKE = new BasicStroke(2); + + private static final Color OUTLINE_COLOR = Color.BLACK; + private static final Color CORRECT_COLOR = Color.GREEN; + private static final Color INCORRECT_COLOR = Color.RED; + private static final Color DEFAULT_COLOR = Color.GRAY; + private static final Color X_COLOR = Color.RED; + + private static final Color CORRECT_COLOR_COLORBLIND = new Color(0, 0, 255); + private static final Color INCORRECT_COLOR_COLORBLIND = new Color(255, 0, 0); + + private static final Color OUTLINE_SELECTION_COLOR = new Color(0x1976D2); + + private static final Color HOVER_COLOR = new Color(0x90CAF9); + private static final Color OUTLINE_HOVER_COLOR = new Color(0xBDBDBD); + + private TreeNodeView childView; + private ArrayList parentViews; + private Polygon arrowhead; + + private List lineStartPoints; + private Point lineEndPoint; + + private Point endPoint; + + /** + * TreeTransitionView Constructor creates a transition arrow for display + * + * @param transition tree transition associated with this view + */ + public TreeTransitionView(TreeTransition transition) { + super(TreeElementType.TRANSITION, transition); + this.parentViews = new ArrayList<>(); + this.isCollapsed = false; + this.endPoint = new Point(); + this.lineStartPoints = new ArrayList<>(); + this.lineEndPoint = new Point(); } - LegupPreferences prefs = LegupPreferences.getInstance(); - boolean colorBlind = prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true"); - - if (isSelected) { - Color c = DEFAULT_COLOR; - if (getTreeElement().isJustified()) { - if (getTreeElement().isCorrect()) { - if (colorBlind) { - c = CORRECT_COLOR_COLORBLIND; - } else { - c = CORRECT_COLOR; - } - } else { - if (colorBlind) { - c = INCORRECT_COLOR_COLORBLIND; - } else { - c = INCORRECT_COLOR; - } + /** + * TreeTransitionView Constructor creates a transition arrow for display + * + * @param transition tree transition associated with this view + * @param parentView TreeNodeView of the parent associated with this transition + */ + public TreeTransitionView(TreeTransition transition, TreeNodeView parentView) { + this(transition); + this.parentViews.add(parentView); + this.lineStartPoints.add(new Point()); + } + + /** + * Draws the TreeTransitionView + * + * @param graphics2D graphics2D used for drawing + */ + public void draw(Graphics2D graphics2D) { + arrowhead = createTransitionTriangle(RADIUS); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.setStroke(MAIN_STROKE); + + for (Point lineStartPoint : lineStartPoints) { + CubicCurve2D c = new CubicCurve2D.Double(); + double ctrlx1 = lineEndPoint.x - 25; + double ctrly1 = lineStartPoint.y; + double ctrlx2 = lineEndPoint.x - 25; + double ctrly2 = lineEndPoint.y; + + c.setCurve( + lineStartPoint.x, + lineStartPoint.y, + ctrlx1, + ctrly1, + ctrlx2, + ctrly2, + lineEndPoint.x, + lineEndPoint.y); + graphics2D.draw(c); } - } - graphics2D.setColor(c); - graphics2D.fillPolygon(arrowhead); + LegupPreferences prefs = LegupPreferences.getInstance(); + boolean colorBlind = prefs.getUserPref(LegupPreferences.COLOR_BLIND).equals("true"); + + if (isSelected) { + Color c = DEFAULT_COLOR; + if (getTreeElement().isJustified()) { + if (getTreeElement().isCorrect()) { + if (colorBlind) { + c = CORRECT_COLOR_COLORBLIND; + } else { + c = CORRECT_COLOR; + } + } else { + if (colorBlind) { + c = INCORRECT_COLOR_COLORBLIND; + } else { + c = INCORRECT_COLOR; + } + } + } + graphics2D.setColor(c); - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); + graphics2D.fillPolygon(arrowhead); - Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); - selection_triangle.translate(7, 0); + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_SELECTION_COLOR); - graphics2D.drawPolygon(selection_triangle); - } else { - if (isHover) { - graphics2D.setColor(HOVER_COLOR); - graphics2D.fillPolygon(arrowhead); + Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); + selection_triangle.translate(7, 0); - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); - - Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); - selection_triangle.translate(7, 0); - - graphics2D.setStroke(SELECTION_STROKE); - graphics2D.setColor(OUTLINE_HOVER_COLOR); - graphics2D.drawPolygon(selection_triangle); - } else { - Color c = DEFAULT_COLOR; - if (getTreeElement().isJustified()) { - if (getTreeElement().isCorrect()) { - if (colorBlind) { - c = CORRECT_COLOR_COLORBLIND; - } else { - c = CORRECT_COLOR; - } - } else { - if (colorBlind) { - c = INCORRECT_COLOR_COLORBLIND; + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_SELECTION_COLOR); + graphics2D.drawPolygon(selection_triangle); + } else { + if (isHover) { + graphics2D.setColor(HOVER_COLOR); + graphics2D.fillPolygon(arrowhead); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); + + Polygon selection_triangle = createTransitionTriangle(RADIUS + 10); + selection_triangle.translate(7, 0); + + graphics2D.setStroke(SELECTION_STROKE); + graphics2D.setColor(OUTLINE_HOVER_COLOR); + graphics2D.drawPolygon(selection_triangle); } else { - c = INCORRECT_COLOR; + Color c = DEFAULT_COLOR; + if (getTreeElement().isJustified()) { + if (getTreeElement().isCorrect()) { + if (colorBlind) { + c = CORRECT_COLOR_COLORBLIND; + } else { + c = CORRECT_COLOR; + } + } else { + if (colorBlind) { + c = INCORRECT_COLOR_COLORBLIND; + } else { + c = INCORRECT_COLOR; + } + } + } + graphics2D.setColor(c); + graphics2D.fillPolygon(arrowhead); + + graphics2D.setColor(OUTLINE_COLOR); + graphics2D.drawPolygon(arrowhead); } - } } - graphics2D.setColor(c); - graphics2D.fillPolygon(arrowhead); + } - graphics2D.setColor(OUTLINE_COLOR); - graphics2D.drawPolygon(arrowhead); - } + /** Constructs the arrowhead shape from the start and end points */ + private Polygon createTransitionTriangle(int radius) { + double thetaArrow = Math.toRadians(30); + + int point1X = endPoint.x; + int point1Y = endPoint.y; + + int point2X = point1X - radius; + int point2Y = point1Y + (int) Math.round(radius / (2 * cos(thetaArrow))); + + int point3X = point1X - radius; + int point3Y = point1Y - (int) Math.round(radius / (2 * cos(thetaArrow))); + + lineEndPoint.x = point2X; + lineEndPoint.y = (point3Y - point2Y) / 2 + point2Y; + + Polygon tri = new Polygon(); + tri.addPoint(point1X, point1Y); + tri.addPoint(point2X, point2Y); + tri.addPoint(point3X, point3Y); + + return tri; + } + + /** + * Gets the TreeElement associated with this view + * + * @return the TreeElement associated with this view + */ + public TreeTransition getTreeElement() { + return (TreeTransition) treeElement; + } + + /** + * Gets the TreeNodeView child view + * + * @return TreeNodeView child view + */ + public TreeNodeView getChildView() { + return childView; + } + + /** + * Sets the TreeNodeView child view + * + * @param childView TreeNodeView child view + */ + public void setChildView(TreeNodeView childView) { + this.childView = childView; + } + + /** + * Gets the list of parent views associated with this tree transition view + * + * @return list of parent views for this tree transition view + */ + public ArrayList getParentViews() { + return parentViews; } - } - - /** Constructs the arrowhead shape from the start and end points */ - private Polygon createTransitionTriangle(int radius) { - double thetaArrow = Math.toRadians(30); - - int point1X = endPoint.x; - int point1Y = endPoint.y; - - int point2X = point1X - radius; - int point2Y = point1Y + (int) Math.round(radius / (2 * cos(thetaArrow))); - - int point3X = point1X - radius; - int point3Y = point1Y - (int) Math.round(radius / (2 * cos(thetaArrow))); - - lineEndPoint.x = point2X; - lineEndPoint.y = (point3Y - point2Y) / 2 + point2Y; - - Polygon tri = new Polygon(); - tri.addPoint(point1X, point1Y); - tri.addPoint(point2X, point2Y); - tri.addPoint(point3X, point3Y); - - return tri; - } - - /** - * Gets the TreeElement associated with this view - * - * @return the TreeElement associated with this view - */ - public TreeTransition getTreeElement() { - return (TreeTransition) treeElement; - } - - /** - * Gets the TreeNodeView child view - * - * @return TreeNodeView child view - */ - public TreeNodeView getChildView() { - return childView; - } - - /** - * Sets the TreeNodeView child view - * - * @param childView TreeNodeView child view - */ - public void setChildView(TreeNodeView childView) { - this.childView = childView; - } - - /** - * Gets the list of parent views associated with this tree transition view - * - * @return list of parent views for this tree transition view - */ - public ArrayList getParentViews() { - return parentViews; - } - - /** - * Sets the list of parent views associated with this tree transition view - * - * @param parentViews list of parent views for this tree transition view - */ - public void setParentViews(ArrayList parentViews) { - this.parentViews = parentViews; - this.lineStartPoints.clear(); - for (TreeNodeView parentView : this.parentViews) { - this.lineStartPoints.add(new Point()); + + /** + * Sets the list of parent views associated with this tree transition view + * + * @param parentViews list of parent views for this tree transition view + */ + public void setParentViews(ArrayList parentViews) { + this.parentViews = parentViews; + this.lineStartPoints.clear(); + for (TreeNodeView parentView : this.parentViews) { + this.lineStartPoints.add(new Point()); + } + } + + /** + * Adds a TreeNodeView to the list of parent views + * + * @param nodeView TreeNodeView to add to the list of parent views + */ + public void addParentView(TreeNodeView nodeView) { + parentViews.add(nodeView); + lineStartPoints.add(new Point()); } - } - - /** - * Adds a TreeNodeView to the list of parent views - * - * @param nodeView TreeNodeView to add to the list of parent views - */ - public void addParentView(TreeNodeView nodeView) { - parentViews.add(nodeView); - lineStartPoints.add(new Point()); - } - - /** - * Removes a TreeNodeView from the list of parent views - * - * @param nodeView TreeNodeView to remove from the list of parent views - */ - public void removeParentView(TreeNodeView nodeView) { - int index = parentViews.indexOf(nodeView); - parentViews.remove(nodeView); - if (index != -1) { - lineStartPoints.remove(index); + + /** + * Removes a TreeNodeView from the list of parent views + * + * @param nodeView TreeNodeView to remove from the list of parent views + */ + public void removeParentView(TreeNodeView nodeView) { + int index = parentViews.indexOf(nodeView); + parentViews.remove(nodeView); + if (index != -1) { + lineStartPoints.remove(index); + } + } + + public Point getEndPoint() { + return endPoint; + } + + public void setEndPoint(Point endPoint) { + this.endPoint = endPoint; + } + + public int getEndX() { + return endPoint.x; + } + + public void setEndX(int x) { + this.endPoint.x = x; + } + + public int getEndY() { + return endPoint.y; + } + + public void setEndY(int y) { + this.endPoint.y = y; + } + + public List getLineStartPoints() { + return lineStartPoints; + } + + public void setLineStartPoints(List lineStartPoints) { + this.lineStartPoints = lineStartPoints; + } + + public Point getLineStartPoint(int index) { + return index < lineStartPoints.size() ? lineStartPoints.get(index) : null; + } + + @Override + public Rectangle getBounds() { + return arrowhead.getBounds(); + } + + @Override + public Rectangle2D getBounds2D() { + return arrowhead.getBounds2D(); + } + + @Override + public boolean contains(double x, double y) { + return arrowhead.contains(x, y); + } + + @Override + public boolean contains(Point2D p) { + return arrowhead != null && arrowhead.contains(p); + } + + @Override + public boolean intersects(double x, double y, double w, double h) { + return arrowhead.intersects(x, y, w, h); + } + + @Override + public boolean intersects(Rectangle2D r) { + return arrowhead.intersects(r); + } + + @Override + public boolean contains(double x, double y, double w, double h) { + return arrowhead.contains(x, y, w, h); + } + + @Override + public boolean contains(Rectangle2D r) { + return arrowhead.contains(r); + } + + @Override + public PathIterator getPathIterator(AffineTransform at) { + return arrowhead.getPathIterator(at); + } + + @Override + public PathIterator getPathIterator(AffineTransform at, double flatness) { + return arrowhead.getPathIterator(at, flatness); } - } - - public Point getEndPoint() { - return endPoint; - } - - public void setEndPoint(Point endPoint) { - this.endPoint = endPoint; - } - - public int getEndX() { - return endPoint.x; - } - - public void setEndX(int x) { - this.endPoint.x = x; - } - - public int getEndY() { - return endPoint.y; - } - - public void setEndY(int y) { - this.endPoint.y = y; - } - - public List getLineStartPoints() { - return lineStartPoints; - } - - public void setLineStartPoints(List lineStartPoints) { - this.lineStartPoints = lineStartPoints; - } - - public Point getLineStartPoint(int index) { - return index < lineStartPoints.size() ? lineStartPoints.get(index) : null; - } - - @Override - public Rectangle getBounds() { - return arrowhead.getBounds(); - } - - @Override - public Rectangle2D getBounds2D() { - return arrowhead.getBounds2D(); - } - - @Override - public boolean contains(double x, double y) { - return arrowhead.contains(x, y); - } - - @Override - public boolean contains(Point2D p) { - return arrowhead != null && arrowhead.contains(p); - } - - @Override - public boolean intersects(double x, double y, double w, double h) { - return arrowhead.intersects(x, y, w, h); - } - - @Override - public boolean intersects(Rectangle2D r) { - return arrowhead.intersects(r); - } - - @Override - public boolean contains(double x, double y, double w, double h) { - return arrowhead.contains(x, y, w, h); - } - - @Override - public boolean contains(Rectangle2D r) { - return arrowhead.contains(r); - } - - @Override - public PathIterator getPathIterator(AffineTransform at) { - return arrowhead.getPathIterator(at); - } - - @Override - public PathIterator getPathIterator(AffineTransform at, double flatness) { - return arrowhead.getPathIterator(at, flatness); - } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java index b46090fed..f491009b4 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeView.java @@ -27,855 +27,885 @@ import org.apache.logging.log4j.Logger; public class TreeView extends ScrollView implements ITreeListener { - private static final Logger LOGGER = LogManager.getLogger(TreeView.class.getName()); - - private static final int TRANS_GAP = 5; - - private static final int NODE_GAP_WIDTH = 70; - private static final int NODE_GAP_HEIGHT = 15; - - private static final int BORDER_GAP_HEIGHT = 20; - private static final int BORDER_GAP_WIDTH = 20; - - private static final int BORDER_SPACING = 100; - - private TreeNodeView nodeHover; - - private ArrayList currentStateBoxes; - private Rectangle bounds = new Rectangle(0, 0, 0, 0); - - private Tree tree; - private TreeNodeView rootNodeView; - private Map viewMap; - private Dimension dimension; - - private TreeViewSelection selection; - - public TreeView(TreeController treeController) { - super(treeController); - currentStateBoxes = new ArrayList<>(); - setSize(dimension = new Dimension(100, 200)); - setPreferredSize(new Dimension(640, 160)); - - viewMap = new HashMap<>(); - - selection = new TreeViewSelection(); - } - - public TreeViewSelection getSelection() { - return selection; - } - - /** - * Gets the tree node puzzleElement that the mouse is hovering over - * - * @return tree node puzzleElement that the mouse is hovering over - */ - public TreeNodeView getNodeHover() { - return nodeHover; - } - - /** - * Sets the tree node puzzleElement that the mouse is hovering over - * - * @param nodeHover tree node puzzleElement the mouse is hovering over - */ - public void setNodeHover(TreeNodeView nodeHover) { - this.nodeHover = nodeHover; - } - - /** - * Gets the TreeElementView by the specified point or null if no view exists at the specified - * point - * - * @param point location to query for a view - * @return TreeElementView at the point specified, otherwise null - */ - public TreeElementView getTreeElementView(Point point) { - return getTreeElementView(point, rootNodeView); - } - - /** - * Recursively gets the TreeElementView by the specified point or null if no view exists at the - * specified point or the view specified is null - * - * @param point location to query for a view - * @param elementView view to determine if the point is contained within it - * @return TreeElementView at the point specified, otherwise null - */ - private TreeElementView getTreeElementView(Point point, TreeElementView elementView) { - if (elementView == null) { - return null; - } else { - if (elementView.contains(point) && elementView.isVisible()) { - if (elementView.getType() == NODE && ((TreeNodeView) elementView).isContradictoryState()) { - return null; - } - return elementView; - } else { - if (elementView.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) elementView; - for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { - TreeElementView view = getTreeElementView(point, transitionView); - if (view != null) { - return view; - } - } + private static final Logger LOGGER = LogManager.getLogger(TreeView.class.getName()); + + private static final int TRANS_GAP = 5; + + private static final int NODE_GAP_WIDTH = 70; + private static final int NODE_GAP_HEIGHT = 15; + + private static final int BORDER_GAP_HEIGHT = 20; + private static final int BORDER_GAP_WIDTH = 20; + + private static final int BORDER_SPACING = 100; + + private TreeNodeView nodeHover; + + private ArrayList currentStateBoxes; + private Rectangle bounds = new Rectangle(0, 0, 0, 0); + + private Tree tree; + private TreeNodeView rootNodeView; + private Map viewMap; + private Dimension dimension; + + private TreeViewSelection selection; + + public TreeView(TreeController treeController) { + super(treeController); + currentStateBoxes = new ArrayList<>(); + setSize(dimension = new Dimension(100, 200)); + setPreferredSize(new Dimension(640, 160)); + + viewMap = new HashMap<>(); + + selection = new TreeViewSelection(); + } + + public TreeViewSelection getSelection() { + return selection; + } + + /** + * Gets the tree node puzzleElement that the mouse is hovering over + * + * @return tree node puzzleElement that the mouse is hovering over + */ + public TreeNodeView getNodeHover() { + return nodeHover; + } + + /** + * Sets the tree node puzzleElement that the mouse is hovering over + * + * @param nodeHover tree node puzzleElement the mouse is hovering over + */ + public void setNodeHover(TreeNodeView nodeHover) { + this.nodeHover = nodeHover; + } + + /** + * Gets the TreeElementView by the specified point or null if no view exists at the specified + * point + * + * @param point location to query for a view + * @return TreeElementView at the point specified, otherwise null + */ + public TreeElementView getTreeElementView(Point point) { + return getTreeElementView(point, rootNodeView); + } + + /** + * Recursively gets the TreeElementView by the specified point or null if no view exists at the + * specified point or the view specified is null + * + * @param point location to query for a view + * @param elementView view to determine if the point is contained within it + * @return TreeElementView at the point specified, otherwise null + */ + private TreeElementView getTreeElementView(Point point, TreeElementView elementView) { + if (elementView == null) { + return null; } else { - TreeTransitionView transitionView = (TreeTransitionView) elementView; - return getTreeElementView(point, transitionView.getChildView()); - } - } - } - return null; - } - - public void updateTreeView(Tree tree) { - this.tree = tree; - if (selection.getSelectedViews().size() == 0) { - selection.newSelection(new TreeNodeView(tree.getRootNode())); - } - repaint(); - } - - /** - * Sets the tree associated with this TreeView - * - * @param tree tree - */ - public void setTree(Tree tree) { - this.tree = tree; - } - - public void updateTreeSize() { - if (GameBoardFacade.getInstance().getTree() == null) { - return; - } - setSize(bounds.getSize()); - } - - public void reset() { - if (bounds.x != 0 || bounds.y != 0) { - updateTreeSize(); - } - } - - public void zoomFit() { - double fitWidth = (viewport.getWidth() - 8.0) / (getSize().width - 200); - double fitHeight = (viewport.getHeight() - 8.0) / (getSize().height - 120); - zoomTo(Math.min(fitWidth, fitHeight)); - viewport.setViewPosition(new Point(0, viewport.getHeight() / 2)); - } - - /** - * Creates a customized viewport for the scroll pane - * - * @return viewport for the scroll pane - */ - @Override - protected JViewport createViewport() { - return new JViewport() { - @Override - protected LayoutManager createLayoutManager() { - return new ViewportLayout() { - @Override - public void layoutContainer(Container parent) { - Point point = viewport.getViewPosition(); - // determine the maximum x and y view positions - int mx = getCanvas().getWidth() - viewport.getWidth(); - int my = getCanvas().getHeight() - viewport.getHeight(); - // obey edge boundaries - if (point.x < 0) { - point.x = 0; - } - if (point.x > mx) { - point.x = mx; - } - if (point.y < 0) { - point.y = 0; - } - if (point.y > my) { - point.y = my; - } - // center margins - if (mx < 0) { - point.x = 0; - } - if (my < 0) { - point.y = my / 2; + if (elementView.contains(point) && elementView.isVisible()) { + if (elementView.getType() == NODE + && ((TreeNodeView) elementView).isContradictoryState()) { + return null; + } + return elementView; + } else { + if (elementView.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) elementView; + for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { + TreeElementView view = getTreeElementView(point, transitionView); + if (view != null) { + return view; + } + } + } else { + TreeTransitionView transitionView = (TreeTransitionView) elementView; + return getTreeElementView(point, transitionView.getChildView()); + } } - viewport.setViewPosition(point); - } - }; - } - }; - } - - public void draw(Graphics2D graphics2D) { - currentStateBoxes.clear(); - Tree tree = GameBoardFacade.getInstance().getTree(); - if (tree != null) { - // setSize(bounds.getDimension()); - graphics2D.setRenderingHint( - RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics2D.setRenderingHint( - RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - - drawTree(graphics2D); - - dimension.width += BORDER_SPACING; - setSize(dimension); - // graphics2D.drawRect(0,0, dimension.width, dimension.height); - - if (selection.getHover() != null) { - drawMouseOver(graphics2D); - } - } - } - - public void zoomReset() { - zoomTo(1.0); - viewport.setViewPosition(new Point(0, 0)); - } - - private void redrawTree(Graphics2D graphics2D, TreeNodeView nodeView) { - if (nodeView != null) { - nodeView.draw(graphics2D); - for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { - transitionView.draw(graphics2D); - redrawTree(graphics2D, transitionView.getChildView()); - } - } - } - - public void removeTreeElement(TreeElementView view) { - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - nodeView.getParentView().setChildView(null); - } else { - TreeTransitionView transitionView = (TreeTransitionView) view; - transitionView - .getParentViews() - .forEach((TreeNodeView n) -> n.removeChildrenView(transitionView)); - } - } - - /** - * When the edu.rpi.legup.user hovers over the transition, draws the corresponding rules image - * - * @param g the graphics to use to draw - */ - public void drawMouseOver(Graphics2D g) { - if (selection.getHover().getType() == TRANSITION - && ((TreeTransitionView) selection.getHover()).getTreeElement().isJustified()) { - TreeTransition transition = (TreeTransition) selection.getHover().treeElement; - int imgWidth = 100; - int imgHeight = 100; - - BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); - image.createGraphics().drawImage(transition.getRule().getImageIcon().getImage(), 0, 0, null); - Point mousePoint = selection.getMousePoint(); - g.drawImage(image, mousePoint.x, mousePoint.y - 50, imgWidth, imgHeight, null); - } - } - - public void resetView() { - this.tree = null; - this.rootNodeView = null; - this.selection.clearSelection(); - this.selection.clearHover(); - } - - /** - * Called when a tree puzzleElement is added to the tree - * - * @param treeElement TreeElement that was added to the tree - */ - @Override - public void onTreeElementAdded(TreeElement treeElement) { - if (treeElement.getType() == NODE) { - addTreeNode((TreeNode) treeElement); - } else { - addTreeTransition((TreeTransition) treeElement); - } - repaint(); - } - - /** - * Called when a tree puzzleElement is removed from the tree - * - * @param element TreeElement that was removed to the tree - */ - @Override - public void onTreeElementRemoved(TreeElement element) { - if (element.getType() == NODE) { - TreeNode node = (TreeNode) element; - TreeNodeView nodeView = (TreeNodeView) viewMap.get(node); - - nodeView.getParentView().setChildView(null); - removeTreeNode(node); - } else { - TreeTransition trans = (TreeTransition) element; - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - - // unlock ancestor elements if case rule deleted - Rule rule = trans.getRule(); - for (TreeNode node : trans.getParents()) { - - // only if the last case of a case rule will be deleted - if (!(rule instanceof CaseRule && node.getChildren().isEmpty())) { - continue; } + return null; + } + + public void updateTreeView(Tree tree) { + this.tree = tree; + if (selection.getSelectedViews().size() == 0) { + selection.newSelection(new TreeNodeView(tree.getRootNode())); + } + repaint(); + } + + /** + * Sets the tree associated with this TreeView + * + * @param tree tree + */ + public void setTree(Tree tree) { + this.tree = tree; + } + + public void updateTreeSize() { + if (GameBoardFacade.getInstance().getTree() == null) { + return; + } + setSize(bounds.getSize()); + } - CaseRule caseRule = (CaseRule) rule; - // set dependent elements to be modifiable by ancestors (if not dependent on others) - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - - for (PuzzleElement pelement : - caseRule.dependentElements(node.getBoard(), trans.getSelection())) { - // decrement, unlock if 0 cases depended - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); - oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); - if (oldElement.getCasesDepended() != 0) { - continue; + public void reset() { + if (bounds.x != 0 || bounds.y != 0) { + updateTreeSize(); + } + } + + public void zoomFit() { + double fitWidth = (viewport.getWidth() - 8.0) / (getSize().width - 200); + double fitHeight = (viewport.getHeight() - 8.0) / (getSize().height - 120); + zoomTo(Math.min(fitWidth, fitHeight)); + viewport.setViewPosition(new Point(0, viewport.getHeight() / 2)); + } + + /** + * Creates a customized viewport for the scroll pane + * + * @return viewport for the scroll pane + */ + @Override + protected JViewport createViewport() { + return new JViewport() { + @Override + protected LayoutManager createLayoutManager() { + return new ViewportLayout() { + @Override + public void layoutContainer(Container parent) { + Point point = viewport.getViewPosition(); + // determine the maximum x and y view positions + int mx = getCanvas().getWidth() - viewport.getWidth(); + int my = getCanvas().getHeight() - viewport.getHeight(); + // obey edge boundaries + if (point.x < 0) { + point.x = 0; + } + if (point.x > mx) { + point.x = mx; + } + if (point.y < 0) { + point.y = 0; + } + if (point.y > my) { + point.y = my; + } + // center margins + if (mx < 0) { + point.x = 0; + } + if (my < 0) { + point.y = my / 2; + } + viewport.setViewPosition(point); + } + }; } + }; + } - // set modifiable if started modifiable - boolean modifiable = - tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); + public void draw(Graphics2D graphics2D) { + currentStateBoxes.clear(); + Tree tree = GameBoardFacade.getInstance().getTree(); + if (tree != null) { + // setSize(bounds.getDimension()); + graphics2D.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics2D.setRenderingHint( + RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - // unmodifiable if already modified - TreeNode modNode = ancestor.getParent().getParents().get(0); - while (modNode.getParent() != null) { - Board modBoard = modNode.getParent().getBoard(); - if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { - modifiable = false; - break; - } - modNode = modNode.getParent().getParents().get(0); + drawTree(graphics2D); + + dimension.width += BORDER_SPACING; + setSize(dimension); + // graphics2D.drawRect(0,0, dimension.width, dimension.height); + + if (selection.getHover() != null) { + drawMouseOver(graphics2D); } - oldElement.setModifiable(modifiable); - } } - } - - transView.getParentViews().forEach(n -> n.removeChildrenView(transView)); - removeTreeTransition(trans); - } - repaint(); - } - - /** - * Called when the tree selection was changed - * - * @param selection tree selection that was changed - */ - @Override - public void onTreeSelectionChanged(TreeViewSelection selection) { - this.selection.getSelectedViews().forEach(v -> v.setSelected(false)); - selection.getSelectedViews().forEach(v -> v.setSelected(true)); - this.selection = selection; - repaint(); - } - - /** Called when the model has finished updating the tree. */ - @Override - public void onUpdateTree() { - repaint(); - } - - /** - * Gets the TreeElementView by the corresponding TreeElement associated with it - * - * @param element TreeElement of the view - * @return TreeElementView of the TreeElement associated with it - */ - public TreeElementView getElementView(TreeElement element) { - return viewMap.get(element); - } - - private void removeTreeNode(TreeNode node) { - viewMap.remove(node); - List children = node.getChildren(); - - // if child is a case rule, unlock ancestor elements - if (!children.isEmpty()) { - Rule rule = children.get(0).getRule(); - if (rule instanceof CaseRule) { - CaseRule caseRule = (CaseRule) rule; - // set dependent elements to be modifiable by ancestors (if not dependent on others) - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement pelement : - caseRule.dependentElements(node.getBoard(), children.get(0).getSelection())) { - // decrement, unlock if 0 cases depended - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(pelement); - oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); - if (oldElement.getCasesDepended() == 0) { - continue; - } + } - // set modifiable if started modifiable - boolean modifiable = - tree.getRootNode().getBoard().getPuzzleElement(oldElement).isModifiable(); + public void zoomReset() { + zoomTo(1.0); + viewport.setViewPosition(new Point(0, 0)); + } - // unmodifiable if already modified - TreeNode modNode = ancestor.getParent().getParents().get(0); - while (modNode.getParent() != null) { - Board modBoard = modNode.getParent().getBoard(); - if (modBoard.getModifiedData().contains(modBoard.getPuzzleElement(oldElement))) { - modifiable = false; - break; - } - modNode = modNode.getParent().getParents().get(0); + private void redrawTree(Graphics2D graphics2D, TreeNodeView nodeView) { + if (nodeView != null) { + nodeView.draw(graphics2D); + for (TreeTransitionView transitionView : nodeView.getChildrenViews()) { + transitionView.draw(graphics2D); + redrawTree(graphics2D, transitionView.getChildView()); } - oldElement.setModifiable(modifiable); - } } - } - } - node.getChildren().forEach(t -> removeTreeTransition(t)); - } - - private void removeTreeTransition(TreeTransition trans) { - viewMap.remove(trans); - if (trans.getChildNode() != null) { - removeTreeNode(trans.getChildNode()); - } - } - - private void addTreeNode(TreeNode node) { - TreeTransition parent = node.getParent(); - - TreeNodeView nodeView = new TreeNodeView(node); - TreeTransitionView parentView = (TreeTransitionView) viewMap.get(parent); - - nodeView.setParentView(parentView); - parentView.setChildView(nodeView); - - viewMap.put(node, nodeView); - - if (!node.getChildren().isEmpty()) { - - // if adding a case rule, lock dependent ancestor elements - Rule rule = node.getChildren().get(0).getRule(); - if (rule instanceof CaseRule) { - CaseRule caseRule = (CaseRule) rule; - - List ancestors = node.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement element : - caseRule.dependentElements( - node.getBoard(), node.getChildren().get(0).getSelection())) { - // increment and lock - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); - oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); - oldElement.setModifiable(false); - } + } + + public void removeTreeElement(TreeElementView view) { + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + nodeView.getParentView().setChildView(null); + } else { + TreeTransitionView transitionView = (TreeTransitionView) view; + transitionView + .getParentViews() + .forEach((TreeNodeView n) -> n.removeChildrenView(transitionView)); + } + } + + /** + * When the edu.rpi.legup.user hovers over the transition, draws the corresponding rules image + * + * @param g the graphics to use to draw + */ + public void drawMouseOver(Graphics2D g) { + if (selection.getHover().getType() == TRANSITION + && ((TreeTransitionView) selection.getHover()).getTreeElement().isJustified()) { + TreeTransition transition = (TreeTransition) selection.getHover().treeElement; + int imgWidth = 100; + int imgHeight = 100; + + BufferedImage image = + new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); + image.createGraphics() + .drawImage(transition.getRule().getImageIcon().getImage(), 0, 0, null); + Point mousePoint = selection.getMousePoint(); + g.drawImage(image, mousePoint.x, mousePoint.y - 50, imgWidth, imgHeight, null); } - } - - node.getChildren().forEach(t -> addTreeTransition(t)); - } - } - - private void addTreeTransition(TreeTransition trans) { - List parents = trans.getParents(); - - TreeTransitionView transView = new TreeTransitionView(trans); - for (TreeNode parent : parents) { - TreeNodeView parentNodeView = (TreeNodeView) viewMap.get(parent); - transView.addParentView(parentNodeView); - parentNodeView.addChildrenView(transView); - - // if transition is a new case rule, lock dependent ancestor elements - Rule rule = trans.getRule(); - if (rule instanceof CaseRule && parent.getChildren().size() == 1) { - CaseRule caseRule = (CaseRule) rule; - - List ancestors = parent.getAncestors(); - for (TreeNode ancestor : ancestors) { - // for all ancestors but root - if (ancestor.getParent() == null) { - continue; - } - for (PuzzleElement element : - caseRule.dependentElements(parent.getBoard(), trans.getSelection())) { - // increment and lock - PuzzleElement oldElement = ancestor.getParent().getBoard().getPuzzleElement(element); - oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); - oldElement.setModifiable(false); - } + } + + public void resetView() { + this.tree = null; + this.rootNodeView = null; + this.selection.clearSelection(); + this.selection.clearHover(); + } + + /** + * Called when a tree puzzleElement is added to the tree + * + * @param treeElement TreeElement that was added to the tree + */ + @Override + public void onTreeElementAdded(TreeElement treeElement) { + if (treeElement.getType() == NODE) { + addTreeNode((TreeNode) treeElement); + } else { + addTreeTransition((TreeTransition) treeElement); } - } + repaint(); } - viewMap.put(trans, transView); + /** + * Called when a tree puzzleElement is removed from the tree + * + * @param element TreeElement that was removed to the tree + */ + @Override + public void onTreeElementRemoved(TreeElement element) { + if (element.getType() == NODE) { + TreeNode node = (TreeNode) element; + TreeNodeView nodeView = (TreeNodeView) viewMap.get(node); + + nodeView.getParentView().setChildView(null); + removeTreeNode(node); + } else { + TreeTransition trans = (TreeTransition) element; + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + + // unlock ancestor elements if case rule deleted + Rule rule = trans.getRule(); + for (TreeNode node : trans.getParents()) { + + // only if the last case of a case rule will be deleted + if (!(rule instanceof CaseRule && node.getChildren().isEmpty())) { + continue; + } + + CaseRule caseRule = (CaseRule) rule; + // set dependent elements to be modifiable by ancestors (if not dependent on others) + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + + for (PuzzleElement pelement : + caseRule.dependentElements(node.getBoard(), trans.getSelection())) { + // decrement, unlock if 0 cases depended + PuzzleElement oldElement = + ancestor.getParent().getBoard().getPuzzleElement(pelement); + oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); + if (oldElement.getCasesDepended() != 0) { + continue; + } + + // set modifiable if started modifiable + boolean modifiable = + tree.getRootNode() + .getBoard() + .getPuzzleElement(oldElement) + .isModifiable(); + + // unmodifiable if already modified + TreeNode modNode = ancestor.getParent().getParents().get(0); + while (modNode.getParent() != null) { + Board modBoard = modNode.getParent().getBoard(); + if (modBoard.getModifiedData() + .contains(modBoard.getPuzzleElement(oldElement))) { + modifiable = false; + break; + } + modNode = modNode.getParent().getParents().get(0); + } + oldElement.setModifiable(modifiable); + } + } + } - if (trans.getChildNode() != null) { - addTreeNode(trans.getChildNode()); + transView.getParentViews().forEach(n -> n.removeChildrenView(transView)); + removeTreeTransition(trans); + } + repaint(); } - } - /// New Draw Methods + /** + * Called when the tree selection was changed + * + * @param selection tree selection that was changed + */ + @Override + public void onTreeSelectionChanged(TreeViewSelection selection) { + this.selection.getSelectedViews().forEach(v -> v.setSelected(false)); + selection.getSelectedViews().forEach(v -> v.setSelected(true)); + this.selection = selection; + repaint(); + } - public void drawTree(Graphics2D graphics2D) { - if (tree == null) { - LOGGER.error("Unable to draw tree."); - } else { - if (rootNodeView == null) { - rootNodeView = new TreeNodeView(tree.getRootNode()); + /** Called when the model has finished updating the tree. */ + @Override + public void onUpdateTree() { + repaint(); + } - LOGGER.debug("Creating new views for tree view."); - createViews(rootNodeView); + /** + * Gets the TreeElementView by the corresponding TreeElement associated with it + * + * @param element TreeElement of the view + * @return TreeElementView of the TreeElement associated with it + */ + public TreeElementView getElementView(TreeElement element) { + return viewMap.get(element); + } - selection.newSelection(rootNodeView); - } + private void removeTreeNode(TreeNode node) { + viewMap.remove(node); + List children = node.getChildren(); + + // if child is a case rule, unlock ancestor elements + if (!children.isEmpty()) { + Rule rule = children.get(0).getRule(); + if (rule instanceof CaseRule) { + CaseRule caseRule = (CaseRule) rule; + // set dependent elements to be modifiable by ancestors (if not dependent on others) + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement pelement : + caseRule.dependentElements( + node.getBoard(), children.get(0).getSelection())) { + // decrement, unlock if 0 cases depended + PuzzleElement oldElement = + ancestor.getParent().getBoard().getPuzzleElement(pelement); + oldElement.setCasesDepended(oldElement.getCasesDepended() - 1); + if (oldElement.getCasesDepended() == 0) { + continue; + } + + // set modifiable if started modifiable + boolean modifiable = + tree.getRootNode() + .getBoard() + .getPuzzleElement(oldElement) + .isModifiable(); + + // unmodifiable if already modified + TreeNode modNode = ancestor.getParent().getParents().get(0); + while (modNode.getParent() != null) { + Board modBoard = modNode.getParent().getBoard(); + if (modBoard.getModifiedData() + .contains(modBoard.getPuzzleElement(oldElement))) { + modifiable = false; + break; + } + modNode = modNode.getParent().getParents().get(0); + } + oldElement.setModifiable(modifiable); + } + } + } + } + node.getChildren().forEach(t -> removeTreeTransition(t)); + } - dimension = new Dimension(0, 0); - calcSpan(rootNodeView); - rootNodeView.setSpan(rootNodeView.getSpan() + DIAMETER + BORDER_SPACING); + private void removeTreeTransition(TreeTransition trans) { + viewMap.remove(trans); + if (trans.getChildNode() != null) { + removeTreeNode(trans.getChildNode()); + } + } - calculateViewLocations(rootNodeView, 0); - dimension.height = (int) rootNodeView.getSpan(); + private void addTreeNode(TreeNode node) { + TreeTransition parent = node.getParent(); + + TreeNodeView nodeView = new TreeNodeView(node); + TreeTransitionView parentView = (TreeTransitionView) viewMap.get(parent); + + nodeView.setParentView(parentView); + parentView.setChildView(nodeView); + + viewMap.put(node, nodeView); + + if (!node.getChildren().isEmpty()) { + + // if adding a case rule, lock dependent ancestor elements + Rule rule = node.getChildren().get(0).getRule(); + if (rule instanceof CaseRule) { + CaseRule caseRule = (CaseRule) rule; + + List ancestors = node.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement element : + caseRule.dependentElements( + node.getBoard(), node.getChildren().get(0).getSelection())) { + // increment and lock + PuzzleElement oldElement = + ancestor.getParent().getBoard().getPuzzleElement(element); + oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); + oldElement.setModifiable(false); + } + } + } - redrawTree(graphics2D, rootNodeView); - LOGGER.debug("DrawTree: dimensions - " + dimension.width + "x" + dimension.height); + node.getChildren().forEach(t -> addTreeTransition(t)); + } } - } - public void createViews(TreeNodeView nodeView) { - if (nodeView != null) { - viewMap.put(nodeView.getTreeElement(), nodeView); + private void addTreeTransition(TreeTransition trans) { + List parents = trans.getParents(); + + TreeTransitionView transView = new TreeTransitionView(trans); + for (TreeNode parent : parents) { + TreeNodeView parentNodeView = (TreeNodeView) viewMap.get(parent); + transView.addParentView(parentNodeView); + parentNodeView.addChildrenView(transView); + + // if transition is a new case rule, lock dependent ancestor elements + Rule rule = trans.getRule(); + if (rule instanceof CaseRule && parent.getChildren().size() == 1) { + CaseRule caseRule = (CaseRule) rule; + + List ancestors = parent.getAncestors(); + for (TreeNode ancestor : ancestors) { + // for all ancestors but root + if (ancestor.getParent() == null) { + continue; + } + for (PuzzleElement element : + caseRule.dependentElements(parent.getBoard(), trans.getSelection())) { + // increment and lock + PuzzleElement oldElement = + ancestor.getParent().getBoard().getPuzzleElement(element); + oldElement.setCasesDepended(oldElement.getCasesDepended() + 1); + oldElement.setModifiable(false); + } + } + } + } - TreeNode node = nodeView.getTreeElement(); - for (TreeTransition trans : node.getChildren()) { - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - if (transView != null) { - nodeView.addChildrenView(transView); - transView.addParentView(nodeView); - break; + viewMap.put(trans, transView); + + if (trans.getChildNode() != null) { + addTreeNode(trans.getChildNode()); } - transView = new TreeTransitionView(trans); + } - viewMap.put(transView.getTreeElement(), transView); + /// New Draw Methods - transView.addParentView(nodeView); - nodeView.addChildrenView(transView); + public void drawTree(Graphics2D graphics2D) { + if (tree == null) { + LOGGER.error("Unable to draw tree."); + } else { + if (rootNodeView == null) { + rootNodeView = new TreeNodeView(tree.getRootNode()); - TreeNode childNode = trans.getChildNode(); - if (childNode != null) { - TreeNodeView childNodeView = new TreeNodeView(childNode); - viewMap.put(childNodeView.getTreeElement(), childNodeView); + LOGGER.debug("Creating new views for tree view."); + createViews(rootNodeView); - childNodeView.setParentView(transView); - transView.setChildView(childNodeView); + selection.newSelection(rootNodeView); + } + + dimension = new Dimension(0, 0); + calcSpan(rootNodeView); + rootNodeView.setSpan(rootNodeView.getSpan() + DIAMETER + BORDER_SPACING); - createViews(childNodeView); + calculateViewLocations(rootNodeView, 0); + dimension.height = (int) rootNodeView.getSpan(); + + redrawTree(graphics2D, rootNodeView); + LOGGER.debug("DrawTree: dimensions - " + dimension.width + "x" + dimension.height); } - } } - } - - public void calculateViewLocations(TreeNodeView nodeView, int depth) { - nodeView.setDepth(depth); - int xLoc = (NODE_GAP_WIDTH + DIAMETER) * depth + DIAMETER; - nodeView.setX(xLoc); - dimension.width = Math.max(dimension.width, xLoc); - TreeTransitionView parentTransView = nodeView.getParentView(); - int yLoc = parentTransView == null ? (int) nodeView.getSpan() / 2 : parentTransView.getEndY(); - nodeView.setY(yLoc); + public void createViews(TreeNodeView nodeView) { + if (nodeView != null) { + viewMap.put(nodeView.getTreeElement(), nodeView); - ArrayList children = nodeView.getChildrenViews(); - switch (children.size()) { - case 0: - break; - case 1: - { - TreeTransitionView childView = children.get(0); + TreeNode node = nodeView.getTreeElement(); + for (TreeTransition trans : node.getChildren()) { + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + if (transView != null) { + nodeView.addChildrenView(transView); + transView.addParentView(nodeView); + break; + } + transView = new TreeTransitionView(trans); - List parentsViews = childView.getParentViews(); - if (parentsViews.size() == 1) { - childView.setEndY(yLoc); + viewMap.put(transView.getTreeElement(), transView); - childView.setDepth(depth); + transView.addParentView(nodeView); + nodeView.addChildrenView(transView); - Point lineStartPoint = childView.getLineStartPoint(0); - lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = yLoc; - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + TreeNode childNode = trans.getChildNode(); + if (childNode != null) { + TreeNodeView childNodeView = new TreeNodeView(childNode); + viewMap.put(childNodeView.getTreeElement(), childNodeView); - dimension.width = Math.max(dimension.width, childView.getEndX()); + childNodeView.setParentView(transView); + transView.setChildView(childNodeView); - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } else { - if (parentsViews.size() > 1 && parentsViews.get(parentsViews.size() - 1) == nodeView) { - int yAvg = 0; - for (int i = 0; i < parentsViews.size(); i++) { - TreeNodeView parentNodeView = parentsViews.get(i); - depth = Math.max(depth, parentNodeView.getDepth()); - yAvg += parentNodeView.getY(); - - Point lineStartPoint = childView.getLineStartPoint(i); - lineStartPoint.x = parentNodeView.getX() + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = parentNodeView.getY(); - } - yAvg /= parentsViews.size(); - childView.setEndY(yAvg); - - childView.setDepth(depth); - - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - - dimension.width = Math.max(dimension.width, childView.getEndX()); - - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } + createViews(childNodeView); + } } - } - break; } - default: - { - int span = 0; - for (TreeTransitionView childView : children) { - span += childView.getSpan(); - } - - span = (int) ((nodeView.getSpan() - span) / 2); - for (int i = 0; i < children.size(); i++) { - TreeTransitionView childView = children.get(i); - - childView.setDepth(depth); - - Point lineStartPoint = childView.getLineStartPoint(0); - lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; - lineStartPoint.y = yLoc; - childView.setEndX((NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); - childView.setEndY( - yLoc - (int) (nodeView.getSpan() / 2) + span + (int) (childView.getSpan() / 2)); - - span += childView.getSpan(); - TreeNodeView childNodeView = childView.getChildView(); - if (childNodeView != null) { - calculateViewLocations(childNodeView, depth + 1); - } - } - break; + } + + public void calculateViewLocations(TreeNodeView nodeView, int depth) { + nodeView.setDepth(depth); + int xLoc = (NODE_GAP_WIDTH + DIAMETER) * depth + DIAMETER; + nodeView.setX(xLoc); + dimension.width = Math.max(dimension.width, xLoc); + + TreeTransitionView parentTransView = nodeView.getParentView(); + int yLoc = + parentTransView == null ? (int) nodeView.getSpan() / 2 : parentTransView.getEndY(); + nodeView.setY(yLoc); + + ArrayList children = nodeView.getChildrenViews(); + switch (children.size()) { + case 0: + break; + case 1: + { + TreeTransitionView childView = children.get(0); + + List parentsViews = childView.getParentViews(); + if (parentsViews.size() == 1) { + childView.setEndY(yLoc); + + childView.setDepth(depth); + + Point lineStartPoint = childView.getLineStartPoint(0); + lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = yLoc; + childView.setEndX( + (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + + dimension.width = Math.max(dimension.width, childView.getEndX()); + + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } + } else { + if (parentsViews.size() > 1 + && parentsViews.get(parentsViews.size() - 1) == nodeView) { + int yAvg = 0; + for (int i = 0; i < parentsViews.size(); i++) { + TreeNodeView parentNodeView = parentsViews.get(i); + depth = Math.max(depth, parentNodeView.getDepth()); + yAvg += parentNodeView.getY(); + + Point lineStartPoint = childView.getLineStartPoint(i); + lineStartPoint.x = parentNodeView.getX() + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = parentNodeView.getY(); + } + yAvg /= parentsViews.size(); + childView.setEndY(yAvg); + + childView.setDepth(depth); + + childView.setEndX( + (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + + RADIUS + - TRANS_GAP / 2); + + dimension.width = Math.max(dimension.width, childView.getEndX()); + + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } + } + } + break; + } + default: + { + int span = 0; + for (TreeTransitionView childView : children) { + span += childView.getSpan(); + } + + span = (int) ((nodeView.getSpan() - span) / 2); + for (int i = 0; i < children.size(); i++) { + TreeTransitionView childView = children.get(i); + + childView.setDepth(depth); + + Point lineStartPoint = childView.getLineStartPoint(0); + lineStartPoint.x = xLoc + RADIUS + TRANS_GAP / 2; + lineStartPoint.y = yLoc; + childView.setEndX( + (NODE_GAP_WIDTH + DIAMETER) * (depth + 1) + RADIUS - TRANS_GAP / 2); + childView.setEndY( + yLoc + - (int) (nodeView.getSpan() / 2) + + span + + (int) (childView.getSpan() / 2)); + + span += childView.getSpan(); + TreeNodeView childNodeView = childView.getChildView(); + if (childNodeView != null) { + calculateViewLocations(childNodeView, depth + 1); + } + } + break; + } } } - } - - public void calcSpan(TreeElementView view) { - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - TreeNode node = nodeView.getTreeElement(); - if (nodeView.getChildrenViews().size() == 0) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - if (nodeView.getChildrenViews().size() == 1) { - TreeTransitionView childView = nodeView.getChildrenViews().get(0); - calcSpan(childView); - if (childView.getParentViews().size() > 1) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - nodeView.setSpan(childView.getSpan()); - } - } else { - DisjointSets branches = node.findMergingBranches(); - List children = node.getChildren(); - if (node == children.get(0).getParents().get(0)) { - reorderBranches(node, branches); - ArrayList newChildrenViews = new ArrayList<>(); - for (TreeTransition trans : node.getChildren()) { - newChildrenViews.add((TreeTransitionView) viewMap.get(trans)); + public void calcSpan(TreeElementView view) { + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + TreeNode node = nodeView.getTreeElement(); + if (nodeView.getChildrenViews().size() == 0) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + if (nodeView.getChildrenViews().size() == 1) { + TreeTransitionView childView = nodeView.getChildrenViews().get(0); + calcSpan(childView); + if (childView.getParentViews().size() > 1) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + nodeView.setSpan(childView.getSpan()); + } + } else { + DisjointSets branches = node.findMergingBranches(); + List children = node.getChildren(); + + if (node == children.get(0).getParents().get(0)) { + reorderBranches(node, branches); + ArrayList newChildrenViews = new ArrayList<>(); + for (TreeTransition trans : node.getChildren()) { + newChildrenViews.add((TreeTransitionView) viewMap.get(trans)); + } + nodeView.setChildrenViews(newChildrenViews); + } + + List> mergingSets = branches.getAllSets(); + + double span = 0.0; + for (Set mergeSet : mergingSets) { + if (mergeSet.size() > 1) { + TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); + TreeTransitionView mergePointView = + (TreeTransitionView) viewMap.get(mergePoint); + double subSpan = 0.0; + for (TreeTransition branch : mergeSet) { + TreeTransitionView branchView = + (TreeTransitionView) viewMap.get(branch); + subCalcSpan(branchView, mergePointView); + subSpan += branchView.getSpan(); + } + calcSpan(mergePointView); + span += Math.max(mergePointView.getSpan(), subSpan); + } else { + TreeTransition trans = mergeSet.iterator().next(); + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + calcSpan(transView); + span += transView.getSpan(); + } + } + nodeView.setSpan(span); + } } - nodeView.setChildrenViews(newChildrenViews); - } - - List> mergingSets = branches.getAllSets(); - - double span = 0.0; - for (Set mergeSet : mergingSets) { - if (mergeSet.size() > 1) { - TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); - TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); - double subSpan = 0.0; - for (TreeTransition branch : mergeSet) { - TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); - subCalcSpan(branchView, mergePointView); - subSpan += branchView.getSpan(); - } - calcSpan(mergePointView); - span += Math.max(mergePointView.getSpan(), subSpan); + } else { + TreeTransitionView transView = (TreeTransitionView) view; + TreeNodeView nodeView = transView.getChildView(); + if (nodeView == null) { + transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); } else { - TreeTransition trans = mergeSet.iterator().next(); - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - calcSpan(transView); - span += transView.getSpan(); + calcSpan(nodeView); + transView.setSpan(nodeView.getSpan()); } - } - nodeView.setSpan(span); } - } - } else { - TreeTransitionView transView = (TreeTransitionView) view; - TreeNodeView nodeView = transView.getChildView(); - if (nodeView == null) { - transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - calcSpan(nodeView); - transView.setSpan(nodeView.getSpan()); - } - } - } - - /** - * Calculates the sub span of a given sub tree rooted at the specified view and stops at the tree - * puzzleElement view specified as stop. Stop tree puzzleElement is NOT included in the span - * calculation - * - * @param view - * @param stop - */ - private void subCalcSpan(TreeElementView view, TreeElementView stop) { - // safe-guard for infinite loop - if (view == stop) { - return; - } - - if (view.getType() == NODE) { - TreeNodeView nodeView = (TreeNodeView) view; - TreeNode node = nodeView.getTreeElement(); - if (nodeView.getChildrenViews().size() == 0) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - if (nodeView.getChildrenViews().size() == 1) { - TreeTransitionView childView = nodeView.getChildrenViews().get(0); - if (childView == stop) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - subCalcSpan(childView, stop); - if (childView.getParentViews().size() > 1) { - nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } + + /** + * Calculates the sub span of a given sub tree rooted at the specified view and stops at the + * tree puzzleElement view specified as stop. Stop tree puzzleElement is NOT included in the + * span calculation + * + * @param view + * @param stop + */ + private void subCalcSpan(TreeElementView view, TreeElementView stop) { + // safe-guard for infinite loop + if (view == stop) { + return; + } + + if (view.getType() == NODE) { + TreeNodeView nodeView = (TreeNodeView) view; + TreeNode node = nodeView.getTreeElement(); + if (nodeView.getChildrenViews().size() == 0) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); } else { - nodeView.setSpan(childView.getSpan()); + if (nodeView.getChildrenViews().size() == 1) { + TreeTransitionView childView = nodeView.getChildrenViews().get(0); + if (childView == stop) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + subCalcSpan(childView, stop); + if (childView.getParentViews().size() > 1) { + nodeView.setSpan(DIAMETER + NODE_GAP_HEIGHT); + } else { + nodeView.setSpan(childView.getSpan()); + } + } + } else { + DisjointSets branches = node.findMergingBranches(); + List children = node.getChildren(); + + if (node == children.get(0).getParents().get(0)) { + reorderBranches(node, branches); + } + + List> mergingSets = branches.getAllSets(); + + double span = 0.0; + for (Set mergeSet : mergingSets) { + if (mergeSet.size() > 1) { + TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); + TreeTransitionView mergePointView = + (TreeTransitionView) viewMap.get(mergePoint); + double subSpan = 0.0; + for (TreeTransition branch : mergeSet) { + TreeTransitionView branchView = + (TreeTransitionView) viewMap.get(branch); + subCalcSpan(branchView, mergePointView); + subSpan += branchView.getSpan(); + } + subCalcSpan(mergePointView, stop); + span += Math.max(mergePointView.getSpan(), subSpan); + } else { + TreeTransition trans = mergeSet.iterator().next(); + TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); + subCalcSpan(transView, stop); + span += transView.getSpan(); + } + } + + nodeView.setSpan(span); + } } - } } else { - DisjointSets branches = node.findMergingBranches(); - List children = node.getChildren(); - - if (node == children.get(0).getParents().get(0)) { - reorderBranches(node, branches); - } - - List> mergingSets = branches.getAllSets(); - - double span = 0.0; - for (Set mergeSet : mergingSets) { - if (mergeSet.size() > 1) { - TreeTransition mergePoint = TreeNode.findMergingPoint(mergeSet); - TreeTransitionView mergePointView = (TreeTransitionView) viewMap.get(mergePoint); - double subSpan = 0.0; - for (TreeTransition branch : mergeSet) { - TreeTransitionView branchView = (TreeTransitionView) viewMap.get(branch); - subCalcSpan(branchView, mergePointView); - subSpan += branchView.getSpan(); - } - subCalcSpan(mergePointView, stop); - span += Math.max(mergePointView.getSpan(), subSpan); + TreeTransitionView transView = (TreeTransitionView) view; + TreeNodeView nodeView = transView.getChildView(); + if (nodeView == null || nodeView == stop) { + transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); } else { - TreeTransition trans = mergeSet.iterator().next(); - TreeTransitionView transView = (TreeTransitionView) viewMap.get(trans); - subCalcSpan(transView, stop); - span += transView.getSpan(); + calcSpan(nodeView); + transView.setSpan(nodeView.getSpan()); } - } + } + } - nodeView.setSpan(span); + /** + * Reorders branches such that merging branches are sequentially grouped together and + * transitions are kept in relative order in the list of child transitions of the specified node + * + * @param node root node of the branches + * @param branches DisjointSets of the child branches of the specified node which determine + * which branches merge + */ + private void reorderBranches(TreeNode node, DisjointSets branches) { + List children = node.getChildren(); + List> mergingSets = branches.getAllSets(); + + List> newOrder = new ArrayList<>(); + for (Set set : mergingSets) { + List mergeBranch = new ArrayList<>(); + newOrder.add(mergeBranch); + children.forEach( + t -> { + if (set.contains(t)) { + mergeBranch.add(t); + } + }); + mergeBranch.sort( + (TreeTransition t1, TreeTransition t2) -> + children.indexOf(t1) <= children.indexOf(t2) ? -1 : 1); } - } - } else { - TreeTransitionView transView = (TreeTransitionView) view; - TreeNodeView nodeView = transView.getChildView(); - if (nodeView == null || nodeView == stop) { - transView.setSpan(DIAMETER + NODE_GAP_HEIGHT); - } else { - calcSpan(nodeView); - transView.setSpan(nodeView.getSpan()); - } - } - } - - /** - * Reorders branches such that merging branches are sequentially grouped together and transitions - * are kept in relative order in the list of child transitions of the specified node - * - * @param node root node of the branches - * @param branches DisjointSets of the child branches of the specified node which determine which - * branches merge - */ - private void reorderBranches(TreeNode node, DisjointSets branches) { - List children = node.getChildren(); - List> mergingSets = branches.getAllSets(); - - List> newOrder = new ArrayList<>(); - for (Set set : mergingSets) { - List mergeBranch = new ArrayList<>(); - newOrder.add(mergeBranch); - children.forEach( - t -> { - if (set.contains(t)) { - mergeBranch.add(t); - } - }); - mergeBranch.sort( - (TreeTransition t1, TreeTransition t2) -> - children.indexOf(t1) <= children.indexOf(t2) ? -1 : 1); - } - - newOrder.sort( - (List b1, List b2) -> { - int low1 = -1; - int low2 = -1; - for (TreeTransition t1 : b1) { - int curIndex = children.indexOf(t1); - if (low1 == -1 || curIndex < low1) { - low1 = curIndex; - } - } - for (TreeTransition t1 : b2) { - int curIndex = children.indexOf(t1); - if (low1 == -1 || curIndex < low1) { - low1 = curIndex; - } - } - return low1 < low2 ? -1 : 1; - }); - - List newChildren = new ArrayList<>(); - newOrder.forEach(l -> newChildren.addAll(l)); - node.setChildren(newChildren); - } + + newOrder.sort( + (List b1, List b2) -> { + int low1 = -1; + int low2 = -1; + for (TreeTransition t1 : b1) { + int curIndex = children.indexOf(t1); + if (low1 == -1 || curIndex < low1) { + low1 = curIndex; + } + } + for (TreeTransition t1 : b2) { + int curIndex = children.indexOf(t1); + if (low1 == -1 || curIndex < low1) { + low1 = curIndex; + } + } + return low1 < low2 ? -1 : 1; + }); + + List newChildren = new ArrayList<>(); + newOrder.forEach(l -> newChildren.addAll(l)); + node.setChildren(newChildren); + } } diff --git a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java index e8eddaa6c..71a65b49e 100644 --- a/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java +++ b/src/main/java/edu/rpi/legup/ui/proofeditorui/treeview/TreeViewSelection.java @@ -5,160 +5,161 @@ import java.util.List; public class TreeViewSelection { - private ArrayList selectedViews; - private TreeElementView hover; - private Point mousePoint; - - /** TreeViewSelection Constructor creates a tree view selection */ - public TreeViewSelection() { - this.selectedViews = new ArrayList<>(); - this.hover = null; - this.mousePoint = null; - } - - /** - * TreeViewSelection Constructor creates a tree view selection with a selected view - * - * @param view selected view - */ - public TreeViewSelection(TreeElementView view) { - this(); - this.selectedViews.add(view); - } - - /** - * TreeViewSelection Constructor creates a tree view selection with a list of selected views - * - * @param views list of selected views - */ - public TreeViewSelection(List views) { - this(); - this.selectedViews.addAll(views); - } - - /** - * Gets the list of selected tree puzzleElement views - * - * @return list of selected tree puzzleElement views - */ - public List getSelectedViews() { - return selectedViews; - } - - /** - * Gets the first selectedViews in the list of views - * - * @return first selectedViews in the list of views - */ - public TreeElementView getFirstSelection() { - return selectedViews.size() == 0 ? null : selectedViews.get(0); - } - - /** - * Toggles a tree puzzleElement view selectedViews - * - * @param treeElementView a tree puzzleElement view to toggle - */ - public void toggleSelection(TreeElementView treeElementView) { - if (selectedViews.contains(treeElementView)) { - selectedViews.remove(treeElementView); - treeElementView.setSelected(false); - } else { - selectedViews.add(treeElementView); - treeElementView.setSelected(true); + private ArrayList selectedViews; + private TreeElementView hover; + private Point mousePoint; + + /** TreeViewSelection Constructor creates a tree view selection */ + public TreeViewSelection() { + this.selectedViews = new ArrayList<>(); + this.hover = null; + this.mousePoint = null; } - } - - /** - * Adds a tree puzzleElement view selectedViews - * - * @param treeElementView a tree puzzleElement view to add - */ - public void addToSelection(TreeElementView treeElementView) { - if (!selectedViews.contains(treeElementView)) { - selectedViews.add(treeElementView); - treeElementView.setSelected(true); + + /** + * TreeViewSelection Constructor creates a tree view selection with a selected view + * + * @param view selected view + */ + public TreeViewSelection(TreeElementView view) { + this(); + this.selectedViews.add(view); + } + + /** + * TreeViewSelection Constructor creates a tree view selection with a list of selected views + * + * @param views list of selected views + */ + public TreeViewSelection(List views) { + this(); + this.selectedViews.addAll(views); + } + + /** + * Gets the list of selected tree puzzleElement views + * + * @return list of selected tree puzzleElement views + */ + public List getSelectedViews() { + return selectedViews; + } + + /** + * Gets the first selectedViews in the list of views + * + * @return first selectedViews in the list of views + */ + public TreeElementView getFirstSelection() { + return selectedViews.size() == 0 ? null : selectedViews.get(0); + } + + /** + * Toggles a tree puzzleElement view selectedViews + * + * @param treeElementView a tree puzzleElement view to toggle + */ + public void toggleSelection(TreeElementView treeElementView) { + if (selectedViews.contains(treeElementView)) { + selectedViews.remove(treeElementView); + treeElementView.setSelected(false); + } else { + selectedViews.add(treeElementView); + treeElementView.setSelected(true); + } + } + + /** + * Adds a tree puzzleElement view selectedViews + * + * @param treeElementView a tree puzzleElement view to add + */ + public void addToSelection(TreeElementView treeElementView) { + if (!selectedViews.contains(treeElementView)) { + selectedViews.add(treeElementView); + treeElementView.setSelected(true); + } + } + + /** + * Creates a new selectedViews and add the specified tree puzzleElement view + * + * @param treeElementView tree puzzleElement view + */ + public void newSelection(TreeElementView treeElementView) { + clearSelection(); + selectedViews.add(treeElementView); + treeElementView.setSelected(true); + } + + /** Clears all selected views */ + public void clearSelection() { + for (TreeElementView treeElementView : selectedViews) { + treeElementView.setSelected(false); + } + selectedViews.clear(); + } + + /** + * Gets tree puzzleElement view that the mouse is hovering over or null is no such view exists + * + * @return tree puzzleElement view that the mouse is hovering over or null is no such view + * exists + */ + public TreeElementView getHover() { + return hover; + } + + /** + * Clears the previous hover and sets the specified tree puzzleElement view to the new hover + * + * @param newHovered tree puzzleElement view for the new hover + */ + public void newHover(TreeElementView newHovered) { + newHovered.setHover(true); + if (hover != null) { + hover.setHover(false); + } + hover = newHovered; + } + + /** Clears the current hover tree puzzleElement view */ + public void clearHover() { + if (hover != null) { + hover.setHover(false); + hover = null; + } } - } - - /** - * Creates a new selectedViews and add the specified tree puzzleElement view - * - * @param treeElementView tree puzzleElement view - */ - public void newSelection(TreeElementView treeElementView) { - clearSelection(); - selectedViews.add(treeElementView); - treeElementView.setSelected(true); - } - - /** Clears all selected views */ - public void clearSelection() { - for (TreeElementView treeElementView : selectedViews) { - treeElementView.setSelected(false); + + /** + * Gets the current mouse location relative to the tree view + * + * @return the current mouse location relative to the tree view + */ + public Point getMousePoint() { + return mousePoint; } - selectedViews.clear(); - } - - /** - * Gets tree puzzleElement view that the mouse is hovering over or null is no such view exists - * - * @return tree puzzleElement view that the mouse is hovering over or null is no such view exists - */ - public TreeElementView getHover() { - return hover; - } - - /** - * Clears the previous hover and sets the specified tree puzzleElement view to the new hover - * - * @param newHovered tree puzzleElement view for the new hover - */ - public void newHover(TreeElementView newHovered) { - newHovered.setHover(true); - if (hover != null) { - hover.setHover(false); + + /** + * Sets the current mouse location relative to the tree view + * + * @param point the current mouse location relative to the tree view + */ + public void setMousePoint(Point point) { + this.mousePoint = point; } - hover = newHovered; - } - - /** Clears the current hover tree puzzleElement view */ - public void clearHover() { - if (hover != null) { - hover.setHover(false); - hover = null; + + /** + * Copies the TreeViewSelection + * + * @return a copy of this TreeViewSelection + */ + @SuppressWarnings("unchecked") + public TreeViewSelection copy() { + TreeViewSelection cpy = new TreeViewSelection(); + cpy.selectedViews = (ArrayList) selectedViews.clone(); + cpy.hover = hover; + cpy.mousePoint = mousePoint; + return cpy; } - } - - /** - * Gets the current mouse location relative to the tree view - * - * @return the current mouse location relative to the tree view - */ - public Point getMousePoint() { - return mousePoint; - } - - /** - * Sets the current mouse location relative to the tree view - * - * @param point the current mouse location relative to the tree view - */ - public void setMousePoint(Point point) { - this.mousePoint = point; - } - - /** - * Copies the TreeViewSelection - * - * @return a copy of this TreeViewSelection - */ - @SuppressWarnings("unchecked") - public TreeViewSelection copy() { - TreeViewSelection cpy = new TreeViewSelection(); - cpy.selectedViews = (ArrayList) selectedViews.clone(); - cpy.hover = hover; - cpy.mousePoint = mousePoint; - return cpy; - } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java index 4c7098765..552d517b9 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementButton.java @@ -7,31 +7,31 @@ public class ElementButton extends JButton { - private Element element; - private final Border originalBorder; - - ElementButton(Element e) { - super(e.getImageIcon()); - this.element = e; - this.originalBorder = this.getBorder(); - this.setFocusPainted(false); - } - - public Element getElement() { - return element; - } - - public void setElement(Element e) { - this.element = e; - } - - public void setBorderToSelected() { - Border newBorderIn = BorderFactory.createLineBorder(new Color(20, 140, 70), 2, true); - Border newBorder = BorderFactory.createCompoundBorder(newBorderIn, this.originalBorder); - this.setBorder(newBorder); - } - - public void resetBorder() { - this.setBorder(this.originalBorder); - } + private Element element; + private final Border originalBorder; + + ElementButton(Element e) { + super(e.getImageIcon()); + this.element = e; + this.originalBorder = this.getBorder(); + this.setFocusPainted(false); + } + + public Element getElement() { + return element; + } + + public void setElement(Element e) { + this.element = e; + } + + public void setBorderToSelected() { + Border newBorderIn = BorderFactory.createLineBorder(new Color(20, 140, 70), 2, true); + Border newBorder = BorderFactory.createCompoundBorder(newBorderIn, this.originalBorder); + this.setBorder(newBorder); + } + + public void resetBorder() { + this.setBorder(this.originalBorder); + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java index 2a7119abb..e0524f84d 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementFrame.java @@ -8,91 +8,92 @@ import javax.swing.border.TitledBorder; public class ElementFrame extends JPanel { - private static final String checkBox = " \u2714 "; - private static final String xBox = " \u2718 "; - private static final String htmlHead = ""; - private static final String htmlTail = ""; - - private PlaceableElementPanel placeableElementPanel; - private NonPlaceableElementPanel nonPlaceableElementPanel; - private JTabbedPane tabbedPane; - private ButtonGroup buttonGroup; - - private EditorElementController controller; - - public ElementFrame(EditorElementController controller) { - this.controller = controller; - MaterialTabbedPaneUI tabOverride = - new MaterialTabbedPaneUI() { - // this prevents the tabs from moving around when you select them - @Override - protected boolean shouldRotateTabRuns(int i) { - return false; - } - }; - - this.tabbedPane = new JTabbedPane(); - tabbedPane.setUI(tabOverride); - JLabel status = new JLabel("", SwingConstants.CENTER); - this.buttonGroup = new ButtonGroup(); - - nonPlaceableElementPanel = new NonPlaceableElementPanel(this); - // nonPlaceableElementPanel.setMinimumSize(new Dimension(100,200)); - tabbedPane.addTab( - nonPlaceableElementPanel.getName(), - nonPlaceableElementPanel.getIcon(), - new JScrollPane(nonPlaceableElementPanel), - nonPlaceableElementPanel.getToolTip()); - - placeableElementPanel = new PlaceableElementPanel(this); - // placeableElementPanel.setMinimuSize(new Dimension(100,200)); - tabbedPane.addTab( - placeableElementPanel.getName(), - placeableElementPanel.getIcon(), - new JScrollPane(placeableElementPanel), - placeableElementPanel.getToolTip()); - tabbedPane.setTabPlacement(JTabbedPane.TOP); - - setLayout(new BorderLayout()); - setMinimumSize(new Dimension(250, 256)); - setPreferredSize(new Dimension(330, 256)); - - add(tabbedPane); - add(status, BorderLayout.SOUTH); - - TitledBorder title = BorderFactory.createTitledBorder("Elements"); - title.setTitleJustification(TitledBorder.CENTER); - setBorder(title); - } - - public ButtonGroup getButtonGroup() { - return buttonGroup; - } - - public void resetSize() { - int buttonWidth = - ((ElementPanel) tabbedPane.getSelectedComponent()).getElementButtons()[0].getWidth(); - this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); - } - - public void setElements(Puzzle puzzle) { - nonPlaceableElementPanel.setElements(puzzle.getNonPlaceableElements()); - placeableElementPanel.setElements(puzzle.getPlaceableElements()); - } - - public EditorElementController getController() { - return controller; - } - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - public NonPlaceableElementPanel getNonPlaceableElementPanel() { - return nonPlaceableElementPanel; - } - - public PlaceableElementPanel getPlaceableElementPanel() { - return placeableElementPanel; - } + private static final String checkBox = " \u2714 "; + private static final String xBox = " \u2718 "; + private static final String htmlHead = ""; + private static final String htmlTail = ""; + + private PlaceableElementPanel placeableElementPanel; + private NonPlaceableElementPanel nonPlaceableElementPanel; + private JTabbedPane tabbedPane; + private ButtonGroup buttonGroup; + + private EditorElementController controller; + + public ElementFrame(EditorElementController controller) { + this.controller = controller; + MaterialTabbedPaneUI tabOverride = + new MaterialTabbedPaneUI() { + // this prevents the tabs from moving around when you select them + @Override + protected boolean shouldRotateTabRuns(int i) { + return false; + } + }; + + this.tabbedPane = new JTabbedPane(); + tabbedPane.setUI(tabOverride); + JLabel status = new JLabel("", SwingConstants.CENTER); + this.buttonGroup = new ButtonGroup(); + + nonPlaceableElementPanel = new NonPlaceableElementPanel(this); + // nonPlaceableElementPanel.setMinimumSize(new Dimension(100,200)); + tabbedPane.addTab( + nonPlaceableElementPanel.getName(), + nonPlaceableElementPanel.getIcon(), + new JScrollPane(nonPlaceableElementPanel), + nonPlaceableElementPanel.getToolTip()); + + placeableElementPanel = new PlaceableElementPanel(this); + // placeableElementPanel.setMinimuSize(new Dimension(100,200)); + tabbedPane.addTab( + placeableElementPanel.getName(), + placeableElementPanel.getIcon(), + new JScrollPane(placeableElementPanel), + placeableElementPanel.getToolTip()); + tabbedPane.setTabPlacement(JTabbedPane.TOP); + + setLayout(new BorderLayout()); + setMinimumSize(new Dimension(250, 256)); + setPreferredSize(new Dimension(330, 256)); + + add(tabbedPane); + add(status, BorderLayout.SOUTH); + + TitledBorder title = BorderFactory.createTitledBorder("Elements"); + title.setTitleJustification(TitledBorder.CENTER); + setBorder(title); + } + + public ButtonGroup getButtonGroup() { + return buttonGroup; + } + + public void resetSize() { + int buttonWidth = + ((ElementPanel) tabbedPane.getSelectedComponent()) + .getElementButtons()[0].getWidth(); + this.setMinimumSize(new Dimension(2 * buttonWidth + 64, this.getHeight())); + } + + public void setElements(Puzzle puzzle) { + nonPlaceableElementPanel.setElements(puzzle.getNonPlaceableElements()); + placeableElementPanel.setElements(puzzle.getPlaceableElements()); + } + + public EditorElementController getController() { + return controller; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public NonPlaceableElementPanel getNonPlaceableElementPanel() { + return nonPlaceableElementPanel; + } + + public PlaceableElementPanel getPlaceableElementPanel() { + return placeableElementPanel; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java index 725bafe3b..46198e226 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/ElementPanel.java @@ -7,74 +7,75 @@ import javax.swing.*; public abstract class ElementPanel extends JPanel { - protected ImageIcon icon; - protected String name; - protected String toolTip; - protected ElementButton[] elementButtons; - protected ElementFrame elementFrame; - protected List elements; + protected ImageIcon icon; + protected String name; + protected String toolTip; + protected ElementButton[] elementButtons; + protected ElementFrame elementFrame; + protected List elements; - public ElementPanel(ElementFrame eFrame) { - this.elementFrame = eFrame; - this.elements = new ArrayList<>(); - setLayout(new WrapLayout()); - } + public ElementPanel(ElementFrame eFrame) { + this.elementFrame = eFrame; + this.elements = new ArrayList<>(); + setLayout(new WrapLayout()); + } - public void setElements(List elements) { - this.elements = elements; - clearButtons(); + public void setElements(List elements) { + this.elements = elements; + clearButtons(); - elementButtons = new ElementButton[elements.size()]; - System.out.println("adding " + elements.size() + " elements to panel"); - for (int i = 0; i < elements.size(); i++) { - Element element = elements.get(i); - elementButtons[i] = new ElementButton(element); - elementFrame.getButtonGroup().add(elementButtons[i]); - System.out.printf("added button: %d, element %s\n", i, element.getElementName()); + elementButtons = new ElementButton[elements.size()]; + System.out.println("adding " + elements.size() + " elements to panel"); + for (int i = 0; i < elements.size(); i++) { + Element element = elements.get(i); + elementButtons[i] = new ElementButton(element); + elementFrame.getButtonGroup().add(elementButtons[i]); + System.out.printf("added button: %d, element %s\n", i, element.getElementName()); - elementButtons[i].setToolTipText(element.getElementName() + ": " + element.getDescription()); - elementButtons[i].addActionListener(elementFrame.getController()); - add(elementButtons[i]); + elementButtons[i].setToolTipText( + element.getElementName() + ": " + element.getDescription()); + elementButtons[i].addActionListener(elementFrame.getController()); + add(elementButtons[i]); + } + revalidate(); } - revalidate(); - } - protected void clearButtons() { - if (elementButtons != null) { - removeAll(); - for (int x = 0; x < elementButtons.length; ++x) { - elementButtons[x].removeActionListener(elementFrame.getController()); - } + protected void clearButtons() { + if (elementButtons != null) { + removeAll(); + for (int x = 0; x < elementButtons.length; ++x) { + elementButtons[x].removeActionListener(elementFrame.getController()); + } + } } - } - public ElementButton[] getElementButtons() { - return elementButtons; - } + public ElementButton[] getElementButtons() { + return elementButtons; + } - public ImageIcon getIcon() { - return icon; - } + public ImageIcon getIcon() { + return icon; + } - public void setIcon(ImageIcon icon) { - this.icon = icon; - } + public void setIcon(ImageIcon icon) { + this.icon = icon; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public void setName(String name) { - this.name = name; - } + @Override + public void setName(String name) { + this.name = name; + } - public String getToolTip() { - return toolTip; - } + public String getToolTip() { + return toolTip; + } - public void setToolTip(String toolTip) { - this.toolTip = toolTip; - } + public void setToolTip(String toolTip) { + this.toolTip = toolTip; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java index b6d447c8f..00b4f5379 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/NonPlaceableElementPanel.java @@ -3,13 +3,13 @@ import javax.swing.*; public class NonPlaceableElementPanel extends ElementPanel { - public NonPlaceableElementPanel(ElementFrame elementFrame) { - super(elementFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Non-Placeable Elements"; - this.toolTip = "Non-Placeable Elements"; - } + public NonPlaceableElementPanel(ElementFrame elementFrame) { + super(elementFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Non-Placeable Elements"; + this.toolTip = "Non-Placeable Elements"; + } } diff --git a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java index 2d9a09962..088e18f8c 100644 --- a/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java +++ b/src/main/java/edu/rpi/legup/ui/puzzleeditorui/elementsview/PlaceableElementPanel.java @@ -3,13 +3,13 @@ import javax.swing.*; public class PlaceableElementPanel extends ElementPanel { - public PlaceableElementPanel(ElementFrame elementFrame) { - super(elementFrame); - this.icon = - new ImageIcon( - ClassLoader.getSystemClassLoader() - .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); - this.name = "Placeable Elements"; - this.toolTip = "Placeable Elements"; - } + public PlaceableElementPanel(ElementFrame elementFrame) { + super(elementFrame); + this.icon = + new ImageIcon( + ClassLoader.getSystemClassLoader() + .getResource("edu/rpi/legup/images/Legup/Direct Rules.gif")); + this.name = "Placeable Elements"; + this.toolTip = "Placeable Elements"; + } } diff --git a/src/main/java/edu/rpi/legup/user/Submission.java b/src/main/java/edu/rpi/legup/user/Submission.java index 2fe174946..42373d2ec 100644 --- a/src/main/java/edu/rpi/legup/user/Submission.java +++ b/src/main/java/edu/rpi/legup/user/Submission.java @@ -3,7 +3,7 @@ import edu.rpi.legup.model.gameboard.Board; public class Submission { - public Submission(Board board) {} + public Submission(Board board) {} - public void submit() {} + public void submit() {} } diff --git a/src/main/java/edu/rpi/legup/user/UsageStatistics.java b/src/main/java/edu/rpi/legup/user/UsageStatistics.java index 80867e445..0bc5d1c62 100644 --- a/src/main/java/edu/rpi/legup/user/UsageStatistics.java +++ b/src/main/java/edu/rpi/legup/user/UsageStatistics.java @@ -11,43 +11,43 @@ public class UsageStatistics { - private static final String url = "https://legup-3b4a5.firebaseio.com/databases/test.json"; + private static final String url = "https://legup-3b4a5.firebaseio.com/databases/test.json"; - public UsageStatistics() {} - - public boolean sendErrorReport() { - try { - HttpClient httpclient = new DefaultHttpClient(); - - HttpPost httppost = new HttpPost(url); - - // Request parameters and other properties. - httppost.setEntity(new StringEntity("{\"test\": \"jeff\"}")); - // List params = new ArrayList<>(2); - // params.add(new BasicNameValuePair("param-1", "12345")); - // params.add(new BasicNameValuePair("param-2", "Hello!")); - // httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); - - // Execute and get the response. - HttpResponse response = httpclient.execute(httppost); - HttpEntity entity = response.getEntity(); - - if (entity != null) { - InputStream instream = entity.getContent(); + public UsageStatistics() {} + public boolean sendErrorReport() { try { - // System.err.println(new String(instream.readAllBytes())); - } finally { - instream.close(); + HttpClient httpclient = new DefaultHttpClient(); + + HttpPost httppost = new HttpPost(url); + + // Request parameters and other properties. + httppost.setEntity(new StringEntity("{\"test\": \"jeff\"}")); + // List params = new ArrayList<>(2); + // params.add(new BasicNameValuePair("param-1", "12345")); + // params.add(new BasicNameValuePair("param-2", "Hello!")); + // httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); + + // Execute and get the response. + HttpResponse response = httpclient.execute(httppost); + HttpEntity entity = response.getEntity(); + + if (entity != null) { + InputStream instream = entity.getContent(); + + try { + // System.err.println(new String(instream.readAllBytes())); + } finally { + instream.close(); + } + } + } catch (IOException e) { + return false; } - } - } catch (IOException e) { - return false; + return false; } - return false; - } - public static void main(String[] args) { - new UsageStatistics().sendErrorReport(); - } + public static void main(String[] args) { + new UsageStatistics().sendErrorReport(); + } } diff --git a/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java b/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java index c52264674..14b68ba40 100644 --- a/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java +++ b/src/main/java/edu/rpi/legup/utility/ConnectedRegions.java @@ -7,66 +7,72 @@ import java.util.Set; public final class ConnectedRegions { - public static List> getConnectedRegions( - int boundaryCell, int[][] cells, int width, int height) { - Set boundaryCells = new HashSet<>(); - boundaryCells.add(boundaryCell); - return getConnectedRegions(boundaryCells, cells, width, height); - } + public static List> getConnectedRegions( + int boundaryCell, int[][] cells, int width, int height) { + Set boundaryCells = new HashSet<>(); + boundaryCells.add(boundaryCell); + return getConnectedRegions(boundaryCells, cells, width, height); + } - public static List> getConnectedRegions( - Set boundaryCells, int[][] cells, int width, int height) { - boolean[][] visited = new boolean[height][width]; - List> results = new ArrayList<>(); - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - Set region = floodfill(boundaryCells, cells, visited, width, height, x, y); - if (region.size() > 0) { - results.add(region); + public static List> getConnectedRegions( + Set boundaryCells, int[][] cells, int width, int height) { + boolean[][] visited = new boolean[height][width]; + List> results = new ArrayList<>(); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + Set region = floodfill(boundaryCells, cells, visited, width, height, x, y); + if (region.size() > 0) { + results.add(region); + } + } } - } + return results; } - return results; - } - public static boolean regionContains(int toFind, int[][] cells, Set region) { - for (Point p : region) { - if (cells[p.y][p.x] == toFind) { - return true; - } + public static boolean regionContains(int toFind, int[][] cells, Set region) { + for (Point p : region) { + if (cells[p.y][p.x] == toFind) { + return true; + } + } + return false; } - return false; - } - - public static Set getRegionAroundPoint( - Point p, int boundaryCell, int[][] cells, int width, int height) { - Set boundaryCells = new HashSet<>(); - boundaryCells.add(boundaryCell); - return getRegionAroundPoint(p, boundaryCells, cells, width, height); - } - public static Set getRegionAroundPoint( - Point p, Set boundaryCells, int[][] cells, int width, int height) { - return floodfill(boundaryCells, cells, new boolean[height][width], width, height, p.x, p.y); - } - - private static Set floodfill( - Set boundaryCells, int[][] cells, boolean[][] visited, int w, int h, int x, int y) { - HashSet result = new HashSet<>(); - if ((x < 0) || (x >= w)) { - return result; + public static Set getRegionAroundPoint( + Point p, int boundaryCell, int[][] cells, int width, int height) { + Set boundaryCells = new HashSet<>(); + boundaryCells.add(boundaryCell); + return getRegionAroundPoint(p, boundaryCells, cells, width, height); } - if ((y < 0) || (y >= h)) { - return result; + + public static Set getRegionAroundPoint( + Point p, Set boundaryCells, int[][] cells, int width, int height) { + return floodfill(boundaryCells, cells, new boolean[height][width], width, height, p.x, p.y); } - if (!visited[y][x] && (!boundaryCells.contains(cells[y][x]))) { - result.add(new Point(x, y)); - visited[y][x] = true; - for (int delta = -1; delta < 2; delta += 2) { - result.addAll(floodfill(boundaryCells, cells, visited, w, h, x + delta, y)); - result.addAll(floodfill(boundaryCells, cells, visited, w, h, x, y + delta)); - } + + private static Set floodfill( + Set boundaryCells, + int[][] cells, + boolean[][] visited, + int w, + int h, + int x, + int y) { + HashSet result = new HashSet<>(); + if ((x < 0) || (x >= w)) { + return result; + } + if ((y < 0) || (y >= h)) { + return result; + } + if (!visited[y][x] && (!boundaryCells.contains(cells[y][x]))) { + result.add(new Point(x, y)); + visited[y][x] = true; + for (int delta = -1; delta < 2; delta += 2) { + result.addAll(floodfill(boundaryCells, cells, visited, w, h, x + delta, y)); + result.addAll(floodfill(boundaryCells, cells, visited, w, h, x, y + delta)); + } + } + return result; } - return result; - } } diff --git a/src/main/java/edu/rpi/legup/utility/DisjointSets.java b/src/main/java/edu/rpi/legup/utility/DisjointSets.java index da2dcb408..f33b8993c 100644 --- a/src/main/java/edu/rpi/legup/utility/DisjointSets.java +++ b/src/main/java/edu/rpi/legup/utility/DisjointSets.java @@ -3,164 +3,164 @@ import java.util.*; public class DisjointSets { - private Map parents; - private Map depths; - private Map> sets; + private Map parents; + private Map depths; + private Map> sets; - /** DisjointSets Constructor creates an empty DisjointSets */ - public DisjointSets() { - this.parents = new HashMap<>(); - this.depths = new HashMap<>(); - this.sets = new HashMap<>(); - } + /** DisjointSets Constructor creates an empty DisjointSets */ + public DisjointSets() { + this.parents = new HashMap<>(); + this.depths = new HashMap<>(); + this.sets = new HashMap<>(); + } - /** - * Creates a unique set that contains the specified puzzleElement. If the specified puzzleElement - * is null or another set already contains that puzzleElement, this method returns false, - * indicating that a set was not created - * - * @param u puzzleElement to create the set from - * @return true if the set was created, false otherwise - */ - public boolean createSet(T u) { - if (u == null || parents.containsKey(u)) { - return false; - } else { - parents.put(u, u); - depths.put(u, 0); - Set newSet = new HashSet<>(); - newSet.add(u); - sets.put(u, newSet); - return true; + /** + * Creates a unique set that contains the specified puzzleElement. If the specified + * puzzleElement is null or another set already contains that puzzleElement, this method returns + * false, indicating that a set was not created + * + * @param u puzzleElement to create the set from + * @return true if the set was created, false otherwise + */ + public boolean createSet(T u) { + if (u == null || parents.containsKey(u)) { + return false; + } else { + parents.put(u, u); + depths.put(u, 0); + Set newSet = new HashSet<>(); + newSet.add(u); + sets.put(u, newSet); + return true; + } } - } - /** - * Finds and returns the representative set puzzleElement of the set that the specified - * puzzleElement contains - * - * @param p puzzleElement of the set of which to find - * @return representative set puzzleElement or null if the specified puzzleElement is null or is - * not in the DisjointSets - */ - public T find(T p) { - if (p == null || parents.get(p) == null) { - return null; - } else { - if (p != parents.get(p)) { - parents.put(p, find(parents.get(p))); - } + /** + * Finds and returns the representative set puzzleElement of the set that the specified + * puzzleElement contains + * + * @param p puzzleElement of the set of which to find + * @return representative set puzzleElement or null if the specified puzzleElement is null or is + * not in the DisjointSets + */ + public T find(T p) { + if (p == null || parents.get(p) == null) { + return null; + } else { + if (p != parents.get(p)) { + parents.put(p, find(parents.get(p))); + } + } + return parents.get(p); } - return parents.get(p); - } - /** - * Unions two sets together. If the set are non-null and disjoint, then it returns true, false - * otherwise - * - * @param p set one - * @param q set two - * @return returns true if sets are non-null and disjoint, false otherwise - */ - public boolean union(T p, T q) { - T pid = find(p); - T qid = find(q); - if (pid == null || qid == null || pid == qid) { - return false; - } else { - if (depths.get(pid) > depths.get(qid)) { - parents.put(qid, pid); - sets.get(pid).addAll(sets.get(qid)); - sets.remove(qid); - } else { - parents.put(pid, qid); - sets.get(qid).addAll(sets.get(pid)); - sets.remove(pid); - if (depths.get(pid) == depths.get(qid)) { - depths.put(qid, depths.get(qid) + 1); + /** + * Unions two sets together. If the set are non-null and disjoint, then it returns true, false + * otherwise + * + * @param p set one + * @param q set two + * @return returns true if sets are non-null and disjoint, false otherwise + */ + public boolean union(T p, T q) { + T pid = find(p); + T qid = find(q); + if (pid == null || qid == null || pid == qid) { + return false; + } else { + if (depths.get(pid) > depths.get(qid)) { + parents.put(qid, pid); + sets.get(pid).addAll(sets.get(qid)); + sets.remove(qid); + } else { + parents.put(pid, qid); + sets.get(qid).addAll(sets.get(pid)); + sets.remove(pid); + if (depths.get(pid) == depths.get(qid)) { + depths.put(qid, depths.get(qid) + 1); + } + } + return true; } - } - return true; } - } - /** - * Unions to elements together, if either puzzleElement is not already in the DisjointSets, it - * creates a set for the puzzleElement then unions the sets together. If either puzzleElement is - * null, no action is taken. - * - * @param p puzzleElement one - * @param q puzzleElement two - */ - public void addAndUnion(T p, T q) { - if (p != null && q != null) { - T pid = find(p); - if (pid == null) { - createSet(p); - } - T qid = find(q); - if (qid == null) { - createSet(q); - } - union(p, q); + /** + * Unions to elements together, if either puzzleElement is not already in the DisjointSets, it + * creates a set for the puzzleElement then unions the sets together. If either puzzleElement is + * null, no action is taken. + * + * @param p puzzleElement one + * @param q puzzleElement two + */ + public void addAndUnion(T p, T q) { + if (p != null && q != null) { + T pid = find(p); + if (pid == null) { + createSet(p); + } + T qid = find(q); + if (qid == null) { + createSet(q); + } + union(p, q); + } } - } - /** - * Determines whether the specified puzzleElement is in the DisjointSets - * - * @param u puzzleElement to check - * @return true if the DisjointSets contains the specified puzzleElement, false otherwise - */ - public boolean contains(T u) { - return parents.containsKey(u); - } + /** + * Determines whether the specified puzzleElement is in the DisjointSets + * + * @param u puzzleElement to check + * @return true if the DisjointSets contains the specified puzzleElement, false otherwise + */ + public boolean contains(T u) { + return parents.containsKey(u); + } - /** - * Gets the set of elements that the specified puzzleElement is contained in, or null if no such - * set exists. - * - * @param p puzzleElement to get the set of - * @return the set of elements that the specified puzzleElement if contained in, or null if no - * such set exists - */ - public Set getSet(T p) { - T pid = find(p); - if (pid != null) { - return new HashSet<>(sets.get(pid)); - } else { - return null; + /** + * Gets the set of elements that the specified puzzleElement is contained in, or null if no such + * set exists. + * + * @param p puzzleElement to get the set of + * @return the set of elements that the specified puzzleElement if contained in, or null if no + * such set exists + */ + public Set getSet(T p) { + T pid = find(p); + if (pid != null) { + return new HashSet<>(sets.get(pid)); + } else { + return null; + } } - } - /** - * Gets a list of all of the sets in the DisjointSets - * - * @return list of the sets in the DisjointSets - */ - public List> getAllSets() { - ArrayList> list = new ArrayList<>(); - for (T e : sets.keySet()) { - list.add(new HashSet<>(sets.get(e))); + /** + * Gets a list of all of the sets in the DisjointSets + * + * @return list of the sets in the DisjointSets + */ + public List> getAllSets() { + ArrayList> list = new ArrayList<>(); + for (T e : sets.keySet()) { + list.add(new HashSet<>(sets.get(e))); + } + return list; } - return list; - } - /** - * Gets the number of disjoint sets - * - * @return the number of disjoint sets - */ - public int setCount() { - return sets.size(); - } + /** + * Gets the number of disjoint sets + * + * @return the number of disjoint sets + */ + public int setCount() { + return sets.size(); + } - /** - * Gets the total number of elements among all sets in the DisjointSets - * - * @return the number of elements in the DisjointSets - */ - public int size() { - return parents.size(); - } + /** + * Gets the total number of elements among all sets in the DisjointSets + * + * @return the number of elements in the DisjointSets + */ + public int size() { + return parents.size(); + } } diff --git a/src/main/java/edu/rpi/legup/utility/Entry.java b/src/main/java/edu/rpi/legup/utility/Entry.java index 9cff78750..0686f0dbf 100644 --- a/src/main/java/edu/rpi/legup/utility/Entry.java +++ b/src/main/java/edu/rpi/legup/utility/Entry.java @@ -1,53 +1,53 @@ package edu.rpi.legup.utility; public class Entry { - private K key; - private V value; + private K key; + private V value; - /** - * Entry Constructor creates a key value pair - * - * @param key key - * @param value value - */ - public Entry(K key, V value) { - this.key = key; - this.value = value; - } + /** + * Entry Constructor creates a key value pair + * + * @param key key + * @param value value + */ + public Entry(K key, V value) { + this.key = key; + this.value = value; + } - /** - * Gets the key - * - * @return key - */ - public K getKey() { - return key; - } + /** + * Gets the key + * + * @return key + */ + public K getKey() { + return key; + } - /** - * Sets the key - * - * @param key key - */ - public void setKey(K key) { - this.key = key; - } + /** + * Sets the key + * + * @param key key + */ + public void setKey(K key) { + this.key = key; + } - /** - * Gets the value - * - * @return value - */ - public V getValue() { - return value; - } + /** + * Gets the value + * + * @return value + */ + public V getValue() { + return value; + } - /** - * Set the value - * - * @param value value - */ - public void setValue(V value) { - this.value = value; - } + /** + * Set the value + * + * @param value value + */ + public void setValue(V value) { + this.value = value; + } } diff --git a/src/main/java/edu/rpi/legup/utility/LegupUtils.java b/src/main/java/edu/rpi/legup/utility/LegupUtils.java index cde415f6a..94f119a5e 100644 --- a/src/main/java/edu/rpi/legup/utility/LegupUtils.java +++ b/src/main/java/edu/rpi/legup/utility/LegupUtils.java @@ -14,85 +14,91 @@ public class LegupUtils { - private static final Logger LOGGER = Logger.getLogger(LegupUtils.class.getName()); + private static final Logger LOGGER = Logger.getLogger(LegupUtils.class.getName()); - /** - * Scans all classes accessible from the context class loader which belong to the given package - * and subpackages. - * - * @param packageName The base package - * @return The classes - * @throws ClassNotFoundException if class is not in package - * @throws IOException if file is not found - */ - public static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - assert classLoader != null; - String path = packageName.replace('.', '/'); + /** + * Scans all classes accessible from the context class loader which belong to the given package + * and subpackages. + * + * @param packageName The base package + * @return The classes + * @throws ClassNotFoundException if class is not in package + * @throws IOException if file is not found + */ + public static Class[] getClasses(String packageName) + throws ClassNotFoundException, IOException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + assert classLoader != null; + String path = packageName.replace('.', '/'); - URL url = LegupUtils.class.getProtectionDomain().getCodeSource().getLocation(); - String jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); - if (jarPath.contains(".jar")) { - List css = findClassesZip(jarPath, path); - return css.toArray(new Class[css.size()]); - } + URL url = LegupUtils.class.getProtectionDomain().getCodeSource().getLocation(); + String jarPath = URLDecoder.decode(url.getFile(), "UTF-8"); + if (jarPath.contains(".jar")) { + List css = findClassesZip(jarPath, path); + return css.toArray(new Class[css.size()]); + } - Enumeration resources = classLoader.getResources(path); - List dirs = new ArrayList<>(); - while (resources.hasMoreElements()) { - URL resource = resources.nextElement(); - dirs.add(new File(resource.getFile())); - } + Enumeration resources = classLoader.getResources(path); + List dirs = new ArrayList<>(); + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + dirs.add(new File(resource.getFile())); + } - ArrayList classes = new ArrayList<>(); - for (File directory : dirs) { - classes.addAll(findClasses(directory, packageName)); + ArrayList classes = new ArrayList<>(); + for (File directory : dirs) { + classes.addAll(findClasses(directory, packageName)); + } + return classes.toArray(new Class[classes.size()]); } - return classes.toArray(new Class[classes.size()]); - } - /** - * Recursive method used to find all classes in a given directory and subdirs. - * - * @param directory The base directory - * @param packageName The package name for classes found inside the base directory - * @return The classes - * @throws ClassNotFoundException - */ - private static List findClasses(File directory, String packageName) - throws ClassNotFoundException { - List classes = new ArrayList<>(); - if (!directory.exists()) { - return classes; - } - File[] files = directory.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - assert !file.getName().contains("."); - classes.addAll(findClasses(file, packageName + "." + file.getName())); - } else { - if (file.getName().endsWith(".class")) { - classes.add( - Class.forName( - packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); + /** + * Recursive method used to find all classes in a given directory and subdirs. + * + * @param directory The base directory + * @param packageName The package name for classes found inside the base directory + * @return The classes + * @throws ClassNotFoundException + */ + private static List findClasses(File directory, String packageName) + throws ClassNotFoundException { + List classes = new ArrayList<>(); + if (!directory.exists()) { + return classes; } - } + File[] files = directory.listFiles(); + for (File file : files) { + if (file.isDirectory()) { + assert !file.getName().contains("."); + classes.addAll(findClasses(file, packageName + "." + file.getName())); + } else { + if (file.getName().endsWith(".class")) { + classes.add( + Class.forName( + packageName + + '.' + + file.getName() + .substring(0, file.getName().length() - 6))); + } + } + } + return classes; } - return classes; - } - private static List findClassesZip(String path, String packageName) - throws IOException, ClassNotFoundException { - List classes = new ArrayList<>(); - ZipInputStream zip = new ZipInputStream(new FileInputStream(path)); - for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { - if (!entry.isDirectory() - && entry.getName().endsWith(".class") - && entry.getName().startsWith(packageName)) { - String className = entry.getName().replace('/', '.'); - classes.add(Class.forName(className.substring(0, className.length() - ".class".length()))); - } + private static List findClassesZip(String path, String packageName) + throws IOException, ClassNotFoundException { + List classes = new ArrayList<>(); + ZipInputStream zip = new ZipInputStream(new FileInputStream(path)); + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + if (!entry.isDirectory() + && entry.getName().endsWith(".class") + && entry.getName().startsWith(packageName)) { + String className = entry.getName().replace('/', '.'); + classes.add( + Class.forName( + className.substring(0, className.length() - ".class".length()))); + } + } + return classes; } - return classes; - } } diff --git a/src/main/java/edu/rpi/legup/utility/Logger.java b/src/main/java/edu/rpi/legup/utility/Logger.java index d423043e7..67048e5b4 100644 --- a/src/main/java/edu/rpi/legup/utility/Logger.java +++ b/src/main/java/edu/rpi/legup/utility/Logger.java @@ -12,33 +12,35 @@ public class Logger { - private static final String LEGUP_HOME = - System.getProperty("user.home") + File.separator + ".legup" + File.separator; + private static final String LEGUP_HOME = + System.getProperty("user.home") + File.separator + ".legup" + File.separator; - public static void initLogger() { - LoggerContext context = (LoggerContext) LogManager.getContext(false); - Configuration config = context.getConfiguration(); - ConsoleAppender consoleAppender = config.getAppender("console"); - PatternLayout consolePattern = (PatternLayout) consoleAppender.getLayout(); - TimeBasedTriggeringPolicy triggeringPolicy = - TimeBasedTriggeringPolicy.newBuilder().withInterval(1).withModulate(true).build(); - PatternLayout patternLayout = - PatternLayout.newBuilder().withPattern(consolePattern.getConversionPattern()).build(); - RollingFileAppender rollingFileAppender = - RollingFileAppender.newBuilder() - .setName("fileLogger") - .withFileName(LEGUP_HOME + "legup.log") - .withFilePattern(LEGUP_HOME + "legup-%d{yyyy-MM-dd}.log.gz") - .withPolicy(triggeringPolicy) - .setLayout(patternLayout) - .setConfiguration(config) - .build(); - rollingFileAppender.start(); - config.addAppender(rollingFileAppender); - LoggerConfig rootLogger = config.getRootLogger(); - rootLogger.addAppender(config.getAppender("fileLogger"), null, null); - context.updateLoggers(); + public static void initLogger() { + LoggerContext context = (LoggerContext) LogManager.getContext(false); + Configuration config = context.getConfiguration(); + ConsoleAppender consoleAppender = config.getAppender("console"); + PatternLayout consolePattern = (PatternLayout) consoleAppender.getLayout(); + TimeBasedTriggeringPolicy triggeringPolicy = + TimeBasedTriggeringPolicy.newBuilder().withInterval(1).withModulate(true).build(); + PatternLayout patternLayout = + PatternLayout.newBuilder() + .withPattern(consolePattern.getConversionPattern()) + .build(); + RollingFileAppender rollingFileAppender = + RollingFileAppender.newBuilder() + .setName("fileLogger") + .withFileName(LEGUP_HOME + "legup.log") + .withFilePattern(LEGUP_HOME + "legup-%d{yyyy-MM-dd}.log.gz") + .withPolicy(triggeringPolicy) + .setLayout(patternLayout) + .setConfiguration(config) + .build(); + rollingFileAppender.start(); + config.addAppender(rollingFileAppender); + LoggerConfig rootLogger = config.getRootLogger(); + rootLogger.addAppender(config.getAppender("fileLogger"), null, null); + context.updateLoggers(); - System.setProperty("sun.java2d.noddraw", Boolean.TRUE.toString()); - } + System.setProperty("sun.java2d.noddraw", Boolean.TRUE.toString()); + } } diff --git a/src/test/java/legup/MockGameBoardFacade.java b/src/test/java/legup/MockGameBoardFacade.java index a1505455c..f4f1db938 100644 --- a/src/test/java/legup/MockGameBoardFacade.java +++ b/src/test/java/legup/MockGameBoardFacade.java @@ -6,37 +6,37 @@ import edu.rpi.legup.model.Puzzle; public class MockGameBoardFacade extends GameBoardFacade { - protected MockGameBoardFacade() { - super(); - Config config = null; - try { - config = new Config(); - } catch (InvalidConfigException e) { - System.exit(1); + protected MockGameBoardFacade() { + super(); + Config config = null; + try { + config = new Config(); + } catch (InvalidConfigException e) { + System.exit(1); + } + setConfig(config); } - setConfig(config); - } - /** - * Gets the singleton instance of GameBoardFacade - * - * @return single instance of GameBoardFacade - */ - public static synchronized GameBoardFacade getInstance() { - if (instance == null) { - instance = new MockGameBoardFacade(); + /** + * Gets the singleton instance of GameBoardFacade + * + * @return single instance of GameBoardFacade + */ + public static synchronized GameBoardFacade getInstance() { + if (instance == null) { + instance = new MockGameBoardFacade(); + } + return instance; } - return instance; - } - @Override - public void initializeUI() {} + @Override + public void initializeUI() {} - @Override - public void setPuzzle(Puzzle puzzle) { - this.puzzle = puzzle; - } + @Override + public void setPuzzle(Puzzle puzzle) { + this.puzzle = puzzle; + } - @Override - public void setWindowTitle(String puzzleName, String fileName) {} + @Override + public void setWindowTitle(String puzzleName, String fileName) {} } diff --git a/src/test/java/legup/TestRunner.java b/src/test/java/legup/TestRunner.java index c8c43bcda..40cc5fa6c 100644 --- a/src/test/java/legup/TestRunner.java +++ b/src/test/java/legup/TestRunner.java @@ -11,96 +11,96 @@ /** This class runs all of the tests for the project without needing to run build scripts. */ public class TestRunner { - public static void main(String[] args) { - // Battleship Tests - Result result1 = JUnitCore.runClasses(AdjacentShipsContradictionRuleTest.class); - printTestResults(result1); - Result result2 = JUnitCore.runClasses(FinishWithShipsDirectRuleTests.class); - printTestResults(result2); + public static void main(String[] args) { + // Battleship Tests + Result result1 = JUnitCore.runClasses(AdjacentShipsContradictionRuleTest.class); + printTestResults(result1); + Result result2 = JUnitCore.runClasses(FinishWithShipsDirectRuleTests.class); + printTestResults(result2); - // Lightup Tests - Result result3 = JUnitCore.runClasses(BulbsInPathContradictionRuleTest.class); - printTestResults(result3); - Result result4 = JUnitCore.runClasses(CannotLightACellContradictionRuleTest.class); - printTestResults(result4); - Result result5 = JUnitCore.runClasses(EmptyCellinLightDirectRuleTest.class); - printTestResults(result5); - Result result6 = JUnitCore.runClasses(EmptyCornersDirectRuleTest.class); - printTestResults(result6); - Result result7 = JUnitCore.runClasses(FinishWithBulbsDirectRuleTest.class); - printTestResults(result7); - Result result8 = JUnitCore.runClasses(LightOrEmptyCaseRuleTest.class); - printTestResults(result8); - Result result9 = JUnitCore.runClasses(MustLightDirectRuleTest.class); - printTestResults(result9); - Result result10 = JUnitCore.runClasses(SatisfyNumberCaseRuleTest.class); - printTestResults(result10); - Result result11 = JUnitCore.runClasses(TooFewBulbsContradictionRuleTest.class); - printTestResults(result11); - Result result12 = JUnitCore.runClasses(TooManyBulbsContradictionRuleTest.class); - printTestResults(result12); + // Lightup Tests + Result result3 = JUnitCore.runClasses(BulbsInPathContradictionRuleTest.class); + printTestResults(result3); + Result result4 = JUnitCore.runClasses(CannotLightACellContradictionRuleTest.class); + printTestResults(result4); + Result result5 = JUnitCore.runClasses(EmptyCellinLightDirectRuleTest.class); + printTestResults(result5); + Result result6 = JUnitCore.runClasses(EmptyCornersDirectRuleTest.class); + printTestResults(result6); + Result result7 = JUnitCore.runClasses(FinishWithBulbsDirectRuleTest.class); + printTestResults(result7); + Result result8 = JUnitCore.runClasses(LightOrEmptyCaseRuleTest.class); + printTestResults(result8); + Result result9 = JUnitCore.runClasses(MustLightDirectRuleTest.class); + printTestResults(result9); + Result result10 = JUnitCore.runClasses(SatisfyNumberCaseRuleTest.class); + printTestResults(result10); + Result result11 = JUnitCore.runClasses(TooFewBulbsContradictionRuleTest.class); + printTestResults(result11); + Result result12 = JUnitCore.runClasses(TooManyBulbsContradictionRuleTest.class); + printTestResults(result12); - // nurikabe tests - Result result13 = JUnitCore.runClasses(BlackBetweenRegionsDirectRuleTest.class); - printTestResults(result13); - Result result14 = JUnitCore.runClasses(BlackBottleNeckDirectRuleTest.class); - printTestResults(result14); - Result result15 = JUnitCore.runClasses(BlackOrWhiteCaseRuleTest.class); - printTestResults(result15); - Result result16 = JUnitCore.runClasses(BlackSquareContradictionRuleTest.class); - printTestResults(result16); - Result result17 = JUnitCore.runClasses(CornerBlackDirectRuleTest.class); - printTestResults(result17); - Result result18 = JUnitCore.runClasses(FillinBlackDirectRuleTest.class); - printTestResults(result18); - Result result19 = JUnitCore.runClasses(FillinWhiteDirectRuleTest.class); - printTestResults(result19); - Result result20 = JUnitCore.runClasses(IsolateBlackContradictionRuleTest.class); - printTestResults(result20); - Result result21 = JUnitCore.runClasses(MultipleNumbersContradictionRuleTest.class); - printTestResults(result21); - Result result22 = JUnitCore.runClasses(NoNumbersContradictionRuleTest.class); - printTestResults(result22); - Result result23 = JUnitCore.runClasses(PreventBlackSquareDirectRuleTest.class); - printTestResults(result23); - Result result24 = JUnitCore.runClasses(SurroundRegionDirectRuleTest.class); - printTestResults(result24); - Result result25 = JUnitCore.runClasses(TooFewSpacesContradictionRuleTest.class); - printTestResults(result25); - Result result26 = JUnitCore.runClasses(TooManySpacesContradictionRuleTest.class); - printTestResults(result26); - Result result27 = JUnitCore.runClasses(WhiteBottleNeckDirectRuleTest.class); - printTestResults(result27); + // nurikabe tests + Result result13 = JUnitCore.runClasses(BlackBetweenRegionsDirectRuleTest.class); + printTestResults(result13); + Result result14 = JUnitCore.runClasses(BlackBottleNeckDirectRuleTest.class); + printTestResults(result14); + Result result15 = JUnitCore.runClasses(BlackOrWhiteCaseRuleTest.class); + printTestResults(result15); + Result result16 = JUnitCore.runClasses(BlackSquareContradictionRuleTest.class); + printTestResults(result16); + Result result17 = JUnitCore.runClasses(CornerBlackDirectRuleTest.class); + printTestResults(result17); + Result result18 = JUnitCore.runClasses(FillinBlackDirectRuleTest.class); + printTestResults(result18); + Result result19 = JUnitCore.runClasses(FillinWhiteDirectRuleTest.class); + printTestResults(result19); + Result result20 = JUnitCore.runClasses(IsolateBlackContradictionRuleTest.class); + printTestResults(result20); + Result result21 = JUnitCore.runClasses(MultipleNumbersContradictionRuleTest.class); + printTestResults(result21); + Result result22 = JUnitCore.runClasses(NoNumbersContradictionRuleTest.class); + printTestResults(result22); + Result result23 = JUnitCore.runClasses(PreventBlackSquareDirectRuleTest.class); + printTestResults(result23); + Result result24 = JUnitCore.runClasses(SurroundRegionDirectRuleTest.class); + printTestResults(result24); + Result result25 = JUnitCore.runClasses(TooFewSpacesContradictionRuleTest.class); + printTestResults(result25); + Result result26 = JUnitCore.runClasses(TooManySpacesContradictionRuleTest.class); + printTestResults(result26); + Result result27 = JUnitCore.runClasses(WhiteBottleNeckDirectRuleTest.class); + printTestResults(result27); - // Treetent - Result result28 = JUnitCore.runClasses(EmptyFieldDirectRuleTest.class); - printTestResults(result28); - Result result29 = JUnitCore.runClasses(FinishWithGrassDirectRuleTest.class); - printTestResults(result29); - Result result30 = JUnitCore.runClasses(FinishWithTentsDirectRuleTest.class); - printTestResults(result30); - Result result31 = JUnitCore.runClasses(LastCampingSpotDirectRuleTest.class); - printTestResults(result31); - Result result32 = JUnitCore.runClasses(NoTentForTreeContradictionRuleTest.class); - printTestResults(result32); - Result result33 = JUnitCore.runClasses(NoTreeForTentContradictionRuleTest.class); - printTestResults(result33); - Result result34 = JUnitCore.runClasses(SurroundTentWithGrassDirectRuleTest.class); - printTestResults(result34); - Result result35 = JUnitCore.runClasses(TreeForTentDirectRuleTest.class); - printTestResults(result35); - Result result36 = JUnitCore.runClasses(TentOrGrassCaseRuleTest.class); - printTestResults(result36); - } - - private static void printTestResults(Result result) { - for (Failure failure : result.getFailures()) { - System.out.println(failure.toString()); + // Treetent + Result result28 = JUnitCore.runClasses(EmptyFieldDirectRuleTest.class); + printTestResults(result28); + Result result29 = JUnitCore.runClasses(FinishWithGrassDirectRuleTest.class); + printTestResults(result29); + Result result30 = JUnitCore.runClasses(FinishWithTentsDirectRuleTest.class); + printTestResults(result30); + Result result31 = JUnitCore.runClasses(LastCampingSpotDirectRuleTest.class); + printTestResults(result31); + Result result32 = JUnitCore.runClasses(NoTentForTreeContradictionRuleTest.class); + printTestResults(result32); + Result result33 = JUnitCore.runClasses(NoTreeForTentContradictionRuleTest.class); + printTestResults(result33); + Result result34 = JUnitCore.runClasses(SurroundTentWithGrassDirectRuleTest.class); + printTestResults(result34); + Result result35 = JUnitCore.runClasses(TreeForTentDirectRuleTest.class); + printTestResults(result35); + Result result36 = JUnitCore.runClasses(TentOrGrassCaseRuleTest.class); + printTestResults(result36); } - System.out.println("Tests run: " + result.getRunCount()); - System.out.println("Tests failed: " + result.getFailureCount()); - System.out.println("All tests passed: " + result.wasSuccessful()); - System.out.println(); - } + private static void printTestResults(Result result) { + for (Failure failure : result.getFailures()) { + System.out.println(failure.toString()); + } + + System.out.println("Tests run: " + result.getRunCount()); + System.out.println("Tests failed: " + result.getFailureCount()); + System.out.println("All tests passed: " + result.wasSuccessful()); + System.out.println(); + } } diff --git a/src/test/java/legup/TestUtilities.java b/src/test/java/legup/TestUtilities.java index a5349197c..83ce773d4 100644 --- a/src/test/java/legup/TestUtilities.java +++ b/src/test/java/legup/TestUtilities.java @@ -8,13 +8,13 @@ import edu.rpi.legup.save.InvalidFileFormatException; public final class TestUtilities { - public static void importTestBoard(String fileName, Puzzle puzzle) - throws InvalidFileFormatException { - puzzle.importPuzzle(ClassLoader.getSystemResourceAsStream(fileName)); - Tree tree = puzzle.getTree(); - TreeNode rootNode = tree.getRootNode(); - Board board = rootNode.getBoard().copy(); - TreeTransition transition = new TreeTransition(rootNode, board); - rootNode.getChildren().add(transition); - } + public static void importTestBoard(String fileName, Puzzle puzzle) + throws InvalidFileFormatException { + puzzle.importPuzzle(ClassLoader.getSystemResourceAsStream(fileName)); + Tree tree = puzzle.getTree(); + TreeNode rootNode = tree.getRootNode(); + Board board = rootNode.getBoard().copy(); + TreeTransition transition = new TreeTransition(rootNode, board); + rootNode.getChildren().add(transition); + } } diff --git a/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java b/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java index 350b6b0e7..08b6633db 100644 --- a/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java +++ b/src/test/java/puzzles/battleship/rules/AdjacentShipsContradictionRuleTest.java @@ -14,57 +14,60 @@ import org.junit.Test; public class AdjacentShipsContradictionRuleTest { - private static final AdjacentShipsContradictionRule RULE = new AdjacentShipsContradictionRule(); + private static final AdjacentShipsContradictionRule RULE = new AdjacentShipsContradictionRule(); - private static Battleship battleship; + private static Battleship battleship; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - battleship = new Battleship(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + battleship = new Battleship(); + } - @Test - public void OrthogonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/AdjacentShipsContradictionRule/OrthogonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void OrthogonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/AdjacentShipsContradictionRule/OrthogonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - } + Assert.assertNotNull(RULE.checkContradiction(board)); + } - @Test - public void InvalidOrthogonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" - + "/AdjacentShipsContradictionRule" - + "/InvalidOrthogonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void InvalidOrthogonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/AdjacentShipsContradictionRule" + + "/InvalidOrthogonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - } + Assert.assertNull(RULE.checkContradiction(board)); + } - @Test - public void DiagonalAdjacentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/AdjacentShipsContradictionRule" + "/DiagonalAdjacentBoards", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void DiagonalAdjacentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/AdjacentShipsContradictionRule" + + "/DiagonalAdjacentBoards", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - BattleshipBoard board = (BattleshipBoard) transition.getBoard(); + BattleshipBoard board = (BattleshipBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - } + Assert.assertNull(RULE.checkContradiction(board)); + } } diff --git a/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java b/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java index a0cf6dc61..1548445fd 100644 --- a/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java +++ b/src/test/java/puzzles/battleship/rules/FinishWithShipsDirectRuleTests.java @@ -10,61 +10,62 @@ import org.junit.*; public class FinishWithShipsDirectRuleTests { - private static final FinishWithShipsDirectRule RULE = new FinishWithShipsDirectRule(); + private static final FinishWithShipsDirectRule RULE = new FinishWithShipsDirectRule(); - private static Battleship battleship; + private static Battleship battleship; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - battleship = new Battleship(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + battleship = new Battleship(); + } - // @Test - public void HorizontalValidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalValidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void HorizontalValidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalValidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } + Assert.assertNull(RULE.checkRule(transition)); + } - // @Test - public void VerticaValidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalValidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void VerticaValidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalValidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } + Assert.assertNull(RULE.checkRule(transition)); + } - // @Test - public void HorizontalInvalidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/HorizontalInvalidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void HorizontalInvalidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + + "/FinishWithShipsBasicRuleTests/HorizontalInvalidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - } + Assert.assertNotNull(RULE.checkRule(transition)); + } - // @Test - public void VerticalInvalidTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalInvalidBoard", - battleship); - TreeNode rootNode = battleship.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // @Test + public void VerticalInvalidTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/battleship/rules" + "/FinishWithShipsBasicRuleTests/VerticalInvalidBoard", + battleship); + TreeNode rootNode = battleship.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - } + Assert.assertNotNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java index b2357b157..316a86f43 100644 --- a/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/BulbsInPathContradictionRuleTest.java @@ -12,78 +12,82 @@ import org.junit.Test; public class BulbsInPathContradictionRuleTest { - private static final BulbsInPathContradictionRule RULE = new BulbsInPathContradictionRule(); - private static LightUp lightUp; + private static final BulbsInPathContradictionRule RULE = new BulbsInPathContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void BulbsInPathContradictionRule_LightInHorizontalPath() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInHorizontalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_LightInHorizontalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInHorizontalPath", + lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + } - @Test - public void BulbsInPathContradictionRule_LightInVerticalPath() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInVerticalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_LightInVerticalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/LightInVerticalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } - @Test - public void BulbsInPathContradictionRule_BlockInVerticalPath() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInVerticalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_BlockInVerticalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInVerticalPath", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } - @Test - public void BulbsInPathContradictionRule_BlockInHorizontalPath() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInHorizontalPath", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void BulbsInPathContradictionRule_BlockInHorizontalPath() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/BulbsInPathContradictionRule/BlockInHorizontalPath", + lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - } + LightUpBoard board = (LightUpBoard) transition.getBoard(); + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + } } diff --git a/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java index 84dc80c83..6db42d39b 100644 --- a/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/CannotLightACellContradictionRuleTest.java @@ -12,83 +12,83 @@ import org.junit.Test; public class CannotLightACellContradictionRuleTest { - private static final CannotLightACellContradictionRule RULE = - new CannotLightACellContradictionRule(); - private static LightUp lightUp; + private static final CannotLightACellContradictionRule RULE = + new CannotLightACellContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - // extensive full testing of null and non-null in a 5x5 board - public void FullLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/FullLightTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // extensive full testing of null and non-null in a 5x5 board + public void FullLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/FullLightTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm it is impossible to light up these squares - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); + // confirm it is impossible to light up these squares + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); - // confirm these are not required to be lit because they are already lit or unable to be - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); - } + // confirm these are not required to be lit because they are already lit or unable to be + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); + } - @Test - // simple contradiction testing for null and non-null in a 3x3 board - public void CannotLightMiddleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/CannotLight", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // simple contradiction testing for null and non-null in a 3x3 board + public void CannotLightMiddleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/CannotLight", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm it is impossible to light up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to light up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } - @Test - public void CanLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/CannotLightACellContradictionRule/CanLightTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void CanLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/CannotLightACellContradictionRule/CanLightTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is not a contradiction somewhere on the board - Assert.assertNotNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is not a contradiction somewhere on the board + Assert.assertNotNull(RULE.checkContradiction(board)); - // confirm that these cells can be lit, are already lit, or that they are just black blocks - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); - } + // confirm that these cells can be lit, are already lit, or that they are just black blocks + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 3))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 3))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(3, 2))); + } } diff --git a/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java index 74ece1cad..264cf928c 100644 --- a/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/EmptyCellinLightDirectRuleTest.java @@ -14,92 +14,92 @@ import org.junit.Test; public class EmptyCellinLightDirectRuleTest { - private static final EmptyCellinLightDirectRule RULE = new EmptyCellinLightDirectRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - @Test - // tests a 3x3 board with with a 0 black tile in the center and lightbulbs in top left and - // bototm - // right - // confirms the rest of the tiles must be empty - public void EmptyCellinLightDirectRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/EmptyCellinLightDirectRule/EmptyCells", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); - - // change the board's cells considering the emptycellinlight rule - LightUpCell cell2 = board.getCell(1, 0); - cell2.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell2); - - LightUpCell cell3 = board.getCell(0, 1); - cell3.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell3); - - LightUpCell cell4 = board.getCell(2, 0); - cell4.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell4); - - LightUpCell cell5 = board.getCell(0, 2); - cell5.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell5); - - LightUpCell cell6 = board.getCell(1, 2); - cell6.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell6); - - LightUpCell cell7 = board.getCell(2, 1); - cell7.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell7); - - LightUpCell cell8 = board.getCell(3, 0); - cell8.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell8); - - LightUpCell cell9 = board.getCell(3, 2); - cell9.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell9); - - LightUpCell cell10 = board.getCell(2, 3); - cell10.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell10); - - LightUpCell cell11 = board.getCell(0, 3); - cell11.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell11); - - // confirm there is a logical following of the EmptyCellinLight rule - Assert.assertNull(RULE.checkRule(transition)); - - // cells (0,0) and (2,2) are not empty because they have lightbulbs, (1,1) - // because it is a black tile, and (1,3),(3,1),(3,3) because they are not lit. Confirm the - // rest - // are empty - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 0 && j == 0) - || (i == 2 && j == 2) - || (i == 1 && j == 1) - || (i == 1 && j == 3) - || (i == 3 && j == 1) - || (i == 3 && j == 3)) { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, c)); + private static final EmptyCellinLightDirectRule RULE = new EmptyCellinLightDirectRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + // tests a 3x3 board with with a 0 black tile in the center and lightbulbs in top left and + // bototm + // right + // confirms the rest of the tiles must be empty + public void EmptyCellinLightDirectRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/EmptyCellinLightDirectRule/EmptyCells", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); + + // change the board's cells considering the emptycellinlight rule + LightUpCell cell2 = board.getCell(1, 0); + cell2.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell2); + + LightUpCell cell3 = board.getCell(0, 1); + cell3.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell3); + + LightUpCell cell4 = board.getCell(2, 0); + cell4.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell4); + + LightUpCell cell5 = board.getCell(0, 2); + cell5.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell5); + + LightUpCell cell6 = board.getCell(1, 2); + cell6.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell6); + + LightUpCell cell7 = board.getCell(2, 1); + cell7.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell7); + + LightUpCell cell8 = board.getCell(3, 0); + cell8.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell8); + + LightUpCell cell9 = board.getCell(3, 2); + cell9.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell9); + + LightUpCell cell10 = board.getCell(2, 3); + cell10.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell10); + + LightUpCell cell11 = board.getCell(0, 3); + cell11.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell11); + + // confirm there is a logical following of the EmptyCellinLight rule + Assert.assertNull(RULE.checkRule(transition)); + + // cells (0,0) and (2,2) are not empty because they have lightbulbs, (1,1) + // because it is a black tile, and (1,3),(3,1),(3,3) because they are not lit. Confirm the + // rest + // are empty + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 0 && j == 0) + || (i == 2 && j == 2) + || (i == 1 && j == 1) + || (i == 1 && j == 3) + || (i == 3 && j == 1) + || (i == 3 && j == 3)) { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java index 0af76baeb..a4f958860 100644 --- a/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/EmptyCornersDirectRuleTest.java @@ -14,65 +14,65 @@ import org.junit.Test; public class EmptyCornersDirectRuleTest { - private static final EmptyCornersDirectRule RULE = new EmptyCornersDirectRule(); - private static LightUp lightUp; + private static final EmptyCornersDirectRule RULE = new EmptyCornersDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void EmptyCornersTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/EmptyCornersDirectRule/EmptyCorners", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void EmptyCornersTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/EmptyCornersDirectRule/EmptyCorners", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the EmptyCorners rule to empty - LightUpCell cell1 = board.getCell(2, 2); - cell1.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell1); + // change the board's cells considering the EmptyCorners rule to empty + LightUpCell cell1 = board.getCell(2, 2); + cell1.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell1); - LightUpCell cell2 = board.getCell(0, 2); - cell2.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell2); + LightUpCell cell2 = board.getCell(0, 2); + cell2.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell2); - LightUpCell cell3 = board.getCell(4, 3); - cell3.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell3); + LightUpCell cell3 = board.getCell(4, 3); + cell3.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell3); - // confirm there is a logical following of the EmptyCorners rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the EmptyCorners rule + Assert.assertNull(RULE.checkRule(transition)); - // this should not be accepted, the cell should remain unknown - LightUpCell cell4 = board.getCell(4, 5); - cell4.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell4); + // this should not be accepted, the cell should remain unknown + LightUpCell cell4 = board.getCell(4, 5); + cell4.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell4); - // this should not be accepted, the cell should be empty but not because of this rule - LightUpCell cell5 = board.getCell(4, 1); - cell5.setData(LightUpCellType.EMPTY.value); - board.addModifiedData(cell5); + // this should not be accepted, the cell should be empty but not because of this rule + LightUpCell cell5 = board.getCell(4, 1); + cell5.setData(LightUpCellType.EMPTY.value); + board.addModifiedData(cell5); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - // confirm the two expected cells are emptied USING THE RULE - // and none of the rest are (others can be empty just not by the same rule) - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 2 && j == 0) || (i == 2 && j == 2) || (i == 3 && j == 4)) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + // confirm the two expected cells are emptied USING THE RULE + // and none of the rest are (others can be empty just not by the same rule) + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 2 && j == 0) || (i == 2 && j == 2) || (i == 3 && j == 4)) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java index d1b0422f9..59cbfdbf9 100644 --- a/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/FinishWithBulbsDirectRuleTest.java @@ -14,91 +14,92 @@ import org.junit.Test; public class FinishWithBulbsDirectRuleTest { - private static final FinishWithBulbsDirectRule RULE = new FinishWithBulbsDirectRule(); - private static LightUp lightUp; + private static final FinishWithBulbsDirectRule RULE = new FinishWithBulbsDirectRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void FinishBulbTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbs", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void FinishBulbTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbs", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the FinishWithBulbs rule to empty - LightUpCell cell1 = board.getCell(1, 0); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); + // change the board's cells considering the FinishWithBulbs rule to empty + LightUpCell cell1 = board.getCell(1, 0); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - // check every square except the top center (2,0) - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if (i == 0 && j == 1) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + // check every square except the top center (2,0) + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if (i == 0 && j == 1) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - // even though this test isnt a completely filled board because it is unsolveable, it tests - // FinishBulbs properly - @Test - public void FinishBulbTestWithThree() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbsWithThree", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // even though this test isnt a completely filled board because it is unsolveable, it tests + // FinishBulbs properly + @Test + public void FinishBulbTestWithThree() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/FinishWithBulbsDirectRule/FinishWithBulbsWithThree", + lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // change the board's cells considering the FinishWithBulbs rule to empty - LightUpCell cell1 = board.getCell(1, 2); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); + // change the board's cells considering the FinishWithBulbs rule to empty + LightUpCell cell1 = board.getCell(1, 2); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); - LightUpCell cell2 = board.getCell(0, 1); - cell2.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell2); + LightUpCell cell2 = board.getCell(0, 1); + cell2.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell2); - LightUpCell cell3 = board.getCell(2, 1); - cell3.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell3); + LightUpCell cell3 = board.getCell(2, 1); + cell3.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell3); - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); - // check every square for logical following - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if ((i == 1 && j == 2) || (i == 2 && j == 1) || (i == 1 && j == 0)) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + // check every square for logical following + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if ((i == 1 && j == 2) || (i == 2 && j == 1) || (i == 1 && j == 0)) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java b/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java index 3a782dfe7..fa0698edb 100644 --- a/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/LightOrEmptyCaseRuleTest.java @@ -16,60 +16,60 @@ import org.junit.Test; public class LightOrEmptyCaseRuleTest { - private static final LightOrEmptyCaseRule RULE = new LightOrEmptyCaseRule(); - private static LightUp lightUp; + private static final LightOrEmptyCaseRule RULE = new LightOrEmptyCaseRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - // creates boards for what is expected output, and checks that the getcases function produces - // the - // correct boards - // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) - @Test - public void LightOrEmptyTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/LightOrEmptyCaseRule/LightOrEmpty", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + // creates boards for what is expected output, and checks that the getcases function produces + // the + // correct boards + // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) + @Test + public void LightOrEmptyTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/LightOrEmptyCaseRule/LightOrEmpty", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(0, 0); // the focus cell - ArrayList cases = RULE.getCases(b, numbered_cell); + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(0, 0); // the focus cell + ArrayList cases = RULE.getCases(b, numbered_cell); - // assert correct number of cases - Assert.assertEquals(2, cases.size()); + // assert correct number of cases + Assert.assertEquals(2, cases.size()); - // make a list of boards that I expect - LightUpCell change_cell; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + // make a list of boards that I expect + LightUpCell change_cell; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - // change the cells of the first new case board - change_cell = case1.getCell(0, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); + // change the cells of the first new case board + change_cell = case1.getCell(0, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); - change_cell = case1.getCell(1, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); + change_cell = case1.getCell(1, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); - // change the cells of the second new case board - change_cell = case2.getCell(0, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); + // change the cells of the second new case board + change_cell = case2.getCell(0, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); - change_cell = case2.getCell(1, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); + change_cell = case2.getCell(1, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); - // check each board I expect and make sure it exists in returned board list - // currently cases is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - } + // check each board I expect and make sure it exists in returned board list + // currently cases is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + } } diff --git a/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java b/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java index 1602b8135..e0e1434c3 100644 --- a/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/MustLightDirectRuleTest.java @@ -14,45 +14,46 @@ import org.junit.Test; public class MustLightDirectRuleTest { - private static final MustLightDirectRule RULE = new MustLightDirectRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - @Test - public void MustLightTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/lightup/rules/MustLightDirectRule/MustLight", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - LightUpBoard board = (LightUpBoard) transition.getBoard(); - - // change the board's cells considering the MustLight rule - LightUpCell cell1 = board.getCell(1, 2); - cell1.setData(LightUpCellType.BULB.value); - board.addModifiedData(cell1); - - // confirm there is a logical following of the FinishWithBulbs rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - LightUpCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int j = 0; j < board.getWidth(); j++) { - c = board.getCell(j, i); - if (i == 2 && j == 1) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + private static final MustLightDirectRule RULE = new MustLightDirectRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + @Test + public void MustLightTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/MustLightDirectRule/MustLight", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + LightUpBoard board = (LightUpBoard) transition.getBoard(); + + // change the board's cells considering the MustLight rule + LightUpCell cell1 = board.getCell(1, 2); + cell1.setData(LightUpCellType.BULB.value); + board.addModifiedData(cell1); + + // confirm there is a logical following of the FinishWithBulbs rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + LightUpCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int j = 0; j < board.getWidth(); j++) { + c = board.getCell(j, i); + if (i == 2 && j == 1) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java b/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java index 238419c71..a04f1c520 100644 --- a/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/SatisfyNumberCaseRuleTest.java @@ -16,146 +16,148 @@ import org.junit.Test; public class SatisfyNumberCaseRuleTest { - private static final SatisfyNumberCaseRule RULE = new SatisfyNumberCaseRule(); - private static LightUp lightUp; - - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } - - // creates two boards for what is expected output, and checks that the getcases function - // produces - // the correct boards - // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) - @Test - public void SatisfyNumberTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumber", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(1, 0); // the tile cell - ArrayList cases = - RULE.getCases(b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE - - // assert correct number of cases - Assert.assertEquals(2, cases.size()); - - // make a list of boards that I expect - LightUpCell change_cell; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - - // change the cells of the first new case board - change_cell = case1.getCell(0, 0); - change_cell.setData(LightUpCellType.BULB.value); - // case1.addModifiedData(change_cell); - - change_cell = case1.getCell(1, 1); - change_cell.setData(LightUpCellType.EMPTY.value); - // case1.addModifiedData(change_cell); - - // change the cells of the second new case board - change_cell = case2.getCell(0, 0); - change_cell.setData(LightUpCellType.EMPTY.value); - // case2.addModifiedData(change_cell); - - change_cell = case2.getCell(1, 1); - change_cell.setData(LightUpCellType.BULB.value); - // case2.addModifiedData(change_cell); - - // check each board I expect and make sure it exists in returned board list - // currently cases is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - } - - @Test - public void SatisfyNumberTestTwo() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumberTwo", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get all new board states using caserule builtin function - LightUpBoard b = (LightUpBoard) transition.getBoard(); - LightUpCell numbered_cell = b.getCell(1, 1); // the tile cell - ArrayList cases = - RULE.getCases(b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE - - // assert correct number of cases - Assert.assertEquals(6, cases.size()); - - // make a list of boards that I expect - LightUpCell change_cell1; - LightUpCell change_cell2; - LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case3 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case4 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case5 = ((LightUpBoard) transition.getBoard()).copy(); - LightUpBoard case6 = ((LightUpBoard) transition.getBoard()).copy(); - - // case 1: lights in (1,0) and (0,1) - change_cell1 = case1.getCell(1, 0); - change_cell2 = case1.getCell(0, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case1.addModifiedData(change_cell1); - case1.addModifiedData(change_cell2); - - // case 2: lights in (1,0) and (1,2) - change_cell1 = case2.getCell(1, 0); - change_cell2 = case2.getCell(1, 2); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case2.addModifiedData(change_cell1); - case2.addModifiedData(change_cell2); - - // case 3: lights in (1,0) and (2,1) - change_cell1 = case3.getCell(1, 0); - change_cell2 = case3.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case3.addModifiedData(change_cell1); - case3.addModifiedData(change_cell2); - - // case 4: lights in (0,1) and (2,1) - change_cell1 = case4.getCell(0, 1); - change_cell2 = case4.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case4.addModifiedData(change_cell1); - case4.addModifiedData(change_cell2); - - // case 5: lights in (0,1) and (1,2) - change_cell1 = case5.getCell(0, 1); - change_cell2 = case5.getCell(1, 2); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case5.addModifiedData(change_cell1); - case5.addModifiedData(change_cell2); - - // case 6: lights in (1,2) and (2,1) - change_cell1 = case6.getCell(1, 2); - change_cell2 = case6.getCell(2, 1); - change_cell1.setData(LightUpCellType.BULB.value); - change_cell2.setData(LightUpCellType.BULB.value); - case6.addModifiedData(change_cell1); - case6.addModifiedData(change_cell2); - - // check each board I expect and make sure it exists in returned board list - // currently the cases list is not made correctly, so the getCases function is flawed. - // Assert.assertTrue(cases.contains((Board) case1)); - // Assert.assertTrue(cases.contains((Board) case2)); - // Assert.assertTrue(cases.contains((Board) case3)); - // Assert.assertTrue(cases.contains((Board) case4)); - // Assert.assertTrue(cases.contains((Board) case5)); - // Assert.assertTrue(cases.contains((Board) case6)); - } + private static final SatisfyNumberCaseRule RULE = new SatisfyNumberCaseRule(); + private static LightUp lightUp; + + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } + + // creates two boards for what is expected output, and checks that the getcases function + // produces + // the correct boards + // IT FAILS BECAUSE THE EXISTING GETCASES FUNCTION IS BUGGY/NOT COMPLETED (not my fault :| ) + @Test + public void SatisfyNumberTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumber", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(1, 0); // the tile cell + ArrayList cases = + RULE.getCases( + b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE + + // assert correct number of cases + Assert.assertEquals(2, cases.size()); + + // make a list of boards that I expect + LightUpCell change_cell; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + + // change the cells of the first new case board + change_cell = case1.getCell(0, 0); + change_cell.setData(LightUpCellType.BULB.value); + // case1.addModifiedData(change_cell); + + change_cell = case1.getCell(1, 1); + change_cell.setData(LightUpCellType.EMPTY.value); + // case1.addModifiedData(change_cell); + + // change the cells of the second new case board + change_cell = case2.getCell(0, 0); + change_cell.setData(LightUpCellType.EMPTY.value); + // case2.addModifiedData(change_cell); + + change_cell = case2.getCell(1, 1); + change_cell.setData(LightUpCellType.BULB.value); + // case2.addModifiedData(change_cell); + + // check each board I expect and make sure it exists in returned board list + // currently cases is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + } + + @Test + public void SatisfyNumberTestTwo() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/SatisfyNumberCaseRule/SatisfyNumberTwo", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get all new board states using caserule builtin function + LightUpBoard b = (LightUpBoard) transition.getBoard(); + LightUpCell numbered_cell = b.getCell(1, 1); // the tile cell + ArrayList cases = + RULE.getCases( + b, numbered_cell); // C MUST BE THE NUMBERED TILE, NOT ANY RANDOM EMPTY ONE + + // assert correct number of cases + Assert.assertEquals(6, cases.size()); + + // make a list of boards that I expect + LightUpCell change_cell1; + LightUpCell change_cell2; + LightUpBoard case1 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case2 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case3 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case4 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case5 = ((LightUpBoard) transition.getBoard()).copy(); + LightUpBoard case6 = ((LightUpBoard) transition.getBoard()).copy(); + + // case 1: lights in (1,0) and (0,1) + change_cell1 = case1.getCell(1, 0); + change_cell2 = case1.getCell(0, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case1.addModifiedData(change_cell1); + case1.addModifiedData(change_cell2); + + // case 2: lights in (1,0) and (1,2) + change_cell1 = case2.getCell(1, 0); + change_cell2 = case2.getCell(1, 2); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case2.addModifiedData(change_cell1); + case2.addModifiedData(change_cell2); + + // case 3: lights in (1,0) and (2,1) + change_cell1 = case3.getCell(1, 0); + change_cell2 = case3.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case3.addModifiedData(change_cell1); + case3.addModifiedData(change_cell2); + + // case 4: lights in (0,1) and (2,1) + change_cell1 = case4.getCell(0, 1); + change_cell2 = case4.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case4.addModifiedData(change_cell1); + case4.addModifiedData(change_cell2); + + // case 5: lights in (0,1) and (1,2) + change_cell1 = case5.getCell(0, 1); + change_cell2 = case5.getCell(1, 2); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case5.addModifiedData(change_cell1); + case5.addModifiedData(change_cell2); + + // case 6: lights in (1,2) and (2,1) + change_cell1 = case6.getCell(1, 2); + change_cell2 = case6.getCell(2, 1); + change_cell1.setData(LightUpCellType.BULB.value); + change_cell2.setData(LightUpCellType.BULB.value); + case6.addModifiedData(change_cell1); + case6.addModifiedData(change_cell2); + + // check each board I expect and make sure it exists in returned board list + // currently the cases list is not made correctly, so the getCases function is flawed. + // Assert.assertTrue(cases.contains((Board) case1)); + // Assert.assertTrue(cases.contains((Board) case2)); + // Assert.assertTrue(cases.contains((Board) case3)); + // Assert.assertTrue(cases.contains((Board) case4)); + // Assert.assertTrue(cases.contains((Board) case5)); + // Assert.assertTrue(cases.contains((Board) case6)); + } } diff --git a/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java index 25389f299..fe994baa6 100644 --- a/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/TooFewBulbsContradictionRuleTest.java @@ -12,57 +12,57 @@ import org.junit.Test; public class TooFewBulbsContradictionRuleTest { - private static final TooFewBulbsContradictionRule RULE = new TooFewBulbsContradictionRule(); - private static LightUp lightUp; + private static final TooFewBulbsContradictionRule RULE = new TooFewBulbsContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooFewBulbsContradictionRule/FullTooFewTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooFewBulbsContradictionRule/FullTooFewTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm that there arent enough bulbs around the black tiles - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(4, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); + // confirm that there arent enough bulbs around the black tiles + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(4, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); - // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(4, 4))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); - } + // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(4, 4))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); + } - @Test - public void TooFewSimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooFewBulbsContradictionRule/TooFew", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void TooFewSimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooFewBulbsContradictionRule/TooFew", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm it is impossible to satisfy up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to satisfy up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } } diff --git a/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java b/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java index 0ee6fdb5e..e27fa3323 100644 --- a/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java +++ b/src/test/java/puzzles/lightup/rules/TooManyBulbsContradictionRuleTest.java @@ -12,57 +12,57 @@ import org.junit.Test; public class TooManyBulbsContradictionRuleTest { - private static final TooManyBulbsContradictionRule RULE = new TooManyBulbsContradictionRule(); - private static LightUp lightUp; + private static final TooManyBulbsContradictionRule RULE = new TooManyBulbsContradictionRule(); + private static LightUp lightUp; - @BeforeClass - public static void setUp() { - lightUp = new LightUp(); - } + @BeforeClass + public static void setUp() { + lightUp = new LightUp(); + } - @Test - // complex extensive toofew test - public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooManyBulbsContradictionRule/FullTooManyTest", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // complex extensive toofew test + public void TooFewBulbsContradictionRule() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooManyBulbsContradictionRule/FullTooManyTest", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm there is a contradiction somewhere on the board - Assert.assertNull(RULE.checkContradiction(board)); + LightUpBoard board = (LightUpBoard) transition.getBoard(); + // confirm there is a contradiction somewhere on the board + Assert.assertNull(RULE.checkContradiction(board)); - // confirm that there are too many bulbs around the black tiles - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); + // confirm that there are too many bulbs around the black tiles + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 4))); - // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); - } + // confirm there are no requirements for number of bulbs around non-black tiles or 0 tiles + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(5, 5))); + } - @Test - // tests a 3x3 board with a 3 in the center and 4 surrounding lightbulbs - public void TooManySimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/lightup/rules/TooManyBulbsContradictionRule/TooMany", lightUp); - TreeNode rootNode = lightUp.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + // tests a 3x3 board with a 3 in the center and 4 surrounding lightbulbs + public void TooManySimpleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/lightup/rules/TooManyBulbsContradictionRule/TooMany", lightUp); + TreeNode rootNode = lightUp.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - LightUpBoard board = (LightUpBoard) transition.getBoard(); + LightUpBoard board = (LightUpBoard) transition.getBoard(); - // confirm it is impossible to satisfy up the center square - Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); + // confirm it is impossible to satisfy up the center square + Assert.assertNull(RULE.checkContradictionAt(board, board.getCell(1, 1))); - // every square except the center - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); - } + // every square except the center + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkContradictionAt(board, board.getCell(2, 1))); + } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java index 3fda4956d..d87398303 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackBetweenRegionsDirectRuleTest.java @@ -19,184 +19,186 @@ public class BlackBetweenRegionsDirectRuleTest { - private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other - * (diagonal going from top left to bottom right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(2, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(1, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final BlackBetweenRegionsDirectRule RULE = new BlackBetweenRegionsDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Black Between Regions direct rule for regions that are diagonal to each other + * (diagonal going from top left to bottom right) + */ + @Test + public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions1Test() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions1", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell1 = board.getCell(2, 1); + cell1.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell2 = board.getCell(1, 2); + cell2.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Black Between Regions direct rule for regions that are diagonal to each other - * (diagonal going from bottom left to top right) - */ - @Test - public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell1 = board.getCell(1, 1); - cell1.setData(NurikabeType.BLACK.toValue()); - NurikabeCell cell2 = board.getCell(2, 2); - cell2.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Black Between Regions direct rule for regions that are diagonal to each other + * (diagonal going from bottom left to top right) + */ + @Test + public void BlackBetweenRegionsDirectRule_DiagonalBlackBetweenRegions2Test() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/DiagonalBlackBetweenRegions2", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell1 = board.getCell(1, 1); + cell1.setData(NurikabeType.BLACK.toValue()); + NurikabeCell cell2 = board.getCell(2, 2); + cell2.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Black Between Regions direct rule for regions that are horizontally opposite each - * other - */ - @Test - public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Black Between Regions direct rule for regions that are horizontally opposite each + * other + */ + @Test + public void BlackBetweenRegionsDirectRule_HorizontalBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/HorizontalBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Black Between Regions direct rule for regions that are vertically opposite each other - */ - @Test - public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Black Between Regions direct rule for regions that are vertically opposite each + * other + */ + @Test + public void BlackBetweenRegionsDirectRule_VerticalBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/VerticalBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Black Between Regions direct rule for a false application of the rule, where a black - * tile is enclosed by one region - */ - @Test - public void BlackBetweenRegionsDirectRule_FalseBlackBetweenRegionsTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/FalseBlackBetweenRegions", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** + * Tests the Black Between Regions direct rule for a false application of the rule, where a + * black tile is enclosed by one region + */ + @Test + public void BlackBetweenRegionsDirectRule_FalseBlackBetweenRegionsTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBetweenRegionsDirectRule/FalseBlackBetweenRegions", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java index cddcd7871..262a4bdbd 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackBottleNeckDirectRuleTest.java @@ -17,94 +17,94 @@ public class BlackBottleNeckDirectRuleTest { - private static final BlackBottleNeckDirectRule RULE = new BlackBottleNeckDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** Tests the Black BottleNeck direct rule for a bottleneck in the center of the board */ - @Test - public void BlackBottleNeckDirectRule_TwoSurroundBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/SimpleBlackBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final BlackBottleNeckDirectRule RULE = new BlackBottleNeckDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** Tests the Black BottleNeck direct rule for a bottleneck in the center of the board */ + @Test + public void BlackBottleNeckDirectRule_TwoSurroundBlackTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/SimpleBlackBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the Black BottleNeck direct rule for a bottleneck in the corner of the board */ - @Test - public void BlackBottleNeckDirectRule_CornerBottleneck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/CornerBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.BLACK.toValue()); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** Tests the Black BottleNeck direct rule for a bottleneck in the corner of the board */ + @Test + public void BlackBottleNeckDirectRule_CornerBottleneck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/CornerBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.BLACK.toValue()); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Black BottleNeck direct rule for a false bottleneck */ - @Test - public void BlackBottleNeckDirectRule_FalseBottleneck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/FalseBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black BottleNeck direct rule for a false bottleneck */ + @Test + public void BlackBottleNeckDirectRule_FalseBottleneck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackBottleNeckDirectRule/FalseBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.BLACK.toValue()); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java index 65f42ac6e..d8f353393 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackOrWhiteCaseRuleTest.java @@ -19,56 +19,57 @@ public class BlackOrWhiteCaseRuleTest { - private static final BlackOrWhiteCaseRule RULE = new BlackOrWhiteCaseRule(); - private static Nurikabe nurikabe; + private static final BlackOrWhiteCaseRule RULE = new BlackOrWhiteCaseRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Black Or White case rule by ensuring that it results in two children, that contain a - * modified cell that is either black or white - */ - @Test - public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackOrWhiteCaseRule/SimpleBlackOrWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Black Or White case rule by ensuring that it results in two children, that contain + * a modified cell that is either black or white + */ + @Test + public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackOrWhiteCaseRule/SimpleBlackOrWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, cell); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, cell); - Assert.assertEquals(2, cases.size()); + Assert.assertEquals(2, cases.size()); - NurikabeBoard caseBoard = (NurikabeBoard) cases.get(0); - NurikabeBoard caseBoard2 = (NurikabeBoard) cases.get(1); + NurikabeBoard caseBoard = (NurikabeBoard) cases.get(0); + NurikabeBoard caseBoard2 = (NurikabeBoard) cases.get(1); - NurikabeType board1Type = caseBoard.getCell(0, 0).getType(); - NurikabeType board2Type = caseBoard2.getCell(0, 0).getType(); + NurikabeType board1Type = caseBoard.getCell(0, 0).getType(); + NurikabeType board2Type = caseBoard2.getCell(0, 0).getType(); - Assert.assertTrue( - (board1Type.equals(NurikabeType.BLACK) || board1Type.equals(NurikabeType.WHITE)) - && (board2Type.equals(NurikabeType.BLACK) || board2Type.equals(NurikabeType.WHITE))); - Assert.assertFalse(board1Type.equals(board2Type)); + Assert.assertTrue( + (board1Type.equals(NurikabeType.BLACK) || board1Type.equals(NurikabeType.WHITE)) + && (board2Type.equals(NurikabeType.BLACK) + || board2Type.equals(NurikabeType.WHITE))); + Assert.assertFalse(board1Type.equals(board2Type)); - Assert.assertEquals(caseBoard.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard.getWidth(), caseBoard2.getWidth(), board.getWidth()); + Assert.assertEquals(caseBoard.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard.getWidth(), caseBoard2.getWidth(), board.getWidth()); - for (int i = 0; i < caseBoard.getHeight(); i++) { - for (int k = 0; k < caseBoard.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(caseBoard.getCell(k, i).getLocation())) { - continue; + for (int i = 0; i < caseBoard.getHeight(); i++) { + for (int k = 0; k < caseBoard.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(caseBoard.getCell(k, i).getLocation())) { + continue; + } + Assert.assertTrue(caseBoard.getCell(k, i).equals(caseBoard2.getCell(k, i))); + } } - Assert.assertTrue(caseBoard.getCell(k, i).equals(caseBoard2.getCell(k, i))); - } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java index d317a7835..d27e546bc 100644 --- a/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/BlackSquareContradictionRuleTest.java @@ -15,97 +15,97 @@ import org.junit.Test; public class BlackSquareContradictionRuleTest { - private static final BlackSquareContradictionRule RULE = new BlackSquareContradictionRule(); - private static Nurikabe nurikabe; + private static final BlackSquareContradictionRule RULE = new BlackSquareContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Black Square contradiction rule for a black square in the middle of the board */ - @Test - public void BlackSquareContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/SimpleBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a black square in the middle of the board */ + @Test + public void BlackSquareContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/SimpleBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); - NurikabeCell cell2 = board.getCell(1, 2); - NurikabeCell cell3 = board.getCell(2, 1); - NurikabeCell cell4 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); + NurikabeCell cell2 = board.getCell(1, 2); + NurikabeCell cell3 = board.getCell(2, 1); + NurikabeCell cell4 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Black Square contradiction rule for a square in the corner of the board */ - @Test - public void BlackSquareContradictionRule_CornerSquareTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/CornerBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a square in the corner of the board */ + @Test + public void BlackSquareContradictionRule_CornerSquareTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/CornerBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 2); - NurikabeCell cell2 = board.getCell(2, 3); - NurikabeCell cell3 = board.getCell(3, 2); - NurikabeCell cell4 = board.getCell(3, 3); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(2, 2); + NurikabeCell cell2 = board.getCell(2, 3); + NurikabeCell cell3 = board.getCell(3, 2); + NurikabeCell cell4 = board.getCell(3, 3); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Black Square contradiction rule for a false contradiction */ - @Test - public void BlackSquareContradictionRule_FalseBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/BlackSquareContradictionRule/FalseBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Black Square contradiction rule for a false contradiction */ + @Test + public void BlackSquareContradictionRule_FalseBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/BlackSquareContradictionRule/FalseBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java index deb93c43f..164e08e38 100644 --- a/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/CannotReachCellDirectRuleTest.java @@ -17,75 +17,76 @@ public class CannotReachCellDirectRuleTest { - private static final CannotReachCellDirectRule RULE = new CannotReachCellDirectRule(); - private static Nurikabe nurikabe; + private static final CannotReachCellDirectRule RULE = new CannotReachCellDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Cannot Reach Cell direct rule for a simple unreachable cell */ - @Test - public void CannotReachCellDirectRule_SimpleUnreachableCell() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CannotReachCellDirectRule/SimpleUnreachableCell", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); + /** Tests the Cannot Reach Cell direct rule for a simple unreachable cell */ + @Test + public void CannotReachCellDirectRule_SimpleUnreachableCell() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CannotReachCellDirectRule/SimpleUnreachableCell", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Cannot Reach Cell direct rule for a more complex board with all cells reachable */ - @Test - public void CannotReachCellDirectRule_AllCellsReachable() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CannotReachCellDirectRule/AllCellsReachable", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); + /** Tests the Cannot Reach Cell direct rule for a more complex board with all cells reachable */ + @Test + public void CannotReachCellDirectRule_AllCellsReachable() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CannotReachCellDirectRule/AllCellsReachable", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 3); - NurikabeCell cell2 = board.getCell(0, 1); - NurikabeCell cell3 = board.getCell(4, 1); + NurikabeCell cell1 = board.getCell(2, 3); + NurikabeCell cell2 = board.getCell(0, 1); + NurikabeCell cell3 = board.getCell(4, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (!(point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()))) { - NurikabeCell newCell = board.getCell(k, i); - newCell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(newCell); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (!(point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()))) { + NurikabeCell newCell = board.getCell(k, i); + newCell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(newCell); + } + } } - } - } - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java index 567d663e8..196a1ac2f 100644 --- a/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/CornerBlackDirectRuleTest.java @@ -17,65 +17,65 @@ public class CornerBlackDirectRuleTest { - private static final CornerBlackDirectRule RULE = new CornerBlackDirectRule(); - private static Nurikabe nurikabe; + private static final CornerBlackDirectRule RULE = new CornerBlackDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Corner Black direct rule for a simple corner black tile */ - @Test - public void CornerBlackContradictionRule_SimpleCornerBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CornerBlackDirectRule/SimpleCornerBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); + /** Tests the Corner Black direct rule for a simple corner black tile */ + @Test + public void CornerBlackContradictionRule_SimpleCornerBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CornerBlackDirectRule/SimpleCornerBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); - NurikabeCell cell = board.getCell(2, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeCell cell = board.getCell(2, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Corner Black direct rule for a false application of the rule */ - @Test - public void CornerBlackContradictionRule_FalseCornerBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/CornerBlackDirectRule/FalseCornerBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); + /** Tests the Corner Black direct rule for a false application of the rule */ + @Test + public void CornerBlackContradictionRule_FalseCornerBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/CornerBlackDirectRule/FalseCornerBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); - NurikabeCell cell = board.getCell(2, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); + NurikabeCell cell = board.getCell(2, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); + Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java index c4ed751b0..5238411b2 100644 --- a/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/FillinBlackDirectRuleTest.java @@ -17,125 +17,126 @@ public class FillinBlackDirectRuleTest { - private static final FillinBlackDirectRule RULE = new FillinBlackDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the middle of the board - */ - @Test - public void FillinBlackDirectRule_UnknownSurroundBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/UnknownSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final FillinBlackDirectRule RULE = new FillinBlackDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the middle of the + * board + */ + @Test + public void FillinBlackDirectRule_UnknownSurroundBlackTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/UnknownSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the top left corner of - * the board - */ - @Test - public void FillinBlackDirectRule_CornerTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the top left corner of + * the board + */ + @Test + public void FillinBlackDirectRule_CornerTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Fillin Black direct rule for a square surrounded by black in the bottom right corner - * of the board - */ - @Test - public void FillinBlackDirectRule_CornerTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 2); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Fillin Black direct rule for a square surrounded by black in the bottom right + * corner of the board + */ + @Test + public void FillinBlackDirectRule_CornerTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/CornerBlack2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 2); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the Fillin Black direct rule for a false application of the rule */ - @Test - public void FillinBlackDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinBlackDirectRule/FalseFillinBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the Fillin Black direct rule for a false application of the rule */ + @Test + public void FillinBlackDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinBlackDirectRule/FalseFillinBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java index 317f44521..e6aea12b9 100644 --- a/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/FillinWhiteDirectRuleTest.java @@ -16,127 +16,128 @@ import org.junit.Test; public class FillinWhiteDirectRuleTest { - private static final FillinWhiteDirectRule RULE = new FillinWhiteDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the middle of the board - */ - @Test - public void FillinWhiteDirectRule_UnknownSurroundWhiteTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/UnknownSurroundWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final FillinWhiteDirectRule RULE = new FillinWhiteDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the middle of the + * board + */ + @Test + public void FillinWhiteDirectRule_UnknownSurroundWhiteTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/UnknownSurroundWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the top left corner of - * the board - */ - @Test - public void FillinWhiteDirectRule_CornerTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the top left corner of + * the board + */ + @Test + public void FillinWhiteDirectRule_CornerTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Fillin White direct rule for a square surrounded by white in the bottom right corner - * of the board - */ - @Test - public void FillinWhiteDirectRule_CornerTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(2, 2); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Fillin White direct rule for a square surrounded by white in the bottom right + * corner of the board + */ + @Test + public void FillinWhiteDirectRule_CornerTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/CornerWhite2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(2, 2); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the Fillin White direct rule for a false application of the rule */ - @Test - public void FillinWhiteDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/FillinWhiteDirectRule/FalseFillinWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the Fillin White direct rule for a false application of the rule */ + @Test + public void FillinWhiteDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/FillinWhiteDirectRule/FalseFillinWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java index 1c6773e35..660542d79 100644 --- a/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/IsolateBlackContradictionRuleTest.java @@ -16,93 +16,96 @@ public class IsolateBlackContradictionRuleTest { - private static final IsolateBlackContradictionRule RULE = new IsolateBlackContradictionRule(); - private static Nurikabe nurikabe; + private static final IsolateBlackContradictionRule RULE = new IsolateBlackContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Isolate Black contradiction rule for a black square in the corner, separated by a - * diagonal of white squares - */ - @Test - public void IsolateBlackContradictionRule_SimpleIsolateBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/SimpleIsolateBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Isolate Black contradiction rule for a black square in the corner, separated by a + * diagonal of white squares + */ + @Test + public void IsolateBlackContradictionRule_SimpleIsolateBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/SimpleIsolateBlack", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Isolate Black contradiction rule for diagonally connected black squares */ - @Test - public void IsolateBlackContradictionRule_DiagonalBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/DiagonalIsolateBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Isolate Black contradiction rule for diagonally connected black squares */ + @Test + public void IsolateBlackContradictionRule_DiagonalBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/DiagonalIsolateBlack", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(1, 1); - NurikabeCell cell3 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(1, 1); + NurikabeCell cell3 = board.getCell(2, 2); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Isolate Black contradiction rule for a false contradiction */ - @Test - public void IsolateBlackContradictionRule_FalseIsolateBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/IsolateBlackContradictionRule/FalseIsolateBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Isolate Black contradiction rule for a false contradiction */ + @Test + public void IsolateBlackContradictionRule_FalseIsolateBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/IsolateBlackContradictionRule/FalseIsolateBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNotNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java index 4bc98a9ac..0ca30c136 100644 --- a/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/MultipleNumbersContradictionRuleTest.java @@ -16,96 +16,99 @@ public class MultipleNumbersContradictionRuleTest { - private static final MultipleNumbersContradictionRule RULE = - new MultipleNumbersContradictionRule(); - private static Nurikabe nurikabe; + private static final MultipleNumbersContradictionRule RULE = + new MultipleNumbersContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Multiple Numbers contradiction rule for a single region with multiple numbers */ - @Test - public void MultipleNumbersContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/MultipleNumbers", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Multiple Numbers contradiction rule for a single region with multiple numbers */ + @Test + public void MultipleNumbersContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/MultipleNumbers", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(0, 0)) || point.equals(new Point(2, 0))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(0, 0)) || point.equals(new Point(2, 0))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** - * Tests the Multiple Numbers contradiction rule for a more complex regions with multiple numbers - */ - @Test - public void MultipleNumbersContradictionRule_ComplexRegion() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/ComplexRegion", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Multiple Numbers contradiction rule for a more complex regions with multiple + * numbers + */ + @Test + public void MultipleNumbersContradictionRule_ComplexRegion() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/ComplexRegion", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(0, 0); - NurikabeCell cell2 = board.getCell(2, 0); - NurikabeCell cell3 = board.getCell(4, 0); - NurikabeCell cell4 = board.getCell(2, 3); - NurikabeCell cell5 = board.getCell(4, 4); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(0, 0); + NurikabeCell cell2 = board.getCell(2, 0); + NurikabeCell cell3 = board.getCell(4, 0); + NurikabeCell cell4 = board.getCell(2, 3); + NurikabeCell cell5 = board.getCell(4, 4); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation()) - || point.equals(cell5.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation()) + || point.equals(cell5.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** - * Tests the Multiple Numbers contradiction rule for two regions with one number each, separated - * diagonally - */ - @Test - public void MultipleNumbersContradictionRule_FalseContradiction() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/FalseContradiction", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Multiple Numbers contradiction rule for two regions with one number each, separated + * diagonally + */ + @Test + public void MultipleNumbersContradictionRule_FalseContradiction() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/MultipleNumbersContradictionRule/FalseContradiction", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java index 2b032e650..c5293880f 100644 --- a/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/NoNumbersContradictionRuleTest.java @@ -15,72 +15,73 @@ public class NoNumbersContradictionRuleTest { - private static final NoNumberContradictionRule RULE = new NoNumberContradictionRule(); - private static Nurikabe nurikabe; + private static final NoNumberContradictionRule RULE = new NoNumberContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the No Number contradiction rule for a white region enclosed by black squares */ - @Test - public void NoNumberContradictionRule_NoNumberSurroundBlack() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/SimpleNoNumber", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the No Number contradiction rule for a white region enclosed by black squares */ + @Test + public void NoNumberContradictionRule_NoNumberSurroundBlack() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/SimpleNoNumber", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Point location = new Point(1, 1); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(location)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + Point location = new Point(1, 1); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(location)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the No Number contradiction rule for a false contradiction */ - @Test - public void NoNumberContradictionRule_FalseNoNumber() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the No Number contradiction rule for a false contradiction */ + @Test + public void NoNumberContradictionRule_FalseNoNumber() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - @Test - public void NoNumberContradictionRule_FalseNoNumber2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber2", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + @Test + public void NoNumberContradictionRule_FalseNoNumber2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/NoNumberContradictionRule/FalseNoNumber2", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkRule(transition)); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java index 67f87e751..c529c81cc 100644 --- a/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/PreventBlackSquareDirectRuleTest.java @@ -17,157 +17,162 @@ public class PreventBlackSquareDirectRuleTest { - private static final PreventBlackSquareDirectRule RULE = new PreventBlackSquareDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the bottom left corner - * missing - */ - @Test - public void PreventBlackSquareDirectRule_BottomLeftWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomLeftWhiteBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final PreventBlackSquareDirectRule RULE = new PreventBlackSquareDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** + * Tests the Prevent Black Square direct rule for a black square with the bottom left corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_BottomLeftWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomLeftWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the bottom right corner - * missing - */ - @Test - public void PreventBlackSquareDirectRule_BottomRightWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomRightWhiteBlackSquare", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Prevent Black Square direct rule for a black square with the bottom right corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_BottomRightWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/BottomRightWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the top left corner missing - */ - @Test - public void PreventBlackSquareDirectRule_TopLeftWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopLeftWhiteBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Prevent Black Square direct rule for a black square with the top left corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_TopLeftWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopLeftWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * Tests the Prevent Black Square direct rule for a black square with the top right corner missing - */ - @Test - public void PreventBlackSquareDirectRule_TopRightWhiteBlackSquareTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopRightWhiteBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell = board.getCell(1, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * Tests the Prevent Black Square direct rule for a black square with the top right corner + * missing + */ + @Test + public void PreventBlackSquareDirectRule_TopRightWhiteBlackSquareTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/TopRightWhiteBlackSquare", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell = board.getCell(1, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the Prevent Black Square direct rule for a false contradiction */ - @Test - public void PreventBlackSquareDirectRule_FalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/FalseBlackSquare", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the Prevent Black Square direct rule for a false contradiction */ + @Test + public void PreventBlackSquareDirectRule_FalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/PreventBlackSquareDirectRule/FalseBlackSquare", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java index 6520e1221..a09475cff 100644 --- a/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/SurroundRegionDirectRuleTest.java @@ -17,103 +17,105 @@ public class SurroundRegionDirectRuleTest { - private static final SurroundRegionDirectRule RULE = new SurroundRegionDirectRule(); - private static Nurikabe nurikabe; + private static final SurroundRegionDirectRule RULE = new SurroundRegionDirectRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Surround Region direct rule for a white square in the middle of the board */ - @Test - public void SurroundRegionDirectRule_SurroundRegionBlackTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a white square in the middle of the board */ + @Test + public void SurroundRegionDirectRule_SurroundRegionBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 0); - cell1.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell1); - NurikabeCell cell2 = board.getCell(0, 1); - cell2.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell2); - NurikabeCell cell3 = board.getCell(2, 1); - cell3.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell3); - NurikabeCell cell4 = board.getCell(1, 2); - cell4.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell4); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 0); + cell1.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell1); + NurikabeCell cell2 = board.getCell(0, 1); + cell2.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell2); + NurikabeCell cell3 = board.getCell(2, 1); + cell3.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell3); + NurikabeCell cell4 = board.getCell(1, 2); + cell4.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell4); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Surround Region direct rule for a white square in the corner of the board */ - @Test - public void SurroundRegionDirectRule_SurroundRegionBlackInCornerTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlackInCorner", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a white square in the corner of the board */ + @Test + public void SurroundRegionDirectRule_SurroundRegionBlackInCornerTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/SurroundRegionBlackInCorner", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 0); - cell1.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell1); - NurikabeCell cell2 = board.getCell(0, 1); - cell2.setData(NurikabeType.BLACK.toValue()); - board.addModifiedData(cell2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 0); + cell1.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell1); + NurikabeCell cell2 = board.getCell(0, 1); + cell2.setData(NurikabeType.BLACK.toValue()); + board.addModifiedData(cell2); - Assert.assertNull(RULE.checkRule(transition)); + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Surround Region direct rule for a false application of the rule */ - @Test - public void SurroundRegionDirectRule_FalseSurroundRegionBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/SurroundRegionDirectRule/FalseSurroundRegion", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Surround Region direct rule for a false application of the rule */ + @Test + public void SurroundRegionDirectRule_FalseSurroundRegionBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/SurroundRegionDirectRule/FalseSurroundRegion", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java index b5774e3dd..89b1a29a7 100644 --- a/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/TooFewSpacesContradictionRuleTest.java @@ -16,84 +16,85 @@ public class TooFewSpacesContradictionRuleTest { - private static final TooFewSpacesContradictionRule RULE = new TooFewSpacesContradictionRule(); - private static Nurikabe nurikabe; + private static final TooFewSpacesContradictionRule RULE = new TooFewSpacesContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** Tests the Too Few Spaces contradiction rule for an isolated completely enclosed number */ - @Test - public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for an isolated completely enclosed number */ + @Test + public void TooFewSpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(1, 1))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(1, 1))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Too Few Spaces contradiction rule for a region with insufficient space */ - @Test - public void TooFewSpacesContradictionRule_InsufficientSpaceTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for a region with insufficient space */ + @Test + public void TooFewSpacesContradictionRule_InsufficientSpaceTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/TwoSurroundBlack", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Too Few Spaces contradiction rule for a false contradiction */ - @Test - public void TooFewSpacesContradictionRule_FalseTooFewSpaces() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/FalseTooFewSpaces", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Few Spaces contradiction rule for a false contradiction */ + @Test + public void TooFewSpacesContradictionRule_FalseTooFewSpaces() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooFewSpacesContradictionRule/FalseTooFewSpaces", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(1, 1); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(1, 1); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java index 1a3280653..31fb92f5d 100644 --- a/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/TooManySpacesContradictionRuleTest.java @@ -15,92 +15,94 @@ public class TooManySpacesContradictionRuleTest { - private static final TooManySpacesContradictionRule RULE = new TooManySpacesContradictionRule(); - private static Nurikabe nurikabe; + private static final TooManySpacesContradictionRule RULE = new TooManySpacesContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Too Many Spaces contradiction rule for a 2 in the center surrounded by 4 white - * squares - */ - @Test - public void TooManySpacesContradictionRule_TwoSurroundBlackTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/TwoSurroundWhite", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Too Many Spaces contradiction rule for a 2 in the center surrounded by 4 white + * squares + */ + @Test + public void TooManySpacesContradictionRule_TwoSurroundBlackTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/TwoSurroundWhite", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(new Point(1, 0)) - || point.equals(new Point(1, 1)) - || point.equals(new Point(2, 1)) - || point.equals(new Point(1, 2)) - || point.equals(new Point(0, 1))) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(new Point(1, 0)) + || point.equals(new Point(1, 1)) + || point.equals(new Point(2, 1)) + || point.equals(new Point(1, 2)) + || point.equals(new Point(0, 1))) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** Tests the Too Many Spaces contradiction rule for an extra diagonal space */ - @Test - public void TooManySpacesContradictionRule_ExtraDiagonalSpace() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/ExtraDiagonalSpace", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** Tests the Too Many Spaces contradiction rule for an extra diagonal space */ + @Test + public void TooManySpacesContradictionRule_ExtraDiagonalSpace() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/ExtraDiagonalSpace", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - /** - * Tests the Too Many Spaces contradiction rule for a contradiction.with multiple numbers, wherein - * one of the numbers is larger than the region - */ - @Test - public void TooManySpacesContradictionRule_MultipleNumberRegion() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/TooManySpacesContradictionRule/MultipleNumberRegion", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Too Many Spaces contradiction rule for a contradiction.with multiple numbers, + * wherein one of the numbers is larger than the region + */ + @Test + public void TooManySpacesContradictionRule_MultipleNumberRegion() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/TooManySpacesContradictionRule/MultipleNumberRegion", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(board.getCell(2, 1).getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + Assert.assertNull(RULE.checkContradiction(board)); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(board.getCell(2, 1).getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java b/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java index 58470d6b0..da94d7598 100644 --- a/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRuleTest.java @@ -16,67 +16,69 @@ public class UnreachableWhiteCellContradictionRuleTest { - private static final UnreachableWhiteCellContradictionRule RULE = - new UnreachableWhiteCellContradictionRule(); - private static Nurikabe nurikabe; + private static final UnreachableWhiteCellContradictionRule RULE = + new UnreachableWhiteCellContradictionRule(); + private static Nurikabe nurikabe; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } - /** - * Tests the Unreachable White Cell contradiction rule for a simple case of an unreachable white - * cell - */ - @Test - public void UnreachableWhiteCellContradictionRule_SimpleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/SimpleUnreachableTest", - nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Unreachable White Cell contradiction rule for a simple case of an unreachable white + * cell + */ + @Test + public void UnreachableWhiteCellContradictionRule_SimpleTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/SimpleUnreachableTest", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - NurikabeCell cell1 = board.getCell(2, 2); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeCell cell1 = board.getCell(2, 2); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - /** - * Tests the Unreachable White Cell contradiction rule for a variety of white square that should - * all be reachable in some manner - */ - @Test - public void UnreachableWhiteCellContradictionRule_AllCellsReachable() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/AllCellsReachable", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the Unreachable White Cell contradiction rule for a variety of white square that should + * all be reachable in some manner + */ + @Test + public void UnreachableWhiteCellContradictionRule_AllCellsReachable() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/UnreachableWhiteCellContradictionRule/AllCellsReachable", + nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((NurikabeBoard) transition.getBoard())); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java b/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java index 4ad9267bd..ce9144879 100644 --- a/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java +++ b/src/test/java/puzzles/nurikabe/rules/WhiteBottleNeckDirectRuleTest.java @@ -17,87 +17,87 @@ public class WhiteBottleNeckDirectRuleTest { - private static final WhiteBottleNeckDirectRule RULE = new WhiteBottleNeckDirectRule(); - private static Nurikabe nurikabe; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - nurikabe = new Nurikabe(); - } - - /** Tests the White BottleNeck direct rule for a bottleneck in the middle of the board */ - @Test - public void WhiteBottleNeckDirectRule_SimpleWhiteBottleNeckTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/SimpleWhiteBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final WhiteBottleNeckDirectRule RULE = new WhiteBottleNeckDirectRule(); + private static Nurikabe nurikabe; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + nurikabe = new Nurikabe(); + } + + /** Tests the White BottleNeck direct rule for a bottleneck in the middle of the board */ + @Test + public void WhiteBottleNeckDirectRule_SimpleWhiteBottleNeckTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/SimpleWhiteBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** Tests the White BottleNeck direct rule for a more complex board */ - @Test - public void WhiteBottleNeckDirectRule_NurikabeBoard1Test() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/NurikabeBoard1", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(0, 0); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the White BottleNeck direct rule for a more complex board */ + @Test + public void WhiteBottleNeckDirectRule_NurikabeBoard1Test() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/NurikabeBoard1", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(0, 0); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - /** Tests the White BottleNeck direct rule for a more false bottle neck */ - @Test - public void WhiteBottleNeckDirectRule_FalseBottleNeck() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/FalseBottleNeck", nurikabe); - TreeNode rootNode = nurikabe.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - NurikabeBoard board = (NurikabeBoard) transition.getBoard(); - transition.setRule(RULE); - - NurikabeCell cell = board.getCell(2, 1); - cell.setData(NurikabeType.WHITE.toValue()); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** Tests the White BottleNeck direct rule for a more false bottle neck */ + @Test + public void WhiteBottleNeckDirectRule_FalseBottleNeck() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/nurikabe/rules/WhiteBottleNeckDirectRule/FalseBottleNeck", nurikabe); + TreeNode rootNode = nurikabe.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + NurikabeBoard board = (NurikabeBoard) transition.getBoard(); + transition.setRule(RULE); + + NurikabeCell cell = board.getCell(2, 1); + cell.setData(NurikabeType.WHITE.toValue()); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java index 693acc682..58fc67824 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndCaseRuleTest.java @@ -18,142 +18,142 @@ public class AndCaseRuleTest { - private static final CaseRuleAnd RULE = new CaseRuleAnd(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - private void falseAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); - - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); - ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); - - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); - ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); - - // Assert that the corresponding cells for the different case rules do not - // match with each other - Assert.assertNotEquals(board1A, board2A); - Assert.assertNotEquals(board1B, board2B); - - // First assert the two cells are not equal, then verify that they are either - // unknown or false. - Assert.assertNotEquals(board1A, board1B); - Assert.assertTrue( - board1A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - board1B.equals(ShortTruthTableCellType.UNKNOWN) - || board1B.equals(ShortTruthTableCellType.FALSE)); - - Assert.assertNotEquals(board2A, board2B); - Assert.assertTrue( - board2A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - board2B.equals(ShortTruthTableCellType.UNKNOWN) - || board2B.equals(ShortTruthTableCellType.FALSE)); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the two cells that should be different - if (!((i == aX && j == aY) || (i == bX && j == bY))) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + private static final CaseRuleAnd RULE = new CaseRuleAnd(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + private void falseAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); + + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); + ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); + + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); + ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); + + // Assert that the corresponding cells for the different case rules do not + // match with each other + Assert.assertNotEquals(board1A, board2A); + Assert.assertNotEquals(board1B, board2B); + + // First assert the two cells are not equal, then verify that they are either + // unknown or false. + Assert.assertNotEquals(board1A, board1B); + Assert.assertTrue( + board1A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + board1B.equals(ShortTruthTableCellType.UNKNOWN) + || board1B.equals(ShortTruthTableCellType.FALSE)); + + Assert.assertNotEquals(board2A, board2B); + Assert.assertTrue( + board2A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + board2B.equals(ShortTruthTableCellType.UNKNOWN) + || board2B.equals(ShortTruthTableCellType.FALSE)); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the two cells that should be different + if (!((i == aX && j == aY) || (i == bX && j == bY))) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + } + } } - } } - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches - * are created: one where A is false and one where B is false. - */ - @Test - public void SimpleStatement1FalseTest() throws InvalidFileFormatException { - falseAndTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring - * that two branches are created: one where ~ is false and one where the second ^ is false. - */ - @Test - public void ComplexStatement1FalseTest() throws InvalidFileFormatException { - falseAndTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); - } - - private void trueAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // There should only be 1 branch - Assert.assertEquals(1, cases.size()); - - ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); - ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); - - // Both cells should be true - Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.TRUE); - Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.TRUE); - Assert.assertEquals(caseBoardAType, caseBoardBType); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is - * created where A and B are both true. - */ - @Test - public void SimpleStatement1AndTest() throws InvalidFileFormatException { - trueAndTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring that - * one branch is created where both ~ and the second ^ are true. - */ - @Test - public void ComplexStatement1TrueTest() throws InvalidFileFormatException { - trueAndTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); - } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches + * are created: one where A is false and one where B is false. + */ + @Test + public void SimpleStatement1FalseTest() throws InvalidFileFormatException { + falseAndTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring + * that two branches are created: one where ~ is false and one where the second ^ is false. + */ + @Test + public void ComplexStatement1FalseTest() throws InvalidFileFormatException { + falseAndTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); + } + + private void trueAndTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AndCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // There should only be 1 branch + Assert.assertEquals(1, cases.size()); + + ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); + ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); + + // Both cells should be true + Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.TRUE); + Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.TRUE); + Assert.assertEquals(caseBoardAType, caseBoardBType); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is + * created where A and B are both true. + */ + @Test + public void SimpleStatement1AndTest() throws InvalidFileFormatException { + trueAndTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring + * that one branch is created where both ~ and the second ^ are true. + */ + @Test + public void ComplexStatement1TrueTest() throws InvalidFileFormatException { + trueAndTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java index 94b99801b..61f29a669 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndEliminationDirectRuleTest.java @@ -15,198 +15,205 @@ import org.junit.Test; public class AndEliminationDirectRuleTest { - private static final DirectRuleAndElimination RULE = new DirectRuleAndElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: B^C where ^ is true - * - *

Checks all possible combinations of true, false, and unknown for B and C except for where - * both B and C are true and asserts that each one of them is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void trueAndTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.TRUE) { - continue; - } + private static final DirectRuleAndElimination RULE = new DirectRuleAndElimination(); + private static ShortTruthTable stt; - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); + /** + * Given one statement: B^C where ^ is true + * + *

Checks all possible combinations of true, false, and unknown for B and C except for where + * both B and C are true and asserts that each one of them is not a valid application of the + * rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void trueAndTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.TRUE) { + continue; + } + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); + + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } + + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); + /** + * Given one statement: B^C where ^ is true + * + *

Checks all possible combinations of true and unknown for B and C except for where both B + * and C are unknown and asserts that each one of them is a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void trueAndTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.UNKNOWN) { + continue; + } + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); + + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } + + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + + Assert.assertNull(RULE.checkRule(transition)); + } } - - Assert.assertNotNull(RULE.checkRule(transition)); - } } - } - - /** - * Given one statement: B^C where ^ is true - * - *

Checks all possible combinations of true and unknown for B and C except for where both B and - * C are unknown and asserts that each one of them is a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void trueAndTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/TrueAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - if (cellType1 == cellType2 && cellType1 == ShortTruthTableCellType.UNKNOWN) { - continue; - } - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); - ShortTruthTableCell clyde = board.getCell(2, 0); - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); + /** + * Given one statement: B^C where ^ is false + * + *

Checks all possible combinations of true, false, and unknown for B and C and asserts that + * each one of them is not a valid application of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithUnknownsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAnd", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); + + if (cellType1 != ShortTruthTableCellType.UNKNOWN) { + bonnie.setData(cellType1); + board.addModifiedData(bonnie); + } + + if (cellType2 != ShortTruthTableCellType.UNKNOWN) { + clyde.setData(cellType2); + board.addModifiedData(clyde); + } + + Assert.assertNotNull(RULE.checkRule(transition)); + } } + } - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } + /** + * Given one statement: B^C where both B and ^ are false + * + *

Asserts that this is not a valid application of the rule if C is set to either true or + * false. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithKnownFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownFalse", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkRule(transition)); - } - } - } - - /** - * Given one statement: B^C where ^ is false - * - *

Checks all possible combinations of true, false, and unknown for B and C and asserts that - * each one of them is not a valid application of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithUnknownsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAnd", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell bonnie = board.getCell(0, 0); + ShortTruthTableCell clyde = board.getCell(2, 0); + clyde.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); - if (cellType1 != ShortTruthTableCellType.UNKNOWN) { - bonnie.setData(cellType1); - board.addModifiedData(bonnie); - } + clyde.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(clyde); + Assert.assertNotNull(RULE.checkRule(transition)); + } - if (cellType2 != ShortTruthTableCellType.UNKNOWN) { - clyde.setData(cellType2); - board.addModifiedData(clyde); - } + /** + * Given one statement: B^C where B is true and ^ is false + * + *

Asserts that this is a valid application of the rule if and only if C is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void falseAndWithKnownTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownTrue", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell clyde = board.getCell(2, 0); + clyde.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(clyde); Assert.assertNotNull(RULE.checkRule(transition)); - } + + clyde.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(clyde); + Assert.assertNull(RULE.checkRule(transition)); } - } - - /** - * Given one statement: B^C where both B and ^ are false - * - *

Asserts that this is not a valid application of the rule if C is set to either true or - * false. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithKnownFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownFalse", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell clyde = board.getCell(2, 0); - clyde.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - - clyde.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: B^C where B is true and ^ is false - * - *

Asserts that this is a valid application of the rule if and only if C is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void falseAndWithKnownTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/AndEliminationDirectRule/FalseAndWithKnownTrue", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell clyde = board.getCell(2, 0); - clyde.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(clyde); - Assert.assertNotNull(RULE.checkRule(transition)); - - clyde.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(clyde); - Assert.assertNull(RULE.checkRule(transition)); - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java index d17ffd6cf..ec03919ae 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AndIntroductionDirectRuleTest.java @@ -15,91 +15,91 @@ import org.junit.Test; public class AndIntroductionDirectRuleTest { - private static final DirectRuleAndIntroduction RULE = new DirectRuleAndIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleAndIntroduction RULE = new DirectRuleAndIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A ^ B - * - *

Asserts that if at least 1 of A or B is false, then this is a valid application of the rule - * if and only if ^ is false. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseAndTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; - falseAndTestHelper(path + "FUF"); - falseAndTestHelper(path + "FUU"); - falseAndTestHelper(path + "UUF"); - falseAndTestHelper(path + "FUT"); - falseAndTestHelper(path + "TUF"); - } + /** + * Given a statement: A ^ B + * + *

Asserts that if at least 1 of A or B is false, then this is a valid application of the + * rule if and only if ^ is false. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseAndTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; + falseAndTestHelper(path + "FUF"); + falseAndTestHelper(path + "FUU"); + falseAndTestHelper(path + "UUF"); + falseAndTestHelper(path + "FUT"); + falseAndTestHelper(path + "TUF"); + } - private void falseAndTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseAndTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell and = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell and = board.getCell(1, 0); - and.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(and); - Assert.assertNotNull(RULE.checkRule(transition)); + and.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(and); + Assert.assertNotNull(RULE.checkRule(transition)); - and.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(and); - Assert.assertNull(RULE.checkRule(transition)); - } + and.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(and); + Assert.assertNull(RULE.checkRule(transition)); + } - /** - * Given a statement: A ^ B - * - *

Asserts that setting ^ to true is a valid application of the rule if and only if both A and - * B are true. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String first : letters) { - for (String second : letters) { - trueAndTestHelper(path + first + "U" + second); - } + /** + * Given a statement: A ^ B + * + *

Asserts that setting ^ to true is a valid application of the rule if and only if both A + * and B are true. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/AndIntroductionDirectRule/"; + String[] letters = {"T", "F", "U"}; + for (String first : letters) { + for (String second : letters) { + trueAndTestHelper(path + first + "U" + second); + } + } } - } - private void trueAndTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueAndTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - ShortTruthTableCell and = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell and = board.getCell(1, 0); - and.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(and); + and.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(and); - if (a.getType() == ShortTruthTableCellType.TRUE - && b.getType() == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + if (a.getType() == ShortTruthTableCellType.TRUE + && b.getType() == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java index 2126fc60d..c631db613 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/AtomicDirectRuleTest.java @@ -15,156 +15,156 @@ import org.junit.Test; public class AtomicDirectRuleTest { - private static final DirectRuleAtomic RULE = new DirectRuleAtomic(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given two statements: A A where the first A is set to false. - * - *

This test sets the second A to false and then asserts that this is a valid application of - * the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MatchingFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: A A where the first A is set to false. - * - *

This test sets the second A to true and then asserts that this is not a valid application of - * the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MismatchingFalseTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: B B where the first B is set to true. - * - *

This test sets the second B to true and then asserts that this is a valid application of the - * rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MatchingTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: B B where the first B is set to true. - * - *

This test sets the second B to false and then asserts that this is not a valid application - * of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void MismatchingTrueTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: C C where neither statement is set to anything. - * - *

This test sets the second C to false and then asserts that this is not a valid application - * of the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void NothingPreviouslyMarkedTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given two statements: C C where neither statement is set to anything. - * - *

This test sets the second C to true and then asserts that this is not a valid application of - * the rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void NothingPreviouslyMarkedTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - - ShortTruthTableCell cell = board.getCell(0, 2); - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - } + private static final DirectRuleAtomic RULE = new DirectRuleAtomic(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given two statements: A A where the first A is set to false. + * + *

This test sets the second A to false and then asserts that this is a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MatchingFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: A A where the first A is set to false. + * + *

This test sets the second A to true and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MismatchingFalseTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: B B where the first B is set to true. + * + *

This test sets the second B to true and then asserts that this is a valid application of + * the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MatchingTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: B B where the first B is set to true. + * + *

This test sets the second B to false and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void MismatchingTrueTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/TrueB", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: C C where neither statement is set to anything. + * + *

This test sets the second C to false and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void NothingPreviouslyMarkedTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given two statements: C C where neither statement is set to anything. + * + *

This test sets the second C to true and then asserts that this is not a valid application + * of the rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void NothingPreviouslyMarkedTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/AtomicDirectRule/Empty", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + + ShortTruthTableCell cell = board.getCell(0, 2); + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java index 36824faee..987d194f9 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalEliminationTest.java @@ -15,380 +15,385 @@ import org.junit.Test; public class BiconditionalEliminationTest { - private static final DirectRuleBiconditionalElimination RULE = - new DirectRuleBiconditionalElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: A <-> B where both A and <-> are true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where both B and <-> are true - * - *

Asserts that this is a valid application of the rule if and only if A is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A is false and <-> is true - * - *

Asserts that this is a valid application of the rule if and only if B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B is false and <-> is true - * - *

Asserts that this is a valid application of the rule if and only if A is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalWithFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A is true and <-> is false - * - *

Asserts that this is a valid application of the rule if and only if B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B is true and <-> is false - * - *

Asserts that this is a valid application of the rule if and only if A is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where A and <-> are false - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell morty = board.getCell(2, 0); - - // Asserts that this is not a valid application of the rule when B is unknown - morty.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when B is true - morty.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(morty); - Assert.assertNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when B is false - morty.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(morty); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where B and <-> are false - * - *

Asserts that this is a valid application of the rule if and only if A is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBiconditionalWithFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); - - // Asserts that this is not a valid application of the rule when A is unknown - rick.setData(ShortTruthTableCellType.UNKNOWN); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is not a valid application of the rule when A is false - rick.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(rick); - Assert.assertNotNull(RULE.checkRule(transition)); - - // Asserts that this is a valid application of the rule when A is true - rick.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(rick); - Assert.assertNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A <-> B where <-> is true - * - *

Asserts that setting any combination of A and B at the same time is not a valid application - * of this rule - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBiconditionalSetBothAtOnceTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { + private static final DirectRuleBiconditionalElimination RULE = + new DirectRuleBiconditionalElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: A <-> B where both A and <-> are true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell rick = board.getCell(0, 0); ShortTruthTableCell morty = board.getCell(2, 0); - rick.setData(cellType1); - morty.setData(cellType2); + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where both B and <-> are true + * + *

Asserts that this is a valid application of the rule if and only if A is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + // Asserts that this is not a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A is false and <-> is true + * + *

Asserts that this is a valid application of the rule if and only if B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + // Asserts that this is not a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); Assert.assertNotNull(RULE.checkRule(transition)); - } + + // Asserts that this is a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); } - } - - /** - * Asserts that setting any combination of A and B at the same time is not a valid application of - * this rule. This is tested on multiple files. - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAandBAtOnceTest() throws InvalidFileFormatException { - String directory = "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/"; - setAandBBothAtOnceTest(directory + "FalseBiconditional"); - setAandBBothAtOnceTest(directory + "TrueBiconditional"); - setAandBBothAtOnceTest(directory + "FalseBiconditionalWithFalseA"); - setAandBBothAtOnceTest(directory + "TrueBiconditionalWithFalseA"); - setAandBBothAtOnceTest(directory + "FalseBiconditionalWithTrueA"); - setAandBBothAtOnceTest(directory + "TrueBiconditionalWithTrueA"); - } - - /** - * Helper function to test biconditional elimination rule with given file path. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - private void setAandBBothAtOnceTest(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { + + /** + * Given one statement: A <-> B where B is false and <-> is true + * + *

Asserts that this is a valid application of the rule if and only if A is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalWithFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell rick = board.getCell(0, 0); + + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A is true and <-> is false + * + *

Asserts that this is a valid application of the rule if and only if B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell morty = board.getCell(2, 0); - rick.setData(cellType1); - morty.setData(cellType2); + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B is true and <-> is false + * + *

Asserts that this is a valid application of the rule if and only if A is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where A and <-> are false + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell morty = board.getCell(2, 0); + + // Asserts that this is not a valid application of the rule when B is unknown + morty.setData(ShortTruthTableCellType.UNKNOWN); board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when B is true + morty.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(morty); + Assert.assertNull(RULE.checkRule(transition)); + + // Asserts that this is not a valid application of the rule when B is false + morty.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(morty); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where B and <-> are false + * + *

Asserts that this is a valid application of the rule if and only if A is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBiconditionalWithFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/FalseBiconditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + // Asserts that this is not a valid application of the rule when A is unknown + rick.setData(ShortTruthTableCellType.UNKNOWN); + board.addModifiedData(rick); Assert.assertNotNull(RULE.checkRule(transition)); - } + + // Asserts that this is not a valid application of the rule when A is false + rick.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(rick); + Assert.assertNotNull(RULE.checkRule(transition)); + + // Asserts that this is a valid application of the rule when A is true + rick.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(rick); + Assert.assertNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A <-> B where <-> is true + * + *

Asserts that setting any combination of A and B at the same time is not a valid + * application of this rule + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBiconditionalSetBothAtOnceTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/TrueBiconditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + ShortTruthTableCell morty = board.getCell(2, 0); + + rick.setData(cellType1); + morty.setData(cellType2); + + board.addModifiedData(rick); + board.addModifiedData(morty); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + + /** + * Asserts that setting any combination of A and B at the same time is not a valid application + * of this rule. This is tested on multiple files. + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAandBAtOnceTest() throws InvalidFileFormatException { + String directory = "puzzles/shorttruthtable/rules/BiconditionalEliminationDirectRule/"; + setAandBBothAtOnceTest(directory + "FalseBiconditional"); + setAandBBothAtOnceTest(directory + "TrueBiconditional"); + setAandBBothAtOnceTest(directory + "FalseBiconditionalWithFalseA"); + setAandBBothAtOnceTest(directory + "TrueBiconditionalWithFalseA"); + setAandBBothAtOnceTest(directory + "FalseBiconditionalWithTrueA"); + setAandBBothAtOnceTest(directory + "TrueBiconditionalWithTrueA"); + } + + /** + * Helper function to test biconditional elimination rule with given file path. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + private void setAandBBothAtOnceTest(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell rick = board.getCell(0, 0); + ShortTruthTableCell morty = board.getCell(2, 0); + + rick.setData(cellType1); + morty.setData(cellType2); + + board.addModifiedData(rick); + board.addModifiedData(morty); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java index 99a86c6f1..e1c5cf957 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/BiconditionalIntroductionTest.java @@ -15,103 +15,103 @@ import org.junit.Test; public class BiconditionalIntroductionTest { - private static final DirectRuleBiconditionalIntroduction RULE = - new DirectRuleBiconditionalIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleBiconditionalIntroduction RULE = + new DirectRuleBiconditionalIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A <-> B - * - *

Asserts that if setting <-> to false is a valid application of this rule if and only if A - * and B do not match. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; + /** + * Given a statement: A <-> B + * + *

Asserts that if setting <-> to false is a valid application of this rule if and only if A + * and B do not match. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - System.out.println(a + b); - falseConditionalHelper(path + a + "U" + b); - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + System.out.println(a + b); + falseConditionalHelper(path + a + "U" + b); + } + } } - } - private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() != b.getType()) { - // Not valid if they don't match but at least one of the values of A or B is unknown - if (a.getType() == ShortTruthTableCellType.UNKNOWN - || b.getType() == ShortTruthTableCellType.UNKNOWN) { - Assert.assertNotNull(RULE.checkRule(transition)); - } else { - Assert.assertNull(RULE.checkRule(transition)); - } - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() != b.getType()) { + // Not valid if they don't match but at least one of the values of A or B is unknown + if (a.getType() == ShortTruthTableCellType.UNKNOWN + || b.getType() == ShortTruthTableCellType.UNKNOWN) { + Assert.assertNotNull(RULE.checkRule(transition)); + } else { + Assert.assertNull(RULE.checkRule(transition)); + } + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } - /** - * Given a statement: A <-> B - * - *

Asserts that if setting <-> to true is a valid application of this rule if and only if A and - * B match. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; + /** + * Given a statement: A <-> B + * + *

Asserts that if setting <-> to true is a valid application of this rule if and only if A + * and B match. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/BiconditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - System.out.println(a + b); - trueConditionalHelper(path + a + "U" + b); - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + System.out.println(a + b); + trueConditionalHelper(path + a + "U" + b); + } + } } - } - private void trueConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == b.getType() && a.getType() != ShortTruthTableCellType.UNKNOWN) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == b.getType() && a.getType() != ShortTruthTableCellType.UNKNOWN) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java index 7574ce337..0f95906f2 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/ConditionalEliminationTest.java @@ -15,229 +15,237 @@ import org.junit.Test; public class ConditionalEliminationTest { - private static final DirectRuleConditionalElimination RULE = - new DirectRuleConditionalElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that the only valid combination of A and B that is a valid application of this rule - * is when A is true and B is false - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { + private static final DirectRuleConditionalElimination RULE = + new DirectRuleConditionalElimination(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that the only valid combination of A and B that is a valid application of this + * rule is when A is true and B is false + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); + ShortTruthTableCell boniato = board.getCell(2, 0); + + aubergine.setData(cellType1); + boniato.setData(cellType2); + + board.addModifiedData(aubergine); + board.addModifiedData(boniato); + + if (cellType1 == ShortTruthTableCellType.TRUE + && cellType2 == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that this is a valid application of the rule if and only if A is set to true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTrueATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell aubergine = board.getCell(0, 0); - ShortTruthTableCell boniato = board.getCell(2, 0); - aubergine.setData(cellType1); - boniato.setData(cellType2); + aubergine.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(aubergine); + Assert.assertNull(RULE.checkRule(transition)); + aubergine.setData(ShortTruthTableCellType.FALSE); board.addModifiedData(aubergine); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where -> is false + * + *

Asserts that this is a valid application of the rule if and only if B is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalFalseBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } - if (cellType1 == ShortTruthTableCellType.TRUE - && cellType2 == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + /** + * Given one statement: A -> B where -> is true + * + *

Asserts that you cannot set any combination of both A and B at the same time. + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAandBTrueConditionalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditional", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell aubergine = board.getCell(0, 0); + ShortTruthTableCell boniato = board.getCell(2, 0); + + aubergine.setData(cellType1); + boniato.setData(cellType2); + + board.addModifiedData(aubergine); + board.addModifiedData(boniato); + + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that this is a valid application of the rule if and only if A is set to true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTrueATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - - aubergine.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(aubergine); - Assert.assertNull(RULE.checkRule(transition)); - - aubergine.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(aubergine); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where -> is false - * - *

Asserts that this is a valid application of the rule if and only if B is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalFalseBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/FalseConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNull(RULE.checkRule(transition)); - - boniato.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where -> is true - * - *

Asserts that you cannot set any combination of both A and B at the same time. - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAandBTrueConditionalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditional", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { + + /** + * Given one statement: A -> B where A and -> are true + * + *

Asserts that this is a valid application of this rule if and only if B is set to true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueAMeansTrueBTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueA", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(boniato); + Assert.assertNull(RULE.checkRule(transition)); + + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where B is false and -> is true + * + *

Asserts that this is a valid application of this rule if and only if A is set to false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseBMeansFalseATest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithFalseB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); ShortTruthTableCell aubergine = board.getCell(0, 0); - ShortTruthTableCell boniato = board.getCell(2, 0); - aubergine.setData(cellType1); - boniato.setData(cellType2); + aubergine.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(aubergine); + Assert.assertNull(RULE.checkRule(transition)); + aubergine.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(aubergine); + Assert.assertNotNull(RULE.checkRule(transition)); + } + + /** + * Given one statement: A -> B where B and -> are true + * + *

Asserts that this is not a valid application of this rule no matter what A is set to. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueBCannotDetermineA() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueB", + stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell boniato = board.getCell(2, 0); + + boniato.setData(ShortTruthTableCellType.TRUE); board.addModifiedData(boniato); + Assert.assertNotNull(RULE.checkRule(transition)); + boniato.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(boniato); Assert.assertNotNull(RULE.checkRule(transition)); - } } - } - - /** - * Given one statement: A -> B where A and -> are true - * - *

Asserts that this is a valid application of this rule if and only if B is set to true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueAMeansTrueBTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueA", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(boniato); - Assert.assertNull(RULE.checkRule(transition)); - - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where B is false and -> is true - * - *

Asserts that this is a valid application of this rule if and only if A is set to false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseBMeansFalseATest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithFalseB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell aubergine = board.getCell(0, 0); - - aubergine.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(aubergine); - Assert.assertNull(RULE.checkRule(transition)); - - aubergine.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(aubergine); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given one statement: A -> B where B and -> are true - * - *

Asserts that this is not a valid application of this rule no matter what A is set to. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueBCannotDetermineA() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/ConditionalEliminationDirectRule/TrueConditionalWithTrueB", - stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell boniato = board.getCell(2, 0); - - boniato.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - - boniato.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(boniato); - Assert.assertNotNull(RULE.checkRule(transition)); - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java index 5eea810a7..1bc28373d 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/ConditionalIntroductionTest.java @@ -15,97 +15,97 @@ import org.junit.Test; public class ConditionalIntroductionTest { - private static final DirectRuleConditionalIntroduction RULE = - new DirectRuleConditionalIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleConditionalIntroduction RULE = + new DirectRuleConditionalIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A -> B - * - *

Asserts that if setting -> to false is a valid application of this rule if and only if A is - * true and B is false. - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; + /** + * Given a statement: A -> B + * + *

Asserts that if setting -> to false is a valid application of this rule if and only if A + * is true and B is false. + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - falseConditionalHelper(path + a + "U" + b); - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + falseConditionalHelper(path + a + "U" + b); + } + } } - } - private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseConditionalHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == ShortTruthTableCellType.TRUE - && b.getType() == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == ShortTruthTableCellType.TRUE + && b.getType() == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } - /** - * Given a statement: A -> B - * - *

Asserts that if setting -> to true is a valid application of this rule if and only if A is - * false or B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueConditionalTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; + /** + * Given a statement: A -> B + * + *

Asserts that if setting -> to true is a valid application of this rule if and only if A is + * false or B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueConditionalTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/ConditionalIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String a : letters) { - for (String b : letters) { - trueConditionalTestHelper(path + a + "U" + b); - } + String[] letters = {"T", "F", "U"}; + for (String a : letters) { + for (String b : letters) { + trueConditionalTestHelper(path + a + "U" + b); + } + } } - } - private void trueConditionalTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueConditionalTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell conditional = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell conditional = board.getCell(1, 0); - conditional.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(conditional); + conditional.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(conditional); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - if (a.getType() == ShortTruthTableCellType.FALSE - || b.getType() == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + if (a.getType() == ShortTruthTableCellType.FALSE + || b.getType() == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java index 9caf2414a..589e3cfb9 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/NotEliminationTest.java @@ -15,116 +15,120 @@ import org.junit.Test; public class NotEliminationTest { - private static final DirectRuleNotElimination RULE = new DirectRuleNotElimination(); - private static ShortTruthTable stt; + private static final DirectRuleNotElimination RULE = new DirectRuleNotElimination(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given one statement: ¬A where ¬ is false - * - *

Asserts that this is a valid application of this rule if and only if A is true - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotEliminationDirectRule/FalseNot", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Given one statement: ¬A where ¬ is false + * + *

Asserts that this is a valid application of this rule if and only if A is true + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotEliminationDirectRule/FalseNot", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(1, 0); - a.setData(cellType); - board.addModifiedData(a); + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(1, 0); + a.setData(cellType); + board.addModifiedData(a); - if (cellType == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } - /** - * Given one statement: ¬A where ¬ is true - * - *

Asserts that this is a valid application of this rule if and only if A is false - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotEliminationDirectRule/TrueNot", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Given one statement: ¬A where ¬ is true + * + *

Asserts that this is a valid application of this rule if and only if A is false + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotEliminationDirectRule/TrueNot", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(1, 0); - a.setData(cellType); - board.addModifiedData(a); + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(1, 0); + a.setData(cellType); + board.addModifiedData(a); - if (cellType == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + if (cellType == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } - // /** - // * Given one statement: ¬A - // * - // * Asserts that setting both ¬ and A to any values would not be a valid - // * application of this rule - // * - // * @throws InvalidFileFormatException - // */ - // @Test - // public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { - // - // TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/BlankNot", stt); - // TreeNode rootNode = stt.getTree().getRootNode(); - // TreeTransition transition = rootNode.getChildren().get(0); - // transition.setRule(RULE); - // - // ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, - // ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; - // - // for (ShortTruthTableCellType cellType1 : cellTypes) { - // for (ShortTruthTableCellType cellType2 : cellTypes) { - // ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - // ShortTruthTableCell not = board.getCell(0, 0); - // ShortTruthTableCell a = board.getCell(1, 0); - // - // not.setData(cellType1); - // a.setData(cellType2); - // - // board.addModifiedData(not); - // board.addModifiedData(a); - // - // System.out.println("TYPE1:" + cellType1); - // System.out.println("TYPE2:" + cellType2); - // Assert.assertNotNull(RULE.checkRule(transition)); - // } - // } - // } + // /** + // * Given one statement: ¬A + // * + // * Asserts that setting both ¬ and A to any values would not be a valid + // * application of this rule + // * + // * @throws InvalidFileFormatException + // */ + // @Test + // public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { + // + // TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/NotEliminationDirectRule/BlankNot", stt); + // TreeNode rootNode = stt.getTree().getRootNode(); + // TreeTransition transition = rootNode.getChildren().get(0); + // transition.setRule(RULE); + // + // ShortTruthTableCellType[] cellTypes = {ShortTruthTableCellType.TRUE, + // ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN}; + // + // for (ShortTruthTableCellType cellType1 : cellTypes) { + // for (ShortTruthTableCellType cellType2 : cellTypes) { + // ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + // ShortTruthTableCell not = board.getCell(0, 0); + // ShortTruthTableCell a = board.getCell(1, 0); + // + // not.setData(cellType1); + // a.setData(cellType2); + // + // board.addModifiedData(not); + // board.addModifiedData(a); + // + // System.out.println("TYPE1:" + cellType1); + // System.out.println("TYPE2:" + cellType2); + // Assert.assertNotNull(RULE.checkRule(transition)); + // } + // } + // } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java index 9949651eb..e338fb9bd 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/NotIntroductionTest.java @@ -15,115 +15,121 @@ import org.junit.Test; public class NotIntroductionTest { - private static final DirectRuleNotIntroduction RULE = new DirectRuleNotIntroduction(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given one statement: ¬A where A is false - * - *

Asserts that this is a valid application of this rule if and only if ¬ is true - * - * @throws InvalidFileFormatException - */ - @Test - public void FalseNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/FalseA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - not.setData(cellType); - board.addModifiedData(not); - - if (cellType == ShortTruthTableCellType.TRUE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + private static final DirectRuleNotIntroduction RULE = new DirectRuleNotIntroduction(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); } - } - - /** - * Given one statement: ¬A where A is true - * - *

Asserts that this is a valid application of this rule if and only if ¬ is false - * - * @throws InvalidFileFormatException - */ - @Test - public void TrueNot() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/TrueA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - not.setData(cellType); - board.addModifiedData(not); - - if (cellType == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } + + /** + * Given one statement: ¬A where A is false + * + *

Asserts that this is a valid application of this rule if and only if ¬ is true + * + * @throws InvalidFileFormatException + */ + @Test + public void FalseNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/FalseA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + not.setData(cellType); + board.addModifiedData(not); + + if (cellType == ShortTruthTableCellType.TRUE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } - - /** - * Given one statement: ¬A - * - *

Asserts that setting both ¬ and A to any values would not be a valid application of this - * rule - * - * @throws InvalidFileFormatException - */ - @Test - public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/BlankA", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell not = board.getCell(0, 0); - ShortTruthTableCell a = board.getCell(1, 0); - - not.setData(cellType1); - a.setData(cellType2); - - board.addModifiedData(not); - board.addModifiedData(a); - - Assert.assertNotNull(RULE.checkRule(transition)); - } + + /** + * Given one statement: ¬A where A is true + * + *

Asserts that this is a valid application of this rule if and only if ¬ is false + * + * @throws InvalidFileFormatException + */ + @Test + public void TrueNot() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/TrueA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + not.setData(cellType); + board.addModifiedData(not); + + if (cellType == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + + /** + * Given one statement: ¬A + * + *

Asserts that setting both ¬ and A to any values would not be a valid application of this + * rule + * + * @throws InvalidFileFormatException + */ + @Test + public void CannotSetBothAtOnceTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/NotIntroductionDirectRule/BlankA", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell not = board.getCell(0, 0); + ShortTruthTableCell a = board.getCell(1, 0); + + not.setData(cellType1); + a.setData(cellType2); + + board.addModifiedData(not); + board.addModifiedData(a); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java index a2cc2abc0..0bfa6fc6e 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrCaseRuleTest.java @@ -18,142 +18,142 @@ public class OrCaseRuleTest { - private static final CaseRuleOr RULE = new CaseRuleOr(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - private void trueOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); - - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); - ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); - - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); - ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); - - // Assert that the corresponding cells for the different case rules do not - // match with each other - Assert.assertNotEquals(board1A, board2A); - Assert.assertNotEquals(board1B, board2B); - - // First assert the two cells are not equal, then verify that they are either - // unknown or false. - Assert.assertNotEquals(board1A, board1B); - Assert.assertTrue( - board1A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.TRUE)); - Assert.assertTrue( - board1B.equals(ShortTruthTableCellType.UNKNOWN) - || board1B.equals(ShortTruthTableCellType.TRUE)); - - Assert.assertNotEquals(board2A, board2B); - Assert.assertTrue( - board2A.equals(ShortTruthTableCellType.UNKNOWN) - || board1A.equals(ShortTruthTableCellType.TRUE)); - Assert.assertTrue( - board2B.equals(ShortTruthTableCellType.UNKNOWN) - || board2B.equals(ShortTruthTableCellType.TRUE)); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the two cells that should be different - if (!((i == aX && j == aY) || (i == bX && j == bY))) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + private static final CaseRuleOr RULE = new CaseRuleOr(); + private static ShortTruthTable stt; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } + + private void trueOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); + + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType board1A = caseBoard1.getCell(aX, aY).getType(); + ShortTruthTableCellType board1B = caseBoard1.getCell(bX, bY).getType(); + + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableCellType board2A = caseBoard2.getCell(aX, aY).getType(); + ShortTruthTableCellType board2B = caseBoard2.getCell(bX, bY).getType(); + + // Assert that the corresponding cells for the different case rules do not + // match with each other + Assert.assertNotEquals(board1A, board2A); + Assert.assertNotEquals(board1B, board2B); + + // First assert the two cells are not equal, then verify that they are either + // unknown or false. + Assert.assertNotEquals(board1A, board1B); + Assert.assertTrue( + board1A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.TRUE)); + Assert.assertTrue( + board1B.equals(ShortTruthTableCellType.UNKNOWN) + || board1B.equals(ShortTruthTableCellType.TRUE)); + + Assert.assertNotEquals(board2A, board2B); + Assert.assertTrue( + board2A.equals(ShortTruthTableCellType.UNKNOWN) + || board1A.equals(ShortTruthTableCellType.TRUE)); + Assert.assertTrue( + board2B.equals(ShortTruthTableCellType.UNKNOWN) + || board2B.equals(ShortTruthTableCellType.TRUE)); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the two cells that should be different + if (!((i == aX && j == aY) || (i == bX && j == bY))) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + } + } } - } } - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches - * are created: one where A is false and one where B is false. - */ - @Test - public void SimpleStatement1TrueTest() throws InvalidFileFormatException { - trueOrTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring - * that two branches are created: one where ~ is false and one where the second ^ is false. - */ - @Test - public void ComplexStatement1TrueTest() throws InvalidFileFormatException { - trueOrTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); - } - - private void falseOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(andX, andY); - ArrayList cases = RULE.getCases(board, cell); - - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); - - // There should only be 1 branch - Assert.assertEquals(1, cases.size()); - - ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); - ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); - - // Both cells should be true - Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.FALSE); - Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.FALSE); - Assert.assertEquals(caseBoardAType, caseBoardBType); - - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); - } - - /** - * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is - * created where A and B are both true. - */ - @Test - public void SimpleStatement1FalseTest() throws InvalidFileFormatException { - falseOrTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); - } - - /** - * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring that - * one branch is created where both ~ and the second ^ are true. - */ - @Test - public void ComplexStatement1FalseTest() throws InvalidFileFormatException { - falseOrTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); - } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that two branches + * are created: one where A is false and one where B is false. + */ + @Test + public void SimpleStatement1TrueTest() throws InvalidFileFormatException { + trueOrTest("SimpleStatement1_True", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is false, tests this case rule by ensuring + * that two branches are created: one where ~ is false and one where the second ^ is false. + */ + @Test + public void ComplexStatement1TrueTest() throws InvalidFileFormatException { + trueOrTest("ComplexStatement1_True", 6, 0, 0, 0, 9, 0); + } + + private void falseOrTest(String fileName, int andX, int andY, int aX, int aY, int bX, int bY) + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrCaseRule/" + fileName, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(andX, andY); + ArrayList cases = RULE.getCases(board, cell); + + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); + + // There should only be 1 branch + Assert.assertEquals(1, cases.size()); + + ShortTruthTableBoard caseBoard = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableCellType caseBoardAType = caseBoard.getCell(aX, aY).getType(); + ShortTruthTableCellType caseBoardBType = caseBoard.getCell(bX, bY).getType(); + + // Both cells should be true + Assert.assertEquals(caseBoardAType, ShortTruthTableCellType.FALSE); + Assert.assertEquals(caseBoardBType, ShortTruthTableCellType.FALSE); + Assert.assertEquals(caseBoardAType, caseBoardBType); + + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard.getHeight(), caseBoard.getHeight(), board.getHeight()); + } + + /** + * Given a statement A ^ B where ^ is false, tests this case rule by ensuring that one branch is + * created where A and B are both true. + */ + @Test + public void SimpleStatement1FalseTest() throws InvalidFileFormatException { + falseOrTest("SimpleStatement1_False", 1, 0, 0, 0, 2, 0); + } + + /** + * Given a statement ~(A|B)^(C^D) where the first ^ is true, tests this case rule by ensuring + * that one branch is created where both ~ and the second ^ are true. + */ + @Test + public void ComplexStatement1FalseTest() throws InvalidFileFormatException { + falseOrTest("ComplexStatement1_False", 6, 0, 0, 0, 9, 0); + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java index b678b6610..e4efad465 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrEliminationTest.java @@ -15,139 +15,148 @@ import org.junit.Test; public class OrEliminationTest { - private static final DirectRuleOrElimination RULE = new DirectRuleOrElimination(); - private static ShortTruthTable stt; - - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } - - /** - * Given a statement: A V B, where A is false and V is true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void FTUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/FTU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(2, 0); - - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); - - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given a statement: A V B, where B is false and V is true - * - *

Asserts that this is a valid application of the rule if and only if B is true. - * - * @throws InvalidFileFormatException - */ - @Test - public void UTFTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTF", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(0, 0); - - cell.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(cell); - Assert.assertNull(RULE.checkRule(transition)); - - cell.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(cell); - Assert.assertNotNull(RULE.checkRule(transition)); - } - - /** - * Given a statement: A V B, where V is false - * - *

Asserts that this is a valid application of the rule if and only if both A and B are false. - * - * @throws InvalidFileFormatException - */ - @Test - public void UFUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UFU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); + private static final DirectRuleOrElimination RULE = new DirectRuleOrElimination(); + private static ShortTruthTable stt; - a.setData(cellType1); - b.setData(cellType2); + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - board.addModifiedData(a); - board.addModifiedData(b); + /** + * Given a statement: A V B, where A is false and V is true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void FTUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/OrEliminationDirectRule/FTU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - if (cellType1 == ShortTruthTableCellType.FALSE - && cellType2 == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); - } - } - } - } - - /** - * Given a statement: A V B, where V is true - * - *

Asserts that setting both A and B is not a valid application of this rule. - * - * @throws InvalidFileFormatException - */ - @Test - public void UTUTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTU", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - ShortTruthTableCellType[] cellTypes = { - ShortTruthTableCellType.TRUE, ShortTruthTableCellType.FALSE, ShortTruthTableCellType.UNKNOWN - }; - - for (ShortTruthTableCellType cellType1 : cellTypes) { - for (ShortTruthTableCellType cellType2 : cellTypes) { ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell cell = board.getCell(2, 0); + + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + Assert.assertNull(RULE.checkRule(transition)); + + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); + Assert.assertNotNull(RULE.checkRule(transition)); + } - a.setData(cellType1); - b.setData(cellType2); + /** + * Given a statement: A V B, where B is false and V is true + * + *

Asserts that this is a valid application of the rule if and only if B is true. + * + * @throws InvalidFileFormatException + */ + @Test + public void UTFTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTF", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - board.addModifiedData(a); - board.addModifiedData(b); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(0, 0); + + cell.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(cell); + Assert.assertNull(RULE.checkRule(transition)); + cell.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(cell); Assert.assertNotNull(RULE.checkRule(transition)); - } } - } + + /** + * Given a statement: A V B, where V is false + * + *

Asserts that this is a valid application of the rule if and only if both A and B are + * false. + * + * @throws InvalidFileFormatException + */ + @Test + public void UFUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UFU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + + a.setData(cellType1); + b.setData(cellType2); + + board.addModifiedData(a); + board.addModifiedData(b); + + if (cellType1 == ShortTruthTableCellType.FALSE + && cellType2 == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } + } + + /** + * Given a statement: A V B, where V is true + * + *

Asserts that setting both A and B is not a valid application of this rule. + * + * @throws InvalidFileFormatException + */ + @Test + public void UTUTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/OrEliminationDirectRule/UTU", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + ShortTruthTableCellType[] cellTypes = { + ShortTruthTableCellType.TRUE, + ShortTruthTableCellType.FALSE, + ShortTruthTableCellType.UNKNOWN + }; + + for (ShortTruthTableCellType cellType1 : cellTypes) { + for (ShortTruthTableCellType cellType2 : cellTypes) { + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + + a.setData(cellType1); + b.setData(cellType2); + + board.addModifiedData(a); + board.addModifiedData(b); + + Assert.assertNotNull(RULE.checkRule(transition)); + } + } + } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java b/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java index 67a111da7..d5f9387eb 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/OrIntroductionTest.java @@ -15,91 +15,91 @@ import org.junit.Test; public class OrIntroductionTest { - private static final DirectRuleOrIntroduction RULE = new DirectRuleOrIntroduction(); - private static ShortTruthTable stt; + private static final DirectRuleOrIntroduction RULE = new DirectRuleOrIntroduction(); + private static ShortTruthTable stt; - @BeforeClass - public static void setup() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setup() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Given a statement: A V B - * - *

Asserts that if at least 1 of A or B is true, then this is a valid application of the rule - * if and only if V is true. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void TrueOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; - trueOrTestHelper(path + "TUT"); - trueOrTestHelper(path + "TUU"); - trueOrTestHelper(path + "UUT"); - trueOrTestHelper(path + "TUF"); - trueOrTestHelper(path + "FUT"); - } + /** + * Given a statement: A V B + * + *

Asserts that if at least 1 of A or B is true, then this is a valid application of the rule + * if and only if V is true. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void TrueOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; + trueOrTestHelper(path + "TUT"); + trueOrTestHelper(path + "TUU"); + trueOrTestHelper(path + "UUT"); + trueOrTestHelper(path + "TUF"); + trueOrTestHelper(path + "FUT"); + } - private void trueOrTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void trueOrTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell or = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell or = board.getCell(1, 0); - or.setData(ShortTruthTableCellType.TRUE); - board.addModifiedData(or); - Assert.assertNull(RULE.checkRule(transition)); + or.setData(ShortTruthTableCellType.TRUE); + board.addModifiedData(or); + Assert.assertNull(RULE.checkRule(transition)); - or.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(or); - Assert.assertNotNull(RULE.checkRule(transition)); - } + or.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(or); + Assert.assertNotNull(RULE.checkRule(transition)); + } - /** - * Given a statement: A V B - * - *

Asserts that setting V to false is a valid application of the rule if and only if both A and - * B are false. - * - * @param filePath The file path for test board setup. - * @throws InvalidFileFormatException - */ - @Test - public void FalseOrTest() throws InvalidFileFormatException { - String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; - String[] letters = {"T", "F", "U"}; - for (String first : letters) { - for (String second : letters) { - falseOrTestHelper(path + first + "U" + second); - } + /** + * Given a statement: A V B + * + *

Asserts that setting V to false is a valid application of the rule if and only if both A + * and B are false. + * + * @param filePath The file path for test board setup. + * @throws InvalidFileFormatException + */ + @Test + public void FalseOrTest() throws InvalidFileFormatException { + String path = "puzzles/shorttruthtable/rules/OrIntroductionDirectRule/"; + String[] letters = {"T", "F", "U"}; + for (String first : letters) { + for (String second : letters) { + falseOrTestHelper(path + first + "U" + second); + } + } } - } - private void falseOrTestHelper(String filePath) throws InvalidFileFormatException { - TestUtilities.importTestBoard(filePath, stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + private void falseOrTestHelper(String filePath) throws InvalidFileFormatException { + TestUtilities.importTestBoard(filePath, stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell a = board.getCell(0, 0); - ShortTruthTableCell b = board.getCell(2, 0); - ShortTruthTableCell or = board.getCell(1, 0); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell a = board.getCell(0, 0); + ShortTruthTableCell b = board.getCell(2, 0); + ShortTruthTableCell or = board.getCell(1, 0); - or.setData(ShortTruthTableCellType.FALSE); - board.addModifiedData(or); + or.setData(ShortTruthTableCellType.FALSE); + board.addModifiedData(or); - if (a.getType() == ShortTruthTableCellType.FALSE - && b.getType() == ShortTruthTableCellType.FALSE) { - Assert.assertNull(RULE.checkRule(transition)); - } else { - Assert.assertNotNull(RULE.checkRule(transition)); + if (a.getType() == ShortTruthTableCellType.FALSE + && b.getType() == ShortTruthTableCellType.FALSE) { + Assert.assertNull(RULE.checkRule(transition)); + } else { + Assert.assertNotNull(RULE.checkRule(transition)); + } } - } } diff --git a/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java b/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java index 3a9c749e7..d0c390785 100644 --- a/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java +++ b/src/test/java/puzzles/shorttruthtable/rules/TrueOrFalseCaseRuleTest.java @@ -18,66 +18,66 @@ public class TrueOrFalseCaseRuleTest { - private static final CaseRuleAtomic RULE = new CaseRuleAtomic(); - private static ShortTruthTable stt; + private static final CaseRuleAtomic RULE = new CaseRuleAtomic(); + private static ShortTruthTable stt; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - stt = new ShortTruthTable(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + stt = new ShortTruthTable(); + } - /** - * Tests the True or False case rule by ensuring that it results in two children, one that - * contains Statement as true and one that contains Statement as false. - */ - @Test - public void TwoBranchesTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/shorttruthtable/rules/TrueOrFalseCaseRule/Statement", stt); - TreeNode rootNode = stt.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * Tests the True or False case rule by ensuring that it results in two children, one that + * contains Statement as true and one that contains Statement as false. + */ + @Test + public void TwoBranchesTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/shorttruthtable/rules/TrueOrFalseCaseRule/Statement", stt); + TreeNode rootNode = stt.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); - ShortTruthTableCell cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, cell); + ShortTruthTableBoard board = (ShortTruthTableBoard) transition.getBoard(); + ShortTruthTableCell cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, cell); - // Make sure that the rule checks out - Assert.assertNull(RULE.checkRule(transition)); + // Make sure that the rule checks out + Assert.assertNull(RULE.checkRule(transition)); - // Make sure there are two branches - Assert.assertEquals(2, cases.size()); + // Make sure there are two branches + Assert.assertEquals(2, cases.size()); - ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); - ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); + ShortTruthTableBoard caseBoard1 = (ShortTruthTableBoard) cases.get(0); + ShortTruthTableBoard caseBoard2 = (ShortTruthTableBoard) cases.get(1); - ShortTruthTableCellType cellType1 = caseBoard1.getCell(0, 0).getType(); - ShortTruthTableCellType cellType2 = caseBoard2.getCell(0, 0).getType(); + ShortTruthTableCellType cellType1 = caseBoard1.getCell(0, 0).getType(); + ShortTruthTableCellType cellType2 = caseBoard2.getCell(0, 0).getType(); - // First assert the two cells are not equal, then verify that they are true - // or false. - Assert.assertNotEquals(cellType1, cellType2); - Assert.assertTrue( - cellType1.equals(ShortTruthTableCellType.TRUE) - || cellType1.equals(ShortTruthTableCellType.FALSE)); - Assert.assertTrue( - cellType2.equals(ShortTruthTableCellType.TRUE) - || cellType2.equals(ShortTruthTableCellType.FALSE)); + // First assert the two cells are not equal, then verify that they are true + // or false. + Assert.assertNotEquals(cellType1, cellType2); + Assert.assertTrue( + cellType1.equals(ShortTruthTableCellType.TRUE) + || cellType1.equals(ShortTruthTableCellType.FALSE)); + Assert.assertTrue( + cellType2.equals(ShortTruthTableCellType.TRUE) + || cellType2.equals(ShortTruthTableCellType.FALSE)); - // Verify the board dimensions are unchanged - Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); - Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); + // Verify the board dimensions are unchanged + Assert.assertEquals(caseBoard1.getHeight(), caseBoard2.getHeight(), board.getHeight()); + Assert.assertEquals(caseBoard1.getWidth(), caseBoard2.getWidth(), board.getWidth()); - // Verify that everywhere else on the board is unchanged - for (int i = 0; i < caseBoard1.getWidth(); i++) { - for (int j = 0; j < caseBoard1.getHeight(); j++) { - // Make sure not to check the one cell that should be different - if (i != 0 && j != 0) { - Assert.assertEquals( - caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + // Verify that everywhere else on the board is unchanged + for (int i = 0; i < caseBoard1.getWidth(); i++) { + for (int j = 0; j < caseBoard1.getHeight(); j++) { + // Make sure not to check the one cell that should be different + if (i != 0 && j != 0) { + Assert.assertEquals( + caseBoard1.getCell(i, j).getType(), caseBoard2.getCell(i, j).getType()); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java b/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java index 598e9fd9c..1fce24cf1 100644 --- a/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/CellForNumberCaseRuleTest.java @@ -17,238 +17,242 @@ public class CellForNumberCaseRuleTest { - private static final CellForNumberCaseRule RULE = new CellForNumberCaseRule(); - private static Skyscrapers skyscrapers; + private static final CellForNumberCaseRule RULE = new CellForNumberCaseRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - // basic, max cases - @Test - public void CellForNumberCaseRule_BasicEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // basic, max cases + @Test + public void CellForNumberCaseRule_BasicEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(false); + board.setDupeFlag(false); + board.setViewFlag(false); - ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); + ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); - Assert.assertEquals(board.getWidth(), cases.size()); + Assert.assertEquals(board.getWidth(), cases.size()); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, i); - changedCell.setData(1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, i); + changedCell.setData(1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // dupe, max cases - @Test - public void CellForNumberCaseRule_DupeEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // dupe, max cases + @Test + public void CellForNumberCaseRule_DupeEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); + ArrayList cases = RULE.getCasesFor(board, board.getNorthClues().get(0), 1); - Assert.assertEquals(board.getWidth(), cases.size()); + Assert.assertEquals(board.getWidth(), cases.size()); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, i); - changedCell.setData(1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, i); + changedCell.setData(1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // dupe, 1 case - @Test - public void CellForNumberCaseRule_DupeSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // dupe, 1 case + @Test + public void CellForNumberCaseRule_DupeSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + board.setDupeFlag(true); + board.setViewFlag(false); - board.setDupeFlag(true); - board.setViewFlag(false); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + Assert.assertEquals(1, cases.size()); - Assert.assertEquals(1, cases.size()); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + // dupe, no cases + @Test + public void CellForNumberCaseRule_DupeNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); - // dupe, no cases - @Test - public void CellForNumberCaseRule_DupeNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + board.setDupeFlag(true); + board.setViewFlag(false); - board.setDupeFlag(true); - board.setViewFlag(false); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + Assert.assertEquals(0, cases.size()); + } - Assert.assertEquals(0, cases.size()); - } + // visibility, max cases + @Test + public void CellForNumberCaseRule_ViewEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - // visibility, max cases - @Test - public void CellForNumberCaseRule_ViewEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + board.setDupeFlag(false); + board.setViewFlag(true); - board.setDupeFlag(false); - board.setViewFlag(true); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(1), 1); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(1), 1); + Assert.assertEquals(board.getWidth(), cases.size()); - Assert.assertEquals(board.getWidth(), cases.size()); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(i, 1); + changedCell.setData(1); + expected.addModifiedData(changedCell); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(i, 1); - changedCell.setData(1); - expected.addModifiedData(changedCell); + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; + Assert.assertTrue(exists); } - } - - Assert.assertTrue(exists); } - } - // visibility, 1 Case, direct - @Test - public void CellForNumberCaseRule_ViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // visibility, 1 Case, direct + @Test + public void CellForNumberCaseRule_ViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, 1 Case, implied - @Test - public void CellForNumberCaseRule_ImpliedViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // visibility, 1 Case, implied + @Test + public void CellForNumberCaseRule_ImpliedViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(0), 5); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(0), 5); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(4, 0); - changedCell.setData(5); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(4, 0); + changedCell.setData(5); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, no cases - @Test - public void CellForNumberCaseRule_ViewNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + // visibility, no cases + @Test + public void CellForNumberCaseRule_ViewNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); + ArrayList cases = RULE.getCasesFor(board, board.getWestClues().get(3), 1); - Assert.assertEquals(0, cases.size()); - } + Assert.assertEquals(0, cases.size()); + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java index cf74604f8..a7bb63a08 100644 --- a/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/DuplicateNumberContradictionTest.java @@ -14,143 +14,149 @@ public class DuplicateNumberContradictionTest { - private static final DuplicateNumberContradictionRule RULE = - new DuplicateNumberContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void DuplicateNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + private static final DuplicateNumberContradictionRule RULE = + new DuplicateNumberContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void DuplicateNumberContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void DuplicateNumberContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - // invalid board, no cont - @Test - public void DuplicateNumberContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + // correct board, no cont + @Test + public void DuplicateNumberContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - // on row - @Test - public void DuplicateNumberContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if ((k == 0 || k == 1) && i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // invalid board, no cont + @Test + public void DuplicateNumberContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - } } - } - - // on col - @Test - public void DuplicateNumberContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 0 && (i == 0 || i == 1)) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // on row + @Test + public void DuplicateNumberContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if ((k == 0 || k == 1) && i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } + } + } + + // on col + @Test + public void DuplicateNumberContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/ColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 0 && (i == 0 || i == 1)) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // multitudes - @Test - public void DuplicateNumberContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/AllContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + // multitudes + @Test + public void DuplicateNumberContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/AllContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java index 5fbadf555..a5a07f997 100644 --- a/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/ExceedingVisibilityContradictionTest.java @@ -14,133 +14,137 @@ public class ExceedingVisibilityContradictionTest { - private static final ExceedingVisibilityContradictionRule RULE = - new ExceedingVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void ExceedingVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + private static final ExceedingVisibilityContradictionRule RULE = + new ExceedingVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void ExceedingVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void ExceedingVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // invalid board, no cont - @Test - public void ExceedingVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); + // correct board, no cont + @Test + public void ExceedingVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on row - @Test - public void ExceedingVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // invalid board, no cont + @Test + public void ExceedingVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on col - @Test - public void ExceedingVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // on row + @Test + public void ExceedingVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } + } + + // on col + @Test + public void ExceedingVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - // multitudes - @Test - public void ExceedingVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void ExceedingVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java index a59fa3746..ee0f3349a 100644 --- a/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/InsufficientVisibilityContradictionTest.java @@ -14,133 +14,137 @@ public class InsufficientVisibilityContradictionTest { - private static final InsufficientVisibilityContradictionRule RULE = - new InsufficientVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void InsufficientVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + private static final InsufficientVisibilityContradictionRule RULE = + new InsufficientVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void InsufficientVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void InsufficientVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // invalid board, no cont - @Test - public void InsufficientVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", skyscrapers); + // correct board, no cont + @Test + public void InsufficientVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on row - @Test - public void InsufficientVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // invalid board, no cont + @Test + public void InsufficientVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/DuplicateNumberContradictionRule/RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on col - @Test - public void InsufficientVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // on row + @Test + public void InsufficientVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } + } + + // on col + @Test + public void InsufficientVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/FullColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - // multitudes - @Test - public void InsufficientVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void InsufficientVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java index 78ba581b9..76540f010 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastSingularCellDirectTest.java @@ -16,213 +16,215 @@ public class LastSingularCellDirectTest { - private static final LastSingularCellDirectRule RULE = new LastSingularCellDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastSingularCellDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastSingularCellDirectRule RULE = new LastSingularCellDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastSingularCellDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // full col - @Test - public void LastSingularCellDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // full col + @Test + public void LastSingularCellDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty row/col - @Test - public void LastSingularCellDirectRule_EmptyTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/0-3Opening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 1); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty row/col + @Test + public void LastSingularCellDirectRule_EmptyTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/0-3Opening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 1); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 row - @Test - public void LastSingularCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 row + @Test + public void LastSingularCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 col - @Test - public void LastSingularCellDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 col + @Test + public void LastSingularCellDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 row - @Test - public void LastSingularCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 row + @Test + public void LastSingularCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 col - @Test - public void LastSingularCellDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 0); - cell.setData(4); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 col + @Test + public void LastSingularCellDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularCellDirectRule/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 0); + cell.setData(4); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java index 5cecb9b4c..6b99994a2 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastSingularNumberDirectTest.java @@ -16,126 +16,132 @@ public class LastSingularNumberDirectTest { - private static final LastSingularNumberDirectRule RULE = new LastSingularNumberDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row / empty col - @Test - public void LastSingularNumberDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastSingularNumberDirectRule RULE = new LastSingularNumberDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row / empty col + @Test + public void LastSingularNumberDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // full col / empty row - @Test - public void LastSingularNumberDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // full col / empty row + @Test + public void LastSingularNumberDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 row / 1-2 col - @Test - public void LastSingularNumberDirectRule_PartialRowColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 1); - cell.setData(4); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 row / 1-2 col + @Test + public void LastSingularNumberDirectRule_PartialRowColTest1() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1RowOpening", + skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 1); + cell.setData(4); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 col / 1-2 row - @Test - public void LastSingularNumberDirectRule_PartialRowColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 col / 1-2 row + @Test + public void LastSingularNumberDirectRule_PartialRowColTest2() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastSingularNumberDirectRule/2-1ColOpening", + skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java index 3fe530a32..756ff7468 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastVisibleCellDirectTest.java @@ -16,236 +16,238 @@ public class LastVisibleCellDirectTest { - private static final LastVisibleCellDirectRule RULE = new LastVisibleCellDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastVisibleCellDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastVisibleCellDirectRule RULE = new LastVisibleCellDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastVisibleCellDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // full col - @Test - public void LastVisibleCellDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // full col + @Test + public void LastVisibleCellDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty row - @Test - public void LastVisibleCellDirectRule_EmptyRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty row + @Test + public void LastVisibleCellDirectRule_EmptyRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty col - @Test - public void LastVisibleCellDirectRule_EmptyColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 4); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty col + @Test + public void LastVisibleCellDirectRule_EmptyColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 4); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 row - public void LastVisibleCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 row + public void LastVisibleCellDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 col - public void LastVisibleCellDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 2); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 col + public void LastVisibleCellDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 2); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 row - public void LastVisibleCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 row + public void LastVisibleCellDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 col - public void LastVisibleCellDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 col + public void LastVisibleCellDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java index 65311f2ca..c628b89da 100644 --- a/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/LastVisibleNumberDirectTest.java @@ -16,236 +16,238 @@ public class LastVisibleNumberDirectTest { - private static final LastVisibleNumberDirectRule RULE = new LastVisibleNumberDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // full row - @Test - public void LastVisibleNumberDirectRule_FullRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 3); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastVisibleNumberDirectRule RULE = new LastVisibleNumberDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } + + // full row + @Test + public void LastVisibleNumberDirectRule_FullRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 3); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // full col - @Test - public void LastVisibleNumberDirectRule_FullColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 1); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // full col + @Test + public void LastVisibleNumberDirectRule_FullColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 1); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty row - @Test - public void LastVisibleNumberDirectRule_EmptyRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty row + @Test + public void LastVisibleNumberDirectRule_EmptyRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // empty col - @Test - public void LastVisibleNumberDirectRule_EmptyColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(3, 4); - cell.setData(5); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // empty col + @Test + public void LastVisibleNumberDirectRule_EmptyColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(3, 4); + cell.setData(5); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 row - public void LastVisibleNumberDirectRule_PartialRowTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 2); - cell.setData(3); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 row + public void LastVisibleNumberDirectRule_PartialRowTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 2); + cell.setData(3); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 1-2 col - public void LastVisibleNumberDirectRule_PartialColTest1() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(2, 2); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 1-2 col + public void LastVisibleNumberDirectRule_PartialColTest1() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/1-2ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(2, 2); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 row - public void LastVisibleNumberDirectRule_PartialRowTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 1); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 row + public void LastVisibleNumberDirectRule_PartialRowTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1ColOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 1); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2-1 col - public void LastVisibleNumberDirectRule_PartialColTest2() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(0, 2); - cell.setData(1); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2-1 col + public void LastVisibleNumberDirectRule_PartialColTest2() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/LastVisibleDirectRules/2-1RowOpening", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(0, 2); + cell.setData(1); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java b/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java index 2ba6d7ad7..ed70fce40 100644 --- a/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/NEdgeDirectTest.java @@ -16,127 +16,127 @@ public class NEdgeDirectTest { - private static final NEdgeDirectRule RULE = new NEdgeDirectRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // -> row, empty -> full - @Test - public void NEdgeDirectRule_RightRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < 5; i++) { - SkyscrapersCell cell = board.getCell(i, 0); - cell.setData(i + 1); - board.addModifiedData(cell); + private static final NEdgeDirectRule RULE = new NEdgeDirectRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - Assert.assertNull(RULE.checkRule(transition)); + // -> row, empty -> full + @Test + public void NEdgeDirectRule_RightRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < 5; i++) { + SkyscrapersCell cell = board.getCell(i, 0); + cell.setData(i + 1); + board.addModifiedData(cell); + } + + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // <-row, partial -> partial - @Test - public void NEdgeDirectRule_LeftRowTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/LeftRowPartial", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - SkyscrapersCell cell = board.getCell(1, 3); - cell.setData(2); - - board.addModifiedData(cell); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // <-row, partial -> partial + @Test + public void NEdgeDirectRule_LeftRowTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/LeftRowPartial", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersCell cell = board.getCell(1, 3); + cell.setData(2); + + board.addModifiedData(cell); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - } - } - - // up col, partial -> full - @Test - public void NEdgeDirectRule_UpColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/UpColPartial", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < 2; i++) { - SkyscrapersCell cell = board.getCell(1, i); - cell.setData(i + 1); - board.addModifiedData(cell); } - Assert.assertNull(RULE.checkRule(transition)); + // up col, partial -> full + @Test + public void NEdgeDirectRule_UpColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/UpColPartial", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < 2; i++) { + SkyscrapersCell cell = board.getCell(1, i); + cell.setData(i + 1); + board.addModifiedData(cell); + } + + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 1 && i < 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 1 && i < 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - } - } - - // down col, empty -> partial - @Test - public void NEdgeDirectRule_DownColTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/NEdgeDirectRule/DownColEmpty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 1; i < 5; i++) { - SkyscrapersCell cell = board.getCell(3, i); - cell.setData(5 - i); - board.addModifiedData(cell); } - Assert.assertNull(RULE.checkRule(transition)); + // down col, empty -> partial + @Test + public void NEdgeDirectRule_DownColTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/NEdgeDirectRule/DownColEmpty", skyscrapers); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 1; i < 5; i++) { + SkyscrapersCell cell = board.getCell(3, i); + cell.setData(5 - i); + board.addModifiedData(cell); + } + + Assert.assertNull(RULE.checkRule(transition)); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 3 && i > 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 3 && i > 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java b/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java index f4a298c7c..b417a5227 100644 --- a/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/NumberForCellCaseRuleTest.java @@ -17,212 +17,216 @@ public class NumberForCellCaseRuleTest { - private static final NumberForCellCaseRule RULE = new NumberForCellCaseRule(); - private static Skyscrapers skyscrapers; + private static final NumberForCellCaseRule RULE = new NumberForCellCaseRule(); + private static Skyscrapers skyscrapers; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); + } - // basic, max cases - @Test - public void NumberForCellCaseRule_BasicEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // basic, max cases + @Test + public void NumberForCellCaseRule_BasicEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(false); + board.setDupeFlag(false); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); + ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); - Assert.assertEquals(board.getWidth(), cases.size()); + Assert.assertEquals(board.getWidth(), cases.size()); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, 0); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, 0); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // dupe, max cases - @Test - public void NumberForCellCaseRule_DupeEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // dupe, max cases + @Test + public void NumberForCellCaseRule_DupeEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); + ArrayList cases = RULE.getCases(board, board.getCell(0, 0)); - Assert.assertEquals(board.getWidth(), cases.size()); + Assert.assertEquals(board.getWidth(), cases.size()); - for (int i = 0; i < board.getWidth(); i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(0, 0); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth(); i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(0, 0); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // dupe, 1 case - @Test - public void NumberForCellCaseRule_DupeSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // dupe, 1 case + @Test + public void NumberForCellCaseRule_DupeSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // dupe, no cases - @Test - public void NumberForCellCaseRule_DupeNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + // dupe, no cases + @Test + public void NumberForCellCaseRule_DupeNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(true); - board.setViewFlag(false); + board.setDupeFlag(true); + board.setViewFlag(false); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(0, cases.size()); - } + Assert.assertEquals(0, cases.size()); + } - // visibility, max cases - @Test - public void NumberForCellCaseRule_ViewEmpty() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); + // visibility, max cases + @Test + public void NumberForCellCaseRule_ViewEmpty() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board, board.getCell(1, 4)); + ArrayList cases = RULE.getCases(board, board.getCell(1, 4)); - Assert.assertEquals(4, cases.size()); + Assert.assertEquals(4, cases.size()); - for (int i = 0; i < board.getWidth() - 1; i++) { - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(1, 4); - changedCell.setData(i + 1); - expected.addModifiedData(changedCell); + for (int i = 0; i < board.getWidth() - 1; i++) { + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(1, 4); + changedCell.setData(i + 1); + expected.addModifiedData(changedCell); - boolean exists = false; - for (Board caseBoard : cases) { - if (expected.equalsBoard(caseBoard)) { - exists = true; - break; - } - } + boolean exists = false; + for (Board caseBoard : cases) { + if (expected.equalsBoard(caseBoard)) { + exists = true; + break; + } + } - Assert.assertTrue(exists); + Assert.assertTrue(exists); + } } - } - // visibility, 1 case - @Test - public void NumberForCellCaseRule_ViewSingular() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); + // visibility, 1 case + @Test + public void NumberForCellCaseRule_ViewSingular() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/common/3-0RowOpening", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(1, cases.size()); + Assert.assertEquals(1, cases.size()); - SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); - PuzzleElement changedCell = expected.getCell(2, 3); - changedCell.setData(1); - expected.addModifiedData(changedCell); + SkyscrapersBoard expected = ((SkyscrapersBoard) transition.getBoard()).copy(); + PuzzleElement changedCell = expected.getCell(2, 3); + changedCell.setData(1); + expected.addModifiedData(changedCell); - Assert.assertTrue(expected.equalsBoard(cases.get(0))); - } + Assert.assertTrue(expected.equalsBoard(cases.get(0))); + } - // visibility, no cases - @Test - public void NumberForCellCaseRule_ViewNone() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); + // visibility, no cases + @Test + public void NumberForCellCaseRule_ViewNone() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - board.setDupeFlag(false); - board.setViewFlag(true); + board.setDupeFlag(false); + board.setViewFlag(true); - ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); + ArrayList cases = RULE.getCases(board, board.getCell(2, 3)); - Assert.assertEquals(0, cases.size()); - } + Assert.assertEquals(0, cases.size()); + } } diff --git a/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java index b615ce7fb..ec49a8194 100644 --- a/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/PreemptiveVisibilityContradictionTest.java @@ -14,155 +14,157 @@ public class PreemptiveVisibilityContradictionTest { - private static final PreemptiveVisibilityContradictionRule RULE = - new PreemptiveVisibilityContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void PreemptiveVisibilityContradictionRule_EmptyBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + private static final PreemptiveVisibilityContradictionRule RULE = + new PreemptiveVisibilityContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void PreemptiveVisibilityContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void PreemptiveVisibilityContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // invalid board, no cont - @Test - public void PreemptiveVisibilityContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); + // correct board, no cont + @Test + public void PreemptiveVisibilityContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on row - @Test - public void PreemptiveVisibilityContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedRowContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // invalid board, no cont + @Test + public void PreemptiveVisibilityContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // on col - @Test - public void PreemptiveVisibilityContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedColContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // on row + @Test + public void PreemptiveVisibilityContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedRowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } + } + + // on col + @Test + public void PreemptiveVisibilityContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - // multitudes - @Test - public void PreemptiveVisibilityContradictionRule_AllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", skyscrapers); + // multitudes + @Test + public void PreemptiveVisibilityContradictionRule_AllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/AllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // multitudes - preemptive - @Test - public void PreemptiveVisibilityContradictionRule_ImpliedAllContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); + // multitudes - preemptive + @Test + public void PreemptiveVisibilityContradictionRule_ImpliedAllContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java index f9509990a..398bba6e5 100644 --- a/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/UnresolvedCellContradictionTest.java @@ -14,147 +14,152 @@ public class UnresolvedCellContradictionTest { - private static final UnresolvedCellContradictionRule RULE = new UnresolvedCellContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void UnresolvedCellContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + private static final UnresolvedCellContradictionRule RULE = + new UnresolvedCellContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void UnresolvedCellContradictionRule_SolvedBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void UnresolvedCellContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } + } + + // correct board, no cont + @Test + public void UnresolvedCellContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - // invalid board, no cont - @Test - public void UnresolvedCellContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + // invalid board, no cont + @Test + public void UnresolvedCellContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } - - // 3 in a row, 1 in col creates contradiction - @Test - public void UnresolvedCellContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 2 && i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 3 in a row, 1 in col creates contradiction + @Test + public void UnresolvedCellContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 2 && i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 3 in a col, 1 in row creates contradiction - @Test - public void UnresolvedCellContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 1 && i == 0) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 3 in a col, 1 in row creates contradiction + @Test + public void UnresolvedCellContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 1 && i == 0) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - // 2 in a col, 2 in row creates cell contradiction - @Test - public void UnresolvedCellContradictionRule_MixedContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if (k == 2 && i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + // 2 in a col, 2 in row creates cell contradiction + @Test + public void UnresolvedCellContradictionRule_MixedContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2CellContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if (k == 2 && i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java b/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java index eb6cf566c..17139fb60 100644 --- a/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java +++ b/src/test/java/puzzles/skyscrapers/rules/UnresolvedNumberContradictionTest.java @@ -14,162 +14,165 @@ public class UnresolvedNumberContradictionTest { - private static final UnresolvedNumberContradictionRule RULE = - new UnresolvedNumberContradictionRule(); - private static Skyscrapers skyscrapers; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - skyscrapers = new Skyscrapers(); - } - - // empty - @Test - public void UnresolvedNumberContradictionRule_EmptyBoardTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + private static final UnresolvedNumberContradictionRule RULE = + new UnresolvedNumberContradictionRule(); + private static Skyscrapers skyscrapers; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + skyscrapers = new Skyscrapers(); } - } - // correct board, no cont - @Test - public void UnresolvedNumberContradictionRule_SolvedBoardTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); + // empty + @Test + public void UnresolvedNumberContradictionRule_EmptyBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/empty", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - // invalid board, no cont - @Test - public void UnresolvedNumberContradictionRule_OtherContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", - skyscrapers); + // correct board, no cont + @Test + public void UnresolvedNumberContradictionRule_SolvedBoardTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard("puzzles/skyscrapers/rules/common/Solved", skyscrapers); - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // 3 in a row, 1 in col creates contradiction - @Test - public void UnresolvedNumberContradictionRule_RowContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // invalid board, no cont + @Test + public void UnresolvedNumberContradictionRule_OtherContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/VisibilityContradictionRules/ImpliedAllContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNotNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } } - } - - // 3 in a col, 1 in row creates contradiction - @Test - public void UnresolvedNumberContradictionRule_ColContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // 3 in a row, 1 in col creates contradiction + @Test + public void UnresolvedNumberContradictionRule_RowContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1RowContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - - // 2 in a row/col, 2 in other row/cols creates number contradiction - @Test - public void UnresolvedNumberContradictionRule_TwoContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2NumberContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 3) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // 3 in a col, 1 in row creates contradiction + @Test + public void UnresolvedNumberContradictionRule_ColContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/3-1ColContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } + } + + // 2 in a row/col, 2 in other row/cols creates number contradiction + @Test + public void UnresolvedNumberContradictionRule_TwoContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/2-2NumberContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 3) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } - - // 1 in a row/col, 3 in other row/cols creates number contradiction - @Test - public void UnresolvedNumberContradictionRule_ThreeContradictionTest() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/skyscrapers/rules/UnresolvedContradictionRules/1-3NumberContradiction", - skyscrapers); - - TreeNode rootNode = skyscrapers.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); - - SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); - for (int i = 0; i < board.getHeight(); i++) { - if (i == 1 || i == 2) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); - } + + // 1 in a row/col, 3 in other row/cols creates number contradiction + @Test + public void UnresolvedNumberContradictionRule_ThreeContradictionTest() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/skyscrapers/rules/UnresolvedContradictionRules/1-3NumberContradiction", + skyscrapers); + + TreeNode rootNode = skyscrapers.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + Assert.assertNull(RULE.checkContradiction((SkyscrapersBoard) transition.getBoard())); + + SkyscrapersBoard board = (SkyscrapersBoard) transition.getBoard(); + for (int i = 0; i < board.getHeight(); i++) { + if (i == 1 || i == 2) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(i, i))); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java index df343b6b9..38284c410 100644 --- a/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/EmptyFieldDirectRuleTest.java @@ -17,259 +17,259 @@ public class EmptyFieldDirectRuleTest { - private static final EmptyFieldDirectRule RULE = new EmptyFieldDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - // creates a 3x3 puzzle with no trees - // make the (1,1) tile GRASS - // checks if tiles logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyField", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + private static final EmptyFieldDirectRule RULE = new EmptyFieldDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + // creates a 3x3 puzzle with no trees + // make the (1,1) tile GRASS + // checks if tiles logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyField", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - // creates a 3x3 puzzle with 4 trees - // trees are at (0,0), (2,0), (0,2), and (2,2) - // make the (1,1) tile GRASS. - // checks if tiles logically follow the EmptyFieldDirectRule - @Test - public void DiagonalTreeTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/DiagonalTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + // creates a 3x3 puzzle with 4 trees + // trees are at (0,0), (2,0), (0,2), and (2,2) + // make the (1,1) tile GRASS. + // checks if tiles logically follow the EmptyFieldDirectRule + @Test + public void DiagonalTreeTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/DiagonalTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - // creates a 3x3 puzzle with 4 trees - // trees are at (0,1), (1,0), (1,2), and (2,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFail() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 4 trees + // trees are at (0,1), (1,0), (1,2), and (2,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFail() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - - // creates a 3x3 puzzle with 1 tree - // tree is at (1,0) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailTop() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailTop", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 1 tree + // tree is at (1,0) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailTop() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailTop", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - - // creates a 3x3 puzzle with 1 tree - // tree is at (1,2) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailTopBottom() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailBottom", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 1 tree + // tree is at (1,2) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailTopBottom() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailBottom", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - - // creates a 3x3 puzzle with 1 tree - // tree is at (0,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 1 tree + // tree is at (0,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - - // creates a 3x3 puzzle with 1 tree - // tree is at (2,1) - // make the (1,1) tile GRASS. - // checks if tiles don't logically follow the EmptyFieldDirectRule - @Test - public void EmptyFieldTestFailRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering breaking the EmptyField rule - TreeTentCell cell1 = board.getCell(1, 1); - cell1.setData(TreeTentType.GRASS); - board.addModifiedData(cell1); - - // confirm there is not a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); - - // the cells should not follow the rule - TreeTentCell c; - for (int i = 0; i < board.getWidth(); i++) { - for (int j = 0; j < board.getHeight(); j++) { - c = board.getCell(j, i); - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } + + // creates a 3x3 puzzle with 1 tree + // tree is at (2,1) + // make the (1,1) tile GRASS. + // checks if tiles don't logically follow the EmptyFieldDirectRule + @Test + public void EmptyFieldTestFailRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/EmptyFieldDirectRule/EmptyFieldFailRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering breaking the EmptyField rule + TreeTentCell cell1 = board.getCell(1, 1); + cell1.setData(TreeTentType.GRASS); + board.addModifiedData(cell1); + + // confirm there is not a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // the cells should not follow the rule + TreeTentCell c; + for (int i = 0; i < board.getWidth(); i++) { + for (int j = 0; j < board.getHeight(); j++) { + c = board.getCell(j, i); + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java index 45a1add86..0783ab8b8 100644 --- a/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/FinishWithGrassDirectRuleTest.java @@ -19,350 +19,350 @@ public class FinishWithGrassDirectRuleTest { - private static final FinishWithGrassDirectRule RULE = new FinishWithGrassDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles - * horizontal of the tent at (1,0) and (2,0) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassHorizontalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final FinishWithGrassDirectRule RULE = new FinishWithGrassDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); } - } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles - * vertical of the tent at (0,1) and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassVerticalTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles + * horizontal of the tent at (1,0) and (2,0) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassHorizontalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - /** - * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles at - * (1,0), (2,0), (0,1), and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithGrassTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.GRASS); - TreeTentCell cell3 = board.getCell(0, 1); - cell3.setData(TreeTentType.GRASS); - TreeTentCell cell4 = board.getCell(0, 2); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles + * vertical of the tent at (0,1) and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassVerticalTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } - } - } - - /** - * 3x3 TreeTent puzzle with no tents Tests FinishWithGrassDirectRule on GRASS tiles GRASS tiles - * fill entire board - * - * @throws InvalidFileFormatException - */ - @Test - public void NoTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/NoTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - List cells = new ArrayList(); - for (int i = 0; i < board.getWidth(); i++) { - for (int k = 0; k < board.getHeight(); k++) { - TreeTentCell c = board.getCell(i, k); - c.setData(TreeTentType.GRASS); - cells.add(c); - } } - for (TreeTentCell c : cells) { - board.addModifiedData(c); + /** + * 3x3 TreeTent puzzle with a tent at (0,0) Tests FinishWithGrassDirectRule on GRASS tiles at + * (1,0), (2,0), (0,1), and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithGrassTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/CornerTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.GRASS); + TreeTentCell cell3 = board.getCell(0, 1); + cell3.setData(TreeTentType.GRASS); + TreeTentCell cell4 = board.getCell(0, 2); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } + } } - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); + /** + * 3x3 TreeTent puzzle with no tents Tests FinishWithGrassDirectRule on GRASS tiles GRASS tiles + * fill entire board + * + * @throws InvalidFileFormatException + */ + @Test + public void NoTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/NoTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + List cells = new ArrayList(); + for (int i = 0; i < board.getWidth(); i++) { + for (int k = 0; k < board.getHeight(); k++) { + TreeTentCell c = board.getCell(i, k); + c.setData(TreeTentType.GRASS); + cells.add(c); + } + } - // all cells should change following the rule - for (TreeTentCell c : cells) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } - } - - /** - * 3x3 TreeTent puzzle with a tent at (1,1) Tests FinishWithGrassDirectRule on GRASS tiles - * surrounding the tent at (1,0), (0,1), (2,1), and (1,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void MiddleTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/MiddleTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(0, 1); - TreeTentCell cell3 = board.getCell(2, 1); - TreeTentCell cell4 = board.getCell(1, 2); - - cell1.setData(TreeTentType.GRASS); - cell2.setData(TreeTentType.GRASS); - cell3.setData(TreeTentType.GRASS); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + for (TreeTentCell c : cells) { + board.addModifiedData(c); + } + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // all cells should change following the rule + for (TreeTentCell c : cells) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); } - } - } - } - - /** - * 3x3 TreeTent puzzle with missing tents Tests FinishWithGrassDirectRule on GRASS tiles filling - * the puzzle all GRASS tiles should fail the FinishWithGrassDirectRule - * - * @throws InvalidFileFormatException - */ - @Test - public void FailTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/FailTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells not following the FinishWithGrass rule - List cells = new ArrayList(); - for (int i = 0; i < board.getWidth(); i++) { - for (int k = 0; k < board.getHeight(); k++) { - TreeTentCell c = board.getCell(i, k); - c.setData(TreeTentType.GRASS); - cells.add(c); - } } - for (TreeTentCell c : cells) { - board.addModifiedData(c); + /** + * 3x3 TreeTent puzzle with a tent at (1,1) Tests FinishWithGrassDirectRule on GRASS tiles + * surrounding the tent at (1,0), (0,1), (2,1), and (1,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void MiddleTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/MiddleTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(0, 1); + TreeTentCell cell3 = board.getCell(2, 1); + TreeTentCell cell4 = board.getCell(1, 2); + + cell1.setData(TreeTentType.GRASS); + cell2.setData(TreeTentType.GRASS); + cell3.setData(TreeTentType.GRASS); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } + } } - // confirm there is a logical following of the EmptyField rule - Assert.assertNotNull(RULE.checkRule(transition)); + /** + * 3x3 TreeTent puzzle with missing tents Tests FinishWithGrassDirectRule on GRASS tiles filling + * the puzzle all GRASS tiles should fail the FinishWithGrassDirectRule + * + * @throws InvalidFileFormatException + */ + @Test + public void FailTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/FailTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells not following the FinishWithGrass rule + List cells = new ArrayList(); + for (int i = 0; i < board.getWidth(); i++) { + for (int k = 0; k < board.getHeight(); k++) { + TreeTentCell c = board.getCell(i, k); + c.setData(TreeTentType.GRASS); + cells.add(c); + } + } - // all cells should fail the rule test - for (TreeTentCell c : cells) { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + for (TreeTentCell c : cells) { + board.addModifiedData(c); + } + + // confirm there is a logical following of the EmptyField rule + Assert.assertNotNull(RULE.checkRule(transition)); + + // all cells should fail the rule test + for (TreeTentCell c : cells) { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } } - } - - /** - * 7x7 TreeTent puzzle with multiple tents spaced out Tests FinishWithGrassDirectRule on GRASS - * tiles between the tents at (0,3), (2,3), (4,3), and (6,3) - * - * @throws InvalidFileFormatException - */ - @Test - public void SpacedOutTentTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithGrassDirectRule/SpacedOutTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - // get board state - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - // change the board's cells considering the FinishWithGrass rule - TreeTentCell cell1 = board.getCell(0, 3); - TreeTentCell cell2 = board.getCell(2, 3); - TreeTentCell cell3 = board.getCell(4, 3); - TreeTentCell cell4 = board.getCell(6, 3); - - cell1.setData(TreeTentType.GRASS); - cell2.setData(TreeTentType.GRASS); - cell3.setData(TreeTentType.GRASS); - cell4.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - // confirm there is a logical following of the EmptyField rule - Assert.assertNull(RULE.checkRule(transition)); - - // only the cell above should change following the rule - TreeTentCell c; - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - c = board.getCell(k, i); - if (c.getLocation().equals(cell1.getLocation()) - || c.getLocation().equals(cell2.getLocation()) - || c.getLocation().equals(cell3.getLocation()) - || c.getLocation().equals(cell4.getLocation())) { - // logically follows - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - // does not use the rule to logically follow - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 7x7 TreeTent puzzle with multiple tents spaced out Tests FinishWithGrassDirectRule on GRASS + * tiles between the tents at (0,3), (2,3), (4,3), and (6,3) + * + * @throws InvalidFileFormatException + */ + @Test + public void SpacedOutTentTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithGrassDirectRule/SpacedOutTent", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + // get board state + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + // change the board's cells considering the FinishWithGrass rule + TreeTentCell cell1 = board.getCell(0, 3); + TreeTentCell cell2 = board.getCell(2, 3); + TreeTentCell cell3 = board.getCell(4, 3); + TreeTentCell cell4 = board.getCell(6, 3); + + cell1.setData(TreeTentType.GRASS); + cell2.setData(TreeTentType.GRASS); + cell3.setData(TreeTentType.GRASS); + cell4.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + // confirm there is a logical following of the EmptyField rule + Assert.assertNull(RULE.checkRule(transition)); + + // only the cell above should change following the rule + TreeTentCell c; + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + c = board.getCell(k, i); + if (c.getLocation().equals(cell1.getLocation()) + || c.getLocation().equals(cell2.getLocation()) + || c.getLocation().equals(cell3.getLocation()) + || c.getLocation().equals(cell4.getLocation())) { + // logically follows + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + // does not use the rule to logically follow + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } } diff --git a/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java index 9903a9685..652af615f 100644 --- a/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/FinishWithTentsDirectRuleTest.java @@ -18,335 +18,337 @@ public class FinishWithTentsDirectRuleTest { - private static final FinishWithTentsDirectRule RULE = new FinishWithTentsDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles - * horizontal of the GRASS tile at (1,0) and (2,0) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithHorizontalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithHorizontalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.TENT); - TreeTentCell cell2 = board.getCell(2, 0); - cell2.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); - } - } + private static final FinishWithTentsDirectRule RULE = new FinishWithTentsDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); } - } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles - * vertical of the GRASS tile at (0,1) and (0,2) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithVerticalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithVerticalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.TENT); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles + * horizontal of the GRASS tile at (1,0) and (2,0) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithHorizontalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithHorizontalTents", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.TENT); + TreeTentCell cell2 = board.getCell(2, 0); + cell2.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - /** - * 3x3 TreeTent puzzle with a GRASS tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the GRASS tile at (1,0), (1,2), (0,1), and (2,1) - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 2); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(2, 1); - - cell1.setData(TreeTentType.TENT); - cell2.setData(TreeTentType.TENT); - cell3.setData(TreeTentType.TENT); - cell4.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation()) - || (c.getLocation()).equals(cell3.getLocation()) - || (c.getLocation()).equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (0,0) Tests FinishWithTentsDirectRule on TENT tiles + * vertical of the GRASS tile at (0,1) and (0,2) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithVerticalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithVerticalTents", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.TENT); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) - * - * @throws InvalidFileFormatException - */ - @Test - public void AdditionalTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/AdditionalTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 2); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(2, 1); - - cell1.setData(TreeTentType.TENT); - cell2.setData(TreeTentType.TENT); - cell3.setData(TreeTentType.TENT); - cell4.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - board.addModifiedData(cell4); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - if ((c.getLocation()).equals(cell1.getLocation()) - || (c.getLocation()).equals(cell2.getLocation()) - || (c.getLocation()).equals(cell3.getLocation()) - || (c.getLocation()).equals(cell4.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, c)); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + + /** + * 3x3 TreeTent puzzle with a GRASS tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the GRASS tile at (1,0), (1,2), (0,1), and (2,1) + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 2); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(2, 1); + + cell1.setData(TreeTentType.TENT); + cell2.setData(TreeTentType.TENT); + cell3.setData(TreeTentType.TENT); + cell4.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation()) + || (c.getLocation()).equals(cell3.getLocation()) + || (c.getLocation()).equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } } - } } - } - - /** - * Empty 3x3 TreeTent puzzle Tests FinishWithTentsDirectRule on TENT tiles of entire puzzle all - * TENT tiles should fail FinishWithTentsDirectRule as no TENT tiles should be there - * - * @throws InvalidFileFormatException - */ - @Test - public void FinishWithTentsFailTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTentsFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - ArrayList cells = new ArrayList(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - TreeTentCell c = board.getCell(k, i); - c.setData(TreeTentType.TENT); - board.addModifiedData(c); - cells.add(c); - } + + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) + * + * @throws InvalidFileFormatException + */ + @Test + public void AdditionalTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/AdditionalTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 2); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(2, 1); + + cell1.setData(TreeTentType.TENT); + cell2.setData(TreeTentType.TENT); + cell3.setData(TreeTentType.TENT); + cell4.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + board.addModifiedData(cell4); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + if ((c.getLocation()).equals(cell1.getLocation()) + || (c.getLocation()).equals(cell2.getLocation()) + || (c.getLocation()).equals(cell3.getLocation()) + || (c.getLocation()).equals(cell4.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, c)); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, c)); + } + } + } } - Assert.assertNotNull(RULE.checkRule(transition)); + /** + * Empty 3x3 TreeTent puzzle Tests FinishWithTentsDirectRule on TENT tiles of entire puzzle all + * TENT tiles should fail FinishWithTentsDirectRule as no TENT tiles should be there + * + * @throws InvalidFileFormatException + */ + @Test + public void FinishWithTentsFailTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/FinishWithTentsFail", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + ArrayList cells = new ArrayList(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + TreeTentCell c = board.getCell(k, i); + c.setData(TreeTentType.TENT); + board.addModifiedData(c); + cells.add(c); + } + } - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail - * FinishWithTentsDirectRule as there were already sufficient number of TENT tiles - * - * @throws InvalidFileFormatException - */ - @Test - public void TooManyTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/TooManyTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - ArrayList cells = new ArrayList(); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - if ((k == 1) && (i == 1)) { - continue; + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } } - TreeTentCell c = board.getCell(k, i); - c.setData(TreeTentType.TENT); - board.addModifiedData(c); - cells.add(c); - } } - Assert.assertNotNull(RULE.checkRule(transition)); + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail + * FinishWithTentsDirectRule as there were already sufficient number of TENT tiles + * + * @throws InvalidFileFormatException + */ + @Test + public void TooManyTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/TooManyTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + ArrayList cells = new ArrayList(); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + if ((k == 1) && (i == 1)) { + continue; + } + TreeTentCell c = board.getCell(k, i); + c.setData(TreeTentType.TENT); + board.addModifiedData(c); + cells.add(c); + } + } - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } - } - - /** - * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles - * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail - * FinishWithTentsDirectRule as there are multiple configurations of the placement of the TENT - * tiles - * - * @throws InvalidFileFormatException - */ - @Test - public void AmbiguousTentsTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/FinishWithTentsDirectRule/AmbiguousTents", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell = board.getCell(0, 1); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); - - Assert.assertNotNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(1, 0); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + /** + * 3x3 TreeTent puzzle with a TENT tile at (1,1) Tests FinishWithTentsDirectRule on TENT tiles + * around the TENT tile at (1,0), (1,2), (0,1), and (2,1) all TENT tiles should fail + * FinishWithTentsDirectRule as there are multiple configurations of the placement of the TENT + * tiles + * + * @throws InvalidFileFormatException + */ + @Test + public void AmbiguousTentsTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/FinishWithTentsDirectRule/AmbiguousTents", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell = board.getCell(0, 1); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); + + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(1, 0); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(2, 1); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(2, 1); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } - } + Assert.assertNotNull(RULE.checkRule(transition)); - cell.setData(TreeTentType.UNKNOWN); - board.addModifiedData(cell); - cell = board.getCell(1, 2); - cell.setData(TreeTentType.TENT); - board.addModifiedData(cell); + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } - Assert.assertNotNull(RULE.checkRule(transition)); + cell.setData(TreeTentType.UNKNOWN); + board.addModifiedData(cell); + cell = board.getCell(1, 2); + cell.setData(TreeTentType.TENT); + board.addModifiedData(cell); - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + Assert.assertNotNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java index b3a1de6d5..92d6e4a59 100644 --- a/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/LastCampingSpotDirectRuleTest.java @@ -17,148 +17,148 @@ public class LastCampingSpotDirectRuleTest { - private static final LastCampingSpotDirectRule RULE = new LastCampingSpotDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square above a tree which is surrounded on all other - * sides. - */ - @Test - public void EmptyFieldTest_Up() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotUp", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final LastCampingSpotDirectRule RULE = new LastCampingSpotDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square above a tree which is surrounded on all + * other sides. + */ + @Test + public void EmptyFieldTest_Up() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotUp", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square below a tree which is surrounded on all other - * sides. - */ - @Test - public void EmptyFieldTest_Down() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotDown", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 2); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square below a tree which is surrounded on all + * other sides. + */ + @Test + public void EmptyFieldTest_Down() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotDown", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 2); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square to the left of a tree which is surrounded on - * all other sides. - */ - @Test - public void EmptyFieldTest_Left() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square to the left of a tree which is surrounded + * on all other sides. + */ + @Test + public void EmptyFieldTest_Left() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotLeft", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Checks if a test works for an empty square to the right of a tree which is surrounded on - * all other sides. - */ - @Test - public void EmptyFieldTest_Right() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(2, 1); - cell1.setData(TreeTentType.TENT); - - board.addModifiedData(cell1); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException + *

Checks if a test works for an empty square to the right of a tree which is surrounded + * on all other sides. + */ + @Test + public void EmptyFieldTest_Right() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/LastCampingSpotDirectRule/LastCampingSpotRight", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(2, 1); + cell1.setData(TreeTentType.TENT); + + board.addModifiedData(cell1); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java index 8d099f283..b17c92486 100644 --- a/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/NoTentForTreeContradictionRuleTest.java @@ -15,96 +15,99 @@ public class NoTentForTreeContradictionRuleTest { - private static final NoTentForTreeContradictionRule RULE = new NoTentForTreeContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Tests if a tree is next to only grass in a 2x2 grid triggers - * the contradiction - */ - @Test - public void NoTentForTreeContradictionRule_Basic() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally - * next to the tree, which should still contradict - */ - @Test - public void NoTentForTreeContradictionRule_Diagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeDiagonal", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests that adjacent trees do not allow a pass - */ - @Test - public void NoTentForTreeContradictionRule_TwoTrees() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTrees", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally - * next to two trees, which should still contradict on one. - */ - @Test - public void NoTentForTreeContradictionRule_TwoTreesDiagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTreesDiagonal", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } + private static final NoTentForTreeContradictionRule RULE = new NoTentForTreeContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Tests if a tree is next to only grass in a 2x2 grid + * triggers the contradiction + */ + @Test + public void NoTentForTreeContradictionRule_Basic() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTree", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally + * next to the tree, which should still contradict + */ + @Test + public void NoTentForTreeContradictionRule_Diagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests that adjacent trees do not allow a pass + */ + @Test + public void NoTentForTreeContradictionRule_TwoTrees() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTrees", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests similarly to above, but now with a tent diagonally + * next to two trees, which should still contradict on one. + */ + @Test + public void NoTentForTreeContradictionRule_TwoTreesDiagonal() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTentForTreeContradictionRule/NoTentForTreeTwoTreesDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } } diff --git a/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java index c639b2a25..fd6be92de 100644 --- a/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/NoTreeForTentContradictionRuleTest.java @@ -14,201 +14,204 @@ public class NoTreeForTentContradictionRuleTest { - private static final NoTreeForTentContradictionRule RULE = new NoTreeForTentContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_NW() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNW", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NE corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_NE() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNE", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_SW() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSW", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the SE corner has no - * adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_SE() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSE", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with no trees, a Tent in the center - * cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_3x3() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTent3x3", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with diagonal trees, a Tent in the - * center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_3x3WithDiagonalTrees() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentDiagonals", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with an adjacent tree, test does not - * assert null. - */ - @Test - public void NoTreeForTentContradictionRule_YesTree() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentYesTree", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } - - /** - * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with touching tents, a Tent in the - * center cell has no adjacent trees - */ - @Test - public void NoTreeForTentContradictionRule_JustTent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentJustTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); - } + private static final NoTreeForTentContradictionRule RULE = new NoTreeForTentContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_NW() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNW", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NE corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_NE() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentNE", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the NW corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_SW() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSW", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 2x2 Grid, a Tent in the SE corner has no + * adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_SE() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentSE", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with no trees, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_3x3() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTent3x3", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with diagonal trees, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_3x3WithDiagonalTrees() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentDiagonals", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with an adjacent tree, test does + * not assert null. + */ + @Test + public void NoTreeForTentContradictionRule_YesTree() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentYesTree", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } + + /** + * @throws InvalidFileFormatException Tests if, in a 3x3 Grid with touching tents, a Tent in the + * center cell has no adjacent trees + */ + @Test + public void NoTreeForTentContradictionRule_JustTent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/NoTreeForTentContradictionRule/NoTreeForTentJustTent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 2))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(2, 2))); + } } diff --git a/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java index e48fd0979..7ff57a052 100644 --- a/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/SurroundTentWithGrassDirectRuleTest.java @@ -17,138 +17,140 @@ public class SurroundTentWithGrassDirectRuleTest { - private static final SurroundTentWithGrassDirectRule RULE = new SurroundTentWithGrassDirectRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Test to check if all adjacent and diagonals not filled with - * a tree are filled with grass - */ - @Test - public void SurroundTentWithGrassBasicRuleTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrass", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(1, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(0, 2); - cell2.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final SurroundTentWithGrassDirectRule RULE = + new SurroundTentWithGrassDirectRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Test to check if all adjacent and diagonals not filled + * with a tree are filled with grass + */ + @Test + public void SurroundTentWithGrassBasicRuleTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrass", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(1, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(0, 2); + cell2.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Test with a 3x3 board with an absolutely empty area aside from a tent in the middle - * While such a situation is an illegal treetent setup, this direct rule doesn't consider that - * aspect, so its ok in this context - */ - @Test - public void SurroundTentWithGrassBasicRuleTest_BadBoard() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassBad", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - cell1.setData(TreeTentType.GRASS); - TreeTentCell cell2 = board.getCell(1, 0); - cell2.setData(TreeTentType.GRASS); - TreeTentCell cell3 = board.getCell(2, 0); - cell3.setData(TreeTentType.GRASS); - TreeTentCell cell4 = board.getCell(0, 1); - cell4.setData(TreeTentType.GRASS); - // Skip (1,1) due to being the Tent - TreeTentCell cell5 = board.getCell(2, 1); - cell5.setData(TreeTentType.GRASS); - TreeTentCell cell6 = board.getCell(0, 2); - cell6.setData(TreeTentType.GRASS); - TreeTentCell cell7 = board.getCell(1, 2); - cell7.setData(TreeTentType.GRASS); - TreeTentCell cell8 = board.getCell(2, 2); - cell8.setData(TreeTentType.GRASS); - - board.addModifiedData(cell1); - board.addModifiedData(cell2); - board.addModifiedData(cell3); - // board.addModifiedData(cell4); - board.addModifiedData(cell5); - board.addModifiedData(cell6); - board.addModifiedData(cell7); - board.addModifiedData(cell8); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || // point.equals(cell4.getLocation()) || - point.equals(cell5.getLocation()) - || point.equals(cell6.getLocation()) - || point.equals(cell7.getLocation()) - || point.equals(cell8.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException + *

Test with a 3x3 board with an absolutely empty area aside from a tent in the middle + * While such a situation is an illegal treetent setup, this direct rule doesn't consider + * that aspect, so its ok in this context + */ + @Test + public void SurroundTentWithGrassBasicRuleTest_BadBoard() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassBad", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + cell1.setData(TreeTentType.GRASS); + TreeTentCell cell2 = board.getCell(1, 0); + cell2.setData(TreeTentType.GRASS); + TreeTentCell cell3 = board.getCell(2, 0); + cell3.setData(TreeTentType.GRASS); + TreeTentCell cell4 = board.getCell(0, 1); + cell4.setData(TreeTentType.GRASS); + // Skip (1,1) due to being the Tent + TreeTentCell cell5 = board.getCell(2, 1); + cell5.setData(TreeTentType.GRASS); + TreeTentCell cell6 = board.getCell(0, 2); + cell6.setData(TreeTentType.GRASS); + TreeTentCell cell7 = board.getCell(1, 2); + cell7.setData(TreeTentType.GRASS); + TreeTentCell cell8 = board.getCell(2, 2); + cell8.setData(TreeTentType.GRASS); + + board.addModifiedData(cell1); + board.addModifiedData(cell2); + board.addModifiedData(cell3); + // board.addModifiedData(cell4); + board.addModifiedData(cell5); + board.addModifiedData(cell6); + board.addModifiedData(cell7); + board.addModifiedData(cell8); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || // point.equals(cell4.getLocation()) || + point.equals(cell5.getLocation()) + || point.equals(cell6.getLocation()) + || point.equals(cell7.getLocation()) + || point.equals(cell8.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException - *

Test to see if the rule passes even if no grass was able to be placed due to the - * presence of trees. - */ - @Test - public void SurroundTentWithGrassBasicRuleTest_FullBoard() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassTrees", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkRule(transition)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** + * @throws InvalidFileFormatException + *

Test to see if the rule passes even if no grass was able to be placed due to the + * presence of trees. + */ + @Test + public void SurroundTentWithGrassBasicRuleTest_FullBoard() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/SurroundTentWithGrassDirectRule/SurroundTentWithGrassTrees", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkRule(transition)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java index 237013212..68dbeaf48 100644 --- a/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TentForTreeDirectRuleTest.java @@ -3,12 +3,12 @@ // This feature is no longer supported public class TentForTreeDirectRuleTest { - // private static final TentForTreeBasicRule RULE = new TentForTreeBasicRule(); - // private static TreeTent treetent; - // - // @BeforeClass - // public static void setUp() { - // MockGameBoardFacade.getInstance(); - // treetent = new TreeTent(); - // } + // private static final TentForTreeBasicRule RULE = new TentForTreeBasicRule(); + // private static TreeTent treetent; + // + // @BeforeClass + // public static void setUp() { + // MockGameBoardFacade.getInstance(); + // treetent = new TreeTent(); + // } } diff --git a/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java b/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java index 1f08fa597..1fe7e4bd0 100644 --- a/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TentOrGrassCaseRuleTest.java @@ -18,62 +18,62 @@ import org.junit.Test; public class TentOrGrassCaseRuleTest { - private static final TentOrGrassCaseRule RULE = new TentOrGrassCaseRule(); - private static TreeTent treetent; + private static final TentOrGrassCaseRule RULE = new TentOrGrassCaseRule(); + private static TreeTent treetent; - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } - /** - * empty 3x3 TreeTent puzzle Tests TentOrGrassCaseRule on UNKOWN tile at (0,0) - * - *

checks 2 cases are created checks first case is TENT tile checks second case is GRASS tile - * checks other cells have not been modified - * - * @throws InvalidFileFormatException - */ - @Test - public void TentOrTreeTest() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TentOrGrassCaseRule/TestPuzzle", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); + /** + * empty 3x3 TreeTent puzzle Tests TentOrGrassCaseRule on UNKOWN tile at (0,0) + * + *

checks 2 cases are created checks first case is TENT tile checks second case is GRASS tile + * checks other cells have not been modified + * + * @throws InvalidFileFormatException + */ + @Test + public void TentOrTreeTest() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TentOrGrassCaseRule/TestPuzzle", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - TreeTentCell testing_cell = board.getCell(0, 0); - ArrayList cases = RULE.getCases(board, testing_cell); + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + TreeTentCell testing_cell = board.getCell(0, 0); + ArrayList cases = RULE.getCases(board, testing_cell); - // assert correct number of cases created - Assert.assertEquals(2, cases.size()); + // assert correct number of cases created + Assert.assertEquals(2, cases.size()); - // TENT case - TreeTentBoard tentCase = (TreeTentBoard) cases.get(0); - Assert.assertEquals(tentCase.getCell(0, 0).getType(), TreeTentType.TENT); + // TENT case + TreeTentBoard tentCase = (TreeTentBoard) cases.get(0); + Assert.assertEquals(tentCase.getCell(0, 0).getType(), TreeTentType.TENT); - // GRASS case - TreeTentBoard grassCase = (TreeTentBoard) cases.get(1); - Assert.assertEquals(grassCase.getCell(0, 0).getType(), TreeTentType.GRASS); + // GRASS case + TreeTentBoard grassCase = (TreeTentBoard) cases.get(1); + Assert.assertEquals(grassCase.getCell(0, 0).getType(), TreeTentType.GRASS); - // checks other cells have not been modified - TreeTentCell original_cell; - TreeTentCell case_cell; + // checks other cells have not been modified + TreeTentCell original_cell; + TreeTentCell case_cell; - for (int w = 0; w < board.getWidth(); w++) { - for (int h = 0; h < board.getHeight(); h++) { - if (w == 0 && h == 0) { - continue; - } - original_cell = board.getCell(w, h); - case_cell = tentCase.getCell(w, h); - Assert.assertEquals(original_cell.getType(), case_cell.getType()); + for (int w = 0; w < board.getWidth(); w++) { + for (int h = 0; h < board.getHeight(); h++) { + if (w == 0 && h == 0) { + continue; + } + original_cell = board.getCell(w, h); + case_cell = tentCase.getCell(w, h); + Assert.assertEquals(original_cell.getType(), case_cell.getType()); - case_cell = grassCase.getCell(w, h); - Assert.assertEquals(original_cell.getType(), case_cell.getType()); - } + case_cell = grassCase.getCell(w, h); + Assert.assertEquals(original_cell.getType(), case_cell.getType()); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java index f08d87a3b..e1773827d 100644 --- a/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TooFewTentsContradictionRuleTest.java @@ -16,225 +16,231 @@ public class TooFewTentsContradictionRuleTest { - private static final TooFewTentsContradictionRule RULE = new TooFewTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if the - * fact it expects a tent on the y-axis is caught. - */ - @Test - public void TooFewTentsContradictionRule_JustY() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsJustY", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just a tent, checks if the - * fact it expects 2 tents on the y-axis is caught. (This is an impossible situation given the - * constraints, but for the purposes of the test it is fine) - */ - @Test - public void TooFewTentsContradictionRule_WithTent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsWithTent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if the - * fact it expects a tent on both x and y is caught. - */ - @Test - public void TooFewTentsContradictionRule_DoubleBad() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsDoubleBad", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: [] Tr [] Gr Column 2 is - * checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_2x2ColumnOnly() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Column", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 1); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final TooFewTentsContradictionRule RULE = new TooFewTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if + * the fact it expects a tent on the y-axis is caught. + */ + @Test + public void TooFewTentsContradictionRule_JustY() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsJustY", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just a tent, checks if + * the fact it expects 2 tents on the y-axis is caught. (This is an impossible situation + * given the constraints, but for the purposes of the test it is fine) + */ + @Test + public void TooFewTentsContradictionRule_WithTent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsWithTent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Using a 1x1 Puzzle Grid, which is just grass, checks if + * the fact it expects a tent on both x and y is caught. + */ + @Test + public void TooFewTentsContradictionRule_DoubleBad() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsDoubleBad", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: [] Tr [] Gr Column 2 + * is checked to have 1 Tent (which is not present, thus producing a contradiction) + */ + @Test + public void TooFewTentsContradictionRule_2x2ColumnOnly() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Column", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 1); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tr Gr [] [] Row 1 is - * checked to have 1 Tent (which is not present, thus producing a contradiction) - */ - @Test - public void TooFewTentsContradictionRule_2x2RowOnly() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Row", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(1, 0); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tr Gr [] [] Row 1 is + * checked to have 1 Tent (which is not present, thus producing a contradiction) + */ + @Test + public void TooFewTentsContradictionRule_2x2RowOnly() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents2x2Row", treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(1, 0); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: [] Tr [] [] Gr [] [] Gr - * [] Column 2 is checked to have 1 Tent (which is not present, thus producing a - * contradiction) - */ - @Test - public void TooFewTentsContradictionRule_3x3OneColumn() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3Column", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(1, 0); - TreeTentCell cell2 = board.getCell(1, 1); - TreeTentCell cell3 = board.getCell(1, 2); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: [] Tr [] [] Gr [] [] + * Gr [] Column 2 is checked to have 1 Tent (which is not present, thus producing a + * contradiction) + */ + @Test + public void TooFewTentsContradictionRule_3x3OneColumn() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3Column", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(1, 0); + TreeTentCell cell2 = board.getCell(1, 1); + TreeTentCell cell3 = board.getCell(1, 2); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: Gr Tr Gr Gr [] Gr Gr Tr - * Gr Column 1 and 3 are checked to have 1 Tent (which is not present, thus producing a - * contradiction) - */ - @Test - public void TooFewTentsContradictionRule_3x3TwoColumn() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3DoubleColumn", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(0, 1); - TreeTentCell cell3 = board.getCell(0, 2); - TreeTentCell cell4 = board.getCell(2, 0); - TreeTentCell cell5 = board.getCell(2, 1); - TreeTentCell cell6 = board.getCell(2, 2); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation()) - || point.equals(cell5.getLocation()) - || point.equals(cell6.getLocation())) { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Looks at a 3x3 Board in the format: Gr Tr Gr Gr [] Gr Gr + * Tr Gr Column 1 and 3 are checked to have 1 Tent (which is not present, thus producing a + * contradiction) + */ + @Test + public void TooFewTentsContradictionRule_3x3TwoColumn() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTents3x3DoubleColumn", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(0, 1); + TreeTentCell cell3 = board.getCell(0, 2); + TreeTentCell cell4 = board.getCell(2, 0); + TreeTentCell cell5 = board.getCell(2, 1); + TreeTentCell cell6 = board.getCell(2, 2); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation()) + || point.equals(cell5.getLocation()) + || point.equals(cell6.getLocation())) { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tn [] Tr [] This should - * fail the contradiction as it is a legal board. - */ - @Test - public void TooFewTentsContradictionRule_NoContradiction() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsNoContradiction", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } + + /** + * @throws InvalidFileFormatException Looks at a 2x2 Board in the format: Tn [] Tr [] This + * should fail the contradiction as it is a legal board. + */ + @Test + public void TooFewTentsContradictionRule_NoContradiction() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooFewTentsContradictionRule/TooFewTentsNoContradiction", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } diff --git a/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java index fb94aa006..2e542b3d2 100644 --- a/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TooManyTentsContradictionRuleTest.java @@ -16,246 +16,253 @@ public class TooManyTentsContradictionRuleTest { - private static final TooManyTentsContradictionRule RULE = new TooManyTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - /* - TESTING BASIS: - All test in this Rule use a 3x3 table. - There is a Tree at (1,1) - There are tents at (0,1) and (2,2) - All Tent Counts are listed left to right or top to bottom - */ - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_TotalFail() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTotalFail", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + private static final TooManyTentsContradictionRule RULE = new TooManyTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + /* + TESTING BASIS: + All test in this Rule use a 3x3 table. + There is a Tree at (1,1) + There are tents at (0,1) and (2,2) + All Tent Counts are listed left to right or top to bottom + */ + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_TotalFail() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTotalFail", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 1,0,0 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_TopRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(0, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 1,0,0 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_TopRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(0, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTests if: Row Tent Counts: 0,0,1 Column - * Tent Counts: 0,0,0 - */ - @Test - public void TooManyTentsContradictionRule_BottomRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomRight", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(0, 2); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTests if: Row Tent Counts: 0,0,1 Column + * Tent Counts: 0,0,0 + */ + @Test + public void TooManyTentsContradictionRule_BottomRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(0, 2); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,1,0 - */ - @Test - public void TooManyTentsContradictionRule_TopDown() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopDown", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(1, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,1,0 + */ + @Test + public void TooManyTentsContradictionRule_TopDown() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopDown", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(1, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column - * Tent Counts: 0,0,1 - */ - @Test - public void TooManyTentsContradictionRule_BottomDown() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomDown", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(2, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if: Row Tent Counts: 0,0,0 Column + * Tent Counts: 0,0,1 + */ + @Test + public void TooManyTentsContradictionRule_BottomDown() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomDown", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(2, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) || point.equals(cell2.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if the Top Tent is completely - * accounted for, but not the bottom Row Tent Counts: 1,0,0 Column Tent Counts: 0,1,0 - */ - @Test - public void TooManyTentsContradictionRule_TopAccount() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopAccount", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 0); - TreeTentCell cell2 = board.getCell(1, 0); - TreeTentCell cell3 = board.getCell(0, 1); - TreeTentCell cell4 = board.getCell(1, 1); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if the Top Tent is completely + * accounted for, but not the bottom Row Tent Counts: 1,0,0 Column Tent Counts: 0,1,0 + */ + @Test + public void TooManyTentsContradictionRule_TopAccount() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsTopAccount", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 0); + TreeTentCell cell2 = board.getCell(1, 0); + TreeTentCell cell3 = board.getCell(0, 1); + TreeTentCell cell4 = board.getCell(1, 1); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } - - /** - * @throws InvalidFileFormatException Tests for TooManyTents if the Bottom Tent is completely - * accounted for, but not the Top Row Tent Counts: 0,0,1 Column Tent Counts: 0,0,1 - */ - @Test - public void TooManyTentsContradictionRule_BottomAccount() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomAccount", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - TreeTentCell cell1 = board.getCell(0, 1); - TreeTentCell cell2 = board.getCell(2, 1); - TreeTentCell cell3 = board.getCell(0, 2); - TreeTentCell cell4 = board.getCell(2, 2); - - Assert.assertNull(RULE.checkContradiction(board)); - - for (int i = 0; i < board.getHeight(); i++) { - for (int k = 0; k < board.getWidth(); k++) { - Point point = new Point(k, i); - if (point.equals(cell1.getLocation()) - || point.equals(cell2.getLocation()) - || point.equals(cell3.getLocation()) - || point.equals(cell4.getLocation())) { - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); - } else { - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + + /** + * @throws InvalidFileFormatException Tests for TooManyTents if the Bottom Tent is completely + * accounted for, but not the Top Row Tent Counts: 0,0,1 Column Tent Counts: 0,0,1 + */ + @Test + public void TooManyTentsContradictionRule_BottomAccount() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TooManyTentsContradictionRule/TooManyTentsBottomAccount", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + TreeTentCell cell1 = board.getCell(0, 1); + TreeTentCell cell2 = board.getCell(2, 1); + TreeTentCell cell3 = board.getCell(0, 2); + TreeTentCell cell4 = board.getCell(2, 2); + + Assert.assertNull(RULE.checkContradiction(board)); + + for (int i = 0; i < board.getHeight(); i++) { + for (int k = 0; k < board.getWidth(); k++) { + Point point = new Point(k, i); + if (point.equals(cell1.getLocation()) + || point.equals(cell2.getLocation()) + || point.equals(cell3.getLocation()) + || point.equals(cell4.getLocation())) { + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } else { + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(k, i))); + } + } } - } } - } } diff --git a/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java b/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java index 6018b6853..9f5455a92 100644 --- a/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TouchingTentsContradictionRuleTest.java @@ -14,239 +14,246 @@ public class TouchingTentsContradictionRuleTest { - private static final TouchingTentsContradictionRule RULE = new TouchingTentsContradictionRule(); - private static TreeTent treetent; - - @BeforeClass - public static void setUp() { - MockGameBoardFacade.getInstance(); - treetent = new TreeTent(); - } - - // DIAGONAL TESTS - /** - * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_DiagonalUpLeftToDownRight() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonal", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - - /** - * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_DiagonalDownLeftToUpRight() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonalAlt", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - // ADJACENT TESTS - /** - * @throws InvalidFileFormatException Tests a tent adjacent of orientation T T - */ - @Test - public void TouchingTentsContradictionRule_AdjacentVertical() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacent", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent adjacent of orientation TT - */ - @Test - public void TouchingTentsContradictionRule_AdjacentHorizontal() - throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacentAlt", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - // MIXED TESTS - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT TT - */ - @Test - public void TouchingTentsContradictionRule_2By2Square() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsFull2By2", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT T - */ - @Test - public void TouchingTentsContradictionRule_UpLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpLeft", treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation TT T - */ - @Test - public void TouchingTentsContradictionRule_UpRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpRight", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation T TT - */ - @Test - public void TouchingTentsContradictionRule_DownLeft() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownLeft", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - } - - /** - * @throws InvalidFileFormatException Tests a tent of orientation T TT - */ - @Test - public void TouchingTentsContradictionRule_DownRight() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownRight", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNull(RULE.checkContradiction(board)); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - } - - /** - * @throws InvalidFileFormatException Tests if tree adjacent triggers a null - */ - @Test - public void TouchingTentsContradictionRule_TreeAdjacent() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeAdjacent", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); - } - - /** - * @throws InvalidFileFormatException Tests if tree diagonal triggers a null - */ - @Test - public void TouchingTentsContradictionRule_TreeDiagonal() throws InvalidFileFormatException { - TestUtilities.importTestBoard( - "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeDiagonal", - treetent); - TreeNode rootNode = treetent.getTree().getRootNode(); - TreeTransition transition = rootNode.getChildren().get(0); - transition.setRule(RULE); - - TreeTentBoard board = (TreeTentBoard) transition.getBoard(); - - Assert.assertNotNull(RULE.checkContradiction(board)); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); - Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); - } + private static final TouchingTentsContradictionRule RULE = new TouchingTentsContradictionRule(); + private static TreeTent treetent; + + @BeforeClass + public static void setUp() { + MockGameBoardFacade.getInstance(); + treetent = new TreeTent(); + } + + // DIAGONAL TESTS + /** + * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_DiagonalUpLeftToDownRight() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } + + /** + * @throws InvalidFileFormatException Tests a tent diagonal of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_DiagonalDownLeftToUpRight() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsDiagonalAlt", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + // ADJACENT TESTS + /** + * @throws InvalidFileFormatException Tests a tent adjacent of orientation T T + */ + @Test + public void TouchingTentsContradictionRule_AdjacentVertical() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent adjacent of orientation TT + */ + @Test + public void TouchingTentsContradictionRule_AdjacentHorizontal() + throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsAdjacentAlt", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + // MIXED TESTS + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT TT + */ + @Test + public void TouchingTentsContradictionRule_2By2Square() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsFull2By2", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT T + */ + @Test + public void TouchingTentsContradictionRule_UpLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpLeft", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation TT T + */ + @Test + public void TouchingTentsContradictionRule_UpRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedUpRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation T TT + */ + @Test + public void TouchingTentsContradictionRule_DownLeft() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownLeft", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + } + + /** + * @throws InvalidFileFormatException Tests a tent of orientation T TT + */ + @Test + public void TouchingTentsContradictionRule_DownRight() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsMixedDownRight", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNull(RULE.checkContradiction(board)); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + Assert.assertNull(RULE.checkRuleAt(transition, board.getCell(1, 1))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + } + + /** + * @throws InvalidFileFormatException Tests if tree adjacent triggers a null + */ + @Test + public void TouchingTentsContradictionRule_TreeAdjacent() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeAdjacent", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 1))); + } + + /** + * @throws InvalidFileFormatException Tests if tree diagonal triggers a null + */ + @Test + public void TouchingTentsContradictionRule_TreeDiagonal() throws InvalidFileFormatException { + TestUtilities.importTestBoard( + "puzzles/treetent/rules/TouchingTentsContradictionRule/TouchingTentsTreeDiagonal", + treetent); + TreeNode rootNode = treetent.getTree().getRootNode(); + TreeTransition transition = rootNode.getChildren().get(0); + transition.setRule(RULE); + + TreeTentBoard board = (TreeTentBoard) transition.getBoard(); + + Assert.assertNotNull(RULE.checkContradiction(board)); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(0, 0))); + Assert.assertNotNull(RULE.checkRuleAt(transition, board.getCell(1, 0))); + } } diff --git a/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java b/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java index 2aecd0f0a..f4ea6703b 100644 --- a/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java +++ b/src/test/java/puzzles/treetent/rules/TreeForTentDirectRuleTest.java @@ -3,12 +3,12 @@ // This feature is no longer supported public class TreeForTentDirectRuleTest { - // private static final TreeForTentBasicRule RULE = new TreeForTentBasicRule(); - // private static TreeTent treetent; + // private static final TreeForTentBasicRule RULE = new TreeForTentBasicRule(); + // private static TreeTent treetent; - // @BeforeClass - // public static void setUp() { - // MockGameBoardFacade.getInstance(); - // treetent = new TreeTent(); - // } + // @BeforeClass + // public static void setUp() { + // MockGameBoardFacade.getInstance(); + // treetent = new TreeTent(); + // } } From bee026f56acbf1d7ad0675032107e06513b916a5 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Wed, 14 Feb 2024 13:08:41 -0500 Subject: [PATCH 49/54] Update checkstyle.xml Removed problematic LeftCurly and RightCurly requirements --- config/checkstyle/checkstyle.xml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 0cd09a2ae..7b2727713 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -6,9 +6,10 @@ - - - + + + + From 58953d8edb6d903e8c7139affae25b0c761f3c14 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Wed, 14 Feb 2024 14:25:14 -0500 Subject: [PATCH 50/54] Changing back to tabWidth --- config/checkstyle/checkstyle.xml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 7b2727713..6e17e3fc5 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -6,11 +6,7 @@ - - - - - + From 0a10c76d86b18a802cd395bfa67ec21ddb37bab0 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln <56417002+jadeandtea@users.noreply.github.com> Date: Wed, 14 Feb 2024 14:28:34 -0500 Subject: [PATCH 51/54] Add newline to test formatter + build --- src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java index b413bebb7..a077ef6da 100644 --- a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java @@ -42,6 +42,8 @@ public void executeCommand() { if (child == null) { child = tree.addTreeElement(treeElement); } else { + + if (treeElement.getType() == TreeElementType.NODE) { child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); } else { From 30afaf1d36a4d3c44aabdab796a27cd3fa453a65 Mon Sep 17 00:00:00 2001 From: Bram van Heuveln Date: Wed, 14 Feb 2024 19:30:10 +0000 Subject: [PATCH 52/54] Automated Java code formatting changes --- src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java index a077ef6da..12b39cd85 100644 --- a/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java +++ b/src/main/java/edu/rpi/legup/history/AddTreeElementCommand.java @@ -43,7 +43,6 @@ public void executeCommand() { child = tree.addTreeElement(treeElement); } else { - if (treeElement.getType() == TreeElementType.NODE) { child = tree.addTreeElement((TreeNode) treeElement, (TreeTransition) child); } else { From 19697b9b53101014f5e6ab791d95c09a5bbc0b96 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Wed, 14 Feb 2024 14:52:41 -0500 Subject: [PATCH 53/54] Trying some ChatGPT stuff --- build.gradle | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/build.gradle b/build.gradle index 49829e473..95465156f 100644 --- a/build.gradle +++ b/build.gradle @@ -33,7 +33,24 @@ spotless{ googleJavaFormat('1.19.2').aosp() + // Define custom formatting rules to remove blank lines after keywords + customLazy('removeBlankLinesAfterKeywords', { + target '*.java' + replace 'else {\\s+\\n(\\s+)', 'else {$1' + replace 'for \\(.*?\\) {\\s+\\n(\\s+)', 'for ($1) {$2' + replace 'while \\(.*?\\) {\\s+\\n(\\s+)', 'while ($1) {$2' + replace 'do {\\s+\\n(\\s+)', 'do {$1' + replace 'try {\\s+\\n(\\s+)', 'try {$1' + replace 'catch \\(.*?\\) {\\s+\\n(\\s+)', 'catch ($1) {$2' + replace 'finally {\\s+\\n(\\s+)', 'finally {$1' + replace 'switch \\(.*?\\) {\\s+\\n(\\s+)', 'switch ($1) {$2' + replace 'case .*?:\\s+\\n(\\s+)', 'case $1:$2' + replace 'default:\\s+\\n(\\s+)', 'default:$1' + }) + formatAnnotations() + + format('removeBlankLinesAfterKeywords') } } From 6933cb0771767228b7d04f8374ccc9972c35b729 Mon Sep 17 00:00:00 2001 From: charlestian23 Date: Wed, 14 Feb 2024 15:50:20 -0500 Subject: [PATCH 54/54] Getting rid of problematic experimentation --- build.gradle | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/build.gradle b/build.gradle index 95465156f..49829e473 100644 --- a/build.gradle +++ b/build.gradle @@ -33,24 +33,7 @@ spotless{ googleJavaFormat('1.19.2').aosp() - // Define custom formatting rules to remove blank lines after keywords - customLazy('removeBlankLinesAfterKeywords', { - target '*.java' - replace 'else {\\s+\\n(\\s+)', 'else {$1' - replace 'for \\(.*?\\) {\\s+\\n(\\s+)', 'for ($1) {$2' - replace 'while \\(.*?\\) {\\s+\\n(\\s+)', 'while ($1) {$2' - replace 'do {\\s+\\n(\\s+)', 'do {$1' - replace 'try {\\s+\\n(\\s+)', 'try {$1' - replace 'catch \\(.*?\\) {\\s+\\n(\\s+)', 'catch ($1) {$2' - replace 'finally {\\s+\\n(\\s+)', 'finally {$1' - replace 'switch \\(.*?\\) {\\s+\\n(\\s+)', 'switch ($1) {$2' - replace 'case .*?:\\s+\\n(\\s+)', 'case $1:$2' - replace 'default:\\s+\\n(\\s+)', 'default:$1' - }) - formatAnnotations() - - format('removeBlankLinesAfterKeywords') } }